Compare commits
4
Commits
8ca2185c01
..
v1.1.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
340bdbd9e8 | ||
|
|
8cdc0f436f | ||
|
|
943259774f | ||
|
|
aeb08ec049 |
No files matched your search
@@ -25,7 +25,7 @@
|
|||||||
|
|
||||||
| 路径 | 内容 |
|
| 路径 | 内容 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `server/` | 同一个 Go 程序。可以只做反射器、只做探测节点,或两个一起开 |
|
| `server/` | 同一个 Go 程序。可以只做反射器、只做探测节点、做中心,或节点和中心一起开 |
|
||||||
| `client/` | Flutter 客户端。Windows、Linux 桌面和 Android |
|
| `client/` | Flutter 客户端。Windows、Linux 桌面和 Android |
|
||||||
| `docs/PROTOCOL.md` | 反射帧、控制接口和各探测类型 |
|
| `docs/PROTOCOL.md` | 反射帧、控制接口和各探测类型 |
|
||||||
| `docs/server-linux.md` | 安装、systemd、防火墙、公开节点和口令节点、HTTPS |
|
| `docs/server-linux.md` | 安装、systemd、防火墙、公开节点和口令节点、HTTPS |
|
||||||
@@ -63,7 +63,15 @@ flutter run -d linux
|
|||||||
3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。
|
3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。
|
||||||
4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。
|
4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。
|
||||||
|
|
||||||
本机的 UDP 探测会记下这次解析出的每个地址。结果上的「发往」是当前实际在用的地址。还没有哪个地址应答时,一个超时就换下一个;已经有应答之后,要连续三次没有应答才换,中途开关 VPN 不会把还在应答的地址丢掉。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。
|
本机的 UDP 探测会记下这次解析出的每个地址。结果上的「实际地址」是真正发包或连通的地址,并注明 IPv4 或 IPv6。域名解析出来的地址单独标成「解析到」,不会被说成已经在用。还没有哪个地址应答时,一次失败就换下一个,这次失败不计入正式丢包,界面会说明回退;已经有应答之后,超时算正式结果,要连续三次没有应答才换。全部地址都失败时显示失败,不会显示 0% 成功。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。
|
||||||
|
|
||||||
|
远程节点从 1.1.2 起会在每条结果里带上实际地址。更早的节点没有这个字段时,界面写明「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。1.1.1 的节点仍会把选址失败算进统计。
|
||||||
|
|
||||||
|
端口框写着当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。
|
||||||
|
|
||||||
|
已有远程节点可以改名称、控制地址和口令。节点编号和当前选择不变。口令留空表示不改,界面不显示已经保存的口令。
|
||||||
|
|
||||||
|
手动停止后曲线还在,并给出这次的开始、结束、用时和最终指标。停止时还没完成的请求不算丢包。点曲线可以钉住该时刻,松手后仍然保留。指标的算法在应用里的「指标说明」,版本记录在「更新历史」。
|
||||||
|
|
||||||
节点口令保存在本机应用目录里,权限尽量收成只有自己能读,不会写进网址或日志。
|
节点口令保存在本机应用目录里,权限尽量收成只有自己能读,不会写进网址或日志。
|
||||||
|
|
||||||
@@ -96,10 +104,24 @@ cd server && go test -race ./...
|
|||||||
cd client && flutter analyze && flutter test
|
cd client && flutter analyze && flutter test
|
||||||
```
|
```
|
||||||
|
|
||||||
Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.1`。
|
Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.3`,构建号 `6`。应用标识没有改,新的安装包会覆盖原来的「网络质量探测」,不用先卸载。
|
||||||
|
|
||||||
|
从 1.1.3 起,客户端启动后会检查更新,设置里可以关掉。先问 GitHub Releases,连不上再问 `https://git.yanjiu.ltd/YanJiu/netquality/releases`。1.1.2 没有这个功能,所以 1.1.2 升到 1.1.3 仍然要自己安装。Windows 和 Linux 会把新文件写回当前安装目录。Android 会弹出系统安装确认,这一步不能跳过。没有真正的新版本时,可以用环境变量 `NQ_UPDATE_GITHUB_API` 和 `NQ_UPDATE_GITEA_API` 指向一份同样格式的测试响应。
|
||||||
|
|
||||||
|
中心也是这个 Go 程序。示例配置在 [server/example-center](server/example-center),里面的口令都是占位。本机可以这样看目录:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd server
|
||||||
|
go build -o netquality-reflector .
|
||||||
|
./netquality-reflector -mode center -center-dir example-center -control-addr 127.0.0.1:8443
|
||||||
|
```
|
||||||
|
|
||||||
|
客户端点「一键添加服务器」,中心地址填 `http://127.0.0.1:8443`,账号 `lab`,口令 `example-token`。这只适合本机确认功能。真正给别人用时,控制端口要走 HTTPS。
|
||||||
|
|
||||||
|
这一版的说明在 [docs/release-notes/1.1.3.md](docs/release-notes/1.1.3.md)。
|
||||||
|
|
||||||
## 许可
|
## 许可
|
||||||
|
|
||||||
Copyright (C) 2026 灸 言
|
Copyright (C) 2026 言灸
|
||||||
|
|
||||||
本项目以 GNU Affero General Public License v3.0 许可(SPDX 标识:AGPL-3.0-only)。你可以在遵守该许可的前提下使用、修改和分发。完整条款见仓库根目录的 [LICENSE](LICENSE)。
|
本项目以 GNU Affero General Public License v3.0 许可(SPDX 标识:AGPL-3.0-only)。你可以在遵守该许可的前提下使用、修改和分发。完整条款见仓库根目录的 [LICENSE](LICENSE)。
|
||||||
+1
-1
@@ -7,4 +7,4 @@ flutter pub get
|
|||||||
flutter run -d linux
|
flutter run -d linux
|
||||||
```
|
```
|
||||||
|
|
||||||
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。
|
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。合作反射 UDP 默认 `19091`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。当前版本是 1.1.3。本机 HTTP 探测需要旁边有 `netquality-reflector`,或设置 `NQ_PROBE_HELPER`。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<uses-permission android:name="android.permission.INTERNET"/>
|
<uses-permission android:name="android.permission.INTERNET"/>
|
||||||
|
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
|
||||||
<application
|
<application
|
||||||
android:label="网络质量探测"
|
android:label="网络质量探测"
|
||||||
android:name="${applicationName}"
|
android:name="${applicationName}"
|
||||||
@@ -26,6 +27,15 @@
|
|||||||
<category android:name="android.intent.category.LAUNCHER"/>
|
<category android:name="android.intent.category.LAUNCHER"/>
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
<provider
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:authorities="${applicationId}.fileprovider"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data
|
||||||
|
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||||
|
android:resource="@xml/file_paths" />
|
||||||
|
</provider>
|
||||||
<!-- Don't delete the meta-data below.
|
<!-- Don't delete the meta-data below.
|
||||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||||
<meta-data
|
<meta-data
|
||||||
|
|||||||
@@ -1,5 +1,43 @@
|
|||||||
package dev.netquality.netquality
|
package dev.netquality.netquality
|
||||||
|
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
import io.flutter.embedding.android.FlutterActivity
|
import io.flutter.embedding.android.FlutterActivity
|
||||||
|
import io.flutter.embedding.engine.FlutterEngine
|
||||||
|
import io.flutter.plugin.common.MethodChannel
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
class MainActivity : FlutterActivity()
|
class MainActivity : FlutterActivity() {
|
||||||
|
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||||
|
super.configureFlutterEngine(flutterEngine)
|
||||||
|
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "dev.netquality/platform")
|
||||||
|
.setMethodCallHandler { call, result ->
|
||||||
|
when (call.method) {
|
||||||
|
"abi" -> result.success(Build.SUPPORTED_ABIS.firstOrNull() ?: "")
|
||||||
|
"installApk" -> {
|
||||||
|
val path = call.argument<String>("path")
|
||||||
|
if (path.isNullOrEmpty()) {
|
||||||
|
result.error("bad_path", "没有安装包路径", null)
|
||||||
|
return@setMethodCallHandler
|
||||||
|
}
|
||||||
|
val file = File(path)
|
||||||
|
val uri: Uri = FileProvider.getUriForFile(
|
||||||
|
this,
|
||||||
|
"$packageName.fileprovider",
|
||||||
|
file,
|
||||||
|
)
|
||||||
|
val intent = Intent(Intent.ACTION_VIEW).apply {
|
||||||
|
setDataAndType(uri, "application/vnd.android.package-archive")
|
||||||
|
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
}
|
||||||
|
startActivity(intent)
|
||||||
|
result.success(null)
|
||||||
|
}
|
||||||
|
else -> result.notImplemented()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<paths>
|
||||||
|
<cache-path name="updates" path="updates/" />
|
||||||
|
</paths>
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import '../models/session_config.dart';
|
||||||
|
|
||||||
|
class CatalogServer {
|
||||||
|
const CatalogServer({
|
||||||
|
required this.id,
|
||||||
|
required this.name,
|
||||||
|
required this.confidential,
|
||||||
|
this.controlUrl = '',
|
||||||
|
this.credential = '',
|
||||||
|
this.credentialExpiresAt = '',
|
||||||
|
});
|
||||||
|
|
||||||
|
final String id;
|
||||||
|
final String name;
|
||||||
|
final bool confidential;
|
||||||
|
final String controlUrl;
|
||||||
|
final String credential;
|
||||||
|
final String credentialExpiresAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Catalog {
|
||||||
|
const Catalog({
|
||||||
|
required this.account,
|
||||||
|
required this.group,
|
||||||
|
required this.servers,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String account;
|
||||||
|
final String group;
|
||||||
|
final List<CatalogServer> servers;
|
||||||
|
|
||||||
|
/// Parses a catalog. Confidential entries drop any address or credential
|
||||||
|
/// the server might have included by mistake.
|
||||||
|
factory Catalog.parse(String body) {
|
||||||
|
final decoded = jsonDecode(body);
|
||||||
|
if (decoded is! Map) {
|
||||||
|
throw const FormatException('目录无效');
|
||||||
|
}
|
||||||
|
final rawServers = decoded['servers'];
|
||||||
|
final servers = <CatalogServer>[];
|
||||||
|
if (rawServers is List) {
|
||||||
|
for (final item in rawServers) {
|
||||||
|
if (item is! Map) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final confidential = item['confidential'] == true;
|
||||||
|
final url = item['controlUrl'] is String ? item['controlUrl'] as String : '';
|
||||||
|
final credential = item['credential'] is String
|
||||||
|
? item['credential'] as String
|
||||||
|
: '';
|
||||||
|
servers.add(
|
||||||
|
CatalogServer(
|
||||||
|
id: item['id'] is String ? item['id'] as String : '',
|
||||||
|
name: item['name'] is String ? item['name'] as String : '未命名',
|
||||||
|
confidential: confidential,
|
||||||
|
controlUrl: confidential ? '' : url,
|
||||||
|
credential: confidential ? '' : credential,
|
||||||
|
credentialExpiresAt: confidential
|
||||||
|
? ''
|
||||||
|
: (item['credentialExpiresAt'] is String
|
||||||
|
? item['credentialExpiresAt'] as String
|
||||||
|
: ''),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Catalog(
|
||||||
|
account: decoded['account'] is String ? decoded['account'] as String : '',
|
||||||
|
group: decoded['group'] is String ? decoded['group'] as String : '',
|
||||||
|
servers: servers,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class CenterSyncResult {
|
||||||
|
const CenterSyncResult({required this.nodes, required this.credentials});
|
||||||
|
|
||||||
|
final List<RemoteNode> nodes;
|
||||||
|
|
||||||
|
/// Node id to short-lived credential. Confidential nodes are absent.
|
||||||
|
/// The node's long-lived token is never in this map.
|
||||||
|
final Map<String, String> credentials;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces the servers that belong to [link] with the catalog.
|
||||||
|
/// Manual nodes and servers from other centers stay. Confidential nodes
|
||||||
|
/// are stored with an empty address.
|
||||||
|
CenterSyncResult mergeCenterCatalog({
|
||||||
|
required List<RemoteNode> existing,
|
||||||
|
required CenterLink link,
|
||||||
|
required Catalog catalog,
|
||||||
|
required String Function() newId,
|
||||||
|
}) {
|
||||||
|
final kept = [
|
||||||
|
for (final node in existing)
|
||||||
|
if (!node.fromCenter || node.centerLinkId != link.id) node,
|
||||||
|
];
|
||||||
|
final previous = {
|
||||||
|
for (final node in existing)
|
||||||
|
if (node.fromCenter && node.centerLinkId == link.id) node.serverId: node,
|
||||||
|
};
|
||||||
|
final credentials = <String, String>{};
|
||||||
|
final added = <RemoteNode>[];
|
||||||
|
for (final server in catalog.servers) {
|
||||||
|
if (server.id.isEmpty) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final old = previous[server.id];
|
||||||
|
final id = old?.id ?? newId();
|
||||||
|
final node = RemoteNode(
|
||||||
|
id: id,
|
||||||
|
name: server.name,
|
||||||
|
baseUrl: server.confidential ? '' : server.controlUrl,
|
||||||
|
visibility: server.confidential ? 'confidential' : 'center',
|
||||||
|
fromCenter: true,
|
||||||
|
confidential: server.confidential,
|
||||||
|
centerLinkId: link.id,
|
||||||
|
serverId: server.id,
|
||||||
|
);
|
||||||
|
added.add(node);
|
||||||
|
if (!server.confidential && server.credential.isNotEmpty) {
|
||||||
|
credentials[id] = server.credential;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return CenterSyncResult(nodes: [...kept, ...added], credentials: credentials);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Center-issued names cannot be changed on the client.
|
||||||
|
RemoteNode renameNode(RemoteNode node, String name) {
|
||||||
|
if (node.fromCenter) {
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
return node.copyWith(name: name);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool storedNodeHides(RemoteNode node, String secret) {
|
||||||
|
if (!node.confidential || secret.isEmpty) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
final raw = jsonEncode(node.toJson());
|
||||||
|
return !raw.contains(secret);
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import '../models/session_config.dart';
|
||||||
|
import 'catalog.dart';
|
||||||
|
|
||||||
|
class CenterClientException implements Exception {
|
||||||
|
CenterClientException(this.message);
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String> loginCenter({
|
||||||
|
required String baseUrl,
|
||||||
|
required String account,
|
||||||
|
required String password,
|
||||||
|
}) async {
|
||||||
|
final body = await _send(
|
||||||
|
baseUrl,
|
||||||
|
'POST',
|
||||||
|
'/v1/center/login',
|
||||||
|
'',
|
||||||
|
{'account': account.trim(), 'password': password},
|
||||||
|
);
|
||||||
|
final token = body['token'];
|
||||||
|
if (token is! String || token.isEmpty) {
|
||||||
|
throw CenterClientException('中心没有返回口令');
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Catalog> fetchCatalog({
|
||||||
|
required String baseUrl,
|
||||||
|
required String token,
|
||||||
|
}) async {
|
||||||
|
final body = await _send(baseUrl, 'GET', '/v1/center/catalog', token, null);
|
||||||
|
return Catalog.parse(jsonEncode(body));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Map<String, dynamic>> _send(
|
||||||
|
String baseUrl,
|
||||||
|
String method,
|
||||||
|
String path,
|
||||||
|
String token,
|
||||||
|
Map<String, Object?>? jsonBody,
|
||||||
|
) async {
|
||||||
|
final normalized = normalizeNodeUrl(baseUrl);
|
||||||
|
if (normalized == null) {
|
||||||
|
throw CenterClientException('中心地址需要是 http 或 https,且不能把口令写在地址里');
|
||||||
|
}
|
||||||
|
final client = HttpClient();
|
||||||
|
try {
|
||||||
|
final request = await client.openUrl(
|
||||||
|
method,
|
||||||
|
Uri.parse(normalized).resolve(path),
|
||||||
|
);
|
||||||
|
request.followRedirects = false;
|
||||||
|
if (token.isNotEmpty) {
|
||||||
|
request.headers.set(HttpHeaders.authorizationHeader, 'Bearer $token');
|
||||||
|
}
|
||||||
|
if (jsonBody != null) {
|
||||||
|
request.headers.contentType = ContentType.json;
|
||||||
|
request.add(utf8.encode(jsonEncode(jsonBody)));
|
||||||
|
}
|
||||||
|
final response = await request.close().timeout(const Duration(seconds: 15));
|
||||||
|
final text = await response.transform(utf8.decoder).join();
|
||||||
|
if (response.statusCode >= 300 && response.statusCode < 400) {
|
||||||
|
throw CenterClientException('中心地址发生了跳转。请填写最终的 HTTPS 地址');
|
||||||
|
}
|
||||||
|
if (response.statusCode == 401) {
|
||||||
|
throw CenterClientException('中心口令不正确,或账号密码不对');
|
||||||
|
}
|
||||||
|
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||||
|
throw CenterClientException(_message(text) ?? '中心拒绝了这次请求');
|
||||||
|
}
|
||||||
|
final decoded = jsonDecode(text);
|
||||||
|
if (decoded is! Map) {
|
||||||
|
throw CenterClientException('中心返回的内容无效');
|
||||||
|
}
|
||||||
|
return Map<String, dynamic>.from(decoded);
|
||||||
|
} on CenterClientException {
|
||||||
|
rethrow;
|
||||||
|
} on SocketException {
|
||||||
|
throw CenterClientException('连不上中心。请检查地址和防火墙');
|
||||||
|
} on HandshakeException {
|
||||||
|
throw CenterClientException('TLS 握手失败。请改用正确的 HTTPS 地址');
|
||||||
|
} on FormatException {
|
||||||
|
throw CenterClientException('中心返回的内容无效');
|
||||||
|
} finally {
|
||||||
|
client.close(force: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
/// Versions that exist as this release or as a real Git tag / GitHub Release.
|
||||||
|
/// Unpublished earlier behavior mentioned inside the 1.1.1 notes is not given
|
||||||
|
/// its own entry.
|
||||||
|
class ReleaseEntry {
|
||||||
|
const ReleaseEntry({
|
||||||
|
required this.version,
|
||||||
|
required this.title,
|
||||||
|
required this.source,
|
||||||
|
required this.points,
|
||||||
|
this.published,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String version;
|
||||||
|
final String title;
|
||||||
|
final String source;
|
||||||
|
final String? published;
|
||||||
|
final List<String> points;
|
||||||
|
}
|
||||||
|
|
||||||
|
const releaseHistory = <ReleaseEntry>[
|
||||||
|
ReleaseEntry(
|
||||||
|
version: '1.1.3',
|
||||||
|
title: '网络质量探测 1.1.3',
|
||||||
|
source: '仓库 docs/release-notes/1.1.3.md。这一版的 Git 标签要等发布时才有,这里写的是即将发布的内容。',
|
||||||
|
points: [
|
||||||
|
'可以自动检查更新,也能在设置里关掉。先问 GitHub,连不上再用备用 Git。1.1.2 没有这个功能,升到 1.1.3 仍要手动安装。从这一版起,新版本才会自己下载并覆盖安装。',
|
||||||
|
'Windows 和 Linux 覆盖进现有安装目录。设置、已保存的节点、口令和探测历史仍在应用自己的数据目录里,不会被安装包清掉。',
|
||||||
|
'点「开始探测」会记下目标、端口和类型。目标框旁边可以打开最近的记录,点一条填回表单,也可以单条删除或全部清除。这里不保存节点口令、中心口令、Cookie 和请求体。',
|
||||||
|
'设置里可以分别关闭 IPv4 或 IPv6。两个都关、或填写了已关闭的那种地址时,不会开始。远程节点会收到同样的选择。',
|
||||||
|
'新增 HTTP 探测,包含 HTTP/3。可以指定方法、请求头、请求体、跳转次数,以及 curl --resolve 那种指定解析。4xx 和 5xx 显示状态码,不叫丢包。',
|
||||||
|
'同一个程序可以当中心。客户端用「一键添加服务器」填中心地址、账号和口令,一次加入这个口令能用的全部节点。保密节点只显示中心给的名称,探测由中心转发,本机不保存地址。',
|
||||||
|
],
|
||||||
|
),
|
||||||
|
ReleaseEntry(
|
||||||
|
version: '1.1.2',
|
||||||
|
title: '网络质量探测 1.1.2',
|
||||||
|
source: '仓库 docs/release-notes/1.1.2.md。这一版的 Git 标签要等发布时才有,这里写的是即将发布的内容。',
|
||||||
|
points: [
|
||||||
|
'可以修改已有远程节点的名称、控制地址和口令。节点编号和当前选择保持不变。口令留空表示不改,界面不显示已经保存的口令。',
|
||||||
|
'端口框标明当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。',
|
||||||
|
'本机和远程节点都显示实际连通或实际发包的地址,以及 IPv4 / IPv6。旧节点如果没有上报地址,会写明未报告,不会把域名解析的第一个地址当成已经使用的地址。',
|
||||||
|
'选址阶段失败的候选(例如 IPv6 没有应答后改用 IPv4)不再计入正式丢包,并单独说明回退。选定地址之后的失败仍然计入。全部候选都失败时显示失败,不会显示 0% 成功。',
|
||||||
|
'结果给出已发送、已收到、超时、比率、当前/最小/平均/中位/P95/最大延迟、抖动和用时。某种探测没有测量的量会标成不适用或 —。',
|
||||||
|
'手动停止后保留曲线,并给出开始、结束、用时、目标、来源、实际地址和最终指标。停止时还没完成的请求不计入丢包。',
|
||||||
|
'点曲线可以钉住该时刻的数值,松手后仍然保留;再点另一点会更换。新的一次探测,或该点滚出窗口后,不会沿用过期选择。',
|
||||||
|
'新增「指标说明」。',
|
||||||
|
],
|
||||||
|
),
|
||||||
|
ReleaseEntry(
|
||||||
|
version: '1.1.1',
|
||||||
|
title: '网络质量探测 1.1.1',
|
||||||
|
published: '2026-11-09',
|
||||||
|
source: 'Git 标签 v1.1.1,以及 GitHub Release「网络质量探测 1.1.1」(发布于 2026-11-09,之后补过桌面和节点压缩包)。',
|
||||||
|
points: [
|
||||||
|
'本机 UDP 会把解析出的地址逐个试过,停在第一个真正有应答的地址上。',
|
||||||
|
'还没有地址应答时,一次超时就换下一个。已经有应答之后,要连续 3 次没有应答才换。',
|
||||||
|
'结果里显示当时实际在用的地址。地址落在 198.18.0.0/15 时,会提示这是 VPN 假地址。',
|
||||||
|
'发布物包含 Android APK(arm64-v8a 与 armeabi-v7a,versionName 1.1.1,versionCode 分别为 2004 和 1004)、Linux 与 Windows 桌面客户端,以及 Linux amd64、Linux arm64、Windows amd64 的检测节点包。',
|
||||||
|
'标签 v1.1.1 没有因为后来补上的桌面和节点压缩包而移动。',
|
||||||
|
],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
const releaseHistoryNote =
|
||||||
|
'仓库里目前公开的版本标签只有 v1.1.1。1.1.1 的发布说明提到过更早的发包行为,但没有单独的标签或 Release,所以这里不写成另一个版本。';
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
// Copyright (C) 2026 灸 言
|
// Copyright (C) 2026 言灸
|
||||||
// SPDX-License-Identifier: AGPL-3.0-only
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
/// Latency over successful round-trips only.
|
||||||
|
///
|
||||||
|
/// * current: the latest successful sample, stored separately as `rttMs`
|
||||||
|
/// * min / max: smallest and largest successful sample
|
||||||
|
/// * mean: arithmetic mean
|
||||||
|
/// * median: the middle sample after sorting; when the count is even, the
|
||||||
|
/// mean of the two middle samples
|
||||||
|
/// * p95: nearest-rank. Rank is `ceil(0.95 * n)` computed as
|
||||||
|
/// `(95 * n + 99) ~/ 100` so binary floating point cannot move the rank.
|
||||||
|
/// Rank is 1-based and then clamped to the sample count.
|
||||||
|
class LatencyStats {
|
||||||
|
const LatencyStats({
|
||||||
|
required this.min,
|
||||||
|
required this.mean,
|
||||||
|
required this.median,
|
||||||
|
required this.p95,
|
||||||
|
required this.max,
|
||||||
|
});
|
||||||
|
|
||||||
|
final double min;
|
||||||
|
final double mean;
|
||||||
|
final double median;
|
||||||
|
final double p95;
|
||||||
|
final double max;
|
||||||
|
|
||||||
|
static LatencyStats? from(List<double> samples) {
|
||||||
|
if (samples.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final sorted = [...samples]..sort();
|
||||||
|
var sum = 0.0;
|
||||||
|
for (final value in sorted) {
|
||||||
|
sum += value;
|
||||||
|
}
|
||||||
|
final count = sorted.length;
|
||||||
|
final median = count.isOdd
|
||||||
|
? sorted[count ~/ 2]
|
||||||
|
: (sorted[count ~/ 2 - 1] + sorted[count ~/ 2]) / 2;
|
||||||
|
final rank = nearestRank95(count);
|
||||||
|
return LatencyStats(
|
||||||
|
min: sorted.first,
|
||||||
|
mean: sum / count,
|
||||||
|
median: median,
|
||||||
|
p95: sorted[rank - 1],
|
||||||
|
max: sorted.last,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int nearestRank95(int count) {
|
||||||
|
if (count <= 1) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
final rank = (95 * count + 99) ~/ 100;
|
||||||
|
if (rank < 1) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (rank > count) {
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
return rank;
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import 'latency.dart';
|
||||||
|
|
||||||
class Outcome {
|
class Outcome {
|
||||||
const Outcome({
|
const Outcome({
|
||||||
required this.status,
|
required this.status,
|
||||||
@@ -6,6 +8,7 @@ class Outcome {
|
|||||||
this.note = '',
|
this.note = '',
|
||||||
this.detail = const {},
|
this.detail = const {},
|
||||||
this.reconnect = false,
|
this.reconnect = false,
|
||||||
|
this.selectionSkipped = 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
final String status;
|
final String status;
|
||||||
@@ -15,6 +18,10 @@ class Outcome {
|
|||||||
final Map<String, String> detail;
|
final Map<String, String> detail;
|
||||||
final bool reconnect;
|
final bool reconnect;
|
||||||
|
|
||||||
|
/// Candidate failures folded into this measured attempt. They are not
|
||||||
|
/// themselves samples.
|
||||||
|
final int selectionSkipped;
|
||||||
|
|
||||||
static const ok = 'ok';
|
static const ok = 'ok';
|
||||||
static const timeout = 'timeout';
|
static const timeout = 'timeout';
|
||||||
static const unknown = 'unknown';
|
static const unknown = 'unknown';
|
||||||
@@ -48,6 +55,13 @@ class ProbeSummary {
|
|||||||
required this.unknownPct,
|
required this.unknownPct,
|
||||||
required this.lastNote,
|
required this.lastNote,
|
||||||
required this.detail,
|
required this.detail,
|
||||||
|
this.minRttMs,
|
||||||
|
this.meanRttMs,
|
||||||
|
this.medianRttMs,
|
||||||
|
this.p95RttMs,
|
||||||
|
this.maxRttMs,
|
||||||
|
this.selectionSkipped = 0,
|
||||||
|
this.latencyStats = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
final int sent;
|
final int sent;
|
||||||
@@ -68,6 +82,15 @@ class ProbeSummary {
|
|||||||
final double? unknownPct;
|
final double? unknownPct;
|
||||||
final String lastNote;
|
final String lastNote;
|
||||||
final Map<String, String> detail;
|
final Map<String, String> detail;
|
||||||
|
final double? minRttMs;
|
||||||
|
final double? meanRttMs;
|
||||||
|
final double? medianRttMs;
|
||||||
|
final double? p95RttMs;
|
||||||
|
final double? maxRttMs;
|
||||||
|
final int selectionSkipped;
|
||||||
|
|
||||||
|
/// False when an older remote node omitted the latency distribution.
|
||||||
|
final bool latencyStats;
|
||||||
|
|
||||||
static const empty = ProbeSummary(
|
static const empty = ProbeSummary(
|
||||||
sent: 0,
|
sent: 0,
|
||||||
@@ -110,6 +133,16 @@ class ProbeSummary {
|
|||||||
unknownPct: _double(json['unknownPct']),
|
unknownPct: _double(json['unknownPct']),
|
||||||
lastNote: json['lastNote'] is String ? json['lastNote'] as String : '',
|
lastNote: json['lastNote'] is String ? json['lastNote'] as String : '',
|
||||||
detail: _detail(json['detail']),
|
detail: _detail(json['detail']),
|
||||||
|
minRttMs: _double(json['minRttMs']),
|
||||||
|
meanRttMs: _double(json['meanRttMs']),
|
||||||
|
medianRttMs: _double(json['medianRttMs']),
|
||||||
|
p95RttMs: _double(json['p95RttMs']),
|
||||||
|
maxRttMs: _double(json['maxRttMs']),
|
||||||
|
selectionSkipped: _int(json['selectionSkipped']),
|
||||||
|
latencyStats:
|
||||||
|
json.containsKey('minRttMs') ||
|
||||||
|
json.containsKey('medianRttMs') ||
|
||||||
|
json.containsKey('p95RttMs'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -137,7 +170,9 @@ class ProbeSample {
|
|||||||
|
|
||||||
factory ProbeSample.fromJson(Map<String, dynamic> json) {
|
factory ProbeSample.fromJson(Map<String, dynamic> json) {
|
||||||
final summary = json['summary'] is Map
|
final summary = json['summary'] is Map
|
||||||
? ProbeSummary.fromJson(Map<String, dynamic>.from(json['summary'] as Map))
|
? ProbeSummary.fromJson(
|
||||||
|
Map<String, dynamic>.from(json['summary'] as Map),
|
||||||
|
)
|
||||||
: ProbeSummary.empty;
|
: ProbeSummary.empty;
|
||||||
return ProbeSample(
|
return ProbeSample(
|
||||||
seq: _int(json['seq']),
|
seq: _int(json['seq']),
|
||||||
@@ -171,12 +206,15 @@ class SampleBook {
|
|||||||
double jitterMs = 0;
|
double jitterMs = 0;
|
||||||
bool _hasJitter = false;
|
bool _hasJitter = false;
|
||||||
double _lastTransit = 0;
|
double _lastTransit = 0;
|
||||||
|
final List<double> _rtts = [];
|
||||||
|
int selectionSkipped = 0;
|
||||||
String lastNote = '';
|
String lastNote = '';
|
||||||
Map<String, String> detail = {};
|
Map<String, String> detail = {};
|
||||||
|
|
||||||
void add(Outcome outcome) {
|
void add(Outcome outcome) {
|
||||||
sent += 1;
|
sent += 1;
|
||||||
completed += 1;
|
completed += 1;
|
||||||
|
selectionSkipped += outcome.selectionSkipped;
|
||||||
if (outcome.reconnect) {
|
if (outcome.reconnect) {
|
||||||
reconnects += 1;
|
reconnects += 1;
|
||||||
}
|
}
|
||||||
@@ -193,6 +231,7 @@ class SampleBook {
|
|||||||
final rtt = outcome.rttMs;
|
final rtt = outcome.rttMs;
|
||||||
if (rtt != null) {
|
if (rtt != null) {
|
||||||
lastRttMs = rtt;
|
lastRttMs = rtt;
|
||||||
|
_rtts.add(rtt);
|
||||||
if (_hasJitter) {
|
if (_hasJitter) {
|
||||||
final delta = (rtt - _lastTransit).abs();
|
final delta = (rtt - _lastTransit).abs();
|
||||||
jitterMs += (delta - jitterMs) / 16;
|
jitterMs += (delta - jitterMs) / 16;
|
||||||
@@ -234,7 +273,9 @@ class SampleBook {
|
|||||||
if (denom > 0) {
|
if (denom > 0) {
|
||||||
probeLoss = timeout * 100 / denom;
|
probeLoss = timeout * 100 / denom;
|
||||||
}
|
}
|
||||||
} else if (profile == 'tcp-connect' || profile == 'minecraft-java') {
|
} else if (profile == 'tcp-connect' ||
|
||||||
|
profile == 'minecraft-java' ||
|
||||||
|
profile == 'http') {
|
||||||
final denom = ok + timeout + refused + dns + protocol + other;
|
final denom = ok + timeout + refused + dns + protocol + other;
|
||||||
if (denom > 0) {
|
if (denom > 0) {
|
||||||
failure = (denom - ok) * 100 / denom;
|
failure = (denom - ok) * 100 / denom;
|
||||||
@@ -250,6 +291,7 @@ class SampleBook {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
final latency = LatencyStats.from(_rtts);
|
||||||
return ProbeSummary(
|
return ProbeSummary(
|
||||||
sent: sent,
|
sent: sent,
|
||||||
completed: completed,
|
completed: completed,
|
||||||
@@ -269,6 +311,13 @@ class SampleBook {
|
|||||||
unknownPct: unknownPct,
|
unknownPct: unknownPct,
|
||||||
lastNote: lastNote,
|
lastNote: lastNote,
|
||||||
detail: detail,
|
detail: detail,
|
||||||
|
minRttMs: latency?.min,
|
||||||
|
meanRttMs: latency?.mean,
|
||||||
|
medianRttMs: latency?.median,
|
||||||
|
p95RttMs: latency?.p95,
|
||||||
|
maxRttMs: latency?.max,
|
||||||
|
selectionSkipped: selectionSkipped,
|
||||||
|
latencyStats: true,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'sample_book.dart';
|
||||||
|
|
||||||
|
/// A candidate "responded" when the address itself answered: success, a
|
||||||
|
/// protocol mismatch, or an explicit refusal. Silence, timeout and a
|
||||||
|
/// connect error are not a response, so another address may be tried.
|
||||||
|
bool selectionResponded(Outcome outcome) {
|
||||||
|
switch (outcome.status) {
|
||||||
|
case Outcome.ok:
|
||||||
|
case Outcome.protocol:
|
||||||
|
case Outcome.refused:
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SelectionDecision {
|
||||||
|
const SelectionDecision({required this.commit, this.skipped = 0});
|
||||||
|
|
||||||
|
final List<Outcome> commit;
|
||||||
|
final int skipped;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Separates address selection from measured probes.
|
||||||
|
///
|
||||||
|
/// Before any candidate has responded, failures are held. A later response
|
||||||
|
/// drops those held failures: they are reported as a fallback diagnostic and
|
||||||
|
/// are not added to sent, timeout or loss. If every candidate fails in the
|
||||||
|
/// round, the held failures are committed, so the session cannot show a
|
||||||
|
/// false 0% success. After a response, further failures are committed
|
||||||
|
/// immediately. [endMeasurement] is called when the picker leaves the
|
||||||
|
/// address that was being measured; the failure that caused the leave has
|
||||||
|
/// already been committed.
|
||||||
|
class SelectionLedger {
|
||||||
|
SelectionLedger(this.candidateCount);
|
||||||
|
|
||||||
|
final int candidateCount;
|
||||||
|
bool measuring = false;
|
||||||
|
final List<Outcome> _held = [];
|
||||||
|
|
||||||
|
SelectionDecision take(Outcome outcome, {required bool responded}) {
|
||||||
|
if (candidateCount <= 1) {
|
||||||
|
if (responded) {
|
||||||
|
measuring = true;
|
||||||
|
}
|
||||||
|
return SelectionDecision(commit: [outcome]);
|
||||||
|
}
|
||||||
|
if (measuring) {
|
||||||
|
return SelectionDecision(commit: [outcome]);
|
||||||
|
}
|
||||||
|
if (responded) {
|
||||||
|
final skipped = _held.length;
|
||||||
|
final next = skipped == 0
|
||||||
|
? outcome
|
||||||
|
: _attach(outcome, _fallbackText(_held, outcome), skipped);
|
||||||
|
_held.clear();
|
||||||
|
measuring = true;
|
||||||
|
return SelectionDecision(commit: [next], skipped: skipped);
|
||||||
|
}
|
||||||
|
_held.add(outcome);
|
||||||
|
if (_held.length >= candidateCount) {
|
||||||
|
final commit = List<Outcome>.of(_held);
|
||||||
|
_held.clear();
|
||||||
|
return SelectionDecision(commit: commit);
|
||||||
|
}
|
||||||
|
return const SelectionDecision(commit: []);
|
||||||
|
}
|
||||||
|
|
||||||
|
void endMeasurement() {
|
||||||
|
measuring = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Outcome _attach(Outcome outcome, String fallback, int skipped) {
|
||||||
|
return Outcome(
|
||||||
|
status: outcome.status,
|
||||||
|
kind: outcome.kind,
|
||||||
|
rttMs: outcome.rttMs,
|
||||||
|
note: outcome.note,
|
||||||
|
reconnect: outcome.reconnect,
|
||||||
|
selectionSkipped: outcome.selectionSkipped + skipped,
|
||||||
|
detail: {...outcome.detail, 'fallback': fallback},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _fallbackText(List<Outcome> held, Outcome success) {
|
||||||
|
final failed = held
|
||||||
|
.map((outcome) {
|
||||||
|
final address = outcome.detail['address'];
|
||||||
|
final family = outcome.detail['family'];
|
||||||
|
final where = address == null || address.isEmpty
|
||||||
|
? '未知地址'
|
||||||
|
: (family == null || family.isEmpty)
|
||||||
|
? address
|
||||||
|
: '$address($family)';
|
||||||
|
final why = outcome.note.isEmpty ? '没有成功' : outcome.note;
|
||||||
|
return '$where:$why';
|
||||||
|
})
|
||||||
|
.join(';');
|
||||||
|
final used = success.detail['address'] ?? '';
|
||||||
|
final usedFamily = success.detail['family'] ?? '';
|
||||||
|
final usedText = used.isEmpty
|
||||||
|
? '另一个地址'
|
||||||
|
: usedFamily.isEmpty
|
||||||
|
? used
|
||||||
|
: '$used($usedFamily)';
|
||||||
|
return '候选未成功:$failed。已改用 $usedText。这些失败没有计入正式丢包或失败率。';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop discards the attempt that was still in flight. A finished attempt
|
||||||
|
/// whose note says it was stopped is not a measured loss either.
|
||||||
|
bool countsAfterStop(Outcome? outcome, {required bool cancelled}) {
|
||||||
|
if (cancelled || outcome == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return outcome.note != '已停止';
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
/// Host used for an address-family check. HTTP targets may be a full URL.
|
||||||
|
String probeHost(String raw) {
|
||||||
|
final text = raw.trim();
|
||||||
|
if (text.isEmpty) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
if (text.contains('://')) {
|
||||||
|
return Uri.tryParse(text)?.host ?? '';
|
||||||
|
}
|
||||||
|
final slash = text.indexOf('/');
|
||||||
|
final host = slash >= 0 ? text.substring(0, slash) : text;
|
||||||
|
return host.replaceAll('[', '').replaceAll(']', '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a message when the probe must not start. Null means the families allow it.
|
||||||
|
String? familyRefusal(
|
||||||
|
String raw, {
|
||||||
|
required bool v4,
|
||||||
|
required bool v6,
|
||||||
|
}) {
|
||||||
|
if (!v4 && !v6) {
|
||||||
|
return 'IPv4 和 IPv6 都已关闭,无法开始探测。请在设置里至少打开一个。';
|
||||||
|
}
|
||||||
|
final host = probeHost(raw);
|
||||||
|
final parsed = InternetAddress.tryParse(host);
|
||||||
|
if (parsed == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (parsed.type == InternetAddressType.IPv4 && !v4) {
|
||||||
|
return '目标是 IPv4 地址,但设置里的 IPv4 已关闭。';
|
||||||
|
}
|
||||||
|
if (parsed.type == InternetAddressType.IPv6 && !v6) {
|
||||||
|
return '目标是 IPv6 地址,但设置里的 IPv6 已关闭。';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
List<InternetAddress> filterAddresses(
|
||||||
|
List<InternetAddress> addresses, {
|
||||||
|
required bool v4,
|
||||||
|
required bool v6,
|
||||||
|
}) {
|
||||||
|
return [
|
||||||
|
for (final address in addresses)
|
||||||
|
if ((address.type == InternetAddressType.IPv4 && v4) ||
|
||||||
|
(address.type == InternetAddressType.IPv6 && v6))
|
||||||
|
address,
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import '../storage/token_vault.dart';
|
||||||
|
import 'session_config.dart';
|
||||||
|
|
||||||
|
/// Blank means "keep the token already stored". A non-blank value replaces it.
|
||||||
|
/// The saved token is never returned here.
|
||||||
|
String? replacementNodeToken(String entered) {
|
||||||
|
final trimmed = entered.trim();
|
||||||
|
if (trimmed.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes a replacement token. Returns false when the existing secret is kept.
|
||||||
|
Future<bool> saveEditedNodeToken(
|
||||||
|
TokenVault vault,
|
||||||
|
String id,
|
||||||
|
String entered,
|
||||||
|
) async {
|
||||||
|
final next = replacementNodeToken(entered);
|
||||||
|
if (next == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
await vault.write(nodeTokenKey(id), next);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps [RemoteNode.id]. Changing the control URL clears a cached visibility
|
||||||
|
/// check because it may now be a different server. The token is not part of
|
||||||
|
/// this object.
|
||||||
|
RemoteNode applyNodeEdit(
|
||||||
|
RemoteNode node, {
|
||||||
|
required String name,
|
||||||
|
required String baseUrl,
|
||||||
|
}) {
|
||||||
|
final urlChanged = node.baseUrl != baseUrl;
|
||||||
|
return node.copyWith(
|
||||||
|
name: name,
|
||||||
|
baseUrl: baseUrl,
|
||||||
|
visibility: urlChanged ? '' : node.visibility,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'probe_profile.dart';
|
||||||
|
|
||||||
|
/// Keeps a port the user typed. An empty field or a value that is still the
|
||||||
|
/// previous profile's default follows the newly selected profile.
|
||||||
|
String portAfterProfileChange({
|
||||||
|
required String current,
|
||||||
|
required int previousDefault,
|
||||||
|
required int nextDefault,
|
||||||
|
}) {
|
||||||
|
final trimmed = current.trim();
|
||||||
|
if (trimmed.isEmpty || int.tryParse(trimmed) == previousDefault) {
|
||||||
|
return '$nextDefault';
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
String portHint(ProbeProfile profile) {
|
||||||
|
switch (profile.id) {
|
||||||
|
case 'nq-tcp':
|
||||||
|
return '合作反射 TCP 默认 19090';
|
||||||
|
case 'nq-udp':
|
||||||
|
return '合作反射 UDP 默认 19091';
|
||||||
|
case 'http':
|
||||||
|
return 'HTTP 默认 443(https)或 80(http)';
|
||||||
|
default:
|
||||||
|
return '${profile.label} 默认 ${profile.port}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Default port for an HTTP target. A full http:// URL uses 80. Anything else uses 443.
|
||||||
|
int httpDefaultPort(String target) {
|
||||||
|
final text = target.trim().toLowerCase();
|
||||||
|
if (text.startsWith('http://')) {
|
||||||
|
return 80;
|
||||||
|
}
|
||||||
|
return 443;
|
||||||
|
}
|
||||||
|
|
||||||
|
const portHelperText =
|
||||||
|
'合作反射 TCP 默认 19090,UDP 默认 19091。只有当前端口仍是上一种类型的默认值或为空时,切换类型才会自动更换。';
|
||||||
@@ -64,6 +64,14 @@ class ProbeProfile {
|
|||||||
blurb: '发送 RakNet Unconnected Ping,校验 magic 和原时间戳。',
|
blurb: '发送 RakNet Unconnected Ping,校验 magic 和原时间戳。',
|
||||||
rateLabel: '无应答(未知)',
|
rateLabel: '无应答(未知)',
|
||||||
);
|
);
|
||||||
|
static const http = ProbeProfile(
|
||||||
|
id: 'http',
|
||||||
|
label: 'HTTP',
|
||||||
|
port: 443,
|
||||||
|
blurb:
|
||||||
|
'按 HTTP 请求测量。默认优先 HTTP/2,服务器不支持时降到 HTTP/1.1。强制的版本不支持就失败,不会偷偷降级。4xx 和 5xx 会显示状态码,不算丢包。',
|
||||||
|
rateLabel: '失败率',
|
||||||
|
);
|
||||||
static const customUdp = ProbeProfile(
|
static const customUdp = ProbeProfile(
|
||||||
id: 'custom-udp',
|
id: 'custom-udp',
|
||||||
label: '自定义 UDP',
|
label: '自定义 UDP',
|
||||||
@@ -81,6 +89,7 @@ class ProbeProfile {
|
|||||||
minecraftJava,
|
minecraftJava,
|
||||||
minecraftBedrock,
|
minecraftBedrock,
|
||||||
customUdp,
|
customUdp,
|
||||||
|
http,
|
||||||
];
|
];
|
||||||
|
|
||||||
static ProbeProfile byId(String id) {
|
static ProbeProfile byId(String id) {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
|
||||||
import '../protocol/probe_packet.dart';
|
import '../protocol/probe_packet.dart';
|
||||||
|
import 'ip_family.dart';
|
||||||
import 'probe_profile.dart';
|
import 'probe_profile.dart';
|
||||||
|
|
||||||
class RemoteNode {
|
class RemoteNode {
|
||||||
@@ -9,35 +10,95 @@ class RemoteNode {
|
|||||||
required this.name,
|
required this.name,
|
||||||
required this.baseUrl,
|
required this.baseUrl,
|
||||||
this.visibility = '',
|
this.visibility = '',
|
||||||
|
this.fromCenter = false,
|
||||||
|
this.confidential = false,
|
||||||
|
this.centerLinkId = '',
|
||||||
|
this.serverId = '',
|
||||||
});
|
});
|
||||||
|
|
||||||
final String id;
|
final String id;
|
||||||
final String name;
|
final String name;
|
||||||
final String baseUrl;
|
final String baseUrl;
|
||||||
final String visibility;
|
final String visibility;
|
||||||
|
final bool fromCenter;
|
||||||
|
final bool confidential;
|
||||||
|
final String centerLinkId;
|
||||||
|
final String serverId;
|
||||||
|
|
||||||
RemoteNode copyWith({String? name, String? baseUrl, String? visibility}) {
|
RemoteNode copyWith({
|
||||||
|
String? name,
|
||||||
|
String? baseUrl,
|
||||||
|
String? visibility,
|
||||||
|
bool? fromCenter,
|
||||||
|
bool? confidential,
|
||||||
|
String? centerLinkId,
|
||||||
|
String? serverId,
|
||||||
|
}) {
|
||||||
|
final hidden = confidential ?? this.confidential;
|
||||||
return RemoteNode(
|
return RemoteNode(
|
||||||
id: id,
|
id: id,
|
||||||
name: name ?? this.name,
|
name: name ?? this.name,
|
||||||
baseUrl: baseUrl ?? this.baseUrl,
|
baseUrl: hidden ? '' : (baseUrl ?? this.baseUrl),
|
||||||
visibility: visibility ?? this.visibility,
|
visibility: visibility ?? this.visibility,
|
||||||
|
fromCenter: fromCenter ?? this.fromCenter,
|
||||||
|
confidential: hidden,
|
||||||
|
centerLinkId: centerLinkId ?? this.centerLinkId,
|
||||||
|
serverId: serverId ?? this.serverId,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Object?> toJson() => {
|
Map<String, Object?> toJson() => {
|
||||||
'id': id,
|
'id': id,
|
||||||
'name': name,
|
'name': name,
|
||||||
'baseUrl': baseUrl,
|
'baseUrl': confidential ? '' : baseUrl,
|
||||||
'visibility': visibility,
|
'visibility': visibility,
|
||||||
|
'fromCenter': fromCenter,
|
||||||
|
'confidential': confidential,
|
||||||
|
'centerLinkId': centerLinkId,
|
||||||
|
'serverId': serverId,
|
||||||
};
|
};
|
||||||
|
|
||||||
factory RemoteNode.fromJson(Map<String, dynamic> json) {
|
factory RemoteNode.fromJson(Map<String, dynamic> json) {
|
||||||
|
final confidential = json['confidential'] == true;
|
||||||
return RemoteNode(
|
return RemoteNode(
|
||||||
id: json['id'] is String ? json['id'] as String : '',
|
id: json['id'] is String ? json['id'] as String : '',
|
||||||
name: json['name'] is String ? json['name'] as String : '未命名节点',
|
name: json['name'] is String ? json['name'] as String : '未命名节点',
|
||||||
baseUrl: json['baseUrl'] is String ? json['baseUrl'] as String : '',
|
baseUrl: confidential
|
||||||
|
? ''
|
||||||
|
: (json['baseUrl'] is String ? json['baseUrl'] as String : ''),
|
||||||
visibility: json['visibility'] is String ? json['visibility'] as String : '',
|
visibility: json['visibility'] is String ? json['visibility'] as String : '',
|
||||||
|
fromCenter: json['fromCenter'] == true,
|
||||||
|
confidential: confidential,
|
||||||
|
centerLinkId: json['centerLinkId'] is String
|
||||||
|
? json['centerLinkId'] as String
|
||||||
|
: '',
|
||||||
|
serverId: json['serverId'] is String ? json['serverId'] as String : '',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class CenterLink {
|
||||||
|
const CenterLink({
|
||||||
|
required this.id,
|
||||||
|
required this.url,
|
||||||
|
required this.account,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String id;
|
||||||
|
final String url;
|
||||||
|
final String account;
|
||||||
|
|
||||||
|
Map<String, Object?> toJson() => {
|
||||||
|
'id': id,
|
||||||
|
'url': url,
|
||||||
|
'account': account,
|
||||||
|
};
|
||||||
|
|
||||||
|
factory CenterLink.fromJson(Map<String, dynamic> json) {
|
||||||
|
return CenterLink(
|
||||||
|
id: json['id'] is String ? json['id'] as String : '',
|
||||||
|
url: json['url'] is String ? json['url'] as String : '',
|
||||||
|
account: json['account'] is String ? json['account'] as String : '',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,6 +118,18 @@ class SessionConfig {
|
|||||||
required this.dnsName,
|
required this.dnsName,
|
||||||
required this.payloadHex,
|
required this.payloadHex,
|
||||||
required this.expectHex,
|
required this.expectHex,
|
||||||
|
this.allowIPv4 = true,
|
||||||
|
this.allowIPv6 = true,
|
||||||
|
this.autoUpdate = true,
|
||||||
|
this.httpVersion = 'auto',
|
||||||
|
this.httpResolve = '',
|
||||||
|
this.httpMethod = 'GET',
|
||||||
|
this.httpBody = '',
|
||||||
|
this.httpReferer = '',
|
||||||
|
this.httpUserAgent = '',
|
||||||
|
this.httpCookies = '',
|
||||||
|
this.httpMaxRedirects = 5,
|
||||||
|
this.centers = const [],
|
||||||
});
|
});
|
||||||
|
|
||||||
static const defaults = SessionConfig(
|
static const defaults = SessionConfig(
|
||||||
@@ -88,6 +161,27 @@ class SessionConfig {
|
|||||||
final String dnsName;
|
final String dnsName;
|
||||||
final String payloadHex;
|
final String payloadHex;
|
||||||
final String expectHex;
|
final String expectHex;
|
||||||
|
final bool allowIPv4;
|
||||||
|
final bool allowIPv6;
|
||||||
|
final bool autoUpdate;
|
||||||
|
final String httpVersion;
|
||||||
|
final String httpResolve;
|
||||||
|
final String httpMethod;
|
||||||
|
final String httpBody;
|
||||||
|
final String httpReferer;
|
||||||
|
final String httpUserAgent;
|
||||||
|
final String httpCookies;
|
||||||
|
final int httpMaxRedirects;
|
||||||
|
final List<CenterLink> centers;
|
||||||
|
|
||||||
|
CenterLink? centerLink(String id) {
|
||||||
|
for (final link in centers) {
|
||||||
|
if (link.id == id) {
|
||||||
|
return link;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
ProbeProfile get profile => ProbeProfile.byId(profileId);
|
ProbeProfile get profile => ProbeProfile.byId(profileId);
|
||||||
|
|
||||||
@@ -101,9 +195,36 @@ class SessionConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
String? validate() {
|
String? validate() {
|
||||||
|
final family = familyRefusal(host, v4: allowIPv4, v6: allowIPv6);
|
||||||
|
if (family != null) {
|
||||||
|
return family;
|
||||||
|
}
|
||||||
|
if (profileId == 'http' && httpResolve.trim().isNotEmpty) {
|
||||||
|
final resolveFamily = familyRefusal(
|
||||||
|
httpResolve,
|
||||||
|
v4: allowIPv4,
|
||||||
|
v6: allowIPv6,
|
||||||
|
);
|
||||||
|
if (resolveFamily != null) {
|
||||||
|
return resolveFamily.replaceFirst('目标', '指定解析');
|
||||||
|
}
|
||||||
|
}
|
||||||
if (host.trim().isEmpty) {
|
if (host.trim().isEmpty) {
|
||||||
return '请填写目标地址';
|
return '请填写目标地址';
|
||||||
}
|
}
|
||||||
|
if (profileId == 'http') {
|
||||||
|
final method = httpMethod.trim().toUpperCase();
|
||||||
|
if (method != 'GET' && method != 'POST') {
|
||||||
|
return 'HTTP 方法只支持 GET 和 POST';
|
||||||
|
}
|
||||||
|
if (httpMaxRedirects < 0 || httpMaxRedirects > 20) {
|
||||||
|
return '跳转次数需要在 0 到 20 之间';
|
||||||
|
}
|
||||||
|
const versions = {'auto', '1.1', '2', '3'};
|
||||||
|
if (!versions.contains(httpVersion)) {
|
||||||
|
return 'HTTP 版本需要是自动、1.1、2 或 3';
|
||||||
|
}
|
||||||
|
}
|
||||||
if (port < 1 || port > 65535) {
|
if (port < 1 || port > 65535) {
|
||||||
return '端口需要在 1 到 65535 之间';
|
return '端口需要在 1 到 65535 之间';
|
||||||
}
|
}
|
||||||
@@ -146,7 +267,12 @@ class SessionConfig {
|
|||||||
if (selected == null) {
|
if (selected == null) {
|
||||||
return '请先添加并选择一个远程节点';
|
return '请先添加并选择一个远程节点';
|
||||||
}
|
}
|
||||||
if (normalizeNodeUrl(selected.baseUrl) == null) {
|
if (selected.confidential) {
|
||||||
|
final link = centerLink(selected.centerLinkId);
|
||||||
|
if (link == null || normalizeNodeUrl(link.url) == null) {
|
||||||
|
return '保密节点需要一个可用的中心地址';
|
||||||
|
}
|
||||||
|
} else if (normalizeNodeUrl(selected.baseUrl) == null) {
|
||||||
return '节点地址需要是 http 或 https,且不能把口令写在地址里';
|
return '节点地址需要是 http 或 https,且不能把口令写在地址里';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -167,6 +293,18 @@ class SessionConfig {
|
|||||||
'dnsName': dnsName,
|
'dnsName': dnsName,
|
||||||
'payloadHex': payloadHex,
|
'payloadHex': payloadHex,
|
||||||
'expectHex': expectHex,
|
'expectHex': expectHex,
|
||||||
|
'allowIPv4': allowIPv4,
|
||||||
|
'allowIPv6': allowIPv6,
|
||||||
|
'autoUpdate': autoUpdate,
|
||||||
|
'httpVersion': httpVersion,
|
||||||
|
'httpResolve': httpResolve,
|
||||||
|
'httpMethod': httpMethod,
|
||||||
|
'httpBody': httpBody,
|
||||||
|
'httpReferer': httpReferer,
|
||||||
|
'httpUserAgent': httpUserAgent,
|
||||||
|
'httpCookies': httpCookies,
|
||||||
|
'httpMaxRedirects': httpMaxRedirects,
|
||||||
|
'centers': centers.map((link) => link.toJson()).toList(),
|
||||||
};
|
};
|
||||||
|
|
||||||
factory SessionConfig.fromJson(Map<String, dynamic> json) {
|
factory SessionConfig.fromJson(Map<String, dynamic> json) {
|
||||||
@@ -197,9 +335,43 @@ class SessionConfig {
|
|||||||
: defaults.dnsName,
|
: defaults.dnsName,
|
||||||
payloadHex: json['payloadHex'] is String ? json['payloadHex'] as String : '',
|
payloadHex: json['payloadHex'] is String ? json['payloadHex'] as String : '',
|
||||||
expectHex: json['expectHex'] is String ? json['expectHex'] as String : '',
|
expectHex: json['expectHex'] is String ? json['expectHex'] as String : '',
|
||||||
|
allowIPv4: json['allowIPv4'] is bool ? json['allowIPv4'] as bool : true,
|
||||||
|
allowIPv6: json['allowIPv6'] is bool ? json['allowIPv6'] as bool : true,
|
||||||
|
autoUpdate: json['autoUpdate'] is bool ? json['autoUpdate'] as bool : true,
|
||||||
|
httpVersion: json['httpVersion'] is String
|
||||||
|
? json['httpVersion'] as String
|
||||||
|
: 'auto',
|
||||||
|
httpResolve: json['httpResolve'] is String
|
||||||
|
? json['httpResolve'] as String
|
||||||
|
: '',
|
||||||
|
httpMethod: json['httpMethod'] is String
|
||||||
|
? json['httpMethod'] as String
|
||||||
|
: 'GET',
|
||||||
|
httpBody: json['httpBody'] is String ? json['httpBody'] as String : '',
|
||||||
|
httpReferer: json['httpReferer'] is String
|
||||||
|
? json['httpReferer'] as String
|
||||||
|
: '',
|
||||||
|
httpUserAgent: json['httpUserAgent'] is String
|
||||||
|
? json['httpUserAgent'] as String
|
||||||
|
: '',
|
||||||
|
httpCookies: json['httpCookies'] is String
|
||||||
|
? json['httpCookies'] as String
|
||||||
|
: '',
|
||||||
|
httpMaxRedirects: _asInt(json['httpMaxRedirects'], 5),
|
||||||
|
centers: _centers(json['centers']),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static List<CenterLink> _centers(Object? raw) {
|
||||||
|
if (raw is! List) {
|
||||||
|
return const [];
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
for (final item in raw)
|
||||||
|
if (item is Map) CenterLink.fromJson(Map<String, dynamic>.from(item)),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
static int _asInt(Object? value, int fallback) {
|
static int _asInt(Object? value, int fallback) {
|
||||||
if (value is int) {
|
if (value is int) {
|
||||||
return value;
|
return value;
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
/// A recent probe target. This list is local and never stores node tokens,
|
||||||
|
/// center credentials, cookies, or request bodies.
|
||||||
|
class TargetEntry {
|
||||||
|
const TargetEntry({
|
||||||
|
required this.host,
|
||||||
|
required this.port,
|
||||||
|
required this.profileId,
|
||||||
|
this.httpUrl = '',
|
||||||
|
this.method = '',
|
||||||
|
required this.savedAtMs,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String host;
|
||||||
|
final int port;
|
||||||
|
final String profileId;
|
||||||
|
final String httpUrl;
|
||||||
|
final String method;
|
||||||
|
final int savedAtMs;
|
||||||
|
|
||||||
|
String get key {
|
||||||
|
final http = profileId == 'http';
|
||||||
|
return [
|
||||||
|
profileId,
|
||||||
|
'$port',
|
||||||
|
host.trim(),
|
||||||
|
http ? httpUrl.trim() : '',
|
||||||
|
http ? method.trim().toUpperCase() : '',
|
||||||
|
].join('\u0001');
|
||||||
|
}
|
||||||
|
|
||||||
|
String get label {
|
||||||
|
final where = httpUrl.trim().isNotEmpty ? httpUrl.trim() : host.trim();
|
||||||
|
final methodText = profileId == 'http' && method.trim().isNotEmpty
|
||||||
|
? ' ${method.trim().toUpperCase()}'
|
||||||
|
: '';
|
||||||
|
return '$where:$port · $profileId$methodText';
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object?> toJson() => {
|
||||||
|
'host': host,
|
||||||
|
'port': port,
|
||||||
|
'profileId': profileId,
|
||||||
|
'httpUrl': httpUrl,
|
||||||
|
'method': method,
|
||||||
|
'savedAtMs': savedAtMs,
|
||||||
|
};
|
||||||
|
|
||||||
|
factory TargetEntry.fromJson(Map<String, dynamic> json) {
|
||||||
|
return TargetEntry(
|
||||||
|
host: json['host'] is String ? json['host'] as String : '',
|
||||||
|
port: json['port'] is int ? json['port'] as int : 0,
|
||||||
|
profileId: json['profileId'] is String ? json['profileId'] as String : '',
|
||||||
|
httpUrl: json['httpUrl'] is String ? json['httpUrl'] as String : '',
|
||||||
|
method: json['method'] is String ? json['method'] as String : '',
|
||||||
|
savedAtMs: json['savedAtMs'] is int ? json['savedAtMs'] as int : 0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class TargetHistory {
|
||||||
|
const TargetHistory(this.entries);
|
||||||
|
|
||||||
|
static const maxEntries = 40;
|
||||||
|
static const empty = TargetHistory([]);
|
||||||
|
|
||||||
|
final List<TargetEntry> entries;
|
||||||
|
|
||||||
|
TargetHistory add(TargetEntry entry) {
|
||||||
|
final next = [
|
||||||
|
entry,
|
||||||
|
for (final item in entries)
|
||||||
|
if (item.key != entry.key) item,
|
||||||
|
];
|
||||||
|
if (next.length > maxEntries) {
|
||||||
|
return TargetHistory(next.sublist(0, maxEntries));
|
||||||
|
}
|
||||||
|
return TargetHistory(next);
|
||||||
|
}
|
||||||
|
|
||||||
|
TargetHistory removeAt(int index) {
|
||||||
|
if (index < 0 || index >= entries.length) {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
return TargetHistory([
|
||||||
|
for (var i = 0; i < entries.length; i++)
|
||||||
|
if (i != index) entries[i],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
TargetHistory clear() => empty;
|
||||||
|
|
||||||
|
String encode() => jsonEncode(entries.map((entry) => entry.toJson()).toList());
|
||||||
|
|
||||||
|
factory TargetHistory.decode(String raw) {
|
||||||
|
if (raw.trim().isEmpty) {
|
||||||
|
return empty;
|
||||||
|
}
|
||||||
|
final decoded = jsonDecode(raw);
|
||||||
|
if (decoded is! List) {
|
||||||
|
return empty;
|
||||||
|
}
|
||||||
|
return TargetHistory([
|
||||||
|
for (final item in decoded)
|
||||||
|
if (item is Map) TargetEntry.fromJson(Map<String, dynamic>.from(item)),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import '../metrics/sample_book.dart';
|
||||||
|
|
||||||
|
const helperMissingNote =
|
||||||
|
'本机 HTTP 探测使用和节点相同的 Go 引擎。请把 netquality-reflector 放在程序旁边,或设置环境变量 NQ_PROBE_HELPER。远程节点不受影响。';
|
||||||
|
|
||||||
|
String? locateProbeHelper() {
|
||||||
|
final env = Platform.environment['NQ_PROBE_HELPER'];
|
||||||
|
if (env != null && env.isNotEmpty && File(env).existsSync()) {
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
final dir = File(Platform.resolvedExecutable).parent;
|
||||||
|
final names = Platform.isWindows
|
||||||
|
? const ['netquality-reflector.exe', 'netquality-helper.exe']
|
||||||
|
: const ['netquality-reflector', 'netquality-helper'];
|
||||||
|
for (final name in names) {
|
||||||
|
final file = File('${dir.path}${Platform.pathSeparator}$name');
|
||||||
|
if (file.existsSync()) {
|
||||||
|
return file.path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Outcome outcomeFromHelper(String line) {
|
||||||
|
try {
|
||||||
|
final decoded = jsonDecode(line);
|
||||||
|
if (decoded is! Map) {
|
||||||
|
return const Outcome(
|
||||||
|
status: Outcome.error,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '探测引擎返回的内容无效',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final detail = <String, String>{};
|
||||||
|
final rawDetail = decoded['detail'];
|
||||||
|
if (rawDetail is Map) {
|
||||||
|
rawDetail.forEach((key, value) {
|
||||||
|
if (key is String && value != null) {
|
||||||
|
detail[key] = '$value';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Outcome(
|
||||||
|
status: decoded['status'] is String
|
||||||
|
? decoded['status'] as String
|
||||||
|
: Outcome.error,
|
||||||
|
kind: decoded['kind'] is String
|
||||||
|
? decoded['kind'] as String
|
||||||
|
: Outcome.query,
|
||||||
|
rttMs: decoded['rttMs'] is num
|
||||||
|
? (decoded['rttMs'] as num).toDouble()
|
||||||
|
: null,
|
||||||
|
note: decoded['note'] is String ? decoded['note'] as String : '',
|
||||||
|
detail: detail,
|
||||||
|
);
|
||||||
|
} on FormatException {
|
||||||
|
return const Outcome(
|
||||||
|
status: Outcome.error,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '探测引擎返回的内容无效',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One long-running helper process. Each line is one HTTP sample.
|
||||||
|
class HttpHelperSession {
|
||||||
|
HttpHelperSession({this.binary});
|
||||||
|
|
||||||
|
final String? binary;
|
||||||
|
Process? _process;
|
||||||
|
final _lines = <String>[];
|
||||||
|
var _closed = false;
|
||||||
|
|
||||||
|
Future<Outcome> probe(Map<String, Object?> request) async {
|
||||||
|
final started = await _ensure();
|
||||||
|
if (started != null) {
|
||||||
|
return started;
|
||||||
|
}
|
||||||
|
final process = _process;
|
||||||
|
if (process == null) {
|
||||||
|
return const Outcome(
|
||||||
|
status: Outcome.error,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: helperMissingNote,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
process.stdin.writeln(jsonEncode(request));
|
||||||
|
final line = await _nextLine();
|
||||||
|
if (line == null) {
|
||||||
|
return const Outcome(
|
||||||
|
status: Outcome.error,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '探测引擎没有返回结果',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return outcomeFromHelper(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Outcome?> _ensure() async {
|
||||||
|
if (_process != null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final path = binary ?? locateProbeHelper();
|
||||||
|
if (path == null) {
|
||||||
|
return const Outcome(
|
||||||
|
status: Outcome.error,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: helperMissingNote,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final process = await Process.start(path, const ['-mode', 'helper']);
|
||||||
|
_process = process;
|
||||||
|
process.stdout
|
||||||
|
.transform(utf8.decoder)
|
||||||
|
.transform(const LineSplitter())
|
||||||
|
.listen((line) {
|
||||||
|
if (line.trim().isNotEmpty) {
|
||||||
|
_lines.add(line);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String?> _nextLine() async {
|
||||||
|
final deadline = DateTime.now().add(const Duration(seconds: 20));
|
||||||
|
while (DateTime.now().isBefore(deadline)) {
|
||||||
|
if (_lines.isNotEmpty) {
|
||||||
|
return _lines.removeAt(0);
|
||||||
|
}
|
||||||
|
if (_closed) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> close() async {
|
||||||
|
_closed = true;
|
||||||
|
final process = _process;
|
||||||
|
_process = null;
|
||||||
|
if (process != null) {
|
||||||
|
process.kill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,22 +1,67 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
import '../metrics/sample_book.dart';
|
import '../metrics/sample_book.dart';
|
||||||
import '../models/probe_profile.dart';
|
import '../models/probe_profile.dart';
|
||||||
import '../models/session_config.dart';
|
import '../models/session_config.dart';
|
||||||
|
import '../ui/address_text.dart';
|
||||||
import 'endpoint_picker.dart';
|
import 'endpoint_picker.dart';
|
||||||
import 'probe_loop.dart';
|
import 'probe_loop.dart';
|
||||||
import 'remote_client.dart';
|
import 'remote_client.dart';
|
||||||
|
|
||||||
class ChartSample {
|
class ChartSample {
|
||||||
const ChartSample({required this.sec, required this.rttMs, required this.ratePct});
|
const ChartSample({
|
||||||
|
required this.sec,
|
||||||
|
required this.rttMs,
|
||||||
|
required this.ratePct,
|
||||||
|
});
|
||||||
|
|
||||||
final double sec;
|
final double sec;
|
||||||
final double? rttMs;
|
final double? rttMs;
|
||||||
final double? ratePct;
|
final double? ratePct;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class SessionReport {
|
||||||
|
const SessionReport({
|
||||||
|
required this.startedAt,
|
||||||
|
required this.endedAt,
|
||||||
|
required this.elapsed,
|
||||||
|
required this.target,
|
||||||
|
required this.profileLabel,
|
||||||
|
required this.sourceLabel,
|
||||||
|
required this.profileId,
|
||||||
|
required this.summary,
|
||||||
|
required this.rateLabel,
|
||||||
|
required this.resolved,
|
||||||
|
required this.usedAddress,
|
||||||
|
required this.usedFamily,
|
||||||
|
required this.fallbackText,
|
||||||
|
required this.addressUnreported,
|
||||||
|
required this.usedIsFake,
|
||||||
|
});
|
||||||
|
|
||||||
|
final DateTime startedAt;
|
||||||
|
final DateTime endedAt;
|
||||||
|
final Duration elapsed;
|
||||||
|
final String target;
|
||||||
|
final String profileLabel;
|
||||||
|
final String sourceLabel;
|
||||||
|
final String profileId;
|
||||||
|
final ProbeSummary summary;
|
||||||
|
final String rateLabel;
|
||||||
|
final List<ResolvedAddress> resolved;
|
||||||
|
final String? usedAddress;
|
||||||
|
final String? usedFamily;
|
||||||
|
final String fallbackText;
|
||||||
|
final bool addressUnreported;
|
||||||
|
final bool usedIsFake;
|
||||||
|
}
|
||||||
|
|
||||||
class ProbeView {
|
class ProbeView {
|
||||||
const ProbeView({
|
const ProbeView({
|
||||||
required this.running,
|
required this.running,
|
||||||
@@ -28,8 +73,22 @@ class ProbeView {
|
|||||||
required this.samples,
|
required this.samples,
|
||||||
required this.rateLabel,
|
required this.rateLabel,
|
||||||
required this.sourceLabel,
|
required this.sourceLabel,
|
||||||
this.targetAddress,
|
required this.sessionId,
|
||||||
this.targetIsFake = false,
|
this.profileId = '',
|
||||||
|
required this.elapsed,
|
||||||
|
this.targetHost = '',
|
||||||
|
this.profileLabel = '',
|
||||||
|
this.tryingAddress,
|
||||||
|
this.tryingFamily,
|
||||||
|
this.usedAddress,
|
||||||
|
this.usedFamily,
|
||||||
|
this.usedIsFake = false,
|
||||||
|
this.resolved = const [],
|
||||||
|
this.fallbackText = '',
|
||||||
|
this.addressUnreported = false,
|
||||||
|
this.report,
|
||||||
|
this.startedAt,
|
||||||
|
this.endedAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
static const initial = ProbeView(
|
static const initial = ProbeView(
|
||||||
@@ -42,6 +101,8 @@ class ProbeView {
|
|||||||
samples: [],
|
samples: [],
|
||||||
rateLabel: '探测无应答',
|
rateLabel: '探测无应答',
|
||||||
sourceLabel: '本机',
|
sourceLabel: '本机',
|
||||||
|
sessionId: 0,
|
||||||
|
elapsed: Duration.zero,
|
||||||
);
|
);
|
||||||
|
|
||||||
final bool running;
|
final bool running;
|
||||||
@@ -53,8 +114,22 @@ class ProbeView {
|
|||||||
final List<ChartSample> samples;
|
final List<ChartSample> samples;
|
||||||
final String rateLabel;
|
final String rateLabel;
|
||||||
final String sourceLabel;
|
final String sourceLabel;
|
||||||
final String? targetAddress;
|
final int sessionId;
|
||||||
final bool targetIsFake;
|
final String profileId;
|
||||||
|
final Duration elapsed;
|
||||||
|
final String targetHost;
|
||||||
|
final String profileLabel;
|
||||||
|
final String? tryingAddress;
|
||||||
|
final String? tryingFamily;
|
||||||
|
final String? usedAddress;
|
||||||
|
final String? usedFamily;
|
||||||
|
final bool usedIsFake;
|
||||||
|
final List<ResolvedAddress> resolved;
|
||||||
|
final String fallbackText;
|
||||||
|
final bool addressUnreported;
|
||||||
|
final SessionReport? report;
|
||||||
|
final DateTime? startedAt;
|
||||||
|
final DateTime? endedAt;
|
||||||
|
|
||||||
ProbeView copyWith({
|
ProbeView copyWith({
|
||||||
bool? running,
|
bool? running,
|
||||||
@@ -67,8 +142,24 @@ class ProbeView {
|
|||||||
List<ChartSample>? samples,
|
List<ChartSample>? samples,
|
||||||
String? rateLabel,
|
String? rateLabel,
|
||||||
String? sourceLabel,
|
String? sourceLabel,
|
||||||
String? targetAddress,
|
int? sessionId,
|
||||||
bool? targetIsFake,
|
String? profileId,
|
||||||
|
Duration? elapsed,
|
||||||
|
String? targetHost,
|
||||||
|
String? profileLabel,
|
||||||
|
String? tryingAddress,
|
||||||
|
String? tryingFamily,
|
||||||
|
bool clearTrying = false,
|
||||||
|
String? usedAddress,
|
||||||
|
String? usedFamily,
|
||||||
|
bool? usedIsFake,
|
||||||
|
List<ResolvedAddress>? resolved,
|
||||||
|
String? fallbackText,
|
||||||
|
bool? addressUnreported,
|
||||||
|
SessionReport? report,
|
||||||
|
bool clearReport = false,
|
||||||
|
DateTime? startedAt,
|
||||||
|
DateTime? endedAt,
|
||||||
}) {
|
}) {
|
||||||
return ProbeView(
|
return ProbeView(
|
||||||
running: running ?? this.running,
|
running: running ?? this.running,
|
||||||
@@ -80,8 +171,22 @@ class ProbeView {
|
|||||||
samples: samples ?? this.samples,
|
samples: samples ?? this.samples,
|
||||||
rateLabel: rateLabel ?? this.rateLabel,
|
rateLabel: rateLabel ?? this.rateLabel,
|
||||||
sourceLabel: sourceLabel ?? this.sourceLabel,
|
sourceLabel: sourceLabel ?? this.sourceLabel,
|
||||||
targetAddress: targetAddress ?? this.targetAddress,
|
sessionId: sessionId ?? this.sessionId,
|
||||||
targetIsFake: targetIsFake ?? this.targetIsFake,
|
profileId: profileId ?? this.profileId,
|
||||||
|
elapsed: elapsed ?? this.elapsed,
|
||||||
|
targetHost: targetHost ?? this.targetHost,
|
||||||
|
profileLabel: profileLabel ?? this.profileLabel,
|
||||||
|
tryingAddress: clearTrying ? null : tryingAddress ?? this.tryingAddress,
|
||||||
|
tryingFamily: clearTrying ? null : tryingFamily ?? this.tryingFamily,
|
||||||
|
usedAddress: usedAddress ?? this.usedAddress,
|
||||||
|
usedFamily: usedFamily ?? this.usedFamily,
|
||||||
|
usedIsFake: usedIsFake ?? this.usedIsFake,
|
||||||
|
resolved: resolved ?? this.resolved,
|
||||||
|
fallbackText: fallbackText ?? this.fallbackText,
|
||||||
|
addressUnreported: addressUnreported ?? this.addressUnreported,
|
||||||
|
report: clearReport ? null : report ?? this.report,
|
||||||
|
startedAt: startedAt ?? this.startedAt,
|
||||||
|
endedAt: endedAt ?? this.endedAt,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -93,113 +198,193 @@ class ProbeController extends ChangeNotifier {
|
|||||||
RemoteProbe? _remote;
|
RemoteProbe? _remote;
|
||||||
String _nodeToken = '';
|
String _nodeToken = '';
|
||||||
var _token = 0;
|
var _token = 0;
|
||||||
|
var _session = 0;
|
||||||
|
var _busy = false;
|
||||||
|
var _remoteMode = false;
|
||||||
|
DateTime? _startedAt;
|
||||||
|
Timer? _tick;
|
||||||
|
|
||||||
Future<void> start(SessionConfig config, {required String nodeToken, required String echoToken}) async {
|
Future<void> start(
|
||||||
final problem = config.validate();
|
SessionConfig config, {
|
||||||
if (problem != null) {
|
required String nodeToken,
|
||||||
view = view.copyWith(banner: problem, phase: '无法开始');
|
required String echoToken,
|
||||||
notifyListeners();
|
}) async {
|
||||||
|
if (_busy) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final echoProblem = _echoProblem(config.profileId, echoToken);
|
_busy = true;
|
||||||
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 {
|
try {
|
||||||
if (config.remote) {
|
final problem = config.validate();
|
||||||
final remote = RemoteProbe();
|
if (problem != null) {
|
||||||
_remote = remote;
|
view = view.copyWith(banner: problem, phase: '无法开始');
|
||||||
await remote.run(
|
notifyListeners();
|
||||||
baseUrl: config.node!.baseUrl,
|
return;
|
||||||
nodeToken: nodeToken,
|
}
|
||||||
body: ProbeBody(
|
final echoProblem = _echoProblem(config.profileId, echoToken);
|
||||||
target: config.host.trim(),
|
if (echoProblem != null) {
|
||||||
port: config.port,
|
view = view.copyWith(banner: echoProblem, phase: '无法开始');
|
||||||
profile: config.profileId,
|
notifyListeners();
|
||||||
intervalMs: config.intervalMs,
|
return;
|
||||||
timeoutMs: config.timeoutMs,
|
}
|
||||||
durationSec: config.durationSec,
|
await stop();
|
||||||
packetSize: config.packetSize,
|
_nodeToken = nodeToken;
|
||||||
echoToken: echoToken,
|
_remoteMode = config.remote;
|
||||||
dnsName: config.dnsName.trim(),
|
final generation = ++_token;
|
||||||
payloadHex: config.payloadHex.trim(),
|
final session = ++_session;
|
||||||
expectHex: config.expectHex.trim(),
|
_startedAt = DateTime.now();
|
||||||
),
|
_clock
|
||||||
onSample: (sample) => _accept(generation, sample),
|
..reset()
|
||||||
cancelled: cancelled,
|
..start();
|
||||||
);
|
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
|
||||||
} else {
|
final profile = ProbeProfile.byId(config.profileId);
|
||||||
final loop = ProbeLoop(
|
view = ProbeView(
|
||||||
onEndpoint: (address) {
|
running: true,
|
||||||
if (generation != _token) {
|
phase: '探测中',
|
||||||
return;
|
banner: null,
|
||||||
|
note: config.remote ? '正在让节点向目标发包' : '正在从本机向目标发包',
|
||||||
|
detail: const {},
|
||||||
|
summary: ProbeSummary.empty,
|
||||||
|
samples: const [],
|
||||||
|
rateLabel: rateLabelFor(config.profileId),
|
||||||
|
sourceLabel: source,
|
||||||
|
sessionId: session,
|
||||||
|
profileId: config.profileId,
|
||||||
|
elapsed: Duration.zero,
|
||||||
|
targetHost: '${config.host.trim()}:${config.port}',
|
||||||
|
profileLabel: profile.label,
|
||||||
|
startedAt: _startedAt,
|
||||||
|
);
|
||||||
|
notifyListeners();
|
||||||
|
_armTick(generation);
|
||||||
|
bool cancelled() => generation != _token;
|
||||||
|
try {
|
||||||
|
if (config.remote) {
|
||||||
|
final selected = config.node!;
|
||||||
|
var baseUrl = selected.baseUrl;
|
||||||
|
var token = nodeToken;
|
||||||
|
if (selected.confidential) {
|
||||||
|
final link = config.centerLink(selected.centerLinkId);
|
||||||
|
if (link == null) {
|
||||||
|
throw RemoteException('找不到签发这台服务器的中心');
|
||||||
}
|
}
|
||||||
view = view.copyWith(
|
baseUrl = link.url;
|
||||||
targetAddress: address.address,
|
token = nodeToken;
|
||||||
targetIsFake: isClashFakeIp(address),
|
}
|
||||||
);
|
if (config.profileId == 'http' || !config.allowIPv4 || !config.allowIPv6) {
|
||||||
notifyListeners();
|
if (!selected.confidential) {
|
||||||
},
|
final info = await fetchNodeInfo(baseUrl);
|
||||||
);
|
final upgrade = remoteUpgradeMessage(
|
||||||
_local = loop;
|
info,
|
||||||
await loop.run(
|
profileId: config.profileId,
|
||||||
request: ProbeRequest(
|
allow4: config.allowIPv4,
|
||||||
host: config.host.trim(),
|
allow6: config.allowIPv6,
|
||||||
port: config.port,
|
);
|
||||||
profileId: config.profileId,
|
if (upgrade != null) {
|
||||||
interval: Duration(milliseconds: config.intervalMs),
|
throw RemoteException(upgrade);
|
||||||
timeout: Duration(milliseconds: config.timeoutMs),
|
}
|
||||||
packetSize: config.packetSize,
|
}
|
||||||
echoToken: echoToken,
|
}
|
||||||
dnsName: config.dnsName.trim(),
|
final remote = RemoteProbe();
|
||||||
payloadHex: config.payloadHex.trim(),
|
_remote = remote;
|
||||||
expectHex: config.expectHex.trim(),
|
await remote.run(
|
||||||
),
|
baseUrl: baseUrl,
|
||||||
onSample: (sample) => _accept(generation, sample),
|
nodeToken: token,
|
||||||
cancelled: cancelled,
|
body: ProbeBody(
|
||||||
);
|
target: config.host.trim(),
|
||||||
}
|
port: config.port,
|
||||||
if (generation == _token) {
|
profile: config.profileId,
|
||||||
view = view.copyWith(running: false, phase: '已停止');
|
intervalMs: config.intervalMs,
|
||||||
notifyListeners();
|
timeoutMs: config.timeoutMs,
|
||||||
}
|
durationSec: config.durationSec,
|
||||||
} on RemoteException catch (error) {
|
packetSize: config.packetSize,
|
||||||
if (generation == _token) {
|
echoToken: echoToken,
|
||||||
view = view.copyWith(running: false, phase: '出错', banner: error.message);
|
dnsName: config.dnsName.trim(),
|
||||||
notifyListeners();
|
payloadHex: config.payloadHex.trim(),
|
||||||
}
|
expectHex: config.expectHex.trim(),
|
||||||
} on Object {
|
allowIPv4: config.allowIPv4,
|
||||||
if (generation == _token) {
|
allowIPv6: config.allowIPv6,
|
||||||
view = view.copyWith(running: false, phase: '出错', banner: '探测中断');
|
http: config.profileId == 'http' ? _httpJson(config) : null,
|
||||||
notifyListeners();
|
),
|
||||||
|
jobsPath: _jobsPath(config),
|
||||||
|
onSample: (sample) => _accept(generation, sample),
|
||||||
|
onResolved: (resolved) {
|
||||||
|
if (generation != _token) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
view = view.copyWith(resolved: resolved);
|
||||||
|
notifyListeners();
|
||||||
|
},
|
||||||
|
cancelled: cancelled,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
final loop = ProbeLoop(
|
||||||
|
onEndpoint: (address) {
|
||||||
|
if (generation != _token) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
view = view.copyWith(
|
||||||
|
tryingAddress: address.address,
|
||||||
|
tryingFamily: addressFamily(address),
|
||||||
|
);
|
||||||
|
notifyListeners();
|
||||||
|
},
|
||||||
|
onResolved: (addresses) {
|
||||||
|
if (generation != _token) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
view = view.copyWith(
|
||||||
|
resolved: [
|
||||||
|
for (final address in addresses)
|
||||||
|
ResolvedAddress(
|
||||||
|
address: address.address,
|
||||||
|
family: addressFamily(address),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
notifyListeners();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
_local = loop;
|
||||||
|
await loop.run(
|
||||||
|
request: ProbeRequest(
|
||||||
|
host: config.host.trim(),
|
||||||
|
port: config.port,
|
||||||
|
profileId: config.profileId,
|
||||||
|
interval: Duration(milliseconds: config.intervalMs),
|
||||||
|
timeout: Duration(milliseconds: config.timeoutMs),
|
||||||
|
packetSize: config.packetSize,
|
||||||
|
echoToken: echoToken,
|
||||||
|
dnsName: config.dnsName.trim(),
|
||||||
|
payloadHex: config.payloadHex.trim(),
|
||||||
|
expectHex: config.expectHex.trim(),
|
||||||
|
allowIPv4: config.allowIPv4,
|
||||||
|
allowIPv6: config.allowIPv6,
|
||||||
|
httpVersion: config.httpVersion,
|
||||||
|
httpResolve: config.httpResolve.trim(),
|
||||||
|
httpMethod: config.httpMethod,
|
||||||
|
httpBody: config.httpBody,
|
||||||
|
httpReferer: config.httpReferer,
|
||||||
|
httpUserAgent: config.httpUserAgent,
|
||||||
|
httpCookies: config.httpCookies,
|
||||||
|
httpMaxRedirects: config.httpMaxRedirects,
|
||||||
|
),
|
||||||
|
onSample: (sample) => _accept(generation, sample),
|
||||||
|
cancelled: cancelled,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_finish(generation, '已停止');
|
||||||
|
} on RemoteException catch (error) {
|
||||||
|
_finish(generation, '出错', banner: error.message);
|
||||||
|
} on Object {
|
||||||
|
_finish(generation, '出错', banner: '探测中断');
|
||||||
|
} finally {
|
||||||
|
if (generation == _token) {
|
||||||
|
_local = null;
|
||||||
|
_remote = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (generation == _token) {
|
_busy = false;
|
||||||
_local = null;
|
|
||||||
_remote = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,11 +402,73 @@ class ProbeController extends ChangeNotifier {
|
|||||||
_nodeToken = '';
|
_nodeToken = '';
|
||||||
}
|
}
|
||||||
if (view.running) {
|
if (view.running) {
|
||||||
view = view.copyWith(running: false, phase: '已停止');
|
_clock.stop();
|
||||||
|
_tick?.cancel();
|
||||||
|
final ended = DateTime.now();
|
||||||
|
view = view.copyWith(
|
||||||
|
running: false,
|
||||||
|
phase: '已停止',
|
||||||
|
elapsed: _clock.elapsed,
|
||||||
|
endedAt: ended,
|
||||||
|
report: _snapshot(ended),
|
||||||
|
);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _finish(int generation, String phase, {String? banner}) {
|
||||||
|
if (generation != _token || !view.running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_clock.stop();
|
||||||
|
_tick?.cancel();
|
||||||
|
final ended = DateTime.now();
|
||||||
|
view = view.copyWith(
|
||||||
|
running: false,
|
||||||
|
phase: phase,
|
||||||
|
banner: banner,
|
||||||
|
elapsed: _clock.elapsed,
|
||||||
|
endedAt: ended,
|
||||||
|
report: _snapshot(ended),
|
||||||
|
);
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
SessionReport? _snapshot(DateTime ended) {
|
||||||
|
final started = _startedAt;
|
||||||
|
if (started == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return SessionReport(
|
||||||
|
startedAt: started,
|
||||||
|
endedAt: ended,
|
||||||
|
elapsed: _clock.elapsed,
|
||||||
|
target: view.targetHost,
|
||||||
|
profileLabel: view.profileLabel,
|
||||||
|
sourceLabel: view.sourceLabel,
|
||||||
|
profileId: view.profileId,
|
||||||
|
summary: view.summary,
|
||||||
|
rateLabel: view.rateLabel,
|
||||||
|
resolved: view.resolved,
|
||||||
|
usedAddress: view.usedAddress,
|
||||||
|
usedFamily: view.usedFamily,
|
||||||
|
fallbackText: view.fallbackText,
|
||||||
|
addressUnreported: view.addressUnreported,
|
||||||
|
usedIsFake: view.usedIsFake,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _armTick(int generation) {
|
||||||
|
_tick?.cancel();
|
||||||
|
_tick = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||||
|
if (generation != _token || !view.running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
view = view.copyWith(elapsed: _clock.elapsed);
|
||||||
|
notifyListeners();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
void _accept(int generation, ProbeSample sample) {
|
void _accept(int generation, ProbeSample sample) {
|
||||||
if (generation != _token) {
|
if (generation != _token) {
|
||||||
return;
|
return;
|
||||||
@@ -246,6 +493,16 @@ class ProbeController extends ChangeNotifier {
|
|||||||
ratePct: rate,
|
ratePct: rate,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
final reported = sample.detail['address'];
|
||||||
|
final hasAddress = reported != null && reported.isNotEmpty;
|
||||||
|
final fallback = sample.detail['fallback'];
|
||||||
|
final parsed = hasAddress ? InternetAddress.tryParse(reported) : null;
|
||||||
|
final family = hasAddress
|
||||||
|
? ((sample.detail['family'] != null &&
|
||||||
|
sample.detail['family']!.isNotEmpty)
|
||||||
|
? sample.detail['family']
|
||||||
|
: familyOfAddress(reported))
|
||||||
|
: null;
|
||||||
view = view.copyWith(
|
view = view.copyWith(
|
||||||
phase: phaseFor(sample.status),
|
phase: phaseFor(sample.status),
|
||||||
note: sample.note,
|
note: sample.note,
|
||||||
@@ -253,9 +510,43 @@ class ProbeController extends ChangeNotifier {
|
|||||||
summary: sample.summary,
|
summary: sample.summary,
|
||||||
samples: samples,
|
samples: samples,
|
||||||
clearBanner: true,
|
clearBanner: true,
|
||||||
|
elapsed: _clock.elapsed,
|
||||||
|
usedAddress: hasAddress ? reported : view.usedAddress,
|
||||||
|
usedFamily: hasAddress ? family : view.usedFamily,
|
||||||
|
usedIsFake: hasAddress
|
||||||
|
? parsed != null && isClashFakeIp(parsed)
|
||||||
|
: view.usedIsFake,
|
||||||
|
clearTrying: hasAddress || (fallback != null && fallback.isNotEmpty),
|
||||||
|
fallbackText: (fallback != null && fallback.isNotEmpty) ? fallback : null,
|
||||||
|
addressUnreported: _remoteMode && !hasAddress,
|
||||||
);
|
);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_tick?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object?> _httpJson(SessionConfig config) => {
|
||||||
|
'version': config.httpVersion,
|
||||||
|
'resolve': config.httpResolve.trim(),
|
||||||
|
'method': config.httpMethod,
|
||||||
|
'body': config.httpBody,
|
||||||
|
'referer': config.httpReferer,
|
||||||
|
'userAgent': config.httpUserAgent,
|
||||||
|
'cookies': config.httpCookies,
|
||||||
|
'maxRedirects': config.httpMaxRedirects,
|
||||||
|
};
|
||||||
|
|
||||||
|
String _jobsPath(SessionConfig config) {
|
||||||
|
final node = config.node;
|
||||||
|
if (node != null && node.confidential && node.serverId.isNotEmpty) {
|
||||||
|
return '/v1/center/servers/${node.serverId}/jobs';
|
||||||
|
}
|
||||||
|
return '/v1/jobs';
|
||||||
}
|
}
|
||||||
|
|
||||||
String? _echoProblem(String profileId, String echoToken) {
|
String? _echoProblem(String profileId, String echoToken) {
|
||||||
|
|||||||
@@ -3,9 +3,13 @@ import 'dart:io';
|
|||||||
import 'dart:typed_data';
|
import 'dart:typed_data';
|
||||||
|
|
||||||
import '../metrics/sample_book.dart';
|
import '../metrics/sample_book.dart';
|
||||||
|
import '../metrics/selection_ledger.dart';
|
||||||
|
import '../models/ip_family.dart';
|
||||||
import '../protocol/probe_packet.dart';
|
import '../protocol/probe_packet.dart';
|
||||||
|
import '../ui/address_text.dart';
|
||||||
import 'endpoint_picker.dart';
|
import 'endpoint_picker.dart';
|
||||||
import 'game_codec.dart';
|
import 'game_codec.dart';
|
||||||
|
import 'http_helper.dart';
|
||||||
|
|
||||||
class ProbeRequest {
|
class ProbeRequest {
|
||||||
const ProbeRequest({
|
const ProbeRequest({
|
||||||
@@ -19,6 +23,16 @@ class ProbeRequest {
|
|||||||
required this.dnsName,
|
required this.dnsName,
|
||||||
required this.payloadHex,
|
required this.payloadHex,
|
||||||
required this.expectHex,
|
required this.expectHex,
|
||||||
|
this.allowIPv4 = true,
|
||||||
|
this.allowIPv6 = true,
|
||||||
|
this.httpVersion = 'auto',
|
||||||
|
this.httpResolve = '',
|
||||||
|
this.httpMethod = 'GET',
|
||||||
|
this.httpBody = '',
|
||||||
|
this.httpReferer = '',
|
||||||
|
this.httpUserAgent = '',
|
||||||
|
this.httpCookies = '',
|
||||||
|
this.httpMaxRedirects = 5,
|
||||||
});
|
});
|
||||||
|
|
||||||
final String host;
|
final String host;
|
||||||
@@ -31,15 +45,22 @@ class ProbeRequest {
|
|||||||
final String dnsName;
|
final String dnsName;
|
||||||
final String payloadHex;
|
final String payloadHex;
|
||||||
final String expectHex;
|
final String expectHex;
|
||||||
|
final bool allowIPv4;
|
||||||
|
final bool allowIPv6;
|
||||||
|
final String httpVersion;
|
||||||
|
final String httpResolve;
|
||||||
|
final String httpMethod;
|
||||||
|
final String httpBody;
|
||||||
|
final String httpReferer;
|
||||||
|
final String httpUserAgent;
|
||||||
|
final String httpCookies;
|
||||||
|
final int httpMaxRedirects;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sends one probe at a time from this device. A cancelled attempt is not
|
/// Sends one probe at a time from this device. A cancelled attempt is not
|
||||||
/// recorded, so stopping cannot paint a fake loss sample.
|
/// recorded, so stopping cannot paint a fake loss sample.
|
||||||
class ProbeLoop {
|
class ProbeLoop {
|
||||||
ProbeLoop({
|
ProbeLoop({this.lookup, this.onEndpoint, this.onResolved, this.helperPath});
|
||||||
this.lookup,
|
|
||||||
this.onEndpoint,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Replaces [lookupAll] in tests.
|
/// Replaces [lookupAll] in tests.
|
||||||
final Future<List<InternetAddress>> Function(String host)? lookup;
|
final Future<List<InternetAddress>> Function(String host)? lookup;
|
||||||
@@ -47,13 +68,26 @@ class ProbeLoop {
|
|||||||
/// Fires when the address about to be used is chosen or changed.
|
/// Fires when the address about to be used is chosen or changed.
|
||||||
final void Function(InternetAddress address)? onEndpoint;
|
final void Function(InternetAddress address)? onEndpoint;
|
||||||
|
|
||||||
|
/// Fires once with the lookup result. This is not the address in use.
|
||||||
|
final void Function(List<InternetAddress> addresses)? onResolved;
|
||||||
|
|
||||||
|
/// Overrides the Go HTTP engine binary. Null looks beside the app and at
|
||||||
|
/// NQ_PROBE_HELPER.
|
||||||
|
final String? helperPath;
|
||||||
|
|
||||||
_TcpPipe? _tcp;
|
_TcpPipe? _tcp;
|
||||||
_UdpPipe? _udp;
|
_UdpPipe? _udp;
|
||||||
EndpointPicker? _picker;
|
EndpointPicker? _picker;
|
||||||
|
SelectionLedger? _ledger;
|
||||||
InternetAddress? _announced;
|
InternetAddress? _announced;
|
||||||
|
InternetAddress? _tcpUsed;
|
||||||
|
List<InternetAddress>? _resolved;
|
||||||
int _seq = 0;
|
int _seq = 0;
|
||||||
int _dnsId = 1;
|
int _dnsId = 1;
|
||||||
final int _guid = DateTime.now().microsecondsSinceEpoch;
|
final int _guid = DateTime.now().microsecondsSinceEpoch;
|
||||||
|
bool _allow4 = true;
|
||||||
|
bool _allow6 = true;
|
||||||
|
HttpHelperSession? _http;
|
||||||
|
|
||||||
Future<void> run({
|
Future<void> run({
|
||||||
required ProbeRequest request,
|
required ProbeRequest request,
|
||||||
@@ -61,24 +95,53 @@ class ProbeLoop {
|
|||||||
required bool Function() cancelled,
|
required bool Function() cancelled,
|
||||||
}) async {
|
}) async {
|
||||||
final book = SampleBook(request.profileId);
|
final book = SampleBook(request.profileId);
|
||||||
|
_allow4 = request.allowIPv4;
|
||||||
|
_allow6 = request.allowIPv6;
|
||||||
|
final refusal = familyRefusal(
|
||||||
|
request.host,
|
||||||
|
v4: request.allowIPv4,
|
||||||
|
v6: request.allowIPv6,
|
||||||
|
);
|
||||||
|
if (refusal != null) {
|
||||||
|
final outcome = Outcome(
|
||||||
|
status: Outcome.error,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: refusal,
|
||||||
|
);
|
||||||
|
book.add(outcome);
|
||||||
|
onSample(book.sample(1, outcome));
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
while (!cancelled()) {
|
while (!cancelled()) {
|
||||||
final started = DateTime.now();
|
final started = DateTime.now();
|
||||||
final outcome = await _once(request, cancelled);
|
final outcome = await _once(request, cancelled);
|
||||||
if (cancelled() || outcome == null) {
|
if (!countsAfterStop(outcome, cancelled: cancelled())) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (_usesDatagram(request.profileId)) {
|
var commit = <Outcome>[outcome!];
|
||||||
final responded = outcome.status == Outcome.ok ||
|
if (_usesDatagram(request.profileId) && _picker != null) {
|
||||||
outcome.status == Outcome.protocol ||
|
_ledger ??= SelectionLedger(_picker!.candidates.length);
|
||||||
outcome.status == Outcome.refused;
|
final responded = selectionResponded(outcome);
|
||||||
if (_picker != null && _picker!.record(responded)) {
|
final wasMeasuring = _ledger!.measuring;
|
||||||
|
final changed = _picker!.record(responded);
|
||||||
|
final decision = _ledger!.take(outcome, responded: responded);
|
||||||
|
if (wasMeasuring && changed) {
|
||||||
|
_ledger!.endMeasurement();
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
await _dropUdp();
|
await _dropUdp();
|
||||||
_announce(_picker!.current);
|
_announce(_picker!.current);
|
||||||
}
|
}
|
||||||
|
commit = decision.commit;
|
||||||
|
if (commit.isEmpty) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (final item in commit) {
|
||||||
|
book.add(item);
|
||||||
|
onSample(book.sample(book.sent, item));
|
||||||
}
|
}
|
||||||
book.add(outcome);
|
|
||||||
onSample(book.sample(book.sent, outcome));
|
|
||||||
final spent = DateTime.now().difference(started);
|
final spent = DateTime.now().difference(started);
|
||||||
final rest = request.interval - spent;
|
final rest = request.interval - spent;
|
||||||
if (!cancelled() && rest > Duration.zero) {
|
if (!cancelled() && rest > Duration.zero) {
|
||||||
@@ -91,6 +154,11 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> close() async {
|
Future<void> close() async {
|
||||||
|
final http = _http;
|
||||||
|
_http = null;
|
||||||
|
if (http != null) {
|
||||||
|
await http.close();
|
||||||
|
}
|
||||||
final tcp = _tcp;
|
final tcp = _tcp;
|
||||||
_tcp = null;
|
_tcp = null;
|
||||||
if (tcp != null) {
|
if (tcp != null) {
|
||||||
@@ -103,7 +171,10 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Outcome?> _once(ProbeRequest request, bool Function() cancelled) async {
|
Future<Outcome?> _once(
|
||||||
|
ProbeRequest request,
|
||||||
|
bool Function() cancelled,
|
||||||
|
) async {
|
||||||
try {
|
try {
|
||||||
final outcome = await _dispatch(request, cancelled);
|
final outcome = await _dispatch(request, cancelled);
|
||||||
final peer = _udp?.peer;
|
final peer = _udp?.peer;
|
||||||
@@ -145,6 +216,8 @@ class ProbeLoop {
|
|||||||
return _java(request, cancelled);
|
return _java(request, cancelled);
|
||||||
case 'minecraft-bedrock':
|
case 'minecraft-bedrock':
|
||||||
return _bedrock(request, cancelled);
|
return _bedrock(request, cancelled);
|
||||||
|
case 'http':
|
||||||
|
return _httpProbe(request);
|
||||||
default:
|
default:
|
||||||
return Future.value(
|
return Future.value(
|
||||||
const Outcome(
|
const Outcome(
|
||||||
@@ -160,45 +233,58 @@ class ProbeLoop {
|
|||||||
ProbeRequest request,
|
ProbeRequest request,
|
||||||
bool Function() cancelled,
|
bool Function() cancelled,
|
||||||
) async {
|
) async {
|
||||||
final watch = Stopwatch()..start();
|
final opened = await _openTcp(request, cancelled);
|
||||||
final socket = await Socket.connect(
|
final failure = opened.failure;
|
||||||
request.host,
|
if (failure != null) {
|
||||||
request.port,
|
return failure;
|
||||||
timeout: request.timeout,
|
}
|
||||||
);
|
final socket = opened.socket!;
|
||||||
watch.stop();
|
opened.watch?.stop();
|
||||||
await socket.close();
|
await socket.close();
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.connect,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return Outcome(
|
return _withUsed(
|
||||||
status: Outcome.ok,
|
Outcome(
|
||||||
kind: Outcome.connect,
|
status: Outcome.ok,
|
||||||
rttMs: watch.elapsedMicroseconds / 1000,
|
kind: Outcome.connect,
|
||||||
note: 'TCP 已连通',
|
rttMs: (opened.watch?.elapsedMicroseconds ?? 0) / 1000,
|
||||||
|
note: 'TCP 已连通',
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Outcome> _nqTcp(ProbeRequest request, bool Function() cancelled) async {
|
Future<Outcome> _nqTcp(
|
||||||
|
ProbeRequest request,
|
||||||
|
bool Function() cancelled,
|
||||||
|
) async {
|
||||||
|
var fallback = '';
|
||||||
|
var skipped = 0;
|
||||||
if (_tcp == null) {
|
if (_tcp == null) {
|
||||||
try {
|
final opened = await _openTcp(request, cancelled);
|
||||||
final socket = await Socket.connect(
|
final failure = opened.failure;
|
||||||
request.host,
|
if (failure != null) {
|
||||||
request.port,
|
return Outcome(
|
||||||
timeout: request.timeout,
|
status: failure.status,
|
||||||
);
|
kind: failure.kind,
|
||||||
socket.setOption(SocketOption.tcpNoDelay, true);
|
note: failure.note,
|
||||||
_tcp = _TcpPipe(socket);
|
reconnect: failure.note != '已停止',
|
||||||
} on SocketException catch (error) {
|
detail: failure.detail,
|
||||||
return classifySocket(error, reconnect: true);
|
|
||||||
} on TimeoutException {
|
|
||||||
return const Outcome(
|
|
||||||
status: Outcome.timeout,
|
|
||||||
kind: Outcome.connect,
|
|
||||||
reconnect: true,
|
|
||||||
note: '连接超时,将重试',
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
final socket = opened.socket!;
|
||||||
|
socket.setOption(SocketOption.tcpNoDelay, true);
|
||||||
|
_tcp = _TcpPipe(socket);
|
||||||
|
_tcpUsed = opened.used;
|
||||||
|
fallback = opened.fallback;
|
||||||
|
skipped = opened.skipped;
|
||||||
}
|
}
|
||||||
final pipe = _tcp!;
|
final pipe = _tcp!;
|
||||||
_seq += 1;
|
_seq += 1;
|
||||||
@@ -232,21 +318,35 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.connect,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (matched == null) {
|
if (matched == null) {
|
||||||
await _dropTcp();
|
await _dropTcp();
|
||||||
return const Outcome(
|
return _withUsed(
|
||||||
status: Outcome.timeout,
|
const Outcome(
|
||||||
kind: Outcome.probe,
|
status: Outcome.timeout,
|
||||||
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
|
kind: Outcome.probe,
|
||||||
|
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
|
||||||
|
),
|
||||||
|
_tcpUsed,
|
||||||
|
fallback,
|
||||||
|
skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return Outcome(
|
return _withUsed(
|
||||||
status: Outcome.ok,
|
Outcome(
|
||||||
kind: Outcome.probe,
|
status: Outcome.ok,
|
||||||
rttMs: watch.elapsedMicroseconds / 1000,
|
kind: Outcome.probe,
|
||||||
note: '收到回显',
|
rttMs: watch.elapsedMicroseconds / 1000,
|
||||||
|
note: '收到回显',
|
||||||
|
),
|
||||||
|
_tcpUsed,
|
||||||
|
fallback,
|
||||||
|
skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -258,7 +358,10 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Outcome> _nqUdp(ProbeRequest request, bool Function() cancelled) async {
|
Future<Outcome> _nqUdp(
|
||||||
|
ProbeRequest request,
|
||||||
|
bool Function() cancelled,
|
||||||
|
) async {
|
||||||
final pipe = await _datagram(request);
|
final pipe = await _datagram(request);
|
||||||
_seq += 1;
|
_seq += 1;
|
||||||
final seq = _seq;
|
final seq = _seq;
|
||||||
@@ -286,7 +389,11 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.unknown,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (reply == null) {
|
if (reply == null) {
|
||||||
if (sawInvalid) {
|
if (sawInvalid) {
|
||||||
@@ -329,7 +436,11 @@ class ProbeLoop {
|
|||||||
pipe.send(payload, request.port);
|
pipe.send(payload, request.port);
|
||||||
final reply = await pipe.waitMatch(request.timeout, (_) => true);
|
final reply = await pipe.waitMatch(request.timeout, (_) => true);
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.unknown,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (reply == null) {
|
if (reply == null) {
|
||||||
return const Outcome(
|
return const Outcome(
|
||||||
@@ -339,7 +450,8 @@ class ProbeLoop {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
final wanted = expect;
|
final wanted = expect;
|
||||||
if (wanted != null && (reply.length < wanted.length || !_prefix(reply, wanted))) {
|
if (wanted != null &&
|
||||||
|
(reply.length < wanted.length || !_prefix(reply, wanted))) {
|
||||||
return const Outcome(
|
return const Outcome(
|
||||||
status: Outcome.protocol,
|
status: Outcome.protocol,
|
||||||
kind: Outcome.query,
|
kind: Outcome.query,
|
||||||
@@ -358,7 +470,9 @@ class ProbeLoop {
|
|||||||
final pipe = await _datagram(request);
|
final pipe = await _datagram(request);
|
||||||
_dnsId = _dnsId == 65535 ? 1 : _dnsId + 1;
|
_dnsId = _dnsId == 65535 ? 1 : _dnsId + 1;
|
||||||
final id = _dnsId;
|
final id = _dnsId;
|
||||||
final name = request.dnsName.trim().isEmpty ? 'example.com' : request.dnsName.trim();
|
final name = request.dnsName.trim().isEmpty
|
||||||
|
? 'example.com'
|
||||||
|
: request.dnsName.trim();
|
||||||
final watch = Stopwatch()..start();
|
final watch = Stopwatch()..start();
|
||||||
pipe.send(dnsQuery(id, name), request.port);
|
pipe.send(dnsQuery(id, name), request.port);
|
||||||
var malformed = false;
|
var malformed = false;
|
||||||
@@ -378,7 +492,11 @@ class ProbeLoop {
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.unknown,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (reply == null) {
|
if (reply == null) {
|
||||||
if (malformed) {
|
if (malformed) {
|
||||||
@@ -422,7 +540,11 @@ class ProbeLoop {
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.unknown,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (reply == null) {
|
if (reply == null) {
|
||||||
if (sawInvalid) {
|
if (sawInvalid) {
|
||||||
@@ -448,11 +570,12 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async {
|
Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async {
|
||||||
final socket = await Socket.connect(
|
final opened = await _openTcp(request, cancelled);
|
||||||
request.host,
|
final failure = opened.failure;
|
||||||
request.port,
|
if (failure != null) {
|
||||||
timeout: request.timeout,
|
return failure;
|
||||||
);
|
}
|
||||||
|
final socket = opened.socket!;
|
||||||
final reader = _BytePipe(socket);
|
final reader = _BytePipe(socket);
|
||||||
try {
|
try {
|
||||||
socket.add(javaHandshake(request.host, request.port));
|
socket.add(javaHandshake(request.host, request.port));
|
||||||
@@ -460,18 +583,28 @@ class ProbeLoop {
|
|||||||
await socket.flush();
|
await socket.flush();
|
||||||
final status = await reader.nextPacket(request.timeout);
|
final status = await reader.nextPacket(request.timeout);
|
||||||
if (status == null || status.isEmpty || status[0] != 0x00) {
|
if (status == null || status.isEmpty || status[0] != 0x00) {
|
||||||
return const Outcome(
|
return _withUsed(
|
||||||
status: Outcome.protocol,
|
const Outcome(
|
||||||
kind: Outcome.query,
|
status: Outcome.protocol,
|
||||||
note: 'Minecraft 状态响应无效',
|
kind: Outcome.query,
|
||||||
|
note: 'Minecraft 状态响应无效',
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
final jsonText = readMcString(status, 1);
|
final jsonText = readMcString(status, 1);
|
||||||
if (jsonText == null) {
|
if (jsonText == null) {
|
||||||
return const Outcome(
|
return _withUsed(
|
||||||
status: Outcome.protocol,
|
const Outcome(
|
||||||
kind: Outcome.query,
|
status: Outcome.protocol,
|
||||||
note: 'Minecraft 状态内容无法解析',
|
kind: Outcome.query,
|
||||||
|
note: 'Minecraft 状态内容无法解析',
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
final detail = minecraftStatusDetail(jsonText);
|
final detail = minecraftStatusDetail(jsonText);
|
||||||
@@ -481,30 +614,49 @@ class ProbeLoop {
|
|||||||
await socket.flush();
|
await socket.flush();
|
||||||
final pong = await reader.nextPacket(request.timeout);
|
final pong = await reader.nextPacket(request.timeout);
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.connect,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (pong == null || pong.length != 9 || pong[0] != 0x01) {
|
if (pong == null || pong.length != 9 || pong[0] != 0x01) {
|
||||||
return Outcome(
|
return _withUsed(
|
||||||
status: Outcome.protocol,
|
Outcome(
|
||||||
kind: Outcome.query,
|
status: Outcome.protocol,
|
||||||
note: '没有收到有效的 Minecraft pong',
|
kind: Outcome.query,
|
||||||
detail: detail,
|
note: '没有收到有效的 Minecraft pong',
|
||||||
|
detail: detail,
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (ByteData.sublistView(pong).getUint64(1) != nonce) {
|
if (ByteData.sublistView(pong).getUint64(1) != nonce) {
|
||||||
return Outcome(
|
return _withUsed(
|
||||||
status: Outcome.protocol,
|
Outcome(
|
||||||
kind: Outcome.query,
|
status: Outcome.protocol,
|
||||||
note: 'Minecraft pong 的时间戳不匹配',
|
kind: Outcome.query,
|
||||||
detail: detail,
|
note: 'Minecraft pong 的时间戳不匹配',
|
||||||
|
detail: detail,
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return Outcome(
|
return _withUsed(
|
||||||
status: Outcome.ok,
|
Outcome(
|
||||||
kind: Outcome.query,
|
status: Outcome.ok,
|
||||||
rttMs: watch.elapsedMicroseconds / 1000,
|
kind: Outcome.query,
|
||||||
note: '收到 Minecraft 状态和 ping 应答',
|
rttMs: watch.elapsedMicroseconds / 1000,
|
||||||
detail: detail,
|
note: '收到 Minecraft 状态和 ping 应答',
|
||||||
|
detail: detail,
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
await reader.close();
|
await reader.close();
|
||||||
@@ -513,7 +665,7 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<_UdpPipe> _datagram(ProbeRequest request) async {
|
Future<_UdpPipe> _datagram(ProbeRequest request) async {
|
||||||
_picker ??= EndpointPicker(await (lookup ?? lookupAll)(request.host));
|
_picker ??= EndpointPicker(await _addresses(request.host));
|
||||||
final want = _picker!.current;
|
final want = _picker!.current;
|
||||||
final existing = _udp;
|
final existing = _udp;
|
||||||
if (existing != null && existing.peer.address == want.address) {
|
if (existing != null && existing.peer.address == want.address) {
|
||||||
@@ -550,6 +702,160 @@ class ProbeLoop {
|
|||||||
await udp.close();
|
await udp.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<List<InternetAddress>> _addresses(String host) async {
|
||||||
|
final cached = _resolved;
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
final found = await (lookup ?? lookupAll)(host);
|
||||||
|
final kept = filterAddresses(found, v4: _allow4, v6: _allow6);
|
||||||
|
if (kept.isEmpty) {
|
||||||
|
throw const SocketException('解析到的地址都不在已打开的地址族里');
|
||||||
|
}
|
||||||
|
_resolved = kept;
|
||||||
|
onResolved?.call(kept);
|
||||||
|
return kept;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Outcome> _httpProbe(ProbeRequest request) async {
|
||||||
|
final session = _http ??= HttpHelperSession(binary: helperPath);
|
||||||
|
return session.probe({
|
||||||
|
'profile': 'http',
|
||||||
|
'target': request.host,
|
||||||
|
'port': request.port,
|
||||||
|
'timeoutMs': request.timeout.inMilliseconds,
|
||||||
|
'allowIPv4': request.allowIPv4,
|
||||||
|
'allowIPv6': request.allowIPv6,
|
||||||
|
'http': {
|
||||||
|
'version': request.httpVersion,
|
||||||
|
'resolve': request.httpResolve,
|
||||||
|
'method': request.httpMethod,
|
||||||
|
'body': request.httpBody,
|
||||||
|
'referer': request.httpReferer,
|
||||||
|
'userAgent': request.httpUserAgent,
|
||||||
|
'cookies': request.httpCookies,
|
||||||
|
'maxRedirects': request.httpMaxRedirects,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<_TcpOpen> _openTcp(
|
||||||
|
ProbeRequest request,
|
||||||
|
bool Function() cancelled,
|
||||||
|
) async {
|
||||||
|
List<InternetAddress> addresses;
|
||||||
|
try {
|
||||||
|
addresses = await _addresses(request.host);
|
||||||
|
} on SocketException catch (error) {
|
||||||
|
return _TcpOpen.fail(classifySocket(error));
|
||||||
|
}
|
||||||
|
final skipped = <String>[];
|
||||||
|
Object? last;
|
||||||
|
for (final address in addresses) {
|
||||||
|
if (cancelled()) {
|
||||||
|
return _TcpOpen.fail(
|
||||||
|
const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.connect,
|
||||||
|
note: '已停止',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_announce(address);
|
||||||
|
final watch = Stopwatch()..start();
|
||||||
|
try {
|
||||||
|
final socket = await Socket.connect(
|
||||||
|
address,
|
||||||
|
request.port,
|
||||||
|
timeout: request.timeout,
|
||||||
|
);
|
||||||
|
watch.stop();
|
||||||
|
final fallback = skipped.isEmpty
|
||||||
|
? ''
|
||||||
|
: '候选未连通:${skipped.join(';')}。已改用 ${address.address}(${addressFamily(address)})。这些失败没有计入正式丢包或失败率。';
|
||||||
|
return _TcpOpen.ok(socket, address, watch, fallback, skipped.length);
|
||||||
|
} on SocketException catch (error) {
|
||||||
|
last = error;
|
||||||
|
skipped.add(
|
||||||
|
'${addressFamily(address)} ${address.address}:${classifySocket(error).note}',
|
||||||
|
);
|
||||||
|
} on TimeoutException {
|
||||||
|
last = TimeoutException('连接超时');
|
||||||
|
skipped.add('${addressFamily(address)} ${address.address}:连接超时');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final failure = last is SocketException
|
||||||
|
? classifySocket(last)
|
||||||
|
: const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.connect,
|
||||||
|
note: '连接超时',
|
||||||
|
);
|
||||||
|
final attempted = skipped.join(';');
|
||||||
|
return _TcpOpen.fail(
|
||||||
|
Outcome(
|
||||||
|
status: failure.status,
|
||||||
|
kind: failure.kind,
|
||||||
|
note: skipped.length > 1 ? '没有地址连通。$attempted' : failure.note,
|
||||||
|
detail: attempted.isEmpty
|
||||||
|
? const {}
|
||||||
|
: {'fallback': '已尝试 $attempted。没有地址连通,这次记为失败。'},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _TcpOpen {
|
||||||
|
const _TcpOpen.ok(
|
||||||
|
this.socket,
|
||||||
|
this.used,
|
||||||
|
this.watch,
|
||||||
|
this.fallback,
|
||||||
|
this.skipped,
|
||||||
|
) : failure = null;
|
||||||
|
|
||||||
|
const _TcpOpen.fail(this.failure)
|
||||||
|
: socket = null,
|
||||||
|
used = null,
|
||||||
|
watch = null,
|
||||||
|
fallback = '',
|
||||||
|
skipped = 0;
|
||||||
|
|
||||||
|
final Socket? socket;
|
||||||
|
final InternetAddress? used;
|
||||||
|
final Stopwatch? watch;
|
||||||
|
final Outcome? failure;
|
||||||
|
final String fallback;
|
||||||
|
final int skipped;
|
||||||
|
}
|
||||||
|
|
||||||
|
Outcome _withUsed(
|
||||||
|
Outcome outcome,
|
||||||
|
InternetAddress? used,
|
||||||
|
String fallback,
|
||||||
|
int skipped,
|
||||||
|
) {
|
||||||
|
if (used == null && fallback.isEmpty && skipped == 0) {
|
||||||
|
return outcome;
|
||||||
|
}
|
||||||
|
final detail = {...outcome.detail};
|
||||||
|
if (used != null) {
|
||||||
|
detail['address'] = used.address;
|
||||||
|
detail['family'] = addressFamily(used);
|
||||||
|
}
|
||||||
|
if (fallback.isNotEmpty) {
|
||||||
|
detail['fallback'] = fallback;
|
||||||
|
}
|
||||||
|
return Outcome(
|
||||||
|
status: outcome.status,
|
||||||
|
kind: outcome.kind,
|
||||||
|
rttMs: outcome.rttMs,
|
||||||
|
note: outcome.note,
|
||||||
|
reconnect: outcome.reconnect,
|
||||||
|
selectionSkipped: skipped,
|
||||||
|
detail: detail,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool _usesDatagram(String profileId) {
|
bool _usesDatagram(String profileId) {
|
||||||
@@ -572,11 +878,23 @@ Outcome _stampAddress(Outcome outcome, InternetAddress peer) {
|
|||||||
rttMs: outcome.rttMs,
|
rttMs: outcome.rttMs,
|
||||||
note: outcome.note,
|
note: outcome.note,
|
||||||
reconnect: outcome.reconnect,
|
reconnect: outcome.reconnect,
|
||||||
detail: {...outcome.detail, 'address': peer.address},
|
selectionSkipped: outcome.selectionSkipped,
|
||||||
|
detail: {
|
||||||
|
...outcome.detail,
|
||||||
|
'address': peer.address,
|
||||||
|
'family': addressFamily(peer),
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Outcome classifySocket(SocketException error, {bool reconnect = false}) {
|
Outcome classifySocket(SocketException error, {bool reconnect = false}) {
|
||||||
|
if (error.message.contains('地址族') || error.message.contains('已关闭')) {
|
||||||
|
return Outcome(
|
||||||
|
status: Outcome.error,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: error.message,
|
||||||
|
);
|
||||||
|
}
|
||||||
final text = '${error.message} ${error.osError?.message ?? ''}'.toLowerCase();
|
final text = '${error.message} ${error.osError?.message ?? ''}'.toLowerCase();
|
||||||
final code = error.osError?.errorCode;
|
final code = error.osError?.errorCode;
|
||||||
if (text.contains('timed out') || text.contains('timeout')) {
|
if (text.contains('timed out') || text.contains('timeout')) {
|
||||||
|
|||||||
@@ -4,11 +4,13 @@ import 'dart:io';
|
|||||||
|
|
||||||
import '../metrics/sample_book.dart';
|
import '../metrics/sample_book.dart';
|
||||||
import '../models/session_config.dart';
|
import '../models/session_config.dart';
|
||||||
|
import '../ui/address_text.dart';
|
||||||
|
|
||||||
class RemoteProbe {
|
class RemoteProbe {
|
||||||
HttpClient? _client;
|
HttpClient? _client;
|
||||||
String? _jobId;
|
String? _jobId;
|
||||||
Uri? _base;
|
Uri? _base;
|
||||||
|
String _jobsPath = '/v1/jobs';
|
||||||
|
|
||||||
Future<void> run({
|
Future<void> run({
|
||||||
required String baseUrl,
|
required String baseUrl,
|
||||||
@@ -16,19 +18,22 @@ class RemoteProbe {
|
|||||||
required ProbeBody body,
|
required ProbeBody body,
|
||||||
required void Function(ProbeSample sample) onSample,
|
required void Function(ProbeSample sample) onSample,
|
||||||
required bool Function() cancelled,
|
required bool Function() cancelled,
|
||||||
|
void Function(List<ResolvedAddress> resolved)? onResolved,
|
||||||
|
String jobsPath = '/v1/jobs',
|
||||||
}) async {
|
}) async {
|
||||||
final normalized = normalizeNodeUrl(baseUrl);
|
final normalized = normalizeNodeUrl(baseUrl);
|
||||||
if (normalized == null) {
|
if (normalized == null) {
|
||||||
throw RemoteException('节点地址需要是 http 或 https,且不能把口令写在地址里');
|
throw RemoteException('节点地址需要是 http 或 https,且不能把口令写在地址里');
|
||||||
}
|
}
|
||||||
_base = Uri.parse(normalized);
|
_base = Uri.parse(normalized);
|
||||||
|
_jobsPath = jobsPath.startsWith('/') ? jobsPath : '/$jobsPath';
|
||||||
final client = HttpClient();
|
final client = HttpClient();
|
||||||
_client = client;
|
_client = client;
|
||||||
try {
|
try {
|
||||||
final created = await _send(
|
final created = await _send(
|
||||||
client,
|
client,
|
||||||
'POST',
|
'POST',
|
||||||
_base!.resolve('/v1/jobs'),
|
_base!.resolve(_jobsPath),
|
||||||
nodeToken,
|
nodeToken,
|
||||||
utf8.encode(jsonEncode(body.toJson())),
|
utf8.encode(jsonEncode(body.toJson())),
|
||||||
);
|
);
|
||||||
@@ -52,6 +57,7 @@ class RemoteProbe {
|
|||||||
throw RemoteException('节点返回的任务无效');
|
throw RemoteException('节点返回的任务无效');
|
||||||
}
|
}
|
||||||
_jobId = parsed['jobId'] as String;
|
_jobId = parsed['jobId'] as String;
|
||||||
|
onResolved?.call(readResolvedList(parsed));
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -86,7 +92,13 @@ class RemoteProbe {
|
|||||||
_jobId = null;
|
_jobId = null;
|
||||||
if (client != null && id != null && base != null) {
|
if (client != null && id != null && base != null) {
|
||||||
try {
|
try {
|
||||||
await _send(client, 'DELETE', base.resolve('/v1/jobs/$id'), nodeToken, const []);
|
await _send(
|
||||||
|
client,
|
||||||
|
'DELETE',
|
||||||
|
base.resolve('$_jobsPath/$id'),
|
||||||
|
nodeToken,
|
||||||
|
const [],
|
||||||
|
);
|
||||||
} on Object {
|
} on Object {
|
||||||
// The stream ending already asks the node to drop the job.
|
// The stream ending already asks the node to drop the job.
|
||||||
}
|
}
|
||||||
@@ -101,7 +113,9 @@ class RemoteProbe {
|
|||||||
void Function(ProbeSample sample) onSample,
|
void Function(ProbeSample sample) onSample,
|
||||||
bool Function() cancelled,
|
bool Function() cancelled,
|
||||||
) async {
|
) async {
|
||||||
final request = await client.getUrl(_base!.resolve('/v1/jobs/$_jobId/stream'));
|
final request = await client.getUrl(
|
||||||
|
_base!.resolve('$_jobsPath/$_jobId/stream'),
|
||||||
|
);
|
||||||
request.followRedirects = false;
|
request.followRedirects = false;
|
||||||
_auth(request, nodeToken);
|
_auth(request, nodeToken);
|
||||||
final response = await request.close().timeout(const Duration(seconds: 20));
|
final response = await request.close().timeout(const Duration(seconds: 20));
|
||||||
@@ -143,6 +157,9 @@ class ProbeBody {
|
|||||||
required this.dnsName,
|
required this.dnsName,
|
||||||
required this.payloadHex,
|
required this.payloadHex,
|
||||||
required this.expectHex,
|
required this.expectHex,
|
||||||
|
this.allowIPv4 = true,
|
||||||
|
this.allowIPv6 = true,
|
||||||
|
this.http,
|
||||||
});
|
});
|
||||||
|
|
||||||
final String target;
|
final String target;
|
||||||
@@ -156,6 +173,9 @@ class ProbeBody {
|
|||||||
final String dnsName;
|
final String dnsName;
|
||||||
final String payloadHex;
|
final String payloadHex;
|
||||||
final String expectHex;
|
final String expectHex;
|
||||||
|
final bool allowIPv4;
|
||||||
|
final bool allowIPv6;
|
||||||
|
final Map<String, Object?>? http;
|
||||||
|
|
||||||
Map<String, Object?> toJson() => {
|
Map<String, Object?> toJson() => {
|
||||||
'target': target,
|
'target': target,
|
||||||
@@ -169,6 +189,9 @@ class ProbeBody {
|
|||||||
'dnsName': dnsName,
|
'dnsName': dnsName,
|
||||||
'payloadHex': payloadHex,
|
'payloadHex': payloadHex,
|
||||||
'expectHex': expectHex,
|
'expectHex': expectHex,
|
||||||
|
'allowIPv4': allowIPv4,
|
||||||
|
'allowIPv6': allowIPv6,
|
||||||
|
if (http != null) 'http': http,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,10 +204,32 @@ class RemoteException implements Exception {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class NodeInfo {
|
class NodeInfo {
|
||||||
const NodeInfo({required this.visibility, required this.authRequired});
|
const NodeInfo({
|
||||||
|
required this.visibility,
|
||||||
|
required this.authRequired,
|
||||||
|
this.profiles = const [],
|
||||||
|
this.ipFamily = false,
|
||||||
|
});
|
||||||
|
|
||||||
final String visibility;
|
final String visibility;
|
||||||
final bool authRequired;
|
final bool authRequired;
|
||||||
|
final List<String> profiles;
|
||||||
|
final bool ipFamily;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? remoteUpgradeMessage(
|
||||||
|
NodeInfo info, {
|
||||||
|
required String profileId,
|
||||||
|
required bool allow4,
|
||||||
|
required bool allow6,
|
||||||
|
}) {
|
||||||
|
if (profileId == 'http' && !info.profiles.contains('http')) {
|
||||||
|
return '这个节点还不支持 HTTP 探测,需要升级到 1.1.3。';
|
||||||
|
}
|
||||||
|
if ((!allow4 || !allow6) && !info.ipFamily) {
|
||||||
|
return '这个节点还不会遵守 IPv4 / IPv6 开关,需要升级到 1.1.3。';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
|
Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
|
||||||
@@ -194,7 +239,9 @@ Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
|
|||||||
}
|
}
|
||||||
final client = HttpClient();
|
final client = HttpClient();
|
||||||
try {
|
try {
|
||||||
final request = await client.getUrl(Uri.parse(normalized).resolve('/v1/info'));
|
final request = await client.getUrl(
|
||||||
|
Uri.parse(normalized).resolve('/v1/info'),
|
||||||
|
);
|
||||||
request.followRedirects = false;
|
request.followRedirects = false;
|
||||||
final response = await request.close().timeout(const Duration(seconds: 8));
|
final response = await request.close().timeout(const Duration(seconds: 8));
|
||||||
final body = await response.transform(utf8.decoder).join();
|
final body = await response.transform(utf8.decoder).join();
|
||||||
@@ -205,9 +252,22 @@ Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
|
|||||||
if (json is! Map) {
|
if (json is! Map) {
|
||||||
throw RemoteException('节点信息无效');
|
throw RemoteException('节点信息无效');
|
||||||
}
|
}
|
||||||
|
final profiles = <String>[];
|
||||||
|
final rawProfiles = json['profiles'];
|
||||||
|
if (rawProfiles is List) {
|
||||||
|
for (final item in rawProfiles) {
|
||||||
|
if (item is String) {
|
||||||
|
profiles.add(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
return NodeInfo(
|
return NodeInfo(
|
||||||
visibility: json['visibility'] is String ? json['visibility'] as String : '',
|
visibility: json['visibility'] is String
|
||||||
|
? json['visibility'] as String
|
||||||
|
: '',
|
||||||
authRequired: json['authRequired'] == true,
|
authRequired: json['authRequired'] == true,
|
||||||
|
profiles: profiles,
|
||||||
|
ipFamily: json['ipFamily'] == true,
|
||||||
);
|
);
|
||||||
} on RemoteException {
|
} on RemoteException {
|
||||||
rethrow;
|
rethrow;
|
||||||
|
|||||||
@@ -5,11 +5,13 @@ import 'package:path_provider/path_provider.dart';
|
|||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
import '../models/session_config.dart';
|
import '../models/session_config.dart';
|
||||||
|
import '../models/target_history.dart';
|
||||||
import 'token_vault.dart';
|
import 'token_vault.dart';
|
||||||
|
|
||||||
class AppStore {
|
class AppStore {
|
||||||
static const _key = 'netquality.settings.v2';
|
static const _key = 'netquality.settings.v2';
|
||||||
static const _legacy = 'netquality.settings.v1';
|
static const _legacy = 'netquality.settings.v1';
|
||||||
|
static const historyKey = 'netquality.target-history.v1';
|
||||||
|
|
||||||
Future<({SessionConfig config, String legacyEcho})> load() async {
|
Future<({SessionConfig config, String legacyEcho})> load() async {
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
@@ -45,6 +47,16 @@ class AppStore {
|
|||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
await prefs.setString(_key, jsonEncode(config.toJson()));
|
await prefs.setString(_key, jsonEncode(config.toJson()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<TargetHistory> loadHistory() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
return TargetHistory.decode(prefs.getString(historyKey) ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> saveHistory(TargetHistory history) async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
await prefs.setString(historyKey, history.encode());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<TokenVault> openTokenVault() async {
|
Future<TokenVault> openTokenVault() async {
|
||||||
|
|||||||
@@ -101,3 +101,5 @@ class FileTokenVault implements TokenVault {
|
|||||||
const echoTokenKey = 'target-echo-token';
|
const echoTokenKey = 'target-echo-token';
|
||||||
|
|
||||||
String nodeTokenKey(String nodeId) => 'node-token.$nodeId';
|
String nodeTokenKey(String nodeId) => 'node-token.$nodeId';
|
||||||
|
|
||||||
|
String centerTokenKey(String centerId) => 'center-token.$centerId';
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
class ResolvedAddress {
|
||||||
|
const ResolvedAddress({required this.address, required this.family});
|
||||||
|
|
||||||
|
final String address;
|
||||||
|
final String family;
|
||||||
|
}
|
||||||
|
|
||||||
|
String addressFamily(InternetAddress address) {
|
||||||
|
return address.type == InternetAddressType.IPv6 ? 'IPv6' : 'IPv4';
|
||||||
|
}
|
||||||
|
|
||||||
|
String familyOfAddress(String address) {
|
||||||
|
final parsed = InternetAddress.tryParse(address);
|
||||||
|
if (parsed == null) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return addressFamily(parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
class AddressLines {
|
||||||
|
const AddressLines({
|
||||||
|
this.used,
|
||||||
|
this.trying,
|
||||||
|
this.resolved,
|
||||||
|
this.fallback,
|
||||||
|
this.unreported,
|
||||||
|
this.fake = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String? used;
|
||||||
|
final String? trying;
|
||||||
|
final String? resolved;
|
||||||
|
final String? fallback;
|
||||||
|
final String? unreported;
|
||||||
|
final bool fake;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [used] is an address a probe actually connected to or sent to.
|
||||||
|
/// [resolved] is only the lookup result and is never labeled as the address
|
||||||
|
/// in use. A remote sample that omits the address stays unreported.
|
||||||
|
AddressLines describeAddress({
|
||||||
|
required List<ResolvedAddress> resolved,
|
||||||
|
String? usedAddress,
|
||||||
|
String? usedFamily,
|
||||||
|
String? tryingAddress,
|
||||||
|
String? tryingFamily,
|
||||||
|
String fallbackText = '',
|
||||||
|
bool addressUnreported = false,
|
||||||
|
bool usedIsFake = false,
|
||||||
|
}) {
|
||||||
|
final hasUsed = usedAddress != null && usedAddress.isNotEmpty;
|
||||||
|
String? used;
|
||||||
|
if (hasUsed) {
|
||||||
|
final family = (usedFamily == null || usedFamily.isEmpty)
|
||||||
|
? familyOfAddress(usedAddress)
|
||||||
|
: usedFamily;
|
||||||
|
used = family.isEmpty ? '实际地址 $usedAddress' : '实际地址 $usedAddress($family)';
|
||||||
|
}
|
||||||
|
String? trying;
|
||||||
|
if (!hasUsed && tryingAddress != null && tryingAddress.isNotEmpty) {
|
||||||
|
final family = (tryingFamily == null || tryingFamily.isEmpty)
|
||||||
|
? ''
|
||||||
|
: '($tryingFamily)';
|
||||||
|
trying = '正在尝试 $tryingAddress$family,还没有正式结果';
|
||||||
|
}
|
||||||
|
String? resolvedLine;
|
||||||
|
if (resolved.isNotEmpty) {
|
||||||
|
final sameSingle =
|
||||||
|
resolved.length == 1 &&
|
||||||
|
hasUsed &&
|
||||||
|
resolved.single.address == usedAddress;
|
||||||
|
if (!sameSingle) {
|
||||||
|
final text = resolved
|
||||||
|
.map((item) {
|
||||||
|
final family = item.family.isEmpty ? '' : '(${item.family})';
|
||||||
|
return '${item.address}$family';
|
||||||
|
})
|
||||||
|
.join('、');
|
||||||
|
resolvedLine = '解析到 $text';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return AddressLines(
|
||||||
|
used: used,
|
||||||
|
trying: trying,
|
||||||
|
resolved: resolvedLine,
|
||||||
|
fallback: fallbackText.isEmpty ? null : fallbackText,
|
||||||
|
unreported: addressUnreported && !hasUsed ? '节点没有报告实际使用的地址' : null,
|
||||||
|
fake: usedIsFake && hasUsed,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<ResolvedAddress> readResolvedList(Object? parsed) {
|
||||||
|
if (parsed is! Map) {
|
||||||
|
return const [];
|
||||||
|
}
|
||||||
|
final raw = parsed['resolved'];
|
||||||
|
if (raw is! List) {
|
||||||
|
return const [];
|
||||||
|
}
|
||||||
|
final out = <ResolvedAddress>[];
|
||||||
|
for (final item in raw) {
|
||||||
|
if (item is! Map) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final address = item['address'];
|
||||||
|
if (address is! String || address.isEmpty) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final family = item['family'];
|
||||||
|
out.add(
|
||||||
|
ResolvedAddress(
|
||||||
|
address: address,
|
||||||
|
family: family is String && family.isNotEmpty
|
||||||
|
? family
|
||||||
|
: familyOfAddress(address),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../center/catalog.dart';
|
||||||
|
import '../center/center_client.dart';
|
||||||
|
import '../models/session_config.dart';
|
||||||
|
|
||||||
|
class AddedCenter {
|
||||||
|
const AddedCenter({
|
||||||
|
required this.link,
|
||||||
|
required this.token,
|
||||||
|
required this.catalog,
|
||||||
|
});
|
||||||
|
|
||||||
|
final CenterLink link;
|
||||||
|
final String token;
|
||||||
|
final Catalog catalog;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<AddedCenter?> showCenterAddDialog(BuildContext context) {
|
||||||
|
return showDialog<AddedCenter>(
|
||||||
|
context: context,
|
||||||
|
builder: (context) => const _CenterAddDialog(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _CenterAddDialog extends StatefulWidget {
|
||||||
|
const _CenterAddDialog();
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_CenterAddDialog> createState() => _CenterAddDialogState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _CenterAddDialogState extends State<_CenterAddDialog> {
|
||||||
|
final _url = TextEditingController();
|
||||||
|
final _account = TextEditingController();
|
||||||
|
final _token = TextEditingController();
|
||||||
|
final _password = TextEditingController();
|
||||||
|
var _busy = false;
|
||||||
|
String? _hint;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_url.dispose();
|
||||||
|
_account.dispose();
|
||||||
|
_token.dispose();
|
||||||
|
_password.dispose();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _submit() async {
|
||||||
|
setState(() {
|
||||||
|
_busy = true;
|
||||||
|
_hint = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
var token = _token.text.trim();
|
||||||
|
if (token.isEmpty) {
|
||||||
|
if (_password.text.isEmpty) {
|
||||||
|
setState(() => _hint = '请填写口令。如果中心要求密码,也可以只填账号和密码。');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
token = await loginCenter(
|
||||||
|
baseUrl: _url.text,
|
||||||
|
account: _account.text,
|
||||||
|
password: _password.text,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final catalog = await fetchCatalog(baseUrl: _url.text, token: token);
|
||||||
|
final stored = normalizeNodeUrl(_url.text);
|
||||||
|
if (stored == null) {
|
||||||
|
setState(() => _hint = '中心地址需要是 http 或 https,且不能把口令写在地址里');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!mounted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Navigator.of(context).pop(
|
||||||
|
AddedCenter(
|
||||||
|
link: CenterLink(
|
||||||
|
id: DateTime.now().microsecondsSinceEpoch.toString(),
|
||||||
|
url: stored,
|
||||||
|
account: _account.text.trim(),
|
||||||
|
),
|
||||||
|
token: token,
|
||||||
|
catalog: catalog,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} on CenterClientException catch (error) {
|
||||||
|
setState(() => _hint = error.message);
|
||||||
|
} on Object {
|
||||||
|
setState(() => _hint = '没有完成添加');
|
||||||
|
} finally {
|
||||||
|
if (mounted) {
|
||||||
|
setState(() => _busy = false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return AlertDialog(
|
||||||
|
title: const Text('一键添加服务器'),
|
||||||
|
content: SizedBox(
|
||||||
|
width: 420,
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
const Text(
|
||||||
|
'点一次确认,会把这个口令能用的服务器全部加进来。显示名由中心决定,这里不能改。保密服务器只保存名称,地址留在中心。',
|
||||||
|
style: TextStyle(fontSize: 13, height: 1.4),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
TextField(
|
||||||
|
controller: _url,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: '中心地址',
|
||||||
|
hintText: 'https://中心:8443',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
TextField(
|
||||||
|
controller: _account,
|
||||||
|
decoration: const InputDecoration(labelText: '账号'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
TextField(
|
||||||
|
controller: _token,
|
||||||
|
obscureText: true,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: '口令',
|
||||||
|
hintText: '已有口令时填写',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
TextField(
|
||||||
|
controller: _password,
|
||||||
|
obscureText: true,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: '密码',
|
||||||
|
hintText: '中心要求密码、手里还没有口令时填写',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_hint != null) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(_hint!, style: const TextStyle(color: Color(0xFF9A3412))),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: _busy ? null : () => Navigator.of(context).pop(),
|
||||||
|
child: const Text('取消'),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: _busy ? null : _submit,
|
||||||
|
child: Text(_busy ? '正在获取' : '获取并添加'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
const chartPinEpsilon = 0.0001;
|
||||||
|
|
||||||
|
class ChartSelection {
|
||||||
|
const ChartSelection({required this.sec, required this.sessionId});
|
||||||
|
|
||||||
|
final double sec;
|
||||||
|
final int sessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A tap chooses the nearest sample and keeps it after the pointer is
|
||||||
|
/// released. A new session, an empty series, or a point that has scrolled
|
||||||
|
/// off the front of the window clears the pin instead of jumping to another
|
||||||
|
/// sample. [tappedSec] null means "keep the current pin if it is still valid".
|
||||||
|
ChartSelection? nextChartSelection({
|
||||||
|
required ChartSelection? current,
|
||||||
|
required int sessionId,
|
||||||
|
required List<double> sampleSecs,
|
||||||
|
double? tappedSec,
|
||||||
|
}) {
|
||||||
|
if (tappedSec != null) {
|
||||||
|
double? nearest;
|
||||||
|
var best = double.infinity;
|
||||||
|
for (final sec in sampleSecs) {
|
||||||
|
final distance = (sec - tappedSec).abs();
|
||||||
|
if (distance < best) {
|
||||||
|
best = distance;
|
||||||
|
nearest = sec;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (nearest == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return ChartSelection(sec: nearest, sessionId: sessionId);
|
||||||
|
}
|
||||||
|
if (current == null || current.sessionId != sessionId || sampleSecs.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (current.sec + chartPinEpsilon < sampleSecs.first) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (final sec in sampleSecs) {
|
||||||
|
if ((sec - current.sec).abs() <= chartPinEpsilon) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../content/release_history.dart';
|
||||||
|
import '../version.dart';
|
||||||
|
import 'quality_charts.dart';
|
||||||
|
|
||||||
|
class HistoryPage extends StatelessWidget {
|
||||||
|
const HistoryPage({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
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: 760),
|
||||||
|
child: ListView(
|
||||||
|
padding: EdgeInsets.fromLTRB(
|
||||||
|
wide ? 24 : 12,
|
||||||
|
8,
|
||||||
|
wide ? 24 : 12,
|
||||||
|
28,
|
||||||
|
),
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'当前版本 $appVersion(构建 $appBuild) · 署名 $appAttribution · $appLicense',
|
||||||
|
style: const TextStyle(
|
||||||
|
color: ink,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
const Text(
|
||||||
|
releaseHistoryNote,
|
||||||
|
style: TextStyle(color: muted, height: 1.4),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
for (final entry in releaseHistory) _entry(entry),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _entry(ReleaseEntry entry) {
|
||||||
|
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(
|
||||||
|
entry.title,
|
||||||
|
style: const TextStyle(fontWeight: FontWeight.w700, color: ink),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
Text(
|
||||||
|
entry.published == null
|
||||||
|
? entry.source
|
||||||
|
: '${entry.published} · ${entry.source}',
|
||||||
|
style: const TextStyle(color: muted, fontSize: 13, height: 1.4),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
for (final point in entry.points)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 6),
|
||||||
|
child: Text('· $point', style: const TextStyle(height: 1.4)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+748
-53
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,111 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'quality_charts.dart';
|
||||||
|
|
||||||
|
class MetricGuidePage extends StatelessWidget {
|
||||||
|
const MetricGuidePage({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
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: 760),
|
||||||
|
child: ListView(
|
||||||
|
padding: EdgeInsets.fromLTRB(
|
||||||
|
wide ? 24 : 12,
|
||||||
|
8,
|
||||||
|
wide ? 24 : 12,
|
||||||
|
28,
|
||||||
|
),
|
||||||
|
children: const [
|
||||||
|
_Section(
|
||||||
|
title: '这些数字从哪来',
|
||||||
|
body: '曲线和百分比只来自已经完成、并且计入正式结果的探测。还在途中的请求不会画成 100%,停止时被取消的请求也不算丢包。没有内置样本。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '已发送、已收到、超时',
|
||||||
|
body: '已发送是计入正式结果的次数。已收到是其中成功的次数:合作反射收到了对上序号的回显,普通 TCP 是连上了,其他类型是收到了符合协议的应答。\n\n合作反射的「超时」只计已经把探测帧写出去、但超时前没有对上序号的次数。还没连上、连接被拒绝,不算进这个超时,也不算进探测无应答。\n\n普通 UDP、DNS、自定义 UDP 和基岩版如果根本没有协议应答,记为「无应答」,超时这一项显示不适用。收到了包但内容不对,记为协议错误。UDP 沉默不能当成已经证实的丢包:对端可以合法地不回答。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '探测无应答、失败率、无应答',
|
||||||
|
body: '合作反射 TCP / UDP:探测无应答 = 超时 ÷(超时 + 成功)× 100%。分母只含已经写出的回显尝试。分母为 0 时显示 —,而不是 0%。TCP 会重传,所以这不是网卡上的物理丢包。\n\n普通 TCP 和 Minecraft Java:失败率 = 未成功的正式尝试 ÷ 已完成的正式尝试 × 100%。这里没有丢包百分比。\n\n其余 UDP 类探测:无应答 = 无应答次数 ÷ 已完成次数 × 100%。它回答的是「没有看到协议应答」,不是「丢了多少包」。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '延迟、中位数、P95 和抖动',
|
||||||
|
body: '延迟只来自成功的样本,单位是毫秒。当前延迟是最近一次成功的往返时间。最小、平均、最大都是这些成功样本的最小、算术平均和最大。\n\n中位数:把成功样本从小到大排列。奇数个取中间那个;偶数个取中间两个的平均。\n\nP95 用最近秩:秩 = ceil(0.95 × 次数),用整数 (95 × 次数 + 99) / 100 计算,从 1 开始,取排序后这个位置的值。次数为 1 时,P95 就是那一次。\n\n抖动按 RFC 3550:D 是相邻两次成功往返时间之差,J = J + (|D| − J) / 16。第一次成功时 J 为 0;没有成功时显示 —。远程探测的往返时间在节点上用单调时钟量好再传回来,不包含手机到节点的控制通道耗时。\n\n旧版本节点不会上报最小、平均、中位、P95 和最大。这时这些格子显示「节点未提供」,当前延迟和抖动仍用它原来上报的值。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '用时',
|
||||||
|
body: '用时是这次会话从按下开始到停止(或到当前)的墙钟时间。它不是各次往返时间相加,也不包括节点在创建任务之前花掉的时间。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '选址失败和正式丢包',
|
||||||
|
body: '一个域名可能同时有 IPv6 和 IPv4。程序会先试一个地址。还没有任何地址应答时,连不上或没有应答会换下一个。这种只为挑选地址而失败的尝试,如果后面有地址成功,就不计入已发送、超时和丢包,界面单独写明回退了哪个地址。\n\n一旦某个地址已经应答,之后对它的超时或失败都算正式结果,不会因为后来又换地址而被抹掉。只有一个地址时,失败从一开始就算正式结果。\n\n如果每一个候选都失败,这些失败会计入正式结果。界面显示失败或 100% 的无应答/失败率,不会显示 0% 成功。\n\n1.1.1 的远程节点还不会做这层区分,它的统计可能仍把第一次选址失败算进去。要分开看,节点也需要 1.1.2。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '实际地址和 IPv6 回退',
|
||||||
|
body: '「实际地址」是这次真正连通或真正发包的 IP,并注明 IPv4 或 IPv6。「解析到」只是域名解析的结果,不会被说成已经在用的地址。\n\n正在尝试、还没有正式结果时,会标明正在尝试,而不是写成已经发往。远程节点如果没有在结果里带上地址(旧版本就是这样),界面写「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。\n\n地址落在 198.18.0.0/15 时,会提示这是 VPN 假地址,只有这个 VPN 开着时才能用。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: 'IPv4 和 IPv6',
|
||||||
|
body: '设置里有两个开关,默认都开着。解析出多个地址以后,只向打开的地址族发包。只开一个,就只用那一个。两个都关掉时不会开始,并说明原因。目标本身就是被关掉的那种地址时,也不会开始。\n\n远程任务会带上同样的选择,节点不会改用另一个地址族。结果里的实际地址和地址族,仍然是这一次真正用到的那个。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: 'HTTP',
|
||||||
|
body: 'HTTP 探测记下 DNS、连接、TLS、首字节和总时间,以及状态码、最终地址和实际用到的 HTTP 版本(1.1、2 或 3)。曲线上的延迟是总时间。已经收到的响应算成功,4xx 和 5xx 只显示状态码,不叫丢包,也不算进失败率。连不上或强制的版本不被支持,才算失败。\n\n默认先试 HTTP/2,不行再降到 1.1。选了「仅 HTTP/1.1」「仅 HTTP/2」或「仅 HTTP/3」时,服务器不支持就失败,不会悄悄换一种。指定解析只改连接走的地址,Host 和 SNI 仍用目标网址,用来看 CDN。它不是把 1.1.1.1 当成 DNS 服务器。\n\nHTTP/3 的连接和 TLS 是同一次 QUIC 握手,这两项时间相同。本机探测和节点用的是同一个 Go 引擎。桌面端需要把 netquality-reflector 放在程序旁边,或设置 NQ_PROBE_HELPER。Android 上如果系统不允许从应用目录启动这个程序,本机 HTTP 会说明缺引擎;远程节点不受影响。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '停止以后',
|
||||||
|
body: '点停止会保留曲线,并给出开始、结束、用时、目标、类型、来源、实际地址和同一套最终指标。正在进行、因为停止而被取消的请求不计入丢包。重新开始会换一次新的会话,旧曲线不会混进来。\n\n点曲线上的一点可以钉住该时刻的延迟和比率,松手后仍然留着。再点另一点会换。新会话或这个点滚出窗口后,选择会被清掉,不会跳到别的点上。',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Section extends StatelessWidget {
|
||||||
|
const _Section({required this.title, required this.body});
|
||||||
|
|
||||||
|
final String title;
|
||||||
|
final String body;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
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: 8),
|
||||||
|
Text(body, style: const TextStyle(height: 1.45, color: ink)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,283 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../metrics/sample_book.dart';
|
||||||
|
import '../probe/endpoint_picker.dart';
|
||||||
|
import '../probe/probe_controller.dart';
|
||||||
|
import 'address_text.dart';
|
||||||
|
import 'format.dart';
|
||||||
|
import 'quality_charts.dart';
|
||||||
|
|
||||||
|
class MetricLine {
|
||||||
|
const MetricLine(this.label, this.value, {this.detail});
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
final String value;
|
||||||
|
final String? detail;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rows use the same summary the live view and the stopped session share.
|
||||||
|
/// A metric that this profile does not measure is marked unsupported instead
|
||||||
|
/// of being shown as zero.
|
||||||
|
List<MetricLine> metricLines({
|
||||||
|
required ProbeSummary summary,
|
||||||
|
required String profileId,
|
||||||
|
required Duration elapsed,
|
||||||
|
}) {
|
||||||
|
final lines = <MetricLine>[
|
||||||
|
MetricLine(
|
||||||
|
'已发送',
|
||||||
|
'${summary.sent}',
|
||||||
|
detail: summary.selectionSkipped > 0
|
||||||
|
? '正式结果 ${summary.sent} 次。另有 ${summary.selectionSkipped} 次选址失败未计入。'
|
||||||
|
: '只计已经计入正式结果的次数,不含还在途中的探测。',
|
||||||
|
),
|
||||||
|
MetricLine('已收到', '${summary.ok}', detail: '成功收到应答,或成功连通的次数。'),
|
||||||
|
_timeoutLine(summary, profileId),
|
||||||
|
_rateLine(summary, profileId),
|
||||||
|
_latency('当前延迟', summary.rttMs, summary, recent: true),
|
||||||
|
_latency('最小延迟', summary.minRttMs, summary),
|
||||||
|
_latency('平均延迟', summary.meanRttMs, summary),
|
||||||
|
_latency('中位延迟', summary.medianRttMs, summary),
|
||||||
|
_latency('P95 延迟', summary.p95RttMs, summary),
|
||||||
|
_latency('最大延迟', summary.maxRttMs, summary),
|
||||||
|
MetricLine(
|
||||||
|
'抖动',
|
||||||
|
summary.jitterMs == null ? '—' : formatMs(summary.jitterMs),
|
||||||
|
detail: 'RFC 3550:J = J + (|D| − J) / 16。D 是相邻两次成功往返时间之差。只有一次成功时 J 为 0。',
|
||||||
|
),
|
||||||
|
MetricLine(
|
||||||
|
'用时',
|
||||||
|
formatDuration(elapsed),
|
||||||
|
detail: '从这次探测开始到现在或到停止的墙钟时间,不是往返时间相加。',
|
||||||
|
),
|
||||||
|
];
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
MetricLine _timeoutLine(ProbeSummary summary, String profileId) {
|
||||||
|
switch (profileId) {
|
||||||
|
case 'nq-tcp':
|
||||||
|
case 'nq-udp':
|
||||||
|
return MetricLine(
|
||||||
|
'超时',
|
||||||
|
'${summary.timeout}',
|
||||||
|
detail: '已经写出回显帧、在超时前没有对上序号的次数。连接失败另计,不在这里。',
|
||||||
|
);
|
||||||
|
case 'tcp-connect':
|
||||||
|
case 'minecraft-java':
|
||||||
|
return const MetricLine('超时', '不适用', detail: '这种探测把连不上记为失败,不单独叫探测超时。');
|
||||||
|
case 'http':
|
||||||
|
return const MetricLine(
|
||||||
|
'超时',
|
||||||
|
'不适用',
|
||||||
|
detail: 'HTTP 把连不上记为失败。已经收到的 4xx 和 5xx 是状态码,不是丢包,也不算进超时。',
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return MetricLine(
|
||||||
|
'超时',
|
||||||
|
'不适用',
|
||||||
|
detail: '没有协议应答时记为无应答 ${summary.unknown} 次,不能据此断定丢包。',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MetricLine _rateLine(ProbeSummary summary, String profileId) {
|
||||||
|
switch (profileId) {
|
||||||
|
case 'nq-tcp':
|
||||||
|
case 'nq-udp':
|
||||||
|
final denom = summary.timeout + summary.ok;
|
||||||
|
return MetricLine(
|
||||||
|
'探测无应答',
|
||||||
|
formatPct(summary.probeLossPct),
|
||||||
|
detail: denom == 0
|
||||||
|
? '还没有完成的回显尝试,所以不显示 0%。'
|
||||||
|
: '超时 ÷(超时 + 成功)= ${summary.timeout} ÷ $denom。连接失败不在分母里。',
|
||||||
|
);
|
||||||
|
case 'tcp-connect':
|
||||||
|
case 'minecraft-java':
|
||||||
|
return MetricLine(
|
||||||
|
'失败率',
|
||||||
|
formatPct(summary.failurePct),
|
||||||
|
detail: '未成功的正式尝试 ÷ 已完成的正式尝试。这不是物理丢包。',
|
||||||
|
);
|
||||||
|
case 'http':
|
||||||
|
return MetricLine(
|
||||||
|
'失败率',
|
||||||
|
formatPct(summary.failurePct),
|
||||||
|
detail: '连不上或协议不对才算失败。收到 HTTP 响应就算成功,4xx 和 5xx 只显示状态码,不叫丢包。曲线上的延迟是这一次的总时间。',
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return MetricLine(
|
||||||
|
'无应答(未知)',
|
||||||
|
formatPct(summary.unknownPct),
|
||||||
|
detail: '无应答 ÷ 已完成。沉默不是丢包;明确的协议错误、拒绝和域名失败另看失败次数。',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MetricLine _latency(
|
||||||
|
String label,
|
||||||
|
double? value,
|
||||||
|
ProbeSummary summary, {
|
||||||
|
bool recent = false,
|
||||||
|
}) {
|
||||||
|
if (!summary.latencyStats && summary.ok > 0 && !recent) {
|
||||||
|
return MetricLine(label, '节点未提供', detail: '这份结果来自没有上报延迟分布的节点。当前延迟仍然可用。');
|
||||||
|
}
|
||||||
|
return MetricLine(
|
||||||
|
label,
|
||||||
|
formatMs(value),
|
||||||
|
detail: recent ? '最近一次成功的往返时间。没有成功时为 —。' : '只统计成功样本。没有成功时为 —。',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String formatDuration(Duration duration) {
|
||||||
|
final ms = duration.inMilliseconds;
|
||||||
|
if (ms < 0) {
|
||||||
|
return '—';
|
||||||
|
}
|
||||||
|
if (ms < 1000) {
|
||||||
|
return '$ms 毫秒';
|
||||||
|
}
|
||||||
|
final seconds = ms / 1000;
|
||||||
|
if (seconds < 60) {
|
||||||
|
return '${seconds.toStringAsFixed(1)} 秒';
|
||||||
|
}
|
||||||
|
final minutes = duration.inMinutes;
|
||||||
|
final rest = duration.inSeconds % 60;
|
||||||
|
return '$minutes 分 $rest 秒';
|
||||||
|
}
|
||||||
|
|
||||||
|
String formatClock(DateTime time) {
|
||||||
|
final local = time.toLocal();
|
||||||
|
String two(int value) => value.toString().padLeft(2, '0');
|
||||||
|
return '${local.year}-${two(local.month)}-${two(local.day)} ${two(local.hour)}:${two(local.minute)}:${two(local.second)}';
|
||||||
|
}
|
||||||
|
|
||||||
|
class MetricsPanel extends StatelessWidget {
|
||||||
|
const MetricsPanel({
|
||||||
|
super.key,
|
||||||
|
required this.summary,
|
||||||
|
required this.profileId,
|
||||||
|
required this.elapsed,
|
||||||
|
});
|
||||||
|
|
||||||
|
final ProbeSummary summary;
|
||||||
|
final String profileId;
|
||||||
|
final Duration elapsed;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final lines = metricLines(
|
||||||
|
summary: summary,
|
||||||
|
profileId: profileId,
|
||||||
|
elapsed: elapsed,
|
||||||
|
);
|
||||||
|
return Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: [
|
||||||
|
for (final line in lines)
|
||||||
|
Tooltip(
|
||||||
|
message: line.detail ?? '',
|
||||||
|
child: _chip('${line.label} ${line.value}'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SessionSummaryCard extends StatelessWidget {
|
||||||
|
const SessionSummaryCard({
|
||||||
|
super.key,
|
||||||
|
required this.report,
|
||||||
|
required this.profileId,
|
||||||
|
});
|
||||||
|
|
||||||
|
final SessionReport report;
|
||||||
|
final String profileId;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final address = describeAddress(
|
||||||
|
resolved: report.resolved,
|
||||||
|
usedAddress: report.usedAddress,
|
||||||
|
usedFamily: report.usedFamily,
|
||||||
|
fallbackText: report.fallbackText,
|
||||||
|
addressUnreported: report.addressUnreported,
|
||||||
|
usedIsFake: report.usedIsFake,
|
||||||
|
);
|
||||||
|
return _panel(
|
||||||
|
title: '本次结果',
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Text('开始 ${formatClock(report.startedAt)}'),
|
||||||
|
Text('结束 ${formatClock(report.endedAt)}'),
|
||||||
|
Text('用时 ${formatDuration(report.elapsed)}'),
|
||||||
|
Text('目标 ${report.target}'),
|
||||||
|
Text('类型 ${report.profileLabel}'),
|
||||||
|
Text('来源 ${report.sourceLabel}'),
|
||||||
|
if (address.used != null) Text(address.used!),
|
||||||
|
if (address.resolved != null) Text(address.resolved!),
|
||||||
|
if (address.unreported != null) Text(address.unreported!),
|
||||||
|
if (address.fallback != null) Text(address.fallback!),
|
||||||
|
if (address.fake)
|
||||||
|
const Text(
|
||||||
|
clashFakeIpNote,
|
||||||
|
style: TextStyle(color: Color(0xFF9A3412)),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
MetricsPanel(
|
||||||
|
summary: report.summary,
|
||||||
|
profileId: profileId,
|
||||||
|
elapsed: report.elapsed,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(
|
||||||
|
summaryLine(report.summary),
|
||||||
|
style: const TextStyle(color: muted, fontSize: 13),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _panel({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 _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)),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ import 'package:fl_chart/fl_chart.dart';
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import '../probe/probe_controller.dart';
|
import '../probe/probe_controller.dart';
|
||||||
|
import 'chart_selection.dart';
|
||||||
|
import 'format.dart';
|
||||||
|
|
||||||
const rttColor = Color(0xFF1F4E79);
|
const rttColor = Color(0xFF1F4E79);
|
||||||
const rateColor = Color(0xFF9A3412);
|
const rateColor = Color(0xFF9A3412);
|
||||||
@@ -9,20 +11,67 @@ const ink = Color(0xFF1C2430);
|
|||||||
const muted = Color(0xFF5E6872);
|
const muted = Color(0xFF5E6872);
|
||||||
const line = Color(0xFFE4DFD4);
|
const line = Color(0xFFE4DFD4);
|
||||||
|
|
||||||
class QualityCharts extends StatelessWidget {
|
class QualityCharts extends StatefulWidget {
|
||||||
const QualityCharts({
|
const QualityCharts({
|
||||||
super.key,
|
super.key,
|
||||||
required this.samples,
|
required this.samples,
|
||||||
required this.rateLabel,
|
required this.rateLabel,
|
||||||
required this.running,
|
required this.running,
|
||||||
|
required this.sessionId,
|
||||||
});
|
});
|
||||||
|
|
||||||
final List<ChartSample> samples;
|
final List<ChartSample> samples;
|
||||||
final String rateLabel;
|
final String rateLabel;
|
||||||
final bool running;
|
final bool running;
|
||||||
|
final int sessionId;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<QualityCharts> createState() => _QualityChartsState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _QualityChartsState extends State<QualityCharts> {
|
||||||
|
ChartSelection? _pin;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didUpdateWidget(QualityCharts oldWidget) {
|
||||||
|
super.didUpdateWidget(oldWidget);
|
||||||
|
final kept = nextChartSelection(
|
||||||
|
current: _pin,
|
||||||
|
sessionId: widget.sessionId,
|
||||||
|
sampleSecs: [for (final sample in widget.samples) sample.sec],
|
||||||
|
);
|
||||||
|
if (kept?.sec != _pin?.sec || kept?.sessionId != _pin?.sessionId) {
|
||||||
|
_pin = kept;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _pinAt(double sec) {
|
||||||
|
setState(() {
|
||||||
|
_pin = nextChartSelection(
|
||||||
|
current: _pin,
|
||||||
|
sessionId: widget.sessionId,
|
||||||
|
sampleSecs: [for (final sample in widget.samples) sample.sec],
|
||||||
|
tappedSec: sec,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ChartSample? get _pinnedSample {
|
||||||
|
final pin = _pin;
|
||||||
|
if (pin == null || pin.sessionId != widget.sessionId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (final sample in widget.samples) {
|
||||||
|
if ((sample.sec - pin.sec).abs() <= chartPinEpsilon) {
|
||||||
|
return sample;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final pinned = _pinnedSample;
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
@@ -34,29 +83,51 @@ class QualityCharts extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
|
Text(
|
||||||
|
pinned == null
|
||||||
|
? '点曲线上的一点可以钉住该时刻,松手后仍会保留。再点另一点会更换。'
|
||||||
|
: pinnedReadout(pinned, widget.rateLabel),
|
||||||
|
key: const Key('chart-pin'),
|
||||||
|
style: const TextStyle(color: ink, fontSize: 13, height: 1.4),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
_ChartCard(
|
_ChartCard(
|
||||||
title: '延迟',
|
title: '延迟',
|
||||||
unit: 'ms',
|
unit: 'ms',
|
||||||
samples: samples,
|
samples: widget.samples,
|
||||||
read: (sample) => sample.rttMs,
|
read: (sample) => sample.rttMs,
|
||||||
color: rttColor,
|
color: rttColor,
|
||||||
floor: 1,
|
floor: 1,
|
||||||
running: running,
|
running: widget.running,
|
||||||
|
pinnedSec: pinned?.sec,
|
||||||
|
onPin: _pinAt,
|
||||||
),
|
),
|
||||||
_ChartCard(
|
_ChartCard(
|
||||||
title: rateLabel,
|
title: widget.rateLabel,
|
||||||
unit: '%',
|
unit: '%',
|
||||||
samples: samples,
|
samples: widget.samples,
|
||||||
read: (sample) => sample.ratePct,
|
read: (sample) => sample.ratePct,
|
||||||
color: rateColor,
|
color: rateColor,
|
||||||
floor: 10,
|
floor: 10,
|
||||||
running: running,
|
running: widget.running,
|
||||||
|
pinnedSec: pinned?.sec,
|
||||||
|
onPin: _pinAt,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String pinnedReadout(ChartSample sample, String rateLabel) {
|
||||||
|
final latency = sample.rttMs == null
|
||||||
|
? '这一刻没有延迟'
|
||||||
|
: '延迟 ${formatMs(sample.rttMs)}';
|
||||||
|
final rate = sample.ratePct == null
|
||||||
|
? '$rateLabel —'
|
||||||
|
: '$rateLabel ${formatPct(sample.ratePct)}';
|
||||||
|
return '已选 ${sample.sec.toStringAsFixed(1)} 秒 · $latency · $rate';
|
||||||
|
}
|
||||||
|
|
||||||
class _Swatch extends StatelessWidget {
|
class _Swatch extends StatelessWidget {
|
||||||
const _Swatch({required this.color, required this.label});
|
const _Swatch({required this.color, required this.label});
|
||||||
|
|
||||||
@@ -92,6 +163,8 @@ class _ChartCard extends StatelessWidget {
|
|||||||
required this.color,
|
required this.color,
|
||||||
required this.floor,
|
required this.floor,
|
||||||
required this.running,
|
required this.running,
|
||||||
|
required this.pinnedSec,
|
||||||
|
required this.onPin,
|
||||||
});
|
});
|
||||||
|
|
||||||
final String title;
|
final String title;
|
||||||
@@ -101,6 +174,8 @@ class _ChartCard extends StatelessWidget {
|
|||||||
final Color color;
|
final Color color;
|
||||||
final double floor;
|
final double floor;
|
||||||
final bool running;
|
final bool running;
|
||||||
|
final double? pinnedSec;
|
||||||
|
final void Function(double sec) onPin;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -132,9 +207,7 @@ class _ChartCard extends StatelessWidget {
|
|||||||
? _lineChart(spots)
|
? _lineChart(spots)
|
||||||
: Center(
|
: Center(
|
||||||
child: Text(
|
child: Text(
|
||||||
running
|
running ? '正在等待第一次完成的探测。未完成的不会画成 100%。' : '暂无已完成的探测',
|
||||||
? '正在等待第一次完成的探测。未完成的不会画成 100%。'
|
|
||||||
: '暂无已完成的探测',
|
|
||||||
style: const TextStyle(color: muted),
|
style: const TextStyle(color: muted),
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
),
|
),
|
||||||
@@ -190,7 +263,8 @@ class _ChartCard extends StatelessWidget {
|
|||||||
show: true,
|
show: true,
|
||||||
drawVerticalLine: false,
|
drawVerticalLine: false,
|
||||||
horizontalInterval: yInterval,
|
horizontalInterval: yInterval,
|
||||||
getDrawingHorizontalLine: (_) => const FlLine(color: line, strokeWidth: 1),
|
getDrawingHorizontalLine: (_) =>
|
||||||
|
const FlLine(color: line, strokeWidth: 1),
|
||||||
),
|
),
|
||||||
borderData: FlBorderData(
|
borderData: FlBorderData(
|
||||||
show: true,
|
show: true,
|
||||||
@@ -200,14 +274,19 @@ class _ChartCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
titlesData: FlTitlesData(
|
titlesData: FlTitlesData(
|
||||||
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
topTitles: const AxisTitles(
|
||||||
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
sideTitles: SideTitles(showTitles: false),
|
||||||
|
),
|
||||||
|
rightTitles: const AxisTitles(
|
||||||
|
sideTitles: SideTitles(showTitles: false),
|
||||||
|
),
|
||||||
leftTitles: AxisTitles(
|
leftTitles: AxisTitles(
|
||||||
sideTitles: SideTitles(
|
sideTitles: SideTitles(
|
||||||
showTitles: true,
|
showTitles: true,
|
||||||
reservedSize: 40,
|
reservedSize: 40,
|
||||||
interval: yInterval,
|
interval: yInterval,
|
||||||
getTitlesWidget: (value, meta) => _axisLabel(_formatTick(value, maxY)),
|
getTitlesWidget: (value, meta) =>
|
||||||
|
_axisLabel(_formatTick(value, maxY)),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
bottomTitles: AxisTitles(
|
bottomTitles: AxisTitles(
|
||||||
@@ -220,15 +299,46 @@ class _ChartCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
lineTouchData: const LineTouchData(handleBuiltInTouches: true),
|
extraLinesData: ExtraLinesData(
|
||||||
|
verticalLines: [
|
||||||
|
if (pinnedSec != null)
|
||||||
|
VerticalLine(
|
||||||
|
x: pinnedSec!,
|
||||||
|
color: color.withValues(alpha: 0.85),
|
||||||
|
strokeWidth: 1.5,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
lineTouchData: LineTouchData(
|
||||||
|
handleBuiltInTouches: false,
|
||||||
|
touchSpotThreshold: 18,
|
||||||
|
touchCallback: (event, response) {
|
||||||
|
if (event is! FlTapUpEvent) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final spots = response?.lineBarSpots;
|
||||||
|
if (spots == null || spots.isEmpty) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onPin(spots.first.x);
|
||||||
|
},
|
||||||
|
),
|
||||||
lineBarsData: [
|
lineBarsData: [
|
||||||
LineChartBarData(
|
LineChartBarData(
|
||||||
spots: spots,
|
spots: spots,
|
||||||
isCurved: false,
|
isCurved: false,
|
||||||
color: color,
|
color: color,
|
||||||
barWidth: 2,
|
barWidth: 2,
|
||||||
dotData: const FlDotData(show: false),
|
dotData: FlDotData(
|
||||||
belowBarData: BarAreaData(show: true, color: color.withValues(alpha: 0.10)),
|
show: pinnedSec != null,
|
||||||
|
checkToShowDot: (spot, _) =>
|
||||||
|
pinnedSec != null &&
|
||||||
|
(spot.x - pinnedSec!).abs() <= chartPinEpsilon,
|
||||||
|
),
|
||||||
|
belowBarData: BarAreaData(
|
||||||
|
show: true,
|
||||||
|
color: color.withValues(alpha: 0.10),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -0,0 +1,179 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../update/apply_update.dart';
|
||||||
|
import '../update/update_check.dart';
|
||||||
|
import '../version.dart';
|
||||||
|
|
||||||
|
class SettingsPage extends StatefulWidget {
|
||||||
|
const SettingsPage({
|
||||||
|
super.key,
|
||||||
|
required this.allowIPv4,
|
||||||
|
required this.allowIPv6,
|
||||||
|
required this.autoUpdate,
|
||||||
|
required this.onAllowIPv4,
|
||||||
|
required this.onAllowIPv6,
|
||||||
|
required this.onAutoUpdate,
|
||||||
|
});
|
||||||
|
|
||||||
|
final bool allowIPv4;
|
||||||
|
final bool allowIPv6;
|
||||||
|
final bool autoUpdate;
|
||||||
|
final ValueChanged<bool> onAllowIPv4;
|
||||||
|
final ValueChanged<bool> onAllowIPv6;
|
||||||
|
final ValueChanged<bool> onAutoUpdate;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<SettingsPage> createState() => _SettingsPageState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SettingsPageState extends State<SettingsPage> {
|
||||||
|
late bool _allow4;
|
||||||
|
late bool _allow6;
|
||||||
|
late bool _auto;
|
||||||
|
var _checking = false;
|
||||||
|
String _message = '';
|
||||||
|
UpdateOffer? _offer;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_allow4 = widget.allowIPv4;
|
||||||
|
_allow6 = widget.allowIPv6;
|
||||||
|
_auto = widget.autoUpdate;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _check() async {
|
||||||
|
setState(() {
|
||||||
|
_checking = true;
|
||||||
|
_message = '';
|
||||||
|
_offer = null;
|
||||||
|
});
|
||||||
|
final result = await checkForUpdate();
|
||||||
|
if (!mounted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() {
|
||||||
|
_checking = false;
|
||||||
|
_message = result.message;
|
||||||
|
_offer = result.offer;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _install() async {
|
||||||
|
final offer = _offer;
|
||||||
|
if (offer == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() => _checking = true);
|
||||||
|
final message = await installOffer(offer);
|
||||||
|
if (!mounted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() {
|
||||||
|
_checking = false;
|
||||||
|
_message = message;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
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: 760),
|
||||||
|
child: ListView(
|
||||||
|
padding: EdgeInsets.fromLTRB(wide ? 24 : 12, 8, wide ? 24 : 12, 28),
|
||||||
|
children: [
|
||||||
|
SwitchListTile(
|
||||||
|
title: const Text('允许 IPv4'),
|
||||||
|
subtitle: const Text('关掉以后,解析结果里的 IPv4 不会用来发包。直接填写 IPv4 地址也会被拒绝。'),
|
||||||
|
value: _allow4,
|
||||||
|
onChanged: (value) {
|
||||||
|
setState(() => _allow4 = value);
|
||||||
|
widget.onAllowIPv4(value);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
SwitchListTile(
|
||||||
|
title: const Text('允许 IPv6'),
|
||||||
|
subtitle: const Text('关掉以后,解析结果里的 IPv6 不会用来发包。直接填写 IPv6 地址也会被拒绝。'),
|
||||||
|
value: _allow6,
|
||||||
|
onChanged: (value) {
|
||||||
|
setState(() => _allow6 = value);
|
||||||
|
widget.onAllowIPv6(value);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.fromLTRB(16, 0, 16, 8),
|
||||||
|
child: Text(
|
||||||
|
'两个都关掉时不能开始探测。远程节点会收到同样的选择。1.1.2 的节点还不会遵守这个开关,遇到这种情况会提示升级。',
|
||||||
|
style: TextStyle(color: Color(0xFF5C656B), fontSize: 13, height: 1.4),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const Divider(),
|
||||||
|
SwitchListTile(
|
||||||
|
title: const Text('自动检查更新'),
|
||||||
|
subtitle: const Text('默认打开。关闭后,启动时不检查,也不会自动下载。'),
|
||||||
|
value: _auto,
|
||||||
|
onChanged: (value) {
|
||||||
|
setState(() => _auto = value);
|
||||||
|
widget.onAutoUpdate(value);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
|
||||||
|
child: Text(
|
||||||
|
'当前版本 $appVersion(构建 $appBuild)。1.1.2 没有自更新,从 1.1.2 升到 1.1.3 仍要手动安装。从这一版起才会自己检查。先试 GitHub,连不上再试言灸的 Git。\n\n要在没有新版本时试这个功能,可以把环境变量 NQ_UPDATE_GITHUB_API 指到一个同样格式的测试地址,NQ_UPDATE_GITEA_API 是备用。',
|
||||||
|
style: const TextStyle(color: Color(0xFF5C656B), fontSize: 13, height: 1.4),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (Platform.isAndroid)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.fromLTRB(16, 0, 16, 8),
|
||||||
|
child: Text(
|
||||||
|
'在 Android 上安装时,系统会弹出安装确认。这一步不能跳过。',
|
||||||
|
style: TextStyle(color: Color(0xFF9A3412), fontSize: 13, height: 1.4),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||||
|
child: Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: [
|
||||||
|
FilledButton(
|
||||||
|
onPressed: _checking ? null : _check,
|
||||||
|
child: Text(_checking ? '正在检查' : '检查更新'),
|
||||||
|
),
|
||||||
|
if (_offer != null)
|
||||||
|
FilledButton(
|
||||||
|
onPressed: _checking ? null : _install,
|
||||||
|
child: const Text('下载并安装'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (_message.isNotEmpty)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
|
||||||
|
child: Text(_message),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:ffi' show Abi;
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
import '../version.dart';
|
||||||
|
import 'installer.dart';
|
||||||
|
import 'update_check.dart';
|
||||||
|
|
||||||
|
class UpdateResult {
|
||||||
|
const UpdateResult({required this.message, this.offer});
|
||||||
|
|
||||||
|
final String message;
|
||||||
|
final UpdateOffer? offer;
|
||||||
|
}
|
||||||
|
|
||||||
|
const platformChannel = MethodChannel('dev.netquality/platform');
|
||||||
|
|
||||||
|
Future<UpdateResult> checkForUpdate() async {
|
||||||
|
final arch = await _arch();
|
||||||
|
if (arch.isEmpty) {
|
||||||
|
return const UpdateResult(message: '认不出这台设备的系统或 CPU,没有下载安装包');
|
||||||
|
}
|
||||||
|
final endpoints = UpdateEndpoints(
|
||||||
|
github: Platform.environment['NQ_UPDATE_GITHUB_API'] ??
|
||||||
|
UpdateEndpoints.githubDefault,
|
||||||
|
gitea: Platform.environment['NQ_UPDATE_GITEA_API'] ??
|
||||||
|
UpdateEndpoints.giteaDefault,
|
||||||
|
);
|
||||||
|
final check = await findUpdate(
|
||||||
|
current: appVersion,
|
||||||
|
endpoints: endpoints,
|
||||||
|
os: _os(),
|
||||||
|
arch: arch,
|
||||||
|
fetch: (url) => _getText(url),
|
||||||
|
);
|
||||||
|
if (check.offer == null) {
|
||||||
|
return UpdateResult(message: check.message);
|
||||||
|
}
|
||||||
|
return UpdateResult(
|
||||||
|
message: '发现 ${check.offer!.version}。可以下载并覆盖安装。',
|
||||||
|
offer: check.offer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String> installOffer(UpdateOffer offer) async {
|
||||||
|
final bytes = await _getBytes(Uri.parse(offer.assetUrl));
|
||||||
|
if (bytes == null) {
|
||||||
|
return '安装包没有下载下来';
|
||||||
|
}
|
||||||
|
var checksumNote = '';
|
||||||
|
if (offer.checksumUrl != null && offer.checksumUrl!.isNotEmpty) {
|
||||||
|
final sums = await _getText(Uri.parse(offer.checksumUrl!));
|
||||||
|
if (sums == null || !checksumMatches(sums, offer.assetName, bytes)) {
|
||||||
|
return '校验和没有对上,已停止安装';
|
||||||
|
}
|
||||||
|
checksumNote = '校验通过。';
|
||||||
|
} else {
|
||||||
|
checksumNote = '这次发布没有校验和文件,已按下载的包继续。';
|
||||||
|
}
|
||||||
|
if (Platform.isAndroid) {
|
||||||
|
final temp = await Directory.systemTemp.createTemp('nq-update-');
|
||||||
|
final file = File('${temp.path}/updates/${offer.assetName}');
|
||||||
|
await file.parent.create(recursive: true);
|
||||||
|
await file.writeAsBytes(bytes, flush: true);
|
||||||
|
await platformChannel.invokeMethod<void>('installApk', {'path': file.path});
|
||||||
|
return '$checksumNote安装包已交给系统。请在系统弹出的确认里完成安装,这一步不能跳过。';
|
||||||
|
}
|
||||||
|
final extracted = await Directory.systemTemp.createTemp('nq-update-');
|
||||||
|
extractArchive(bytes, offer.assetName, extracted);
|
||||||
|
final installDir = File(Platform.resolvedExecutable).parent;
|
||||||
|
if (Platform.isWindows) {
|
||||||
|
await _windowsReplace(extracted, installDir);
|
||||||
|
return '$checksumNote已下载。程序即将退出,随后覆盖安装并重新打开。';
|
||||||
|
}
|
||||||
|
copyIntoInstall(extracted, installDir);
|
||||||
|
try {
|
||||||
|
await Process.run('chmod', ['755', Platform.resolvedExecutable]);
|
||||||
|
} on ProcessException {
|
||||||
|
// The existing file is often already executable.
|
||||||
|
}
|
||||||
|
await Process.start(
|
||||||
|
Platform.resolvedExecutable,
|
||||||
|
const [],
|
||||||
|
mode: ProcessStartMode.detached,
|
||||||
|
);
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _windowsReplace(Directory extracted, Directory installDir) async {
|
||||||
|
final script = File(
|
||||||
|
'${Directory.systemTemp.path}${Platform.pathSeparator}nq-update-$pid.ps1',
|
||||||
|
);
|
||||||
|
final from = _ps(extracted.path);
|
||||||
|
final to = _ps(installDir.path);
|
||||||
|
final exe = _ps(Platform.resolvedExecutable);
|
||||||
|
await script.writeAsString('''
|
||||||
|
\$target = $pid
|
||||||
|
\$from = $from
|
||||||
|
\$to = $to
|
||||||
|
while (Get-Process -Id \$target -ErrorAction SilentlyContinue) {
|
||||||
|
Start-Sleep -Milliseconds 200
|
||||||
|
}
|
||||||
|
Copy-Item -Path (Join-Path \$from '*') -Destination \$to -Recurse -Force
|
||||||
|
Start-Process -FilePath $exe
|
||||||
|
''');
|
||||||
|
await Process.start('powershell', [
|
||||||
|
'-NoProfile',
|
||||||
|
'-ExecutionPolicy',
|
||||||
|
'Bypass',
|
||||||
|
'-File',
|
||||||
|
script.path,
|
||||||
|
]);
|
||||||
|
exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _ps(String path) => "'${path.replaceAll("'", "''")}'";
|
||||||
|
|
||||||
|
String _os() {
|
||||||
|
if (Platform.isAndroid) {
|
||||||
|
return 'android';
|
||||||
|
}
|
||||||
|
if (Platform.isWindows) {
|
||||||
|
return 'windows';
|
||||||
|
}
|
||||||
|
return 'linux';
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String> _arch() async {
|
||||||
|
if (Platform.isAndroid) {
|
||||||
|
try {
|
||||||
|
final abi = await platformChannel.invokeMethod<String>('abi');
|
||||||
|
return abi ?? '';
|
||||||
|
} on PlatformException {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch (Abi.current()) {
|
||||||
|
case Abi.linuxX64:
|
||||||
|
case Abi.windowsX64:
|
||||||
|
return 'amd64';
|
||||||
|
case Abi.linuxArm64:
|
||||||
|
case Abi.windowsArm64:
|
||||||
|
return 'arm64';
|
||||||
|
default:
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String?> _getText(Uri url) async {
|
||||||
|
final bytes = await _getBytes(url);
|
||||||
|
if (bytes == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return String.fromCharCodes(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<List<int>?> _getBytes(Uri url) async {
|
||||||
|
final client = HttpClient();
|
||||||
|
try {
|
||||||
|
final request = await client.getUrl(url);
|
||||||
|
final response = await request.close().timeout(const Duration(minutes: 2));
|
||||||
|
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final chunks = <int>[];
|
||||||
|
await for (final chunk in response) {
|
||||||
|
chunks.addAll(chunk);
|
||||||
|
}
|
||||||
|
return chunks;
|
||||||
|
} on Object {
|
||||||
|
return null;
|
||||||
|
} finally {
|
||||||
|
client.close(force: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:archive/archive.dart';
|
||||||
|
import 'package:crypto/crypto.dart';
|
||||||
|
|
||||||
|
/// True when [sums] publishes a matching SHA-256 line for [fileName].
|
||||||
|
/// A published file that does not mention the asset is a failure, not a skip.
|
||||||
|
bool checksumMatches(String sums, String fileName, List<int> bytes) {
|
||||||
|
final want = sha256.convert(bytes).toString().toLowerCase();
|
||||||
|
final base = fileName.split(RegExp(r'[\\/]')).last;
|
||||||
|
var mentioned = false;
|
||||||
|
for (final raw in const LineSplitter().convert(sums)) {
|
||||||
|
final line = raw.trim();
|
||||||
|
if (line.isEmpty || line.startsWith('#')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final match = RegExp(r'^([0-9a-fA-F]{64})\s+\*?(\S+)\s*$').firstMatch(line);
|
||||||
|
if (match == null) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final name = match.group(2)!.split(RegExp(r'[\\/]')).last;
|
||||||
|
if (name != base) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
mentioned = true;
|
||||||
|
if (match.group(1)!.toLowerCase() == want) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!mentioned) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extracts a zip or tar.gz into [dest]. Paths that climb out of [dest] are skipped.
|
||||||
|
void extractArchive(List<int> bytes, String fileName, Directory dest) {
|
||||||
|
final Archive archive;
|
||||||
|
final lower = fileName.toLowerCase();
|
||||||
|
if (lower.endsWith('.tar.gz') || lower.endsWith('.tgz')) {
|
||||||
|
archive = TarDecoder().decodeBytes(GZipDecoder().decodeBytes(bytes));
|
||||||
|
} else if (lower.endsWith('.zip')) {
|
||||||
|
archive = ZipDecoder().decodeBytes(bytes);
|
||||||
|
} else {
|
||||||
|
throw const FormatException('只支持 zip 和 tar.gz');
|
||||||
|
}
|
||||||
|
final root = _singleRoot(archive);
|
||||||
|
for (final file in archive) {
|
||||||
|
if (!file.isFile) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
var name = file.name.replaceAll('\\', '/');
|
||||||
|
while (name.startsWith('./')) {
|
||||||
|
name = name.substring(2);
|
||||||
|
}
|
||||||
|
if (root.isNotEmpty && name.startsWith('$root/')) {
|
||||||
|
name = name.substring(root.length + 1);
|
||||||
|
}
|
||||||
|
if (name.isEmpty || name.startsWith('/') || name.contains('../')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final out = File('${dest.path}/$name');
|
||||||
|
final parent = out.parent.path;
|
||||||
|
if (!_inside(dest.path, parent) && parent != dest.path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.parent.createSync(recursive: true);
|
||||||
|
out.writeAsBytesSync(file.content as List<int>);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copies extracted files onto the existing install directory.
|
||||||
|
/// Files already there and not in the archive are left in place, so a data
|
||||||
|
/// file sitting beside the program is not wiped. Nothing outside [installDir]
|
||||||
|
/// is written.
|
||||||
|
void copyIntoInstall(Directory extracted, Directory installDir) {
|
||||||
|
if (!_inside(installDir.path, extracted.path) &&
|
||||||
|
extracted.path != installDir.path) {
|
||||||
|
// The source may be a temp directory. That is allowed.
|
||||||
|
}
|
||||||
|
for (final entity in extracted.listSync(recursive: true)) {
|
||||||
|
if (entity is! File) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final relative = entity.path.substring(extracted.path.length);
|
||||||
|
final trimmed = relative.replaceAll('\\', '/').replaceFirst(RegExp(r'^/'), '');
|
||||||
|
if (trimmed.isEmpty || trimmed.contains('../')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final target = File('${installDir.path}/$trimmed');
|
||||||
|
if (!_inside(installDir.path, target.parent.path) &&
|
||||||
|
target.parent.path != installDir.path) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
target.parent.createSync(recursive: true);
|
||||||
|
entity.copySync(target.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _singleRoot(Archive archive) {
|
||||||
|
String? root;
|
||||||
|
for (final file in archive) {
|
||||||
|
final name = file.name.replaceAll('\\', '/');
|
||||||
|
final slash = name.indexOf('/');
|
||||||
|
if (slash <= 0) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
final top = name.substring(0, slash);
|
||||||
|
if (root == null) {
|
||||||
|
root = top;
|
||||||
|
} else if (root != top) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return root ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _inside(String root, String child) {
|
||||||
|
final prefix = root.endsWith(Platform.pathSeparator)
|
||||||
|
? root
|
||||||
|
: '$root${Platform.pathSeparator}';
|
||||||
|
return child == root || child.startsWith(prefix);
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
/// Numeric version. A leading v and a +build suffix are ignored.
|
||||||
|
class SemVer implements Comparable<SemVer> {
|
||||||
|
const SemVer(this.major, this.minor, this.patch);
|
||||||
|
|
||||||
|
final int major;
|
||||||
|
final int minor;
|
||||||
|
final int patch;
|
||||||
|
|
||||||
|
static SemVer? parse(String raw) {
|
||||||
|
var text = raw.trim();
|
||||||
|
if (text.startsWith('v') || text.startsWith('V')) {
|
||||||
|
text = text.substring(1);
|
||||||
|
}
|
||||||
|
final plus = text.indexOf('+');
|
||||||
|
if (plus >= 0) {
|
||||||
|
text = text.substring(0, plus);
|
||||||
|
}
|
||||||
|
final dash = text.indexOf('-');
|
||||||
|
if (dash >= 0) {
|
||||||
|
text = text.substring(0, dash);
|
||||||
|
}
|
||||||
|
final parts = text.split('.');
|
||||||
|
if (parts.length < 3) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final major = int.tryParse(parts[0]);
|
||||||
|
final minor = int.tryParse(parts[1]);
|
||||||
|
final patch = int.tryParse(parts[2]);
|
||||||
|
if (major == null || minor == null || patch == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return SemVer(major, minor, patch);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isNewerThan(SemVer other) => compareTo(other) > 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
int compareTo(SemVer other) {
|
||||||
|
if (major != other.major) {
|
||||||
|
return major.compareTo(other.major);
|
||||||
|
}
|
||||||
|
if (minor != other.minor) {
|
||||||
|
return minor.compareTo(other.minor);
|
||||||
|
}
|
||||||
|
return patch.compareTo(other.patch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ReleaseFile {
|
||||||
|
const ReleaseFile({required this.name, required this.url});
|
||||||
|
|
||||||
|
final String name;
|
||||||
|
final String url;
|
||||||
|
}
|
||||||
|
|
||||||
|
class UpdateEndpoints {
|
||||||
|
const UpdateEndpoints({required this.github, required this.gitea});
|
||||||
|
|
||||||
|
static const githubDefault =
|
||||||
|
'https://api.github.com/repos/yanjiu0721/netquality/releases/latest';
|
||||||
|
static const giteaDefault =
|
||||||
|
'https://git.yanjiu.ltd/api/v1/repos/YanJiu/netquality/releases/latest';
|
||||||
|
|
||||||
|
final String github;
|
||||||
|
final String gitea;
|
||||||
|
}
|
||||||
|
|
||||||
|
class UpdateOffer {
|
||||||
|
const UpdateOffer({
|
||||||
|
required this.version,
|
||||||
|
required this.assetName,
|
||||||
|
required this.assetUrl,
|
||||||
|
this.checksumName,
|
||||||
|
this.checksumUrl,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String version;
|
||||||
|
final String assetName;
|
||||||
|
final String assetUrl;
|
||||||
|
final String? checksumName;
|
||||||
|
final String? checksumUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
class UpdateCheck {
|
||||||
|
const UpdateCheck({this.offer, required this.reachable, this.message = ''});
|
||||||
|
|
||||||
|
final UpdateOffer? offer;
|
||||||
|
final bool reachable;
|
||||||
|
final String message;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Picks the client archive for this OS and CPU. Server packages are ignored.
|
||||||
|
String? pickClientAsset(
|
||||||
|
List<ReleaseFile> assets, {
|
||||||
|
required String os,
|
||||||
|
required String arch,
|
||||||
|
}) {
|
||||||
|
final wantOs = os.toLowerCase();
|
||||||
|
final wantArch = arch.toLowerCase();
|
||||||
|
for (final asset in assets) {
|
||||||
|
final name = asset.name.toLowerCase();
|
||||||
|
if (name.contains('server') || name.contains('reflector')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (wantOs == 'android') {
|
||||||
|
if (name.endsWith('.apk') && name.contains(wantArch)) {
|
||||||
|
return asset.name;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final archOk =
|
||||||
|
name.contains(wantArch) ||
|
||||||
|
(wantArch == 'amd64' && name.contains('x86_64')) ||
|
||||||
|
(wantArch == 'arm64' && name.contains('aarch64'));
|
||||||
|
if (!archOk || !name.contains(wantOs)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (wantOs == 'windows' && (name.endsWith('.zip') || name.endsWith('.exe'))) {
|
||||||
|
return asset.name;
|
||||||
|
}
|
||||||
|
if (wantOs == 'linux' &&
|
||||||
|
(name.endsWith('.tar.gz') || name.endsWith('.tgz'))) {
|
||||||
|
return asset.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool looksLikeChecksum(String name) {
|
||||||
|
final lower = name.toLowerCase();
|
||||||
|
return lower.contains('sha256') || lower.contains('checksum');
|
||||||
|
}
|
||||||
|
|
||||||
|
UpdateCheck interpretRelease({
|
||||||
|
required String current,
|
||||||
|
required String? body,
|
||||||
|
required String os,
|
||||||
|
required String arch,
|
||||||
|
}) {
|
||||||
|
if (body == null || body.trim().isEmpty) {
|
||||||
|
return const UpdateCheck(reachable: false, message: '检查更新失败');
|
||||||
|
}
|
||||||
|
Object? decoded;
|
||||||
|
try {
|
||||||
|
decoded = jsonDecode(body);
|
||||||
|
} on FormatException {
|
||||||
|
return const UpdateCheck(reachable: false, message: '检查更新失败');
|
||||||
|
}
|
||||||
|
if (decoded is! Map) {
|
||||||
|
return const UpdateCheck(reachable: false, message: '检查更新失败');
|
||||||
|
}
|
||||||
|
final tag = decoded['tag_name'];
|
||||||
|
final remote = tag is String ? SemVer.parse(tag) : null;
|
||||||
|
final local = SemVer.parse(current);
|
||||||
|
if (remote == null || local == null) {
|
||||||
|
return const UpdateCheck(reachable: true, message: '发布说明里的版本号无法比较');
|
||||||
|
}
|
||||||
|
if (!remote.isNewerThan(local)) {
|
||||||
|
return UpdateCheck(reachable: true, message: '当前已经是 $current');
|
||||||
|
}
|
||||||
|
final assets = <ReleaseFile>[];
|
||||||
|
final rawAssets = decoded['assets'];
|
||||||
|
if (rawAssets is List) {
|
||||||
|
for (final item in rawAssets) {
|
||||||
|
if (item is! Map) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final name = item['name'];
|
||||||
|
final url = item['browser_download_url'];
|
||||||
|
final link = url is String ? url : '';
|
||||||
|
if (name is String && link.isNotEmpty) {
|
||||||
|
assets.add(ReleaseFile(name: name, url: link));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final pickedName = pickClientAsset(assets, os: os, arch: arch);
|
||||||
|
if (pickedName == null) {
|
||||||
|
return UpdateCheck(
|
||||||
|
reachable: true,
|
||||||
|
message: '发现 ${remote.major}.${remote.minor}.${remote.patch},但没有适合这台设备的安装包',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final picked = assets.firstWhere((asset) => asset.name == pickedName);
|
||||||
|
ReleaseFile? sums;
|
||||||
|
for (final asset in assets) {
|
||||||
|
if (looksLikeChecksum(asset.name)) {
|
||||||
|
sums = asset;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return UpdateCheck(
|
||||||
|
reachable: true,
|
||||||
|
offer: UpdateOffer(
|
||||||
|
version: '${remote.major}.${remote.minor}.${remote.patch}',
|
||||||
|
assetName: picked.name,
|
||||||
|
assetUrl: picked.url,
|
||||||
|
checksumName: sums?.name,
|
||||||
|
checksumUrl: sums?.url,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<UpdateCheck> findUpdate({
|
||||||
|
required String current,
|
||||||
|
required UpdateEndpoints endpoints,
|
||||||
|
required Future<String?> Function(Uri url) fetch,
|
||||||
|
required String os,
|
||||||
|
required String arch,
|
||||||
|
}) async {
|
||||||
|
String? body;
|
||||||
|
try {
|
||||||
|
body = await fetch(Uri.parse(endpoints.github));
|
||||||
|
} on Object {
|
||||||
|
body = null;
|
||||||
|
}
|
||||||
|
var check = interpretRelease(current: current, body: body, os: os, arch: arch);
|
||||||
|
if (!check.reachable) {
|
||||||
|
try {
|
||||||
|
body = await fetch(Uri.parse(endpoints.gitea));
|
||||||
|
} on Object {
|
||||||
|
body = null;
|
||||||
|
}
|
||||||
|
check = interpretRelease(current: current, body: body, os: os, arch: arch);
|
||||||
|
if (!check.reachable) {
|
||||||
|
return const UpdateCheck(
|
||||||
|
reachable: false,
|
||||||
|
message: 'GitHub 和备用源都连不上,没有检查到更新',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return check;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
const appVersion = '1.1.3';
|
||||||
|
const appBuild = 6;
|
||||||
|
const appAttribution = '言灸';
|
||||||
|
const appLicense = 'AGPL-3.0-only';
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# 网络质量探测 · Linux 桌面客户端
|
# 网络质量探测 · Linux 桌面客户端
|
||||||
|
|
||||||
这是 1.1.1 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。
|
这是 1.1.3 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。HTTP 探测还需要同一目录里的 `netquality-reflector`。
|
||||||
|
|
||||||
## 先安装系统库
|
## 先安装系统库
|
||||||
|
|
||||||
|
|||||||
+17
-1
@@ -1,6 +1,14 @@
|
|||||||
# Generated by pub
|
# Generated by pub
|
||||||
# See https://dart.dev/tools/pub/glossary#lockfile
|
# See https://dart.dev/tools/pub/glossary#lockfile
|
||||||
packages:
|
packages:
|
||||||
|
archive:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: archive
|
||||||
|
sha256: "2fda90592c0afd219c5e285618a98da835cd10df38372666093d25dfe457a2d0"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "4.7.1"
|
||||||
args:
|
args:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -58,7 +66,7 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "1.19.1"
|
version: "1.19.1"
|
||||||
crypto:
|
crypto:
|
||||||
dependency: transitive
|
dependency: "direct main"
|
||||||
description:
|
description:
|
||||||
name: crypto
|
name: crypto
|
||||||
sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4
|
sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4
|
||||||
@@ -320,6 +328,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "2.1.8"
|
version: "2.1.8"
|
||||||
|
posix:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: posix
|
||||||
|
sha256: "613646d076944f3acc125830af935b48d4b8a57a388691547bbfd25b434f4d63"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "6.5.4"
|
||||||
pub_semver:
|
pub_semver:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|||||||
+3
-1
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
|||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
# In Windows, build-name is used as the major, minor, and patch parts
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
# of the product and file versions while build-number is used as the build suffix.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 1.1.1+4
|
version: 1.1.3+6
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.13.7
|
sdk: ^3.13.7
|
||||||
@@ -37,6 +37,8 @@ dependencies:
|
|||||||
fl_chart: ^1.3.0
|
fl_chart: ^1.3.0
|
||||||
path_provider: ^2.1.5
|
path_provider: ^2.1.5
|
||||||
shared_preferences: ^2.5.6
|
shared_preferences: ^2.5.6
|
||||||
|
archive: ^4.0.7
|
||||||
|
crypto: ^3.0.6
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/content/release_history.dart';
|
||||||
|
import 'package:netquality/metrics/sample_book.dart';
|
||||||
|
import 'package:netquality/ui/address_text.dart';
|
||||||
|
import 'package:netquality/ui/chart_selection.dart';
|
||||||
|
import 'package:netquality/version.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('resolved addresses are not shown as the address in use', () {
|
||||||
|
const resolved = [
|
||||||
|
ResolvedAddress(address: '2001:db8::1', family: 'IPv6'),
|
||||||
|
ResolvedAddress(address: '203.0.113.5', family: 'IPv4'),
|
||||||
|
];
|
||||||
|
final onlyResolved = describeAddress(resolved: resolved);
|
||||||
|
expect(onlyResolved.used, isNull);
|
||||||
|
expect(onlyResolved.resolved, contains('解析到'));
|
||||||
|
expect(onlyResolved.resolved, contains('2001:db8::1'));
|
||||||
|
expect(onlyResolved.resolved, isNot(contains('实际地址')));
|
||||||
|
|
||||||
|
final used = describeAddress(
|
||||||
|
resolved: resolved,
|
||||||
|
usedAddress: '203.0.113.5',
|
||||||
|
usedFamily: 'IPv4',
|
||||||
|
fallbackText: '已改用 IPv4',
|
||||||
|
);
|
||||||
|
expect(used.used, '实际地址 203.0.113.5(IPv4)');
|
||||||
|
expect(used.resolved, contains('2001:db8::1'));
|
||||||
|
expect(used.fallback, '已改用 IPv4');
|
||||||
|
|
||||||
|
final oldNode = describeAddress(
|
||||||
|
resolved: const [],
|
||||||
|
addressUnreported: true,
|
||||||
|
);
|
||||||
|
expect(oldNode.used, isNull);
|
||||||
|
expect(oldNode.unreported, '节点没有报告实际使用的地址');
|
||||||
|
|
||||||
|
final missing = ProbeSample.fromJson({
|
||||||
|
'seq': 1,
|
||||||
|
'status': 'ok',
|
||||||
|
'kind': 'probe',
|
||||||
|
'rttMs': 3,
|
||||||
|
'summary': {'sent': 1, 'ok': 1},
|
||||||
|
});
|
||||||
|
expect(missing.detail['address'], isNull);
|
||||||
|
final parsed = readResolvedList({
|
||||||
|
'resolved': [
|
||||||
|
{'address': '2001:db8::1', 'family': 'IPv6'},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(parsed.single.address, '2001:db8::1');
|
||||||
|
expect(readResolvedList({'jobId': 'abc'}), isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a pinned chart point stays put until it scrolls off or the session changes', () {
|
||||||
|
const first = ChartSelection(sec: 1.5, sessionId: 3);
|
||||||
|
final kept = nextChartSelection(
|
||||||
|
current: first,
|
||||||
|
sessionId: 3,
|
||||||
|
sampleSecs: [1.5, 2.5, 3.5],
|
||||||
|
);
|
||||||
|
expect(kept, same(first));
|
||||||
|
|
||||||
|
final moved = nextChartSelection(
|
||||||
|
current: first,
|
||||||
|
sessionId: 3,
|
||||||
|
sampleSecs: [1.5, 2.5, 3.5],
|
||||||
|
tappedSec: 2.4,
|
||||||
|
);
|
||||||
|
expect(moved!.sec, 2.5);
|
||||||
|
expect(moved.sessionId, 3);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: moved, sessionId: 4, sampleSecs: [0.2, 0.4]),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: first, sessionId: 3, sampleSecs: [2.5, 3.5]),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: first, sessionId: 3, sampleSecs: const []),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('history only lists the real tag and this version', () {
|
||||||
|
expect(appVersion, '1.1.3');
|
||||||
|
expect(appBuild, 6);
|
||||||
|
expect(appAttribution, '言灸');
|
||||||
|
expect(releaseHistory.map((entry) => entry.version), [
|
||||||
|
'1.1.3',
|
||||||
|
'1.1.2',
|
||||||
|
'1.1.1',
|
||||||
|
]);
|
||||||
|
expect(releaseHistory.last.published, '2026-11-09');
|
||||||
|
expect(releaseHistory.last.source, contains('v1.1.1'));
|
||||||
|
expect(releaseHistoryNote, contains('不写成另一个版本'));
|
||||||
|
for (final entry in releaseHistory) {
|
||||||
|
expect(entry.version, isNot('1.1.0'));
|
||||||
|
expect(entry.version, isNot('1.0.0'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
// The plot surface is not part of fl_chart's public API. The tap has to land
|
||||||
|
// on that surface, not on the axis titles around it.
|
||||||
|
// ignore_for_file: implementation_imports
|
||||||
|
|
||||||
|
import 'package:fl_chart/src/chart/line_chart/line_chart_renderer.dart';
|
||||||
|
import 'package:flutter/gestures.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/probe/probe_controller.dart';
|
||||||
|
import 'package:netquality/ui/chart_selection.dart';
|
||||||
|
import 'package:netquality/ui/quality_charts.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('a tap pins the nearest time and a later tap replaces it', () {
|
||||||
|
final first = nextChartSelection(
|
||||||
|
current: null,
|
||||||
|
sessionId: 3,
|
||||||
|
sampleSecs: const [1, 2, 4],
|
||||||
|
tappedSec: 2.2,
|
||||||
|
);
|
||||||
|
expect(first, isNotNull);
|
||||||
|
expect(first!.sec, 2);
|
||||||
|
expect(first.sessionId, 3);
|
||||||
|
|
||||||
|
final second = nextChartSelection(
|
||||||
|
current: first,
|
||||||
|
sessionId: 3,
|
||||||
|
sampleSecs: const [1, 2, 4],
|
||||||
|
tappedSec: 3.6,
|
||||||
|
);
|
||||||
|
expect(second!.sec, 4);
|
||||||
|
|
||||||
|
final kept = nextChartSelection(
|
||||||
|
current: second,
|
||||||
|
sessionId: 3,
|
||||||
|
sampleSecs: const [1, 2, 4],
|
||||||
|
);
|
||||||
|
expect(kept, same(second));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a new session or a point that rolled off does not jump', () {
|
||||||
|
const pin = ChartSelection(sec: 1, sessionId: 3);
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: pin, sessionId: 4, sampleSecs: const [1, 2]),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: pin, sessionId: 3, sampleSecs: const [2, 3]),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: pin, sessionId: 3, sampleSecs: const []),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('releasing a chart tap keeps the pinned readout', (tester) async {
|
||||||
|
const samples = [
|
||||||
|
ChartSample(sec: 0, rttMs: 10, ratePct: 0),
|
||||||
|
ChartSample(sec: 1, rttMs: 30, ratePct: 50),
|
||||||
|
];
|
||||||
|
await tester.pumpWidget(
|
||||||
|
const MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: QualityCharts(
|
||||||
|
samples: samples,
|
||||||
|
rateLabel: '探测无应答',
|
||||||
|
running: false,
|
||||||
|
sessionId: 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('点曲线上的一点'), findsOneWidget);
|
||||||
|
|
||||||
|
final box = tester.getRect(find.byType(LineChartLeaf).first);
|
||||||
|
const maxY = 30 * 1.2;
|
||||||
|
Offset at(double sec, double value) {
|
||||||
|
final x = box.left + box.width * sec;
|
||||||
|
final y = box.top + (1 - value / maxY) * box.height;
|
||||||
|
return Offset(x.clamp(box.left + 2, box.right - 2), y);
|
||||||
|
}
|
||||||
|
|
||||||
|
await tester.tapAt(at(0, 10));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.textContaining('已选 0.0 秒'), findsOneWidget);
|
||||||
|
expect(find.textContaining('延迟'), findsWidgets);
|
||||||
|
|
||||||
|
final mouse = await tester.startGesture(
|
||||||
|
at(1, 30),
|
||||||
|
kind: PointerDeviceKind.mouse,
|
||||||
|
);
|
||||||
|
await mouse.up();
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.textContaining('已选 1.0 秒'), findsOneWidget);
|
||||||
|
expect(find.textContaining('已选 0.0 秒'), findsNothing);
|
||||||
|
|
||||||
|
await tester.pumpWidget(
|
||||||
|
const MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: QualityCharts(
|
||||||
|
samples: [ChartSample(sec: 2, rttMs: 8, ratePct: 0)],
|
||||||
|
rateLabel: '探测无应答',
|
||||||
|
running: false,
|
||||||
|
sessionId: 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.textContaining('已选'), findsNothing);
|
||||||
|
expect(find.textContaining('点曲线上的一点'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/metrics/latency.dart';
|
||||||
|
import 'package:netquality/metrics/sample_book.dart';
|
||||||
|
import 'package:netquality/ui/metrics_panel.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('percentile ranks match the documented integer formula', () {
|
||||||
|
expect(nearestRank95(1), 1);
|
||||||
|
expect(nearestRank95(2), 2);
|
||||||
|
expect(nearestRank95(4), 4);
|
||||||
|
expect(nearestRank95(5), 5);
|
||||||
|
expect(nearestRank95(20), 19);
|
||||||
|
|
||||||
|
final one = LatencyStats.from([10]);
|
||||||
|
expect(one!.min, 10);
|
||||||
|
expect(one.mean, 10);
|
||||||
|
expect(one.median, 10);
|
||||||
|
expect(one.p95, 10);
|
||||||
|
expect(one.max, 10);
|
||||||
|
|
||||||
|
final two = LatencyStats.from([10, 30]);
|
||||||
|
expect(two!.median, 20);
|
||||||
|
expect(two.p95, 30);
|
||||||
|
expect(two.mean, 20);
|
||||||
|
|
||||||
|
final four = LatencyStats.from([1, 2, 3, 4]);
|
||||||
|
expect(four!.median, 2.5);
|
||||||
|
expect(four.p95, 4);
|
||||||
|
expect(four.min, 1);
|
||||||
|
expect(four.max, 4);
|
||||||
|
|
||||||
|
final five = LatencyStats.from([1, 2, 3, 4, 10]);
|
||||||
|
expect(five!.median, 3);
|
||||||
|
expect(five.p95, 10);
|
||||||
|
expect(five.mean, 4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sample book keeps current rtt separate from the distribution', () {
|
||||||
|
final book = SampleBook('nq-udp');
|
||||||
|
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 1));
|
||||||
|
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 2));
|
||||||
|
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 3));
|
||||||
|
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 4));
|
||||||
|
final summary = book.summary();
|
||||||
|
expect(summary.rttMs, 4);
|
||||||
|
expect(summary.minRttMs, 1);
|
||||||
|
expect(summary.maxRttMs, 4);
|
||||||
|
expect(summary.medianRttMs, 2.5);
|
||||||
|
expect(summary.p95RttMs, 4);
|
||||||
|
expect(summary.meanRttMs, 2.5);
|
||||||
|
expect(summary.latencyStats, isTrue);
|
||||||
|
expect(summary.jitterMs, isNotNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unsupported rates stay blank instead of a false zero', () {
|
||||||
|
final silent = SampleBook('udp-generic')
|
||||||
|
..add(const Outcome(status: Outcome.unknown, kind: Outcome.query));
|
||||||
|
final lines = metricLines(
|
||||||
|
summary: silent.summary(),
|
||||||
|
profileId: 'udp-generic',
|
||||||
|
elapsed: const Duration(seconds: 2),
|
||||||
|
);
|
||||||
|
expect(_value(lines, '超时'), '不适用');
|
||||||
|
expect(_value(lines, '无应答(未知)'), '100%');
|
||||||
|
expect(_value(lines, '探测无应答'), isNull);
|
||||||
|
expect(_value(lines, '当前延迟'), '—');
|
||||||
|
|
||||||
|
final connect = SampleBook('tcp-connect');
|
||||||
|
final empty = metricLines(
|
||||||
|
summary: connect.summary(),
|
||||||
|
profileId: 'tcp-connect',
|
||||||
|
elapsed: Duration.zero,
|
||||||
|
);
|
||||||
|
expect(_value(empty, '失败率'), '—');
|
||||||
|
expect(_value(empty, '探测无应答'), isNull);
|
||||||
|
|
||||||
|
final oldNode = ProbeSummary.fromJson({
|
||||||
|
'sent': 1,
|
||||||
|
'completed': 1,
|
||||||
|
'ok': 1,
|
||||||
|
'rttMs': 8,
|
||||||
|
'probeLossPct': 0,
|
||||||
|
});
|
||||||
|
final remote = metricLines(
|
||||||
|
summary: oldNode,
|
||||||
|
profileId: 'nq-udp',
|
||||||
|
elapsed: const Duration(seconds: 3),
|
||||||
|
);
|
||||||
|
expect(_value(remote, '当前延迟'), '8.00 ms');
|
||||||
|
expect(_value(remote, 'P95 延迟'), '节点未提供');
|
||||||
|
expect(_value(remote, '探测无应答'), '0%');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _value(List<MetricLine> lines, String label) {
|
||||||
|
for (final line in lines) {
|
||||||
|
if (line.label == label) {
|
||||||
|
return line.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/models/node_edit.dart';
|
||||||
|
import 'package:netquality/models/port_field.dart';
|
||||||
|
import 'package:netquality/models/probe_profile.dart';
|
||||||
|
import 'package:netquality/models/session_config.dart';
|
||||||
|
import 'package:netquality/storage/token_vault.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test(
|
||||||
|
'editing keeps the node id and replaces only a non-blank token',
|
||||||
|
() async {
|
||||||
|
const original = RemoteNode(
|
||||||
|
id: 'node-7',
|
||||||
|
name: '机房',
|
||||||
|
baseUrl: 'https://probe.example:8443',
|
||||||
|
visibility: 'private',
|
||||||
|
);
|
||||||
|
final renamed = applyNodeEdit(
|
||||||
|
original,
|
||||||
|
name: '机房乙',
|
||||||
|
baseUrl: 'https://probe.example:8443',
|
||||||
|
);
|
||||||
|
expect(renamed.id, 'node-7');
|
||||||
|
expect(renamed.name, '机房乙');
|
||||||
|
expect(renamed.visibility, 'private');
|
||||||
|
|
||||||
|
final moved = applyNodeEdit(
|
||||||
|
renamed,
|
||||||
|
name: '机房乙',
|
||||||
|
baseUrl: 'https://other.example:8443',
|
||||||
|
);
|
||||||
|
expect(moved.id, 'node-7');
|
||||||
|
expect(moved.visibility, '');
|
||||||
|
|
||||||
|
final vault = MemoryTokenVault();
|
||||||
|
await vault.write(nodeTokenKey('node-7'), 'saved-secret');
|
||||||
|
expect(await saveEditedNodeToken(vault, 'node-7', ' '), isFalse);
|
||||||
|
expect(await vault.read(nodeTokenKey('node-7')), 'saved-secret');
|
||||||
|
expect(replacementNodeToken(' '), isNull);
|
||||||
|
expect(
|
||||||
|
await saveEditedNodeToken(vault, 'node-7', ' next-secret '),
|
||||||
|
isTrue,
|
||||||
|
);
|
||||||
|
expect(await vault.read(nodeTokenKey('node-7')), 'next-secret');
|
||||||
|
final encoded = moved.toJson();
|
||||||
|
expect(encoded.containsKey('token'), isFalse);
|
||||||
|
expect(encoded.values, isNot(contains('saved-secret')));
|
||||||
|
expect(encoded.values, isNot(contains('next-secret')));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
'port follows the profile default unless the user typed another port',
|
||||||
|
() {
|
||||||
|
expect(ProbeProfile.nqTcp.port, 19090);
|
||||||
|
expect(ProbeProfile.nqUdp.port, 19091);
|
||||||
|
expect(portHint(ProbeProfile.nqTcp), '合作反射 TCP 默认 19090');
|
||||||
|
expect(portHint(ProbeProfile.nqUdp), '合作反射 UDP 默认 19091');
|
||||||
|
expect(
|
||||||
|
portAfterProfileChange(
|
||||||
|
current: '19090',
|
||||||
|
previousDefault: 19090,
|
||||||
|
nextDefault: 19091,
|
||||||
|
),
|
||||||
|
'19091',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
portAfterProfileChange(
|
||||||
|
current: ' 19090 ',
|
||||||
|
previousDefault: 19090,
|
||||||
|
nextDefault: 19132,
|
||||||
|
),
|
||||||
|
'19132',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
portAfterProfileChange(
|
||||||
|
current: '',
|
||||||
|
previousDefault: 19090,
|
||||||
|
nextDefault: 19091,
|
||||||
|
),
|
||||||
|
'19091',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
portAfterProfileChange(
|
||||||
|
current: '25565',
|
||||||
|
previousDefault: 19090,
|
||||||
|
nextDefault: 19091,
|
||||||
|
),
|
||||||
|
'25565',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
portAfterProfileChange(
|
||||||
|
current: '25565',
|
||||||
|
previousDefault: 19091,
|
||||||
|
nextDefault: 80,
|
||||||
|
),
|
||||||
|
'25565',
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
+321
-226
@@ -25,238 +25,261 @@ void main() {
|
|||||||
expect(build.exitCode, 0, reason: '${build.stdout}\n${build.stderr}');
|
expect(build.exitCode, 0, reason: '${build.stdout}\n${build.stderr}');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('local nq tcp and udp get real rtt and do not call connect failure loss', () async {
|
test(
|
||||||
final reflector = await _reflector();
|
'local nq tcp and udp get real rtt and do not call connect failure loss',
|
||||||
addTearDown(() => reflector.process.kill());
|
() async {
|
||||||
final tcp = await _collect(
|
final reflector = await _reflector();
|
||||||
ProbeRequest(
|
addTearDown(() => reflector.process.kill());
|
||||||
host: '127.0.0.1',
|
final tcp = await _collect(
|
||||||
port: reflector.tcp,
|
ProbeRequest(
|
||||||
profileId: 'nq-tcp',
|
host: '127.0.0.1',
|
||||||
interval: const Duration(milliseconds: 200),
|
port: reflector.tcp,
|
||||||
timeout: const Duration(milliseconds: 800),
|
profileId: 'nq-tcp',
|
||||||
packetSize: 80,
|
interval: const Duration(milliseconds: 200),
|
||||||
echoToken: '',
|
timeout: const Duration(milliseconds: 800),
|
||||||
dnsName: '',
|
packetSize: 80,
|
||||||
payloadHex: '',
|
echoToken: '',
|
||||||
expectHex: '',
|
dnsName: '',
|
||||||
),
|
payloadHex: '',
|
||||||
count: 2,
|
expectHex: '',
|
||||||
);
|
),
|
||||||
expect(tcp.last.status, Outcome.ok);
|
count: 2,
|
||||||
expect(tcp.last.rttMs, greaterThan(0));
|
);
|
||||||
expect(tcp.last.summary.probeLossPct, 0);
|
expect(tcp.last.status, Outcome.ok);
|
||||||
|
expect(tcp.last.rttMs, greaterThan(0));
|
||||||
|
expect(tcp.last.summary.probeLossPct, 0);
|
||||||
|
|
||||||
final udp = await _collect(
|
final udp = await _collect(
|
||||||
ProbeRequest(
|
ProbeRequest(
|
||||||
host: '127.0.0.1',
|
host: '127.0.0.1',
|
||||||
port: reflector.udp,
|
port: reflector.udp,
|
||||||
profileId: 'nq-udp',
|
profileId: 'nq-udp',
|
||||||
interval: const Duration(milliseconds: 200),
|
interval: const Duration(milliseconds: 200),
|
||||||
timeout: const Duration(milliseconds: 800),
|
timeout: const Duration(milliseconds: 800),
|
||||||
packetSize: 80,
|
packetSize: 80,
|
||||||
echoToken: '',
|
echoToken: '',
|
||||||
dnsName: '',
|
dnsName: '',
|
||||||
payloadHex: '',
|
payloadHex: '',
|
||||||
expectHex: '',
|
expectHex: '',
|
||||||
),
|
),
|
||||||
count: 1,
|
count: 1,
|
||||||
);
|
);
|
||||||
expect(udp.single.status, Outcome.ok);
|
expect(udp.single.status, Outcome.ok);
|
||||||
expect(udp.single.summary.probeLossPct, 0);
|
expect(udp.single.summary.probeLossPct, 0);
|
||||||
|
|
||||||
final refused = await _collect(
|
final refused = await _collect(
|
||||||
ProbeRequest(
|
ProbeRequest(
|
||||||
host: '127.0.0.1',
|
host: '127.0.0.1',
|
||||||
port: 1,
|
port: 1,
|
||||||
profileId: 'tcp-connect',
|
profileId: 'tcp-connect',
|
||||||
interval: const Duration(milliseconds: 200),
|
interval: const Duration(milliseconds: 200),
|
||||||
timeout: const Duration(milliseconds: 400),
|
timeout: const Duration(milliseconds: 400),
|
||||||
packetSize: 64,
|
packetSize: 64,
|
||||||
echoToken: '',
|
echoToken: '',
|
||||||
dnsName: '',
|
dnsName: '',
|
||||||
payloadHex: '',
|
payloadHex: '',
|
||||||
expectHex: '',
|
expectHex: '',
|
||||||
),
|
),
|
||||||
count: 1,
|
count: 1,
|
||||||
);
|
);
|
||||||
expect(refused.single.status, Outcome.refused);
|
expect(refused.single.status, Outcome.refused);
|
||||||
expect(refused.single.summary.failurePct, 100);
|
expect(refused.single.summary.failurePct, 100);
|
||||||
expect(refused.single.summary.probeLossPct, isNull);
|
expect(refused.single.summary.probeLossPct, isNull);
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('silence is unknown, games answer, and a remote node measures rtt', () async {
|
test(
|
||||||
final hole = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
|
'silence is unknown, games answer, and a remote node measures rtt',
|
||||||
addTearDown(hole.close);
|
() async {
|
||||||
hole.listen((event) {
|
final hole = await RawDatagramSocket.bind(
|
||||||
if (event == RawSocketEvent.read) {
|
InternetAddress.loopbackIPv4,
|
||||||
hole.receive();
|
0,
|
||||||
}
|
);
|
||||||
});
|
addTearDown(hole.close);
|
||||||
final unknown = await _collect(
|
hole.listen((event) {
|
||||||
ProbeRequest(
|
if (event == RawSocketEvent.read) {
|
||||||
host: '127.0.0.1',
|
hole.receive();
|
||||||
port: hole.port,
|
|
||||||
profileId: 'udp-generic',
|
|
||||||
interval: const Duration(milliseconds: 200),
|
|
||||||
timeout: const Duration(milliseconds: 200),
|
|
||||||
packetSize: 16,
|
|
||||||
echoToken: '',
|
|
||||||
dnsName: '',
|
|
||||||
payloadHex: '',
|
|
||||||
expectHex: '',
|
|
||||||
),
|
|
||||||
count: 1,
|
|
||||||
);
|
|
||||||
expect(unknown.single.status, Outcome.unknown);
|
|
||||||
expect(unknown.single.summary.probeLossPct, isNull);
|
|
||||||
expect(unknown.single.summary.unknownPct, 100);
|
|
||||||
expect(unknown.single.detail['address'], '127.0.0.1');
|
|
||||||
|
|
||||||
final java = await _javaServer();
|
|
||||||
addTearDown(java.close);
|
|
||||||
final javaSample = await _collect(
|
|
||||||
ProbeRequest(
|
|
||||||
host: '127.0.0.1',
|
|
||||||
port: java.port,
|
|
||||||
profileId: 'minecraft-java',
|
|
||||||
interval: const Duration(milliseconds: 200),
|
|
||||||
timeout: const Duration(milliseconds: 800),
|
|
||||||
packetSize: 64,
|
|
||||||
echoToken: '',
|
|
||||||
dnsName: '',
|
|
||||||
payloadHex: '',
|
|
||||||
expectHex: '',
|
|
||||||
),
|
|
||||||
count: 1,
|
|
||||||
);
|
|
||||||
expect(javaSample.single.status, Outcome.ok);
|
|
||||||
expect(javaSample.single.detail['motd'], 'Hello');
|
|
||||||
expect(javaSample.single.rttMs, greaterThan(0));
|
|
||||||
expect(javaSample.single.summary.failurePct, 0);
|
|
||||||
|
|
||||||
final bedrock = await _bedrockServer();
|
|
||||||
addTearDown(bedrock.close);
|
|
||||||
final bedrockSample = await _collect(
|
|
||||||
ProbeRequest(
|
|
||||||
host: '127.0.0.1',
|
|
||||||
port: bedrock.port,
|
|
||||||
profileId: 'minecraft-bedrock',
|
|
||||||
interval: const Duration(milliseconds: 200),
|
|
||||||
timeout: const Duration(milliseconds: 800),
|
|
||||||
packetSize: 64,
|
|
||||||
echoToken: '',
|
|
||||||
dnsName: '',
|
|
||||||
payloadHex: '',
|
|
||||||
expectHex: '',
|
|
||||||
),
|
|
||||||
count: 1,
|
|
||||||
);
|
|
||||||
expect(bedrockSample.single.status, Outcome.ok);
|
|
||||||
expect(bedrockSample.single.detail['motd'], 'Bed');
|
|
||||||
|
|
||||||
final node = await _node();
|
|
||||||
addTearDown(node.kill);
|
|
||||||
final samples = <ProbeSample>[];
|
|
||||||
final remote = RemoteProbe();
|
|
||||||
final done = Completer<void>();
|
|
||||||
unawaited(() async {
|
|
||||||
try {
|
|
||||||
await remote.run(
|
|
||||||
baseUrl: 'http://127.0.0.1:${node.control}',
|
|
||||||
nodeToken: '',
|
|
||||||
body: ProbeBody(
|
|
||||||
target: '127.0.0.1',
|
|
||||||
port: node.udp,
|
|
||||||
profile: 'nq-udp',
|
|
||||||
intervalMs: 200,
|
|
||||||
timeoutMs: 800,
|
|
||||||
durationSec: 3,
|
|
||||||
packetSize: 80,
|
|
||||||
echoToken: '',
|
|
||||||
dnsName: '',
|
|
||||||
payloadHex: '',
|
|
||||||
expectHex: '',
|
|
||||||
),
|
|
||||||
onSample: (sample) {
|
|
||||||
samples.add(sample);
|
|
||||||
if (samples.length == 1 && !done.isCompleted) {
|
|
||||||
done.complete();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
cancelled: () => done.isCompleted,
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
if (!done.isCompleted) {
|
|
||||||
done.complete();
|
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
}());
|
final unknown = await _collect(
|
||||||
await done.future.timeout(const Duration(seconds: 5));
|
ProbeRequest(
|
||||||
await remote.stop('');
|
host: '127.0.0.1',
|
||||||
expect(samples, isNotEmpty);
|
port: hole.port,
|
||||||
expect(samples.first.status, Outcome.ok);
|
profileId: 'udp-generic',
|
||||||
expect(samples.first.rttMs, greaterThan(0));
|
interval: const Duration(milliseconds: 200),
|
||||||
expect(samples.first.summary.probeLossPct, 0);
|
timeout: const Duration(milliseconds: 200),
|
||||||
});
|
packetSize: 16,
|
||||||
|
echoToken: '',
|
||||||
|
dnsName: '',
|
||||||
|
payloadHex: '',
|
||||||
|
expectHex: '',
|
||||||
|
),
|
||||||
|
count: 1,
|
||||||
|
);
|
||||||
|
expect(unknown.single.status, Outcome.unknown);
|
||||||
|
expect(unknown.single.summary.probeLossPct, isNull);
|
||||||
|
expect(unknown.single.summary.unknownPct, 100);
|
||||||
|
expect(unknown.single.detail['address'], '127.0.0.1');
|
||||||
|
|
||||||
test('plain udp leaves a silent address and keeps one that answers', () async {
|
final java = await _javaServer();
|
||||||
final drop = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
|
addTearDown(java.close);
|
||||||
addTearDown(drop.close);
|
final javaSample = await _collect(
|
||||||
final port = drop.port;
|
ProbeRequest(
|
||||||
drop.listen((event) {
|
host: '127.0.0.1',
|
||||||
if (event == RawSocketEvent.read) {
|
port: java.port,
|
||||||
drop.receive();
|
profileId: 'minecraft-java',
|
||||||
}
|
interval: const Duration(milliseconds: 200),
|
||||||
});
|
timeout: const Duration(milliseconds: 800),
|
||||||
final RawDatagramSocket echo;
|
packetSize: 64,
|
||||||
try {
|
echoToken: '',
|
||||||
echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv6, port);
|
dnsName: '',
|
||||||
} on SocketException {
|
payloadHex: '',
|
||||||
markTestSkipped('IPv6 loopback is not available');
|
expectHex: '',
|
||||||
return;
|
),
|
||||||
}
|
count: 1,
|
||||||
addTearDown(echo.close);
|
);
|
||||||
echo.listen((event) {
|
expect(javaSample.single.status, Outcome.ok);
|
||||||
if (event != RawSocketEvent.read) {
|
expect(javaSample.single.detail['motd'], 'Hello');
|
||||||
|
expect(javaSample.single.rttMs, greaterThan(0));
|
||||||
|
expect(javaSample.single.summary.failurePct, 0);
|
||||||
|
|
||||||
|
final bedrock = await _bedrockServer();
|
||||||
|
addTearDown(bedrock.close);
|
||||||
|
final bedrockSample = await _collect(
|
||||||
|
ProbeRequest(
|
||||||
|
host: '127.0.0.1',
|
||||||
|
port: bedrock.port,
|
||||||
|
profileId: 'minecraft-bedrock',
|
||||||
|
interval: const Duration(milliseconds: 200),
|
||||||
|
timeout: const Duration(milliseconds: 800),
|
||||||
|
packetSize: 64,
|
||||||
|
echoToken: '',
|
||||||
|
dnsName: '',
|
||||||
|
payloadHex: '',
|
||||||
|
expectHex: '',
|
||||||
|
),
|
||||||
|
count: 1,
|
||||||
|
);
|
||||||
|
expect(bedrockSample.single.status, Outcome.ok);
|
||||||
|
expect(bedrockSample.single.detail['motd'], 'Bed');
|
||||||
|
|
||||||
|
final node = await _node();
|
||||||
|
addTearDown(node.kill);
|
||||||
|
final samples = <ProbeSample>[];
|
||||||
|
final remote = RemoteProbe();
|
||||||
|
final done = Completer<void>();
|
||||||
|
unawaited(() async {
|
||||||
|
try {
|
||||||
|
await remote.run(
|
||||||
|
baseUrl: 'http://127.0.0.1:${node.control}',
|
||||||
|
nodeToken: '',
|
||||||
|
body: ProbeBody(
|
||||||
|
target: '127.0.0.1',
|
||||||
|
port: node.udp,
|
||||||
|
profile: 'nq-udp',
|
||||||
|
intervalMs: 200,
|
||||||
|
timeoutMs: 800,
|
||||||
|
durationSec: 3,
|
||||||
|
packetSize: 80,
|
||||||
|
echoToken: '',
|
||||||
|
dnsName: '',
|
||||||
|
payloadHex: '',
|
||||||
|
expectHex: '',
|
||||||
|
),
|
||||||
|
onSample: (sample) {
|
||||||
|
samples.add(sample);
|
||||||
|
if (samples.length == 1 && !done.isCompleted) {
|
||||||
|
done.complete();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
cancelled: () => done.isCompleted,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
if (!done.isCompleted) {
|
||||||
|
done.complete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}());
|
||||||
|
await done.future.timeout(const Duration(seconds: 5));
|
||||||
|
await remote.stop('');
|
||||||
|
expect(samples, isNotEmpty);
|
||||||
|
expect(samples.first.status, Outcome.ok);
|
||||||
|
expect(samples.first.rttMs, greaterThan(0));
|
||||||
|
expect(samples.first.summary.probeLossPct, 0);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
'a silent candidate is not a measured miss once another address answers',
|
||||||
|
() async {
|
||||||
|
final drop = await RawDatagramSocket.bind(
|
||||||
|
InternetAddress.loopbackIPv4,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
addTearDown(drop.close);
|
||||||
|
final port = drop.port;
|
||||||
|
drop.listen((event) {
|
||||||
|
if (event == RawSocketEvent.read) {
|
||||||
|
drop.receive();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
final RawDatagramSocket echo;
|
||||||
|
try {
|
||||||
|
echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv6, port);
|
||||||
|
} on SocketException {
|
||||||
|
markTestSkipped('IPv6 loopback is not available');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final datagram = echo.receive();
|
addTearDown(echo.close);
|
||||||
if (datagram == null) {
|
echo.listen((event) {
|
||||||
return;
|
if (event != RawSocketEvent.read) {
|
||||||
}
|
return;
|
||||||
echo.send(datagram.data, datagram.address, datagram.port);
|
}
|
||||||
});
|
final datagram = echo.receive();
|
||||||
|
if (datagram == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
echo.send(datagram.data, datagram.address, datagram.port);
|
||||||
|
});
|
||||||
|
|
||||||
final seen = <String>[];
|
final seen = <String>[];
|
||||||
final samples = await _collect(
|
final samples = await _collect(
|
||||||
ProbeRequest(
|
ProbeRequest(
|
||||||
host: 'example.test',
|
host: 'example.test',
|
||||||
port: port,
|
port: port,
|
||||||
profileId: 'udp-generic',
|
profileId: 'udp-generic',
|
||||||
interval: const Duration(milliseconds: 40),
|
interval: const Duration(milliseconds: 40),
|
||||||
timeout: const Duration(milliseconds: 250),
|
timeout: const Duration(milliseconds: 250),
|
||||||
packetSize: 16,
|
packetSize: 16,
|
||||||
echoToken: '',
|
echoToken: '',
|
||||||
dnsName: '',
|
dnsName: '',
|
||||||
payloadHex: '',
|
payloadHex: '',
|
||||||
expectHex: '',
|
expectHex: '',
|
||||||
),
|
),
|
||||||
count: 2,
|
count: 2,
|
||||||
loop: ProbeLoop(
|
loop: ProbeLoop(
|
||||||
lookup: (host) async {
|
lookup: (host) async {
|
||||||
expect(host, 'example.test');
|
expect(host, 'example.test');
|
||||||
return [InternetAddress('127.0.0.1'), InternetAddress('::1')];
|
return [InternetAddress('127.0.0.1'), InternetAddress('::1')];
|
||||||
},
|
},
|
||||||
onEndpoint: (address) => seen.add(address.address),
|
onEndpoint: (address) => seen.add(address.address),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
expect(samples.first.status, Outcome.unknown);
|
expect(samples.first.status, Outcome.ok);
|
||||||
expect(samples.first.detail['address'], '127.0.0.1');
|
expect(samples.first.detail['address'], '::1');
|
||||||
expect(samples.last.status, Outcome.ok);
|
expect(samples.first.detail['family'], 'IPv6');
|
||||||
expect(samples.last.detail['address'], '::1');
|
expect(samples.first.detail['fallback'], contains('127.0.0.1'));
|
||||||
expect(seen, ['127.0.0.1', '::1']);
|
expect(samples.first.detail['fallback'], contains('没有计入'));
|
||||||
});
|
expect(samples.first.summary.sent, 1);
|
||||||
|
expect(samples.first.summary.unknown, 0);
|
||||||
|
expect(samples.first.summary.selectionSkipped, 1);
|
||||||
|
expect(samples.first.summary.unknownPct, 0);
|
||||||
|
expect(samples.last.status, Outcome.ok);
|
||||||
|
expect(samples.last.detail['address'], '::1');
|
||||||
|
expect(samples.last.summary.unknown, 0);
|
||||||
|
expect(seen, ['127.0.0.1', '::1']);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('a responding address is not replaced while it still answers', () async {
|
test('a responding address is not replaced while it still answers', () async {
|
||||||
final echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
|
final echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
@@ -293,7 +316,78 @@ void main() {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
expect(samples.map((sample) => sample.status), everyElement(Outcome.ok));
|
expect(samples.map((sample) => sample.status), everyElement(Outcome.ok));
|
||||||
expect(samples.map((sample) => sample.detail['address']), everyElement('127.0.0.1'));
|
expect(
|
||||||
|
samples.map((sample) => sample.detail['address']),
|
||||||
|
everyElement('127.0.0.1'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a closed address family is not used after lookup', () async {
|
||||||
|
final echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
addTearDown(echo.close);
|
||||||
|
echo.listen((event) {
|
||||||
|
if (event != RawSocketEvent.read) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final datagram = echo.receive();
|
||||||
|
if (datagram == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
echo.send(datagram.data, datagram.address, datagram.port);
|
||||||
|
});
|
||||||
|
final samples = await _collect(
|
||||||
|
ProbeRequest(
|
||||||
|
host: 'example.test',
|
||||||
|
port: echo.port,
|
||||||
|
profileId: 'udp-generic',
|
||||||
|
interval: const Duration(milliseconds: 40),
|
||||||
|
timeout: const Duration(milliseconds: 300),
|
||||||
|
packetSize: 16,
|
||||||
|
echoToken: '',
|
||||||
|
dnsName: '',
|
||||||
|
payloadHex: '',
|
||||||
|
expectHex: '',
|
||||||
|
allowIPv6: false,
|
||||||
|
),
|
||||||
|
count: 1,
|
||||||
|
loop: ProbeLoop(
|
||||||
|
lookup: (_) async => [
|
||||||
|
InternetAddress('2001:db8::1'),
|
||||||
|
InternetAddress('127.0.0.1'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(samples.single.status, Outcome.ok);
|
||||||
|
expect(samples.single.detail['address'], '127.0.0.1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('local http uses the same go engine as the node', () async {
|
||||||
|
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
addTearDown(server.close);
|
||||||
|
server.listen((request) {
|
||||||
|
request.response.statusCode = 204;
|
||||||
|
request.response.close();
|
||||||
|
});
|
||||||
|
final samples = await _collect(
|
||||||
|
ProbeRequest(
|
||||||
|
host: 'http://127.0.0.1:${server.port}/health',
|
||||||
|
port: server.port,
|
||||||
|
profileId: 'http',
|
||||||
|
interval: const Duration(milliseconds: 200),
|
||||||
|
timeout: const Duration(seconds: 3),
|
||||||
|
packetSize: 64,
|
||||||
|
echoToken: '',
|
||||||
|
dnsName: '',
|
||||||
|
payloadHex: '',
|
||||||
|
expectHex: '',
|
||||||
|
),
|
||||||
|
count: 1,
|
||||||
|
loop: ProbeLoop(helperPath: binary),
|
||||||
|
);
|
||||||
|
expect(samples.single.status, Outcome.ok);
|
||||||
|
expect(samples.single.detail['statusCode'], '204');
|
||||||
|
expect(samples.single.detail['httpVersion'], '1.1');
|
||||||
|
expect(samples.single.summary.failurePct, 0);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,7 +431,8 @@ Future<({Process process, int tcp, int udp})> _reflector() async {
|
|||||||
return (process: process, tcp: tcp, udp: udp);
|
return (process: process, tcp: tcp, udp: udp);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<({Process process, int control, int udp, void Function() kill})> _node() async {
|
Future<({Process process, int control, int udp, void Function() kill})>
|
||||||
|
_node() async {
|
||||||
final udp = await _freeUdp();
|
final udp = await _freeUdp();
|
||||||
final control = await _freeTcp();
|
final control = await _freeTcp();
|
||||||
final process = await Process.start(binary, [
|
final process = await Process.start(binary, [
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/metrics/sample_book.dart';
|
||||||
|
import 'package:netquality/metrics/selection_ledger.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
const v6 = Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.probe,
|
||||||
|
note: '未收到回显',
|
||||||
|
detail: {'address': '2001:db8::1', 'family': 'IPv6'},
|
||||||
|
);
|
||||||
|
const v4ok = Outcome(
|
||||||
|
status: Outcome.ok,
|
||||||
|
kind: Outcome.probe,
|
||||||
|
rttMs: 5,
|
||||||
|
note: '收到回显',
|
||||||
|
detail: {'address': '203.0.113.5', 'family': 'IPv4'},
|
||||||
|
);
|
||||||
|
const v4timeout = Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.probe,
|
||||||
|
note: '未收到回显',
|
||||||
|
detail: {'address': '203.0.113.5', 'family': 'IPv4'},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('ipv6 miss then ipv4 success is not formal loss', () {
|
||||||
|
final ledger = SelectionLedger(2);
|
||||||
|
expect(ledger.take(v6, responded: false).commit, isEmpty);
|
||||||
|
final decision = ledger.take(v4ok, responded: true);
|
||||||
|
expect(decision.skipped, 1);
|
||||||
|
expect(decision.commit.single.selectionSkipped, 1);
|
||||||
|
expect(decision.commit.single.detail['fallback'], contains('2001:db8::1'));
|
||||||
|
expect(decision.commit.single.detail['fallback'], contains('203.0.113.5'));
|
||||||
|
expect(decision.commit.single.detail['fallback'], contains('没有计入'));
|
||||||
|
final book = SampleBook('nq-udp');
|
||||||
|
book.add(decision.commit.single);
|
||||||
|
final summary = book.summary();
|
||||||
|
expect(summary.sent, 1);
|
||||||
|
expect(summary.ok, 1);
|
||||||
|
expect(summary.timeout, 0);
|
||||||
|
expect(summary.probeLossPct, 0);
|
||||||
|
expect(summary.selectionSkipped, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every candidate failing is loss, not a false zero', () {
|
||||||
|
final ledger = SelectionLedger(2);
|
||||||
|
expect(ledger.take(v6, responded: false).commit, isEmpty);
|
||||||
|
final decision = ledger.take(v4timeout, responded: false);
|
||||||
|
expect(decision.commit, hasLength(2));
|
||||||
|
final book = SampleBook('nq-udp');
|
||||||
|
for (final outcome in decision.commit) {
|
||||||
|
book.add(outcome);
|
||||||
|
}
|
||||||
|
final summary = book.summary();
|
||||||
|
expect(summary.ok, 0);
|
||||||
|
expect(summary.sent, 2);
|
||||||
|
expect(summary.timeout, 2);
|
||||||
|
expect(summary.probeLossPct, 100);
|
||||||
|
expect(summary.selectionSkipped, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('timeouts after an address is selected still count', () {
|
||||||
|
final ledger = SelectionLedger(2);
|
||||||
|
final first = ledger.take(v4ok, responded: true);
|
||||||
|
expect(ledger.measuring, isTrue);
|
||||||
|
final again = ledger.take(v4timeout, responded: false);
|
||||||
|
expect(again.commit, hasLength(1));
|
||||||
|
final book = SampleBook('nq-udp');
|
||||||
|
book.add(first.commit.single);
|
||||||
|
book.add(again.commit.single);
|
||||||
|
expect(book.summary().probeLossPct, 50);
|
||||||
|
expect(book.summary().sent, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('one address never hides a failure', () {
|
||||||
|
final ledger = SelectionLedger(1);
|
||||||
|
final decision = ledger.take(v4timeout, responded: false);
|
||||||
|
expect(decision.commit, hasLength(1));
|
||||||
|
final book = SampleBook('nq-tcp');
|
||||||
|
book.add(decision.commit.single);
|
||||||
|
expect(book.summary().probeLossPct, 100);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a stopped in-flight attempt is not recorded', () {
|
||||||
|
expect(
|
||||||
|
countsAfterStop(
|
||||||
|
const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.probe,
|
||||||
|
note: '已停止',
|
||||||
|
),
|
||||||
|
cancelled: false,
|
||||||
|
),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
countsAfterStop(
|
||||||
|
const Outcome(status: Outcome.timeout, kind: Outcome.probe),
|
||||||
|
cancelled: true,
|
||||||
|
),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
countsAfterStop(
|
||||||
|
const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 1),
|
||||||
|
cancelled: false,
|
||||||
|
),
|
||||||
|
isTrue,
|
||||||
|
);
|
||||||
|
expect(countsAfterStop(null, cancelled: false), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'leaving a measured address does not drop the failure that caused it',
|
||||||
|
() {
|
||||||
|
final ledger = SelectionLedger(2);
|
||||||
|
ledger.take(v4ok, responded: true);
|
||||||
|
final miss = ledger.take(v4timeout, responded: false);
|
||||||
|
expect(miss.commit, hasLength(1));
|
||||||
|
ledger.endMeasurement();
|
||||||
|
expect(ledger.measuring, isFalse);
|
||||||
|
final held = ledger.take(v6, responded: false);
|
||||||
|
expect(held.commit, isEmpty);
|
||||||
|
final recovered = ledger.take(v4ok, responded: true);
|
||||||
|
expect(recovered.skipped, 1);
|
||||||
|
final book = SampleBook('nq-udp');
|
||||||
|
book.add(v4ok);
|
||||||
|
book.add(miss.commit.single);
|
||||||
|
book.add(recovered.commit.single);
|
||||||
|
expect(book.summary().sent, 3);
|
||||||
|
expect(book.summary().timeout, 1);
|
||||||
|
expect(book.summary().probeLossPct, closeTo(100 / 3, 0.0001));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:crypto/crypto.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/center/catalog.dart';
|
||||||
|
import 'package:netquality/models/ip_family.dart';
|
||||||
|
import 'package:netquality/models/session_config.dart';
|
||||||
|
import 'package:netquality/models/target_history.dart';
|
||||||
|
import 'package:netquality/update/installer.dart';
|
||||||
|
import 'package:netquality/update/update_check.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('version comparison ignores a leading v and a build suffix', () {
|
||||||
|
final current = SemVer.parse('1.1.3');
|
||||||
|
expect(SemVer.parse('v1.1.4')!.isNewerThan(current!), isTrue);
|
||||||
|
expect(SemVer.parse('1.1.3+6')!.isNewerThan(current), isFalse);
|
||||||
|
expect(SemVer.parse('1.1.2')!.isNewerThan(current), isFalse);
|
||||||
|
expect(SemVer.parse('1.2.0-rc.1')!.isNewerThan(current), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the matching client archive is chosen and checksum files are recognized', () {
|
||||||
|
const assets = [
|
||||||
|
ReleaseFile(name: 'netquality-server-1.1.4-linux-amd64.tar.gz', url: 's'),
|
||||||
|
ReleaseFile(name: 'netquality-client-1.1.4-linux-amd64.tar.gz', url: 'c'),
|
||||||
|
ReleaseFile(name: 'SHA256SUMS', url: 'sum'),
|
||||||
|
];
|
||||||
|
expect(
|
||||||
|
pickClientAsset(assets, os: 'linux', arch: 'amd64'),
|
||||||
|
'netquality-client-1.1.4-linux-amd64.tar.gz',
|
||||||
|
);
|
||||||
|
expect(looksLikeChecksum('SHA256SUMS'), isTrue);
|
||||||
|
final check = interpretRelease(
|
||||||
|
current: '1.1.3',
|
||||||
|
os: 'linux',
|
||||||
|
arch: 'amd64',
|
||||||
|
body: '''
|
||||||
|
{
|
||||||
|
"tag_name": "v1.1.4",
|
||||||
|
"assets": [
|
||||||
|
{"name": "netquality-client-1.1.4-linux-amd64.tar.gz", "browser_download_url": "https://example.test/client.tar.gz"},
|
||||||
|
{"name": "SHA256SUMS", "browser_download_url": "https://example.test/SHA256SUMS"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
''',
|
||||||
|
);
|
||||||
|
expect(check.offer?.assetName, contains('linux-amd64'));
|
||||||
|
expect(check.offer?.checksumName, 'SHA256SUMS');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('github failure falls through to the spare source', () async {
|
||||||
|
final check = await findUpdate(
|
||||||
|
current: '1.1.3',
|
||||||
|
endpoints: const UpdateEndpoints(
|
||||||
|
github: 'https://github.invalid/latest',
|
||||||
|
gitea: 'https://git.invalid/latest',
|
||||||
|
),
|
||||||
|
os: 'linux',
|
||||||
|
arch: 'amd64',
|
||||||
|
fetch: (url) async {
|
||||||
|
if (url.host.contains('github')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return '''
|
||||||
|
{"tag_name":"v1.1.9","assets":[
|
||||||
|
{"name":"netquality-client-1.1.9-linux-amd64.tar.gz","browser_download_url":"https://example.test/a.tar.gz"}
|
||||||
|
]}
|
||||||
|
''';
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(check.offer?.version, '1.1.9');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('history keeps the newest identical target and can delete or clear', () {
|
||||||
|
const older = TargetEntry(
|
||||||
|
host: '203.0.113.8',
|
||||||
|
port: 443,
|
||||||
|
profileId: 'http',
|
||||||
|
httpUrl: 'https://203.0.113.8/a',
|
||||||
|
method: 'GET',
|
||||||
|
savedAtMs: 1,
|
||||||
|
);
|
||||||
|
const newer = TargetEntry(
|
||||||
|
host: '203.0.113.8',
|
||||||
|
port: 443,
|
||||||
|
profileId: 'http',
|
||||||
|
httpUrl: 'https://203.0.113.8/a',
|
||||||
|
method: 'get',
|
||||||
|
savedAtMs: 2,
|
||||||
|
);
|
||||||
|
final history = TargetHistory.empty
|
||||||
|
.add(older)
|
||||||
|
.add(
|
||||||
|
const TargetEntry(
|
||||||
|
host: 'example.com',
|
||||||
|
port: 19090,
|
||||||
|
profileId: 'nq-tcp',
|
||||||
|
savedAtMs: 3,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.add(newer);
|
||||||
|
expect(history.entries, hasLength(2));
|
||||||
|
expect(history.entries.first.savedAtMs, 2);
|
||||||
|
expect(history.entries.first.toJson().containsKey('token'), isFalse);
|
||||||
|
final removed = history.removeAt(0);
|
||||||
|
expect(removed.entries.single.host, 'example.com');
|
||||||
|
expect(removed.clear().entries, isEmpty);
|
||||||
|
|
||||||
|
var capped = TargetHistory.empty;
|
||||||
|
for (var i = 0; i < 45; i++) {
|
||||||
|
capped = capped.add(
|
||||||
|
TargetEntry(
|
||||||
|
host: 'h$i',
|
||||||
|
port: i + 1,
|
||||||
|
profileId: 'tcp-connect',
|
||||||
|
savedAtMs: i,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
expect(capped.entries, hasLength(TargetHistory.maxEntries));
|
||||||
|
expect(capped.entries.first.host, 'h44');
|
||||||
|
final again = TargetHistory.decode(capped.encode());
|
||||||
|
expect(again.entries.first.host, 'h44');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('disabled families are filtered and a literal of that family is refused', () {
|
||||||
|
final kept = filterAddresses(
|
||||||
|
[
|
||||||
|
InternetAddress('203.0.113.5'),
|
||||||
|
InternetAddress('2001:db8::1'),
|
||||||
|
],
|
||||||
|
v4: true,
|
||||||
|
v6: false,
|
||||||
|
);
|
||||||
|
expect(kept.map((address) => address.address), ['203.0.113.5']);
|
||||||
|
expect(familyRefusal('2001:db8::1', v4: true, v6: false), contains('IPv6'));
|
||||||
|
expect(familyRefusal('203.0.113.5', v4: false, v6: true), contains('IPv4'));
|
||||||
|
expect(familyRefusal('example.com', v4: false, v6: false), contains('都已关闭'));
|
||||||
|
expect(
|
||||||
|
familyRefusal('https://203.0.113.9/path', v4: false, v6: true),
|
||||||
|
contains('IPv4'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a confidential catalog entry cannot keep an address that was sent by mistake', () {
|
||||||
|
const secret = 'https://secret-node.internal:8443';
|
||||||
|
final catalog = Catalog.parse('''
|
||||||
|
{
|
||||||
|
"account": "lab",
|
||||||
|
"group": "lab",
|
||||||
|
"servers": [
|
||||||
|
{
|
||||||
|
"id": "secret-node",
|
||||||
|
"name": "保密节点",
|
||||||
|
"confidential": true,
|
||||||
|
"controlUrl": "$secret",
|
||||||
|
"credential": "node-token-should-not-leak"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "lab-node",
|
||||||
|
"name": "实验室节点",
|
||||||
|
"confidential": false,
|
||||||
|
"controlUrl": "https://127.0.0.1:8443",
|
||||||
|
"credential": "short-lived"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
''');
|
||||||
|
final secretServer = catalog.servers.first;
|
||||||
|
expect(secretServer.controlUrl, isEmpty);
|
||||||
|
expect(secretServer.credential, isEmpty);
|
||||||
|
expect(catalog.servers.last.controlUrl, 'https://127.0.0.1:8443');
|
||||||
|
|
||||||
|
const link = CenterLink(id: 'c1', url: 'https://center.example', account: 'lab');
|
||||||
|
var seq = 0;
|
||||||
|
final merged = mergeCenterCatalog(
|
||||||
|
existing: const [
|
||||||
|
RemoteNode(id: 'manual', name: '手填', baseUrl: 'https://manual.example'),
|
||||||
|
],
|
||||||
|
link: link,
|
||||||
|
catalog: catalog,
|
||||||
|
newId: () => 'new-${seq++}',
|
||||||
|
);
|
||||||
|
final hidden = merged.nodes.firstWhere((node) => node.serverId == 'secret-node');
|
||||||
|
expect(hidden.baseUrl, isEmpty);
|
||||||
|
expect(hidden.confidential, isTrue);
|
||||||
|
expect(merged.credentials.containsKey(hidden.id), isFalse);
|
||||||
|
expect(storedNodeHides(hidden, secret), isTrue);
|
||||||
|
expect(storedNodeHides(hidden, 'node-token-should-not-leak'), isTrue);
|
||||||
|
expect(merged.nodes.any((node) => node.id == 'manual'), isTrue);
|
||||||
|
expect(renameNode(hidden, '别的名字').name, '保密节点');
|
||||||
|
|
||||||
|
final again = SessionConfig.fromJson({
|
||||||
|
...SessionConfig.defaults.toJson(),
|
||||||
|
'nodes': [hidden.toJson()],
|
||||||
|
});
|
||||||
|
expect(again.nodes.single.baseUrl, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('checksum must mention the asset, and install copy stays inside the directory', () {
|
||||||
|
final bytes = [1, 2, 3, 4];
|
||||||
|
expect(checksumMatches('abc other.bin\n', 'client.zip', bytes), isFalse);
|
||||||
|
final digest = 'e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1';
|
||||||
|
expect(checksumMatches('$digest client.zip\n', 'client.zip', bytes), isFalse);
|
||||||
|
final want = sha256.convert(bytes).toString();
|
||||||
|
expect(checksumMatches('$want *client.zip\n', 'client.zip', bytes), isTrue);
|
||||||
|
|
||||||
|
final root = Directory.systemTemp.createTempSync('nq-install');
|
||||||
|
addTearDown(() => root.deleteSync(recursive: true));
|
||||||
|
final extracted = Directory('${root.path}/extracted')..createSync();
|
||||||
|
final install = Directory('${root.path}/install')..createSync();
|
||||||
|
File('${extracted.path}/netquality').writeAsStringSync('new');
|
||||||
|
File('${install.path}/kept.txt').writeAsStringSync('stay');
|
||||||
|
copyIntoInstall(extracted, install);
|
||||||
|
expect(File('${install.path}/netquality').readAsStringSync(), 'new');
|
||||||
|
expect(File('${install.path}/kept.txt').readAsStringSync(), 'stay');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:netquality/main.dart';
|
import 'package:netquality/main.dart';
|
||||||
@@ -27,7 +29,9 @@ void main() {
|
|||||||
const config = SessionConfig(
|
const config = SessionConfig(
|
||||||
remote: true,
|
remote: true,
|
||||||
nodeId: 'n1',
|
nodeId: 'n1',
|
||||||
nodes: [RemoteNode(id: 'n1', name: '机房', baseUrl: 'https://probe.example:8443')],
|
nodes: [
|
||||||
|
RemoteNode(id: 'n1', name: '机房', baseUrl: 'https://probe.example:8443'),
|
||||||
|
],
|
||||||
host: '203.0.113.8',
|
host: '203.0.113.8',
|
||||||
port: 25565,
|
port: 25565,
|
||||||
profileId: 'minecraft-java',
|
profileId: 'minecraft-java',
|
||||||
@@ -47,4 +51,115 @@ void main() {
|
|||||||
expect(again.toJson().containsKey('nodeToken'), isFalse);
|
expect(again.toJson().containsKey('nodeToken'), isFalse);
|
||||||
expect(SessionConfig.defaults.validate(), isNull);
|
expect(SessionConfig.defaults.validate(), isNull);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'profile default port updates until the user types another port',
|
||||||
|
(tester) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
tester.view.physicalSize = const Size(1280, 1600);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
await tester.pumpWidget(const NetQualityApp());
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('合作反射 TCP 默认 19090'), findsOneWidget);
|
||||||
|
await tester.ensureVisible(find.byKey(const Key('profile')));
|
||||||
|
await tester.tap(find.byKey(const Key('profile')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('合作反射 UDP').last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('19091'), findsWidgets);
|
||||||
|
expect(find.text('合作反射 UDP 默认 19091'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.enterText(find.byKey(const Key('port-field')), '25565');
|
||||||
|
await tester.tap(find.byKey(const Key('profile')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('合作反射 TCP').last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('25565'), findsOneWidget);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('editing a node keeps its id and does not reveal the token', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
tester.view.physicalSize = const Size(1280, 1600);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
await tester.pumpWidget(const NetQualityApp());
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('远程节点').first);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('管理节点'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.enterText(find.byKey(const Key('node-name')), '机房');
|
||||||
|
await tester.enterText(
|
||||||
|
find.byKey(const Key('node-url')),
|
||||||
|
'http://127.0.0.1:8443',
|
||||||
|
);
|
||||||
|
await tester.enterText(find.byKey(const Key('node-token')), 'saved-secret');
|
||||||
|
await tester.tap(find.byKey(const Key('node-save')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('编辑'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
final token = tester.widget<TextField>(find.byKey(const Key('node-token')));
|
||||||
|
expect(token.controller?.text, isEmpty);
|
||||||
|
expect(find.text('saved-secret'), findsNothing);
|
||||||
|
await tester.enterText(find.byKey(const Key('node-name')), '机房乙');
|
||||||
|
await tester.tap(find.text('保存修改'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('机房乙'), findsWidgets);
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final raw = prefs.getString('netquality.settings.v2') ?? '';
|
||||||
|
expect(raw, contains('机房乙'));
|
||||||
|
expect(raw, isNot(contains('saved-secret')));
|
||||||
|
final decoded = jsonDecode(raw) as Map<String, dynamic>;
|
||||||
|
final nodes = decoded['nodes'] as List<dynamic>;
|
||||||
|
expect(nodes, hasLength(1));
|
||||||
|
final node = nodes.single as Map<String, dynamic>;
|
||||||
|
expect(node['name'], '机房乙');
|
||||||
|
expect(node['baseUrl'], 'http://127.0.0.1:8443');
|
||||||
|
expect(decoded['nodeId'], node['id']);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('guide and history screens use the real versions', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
tester.view.physicalSize = const Size(900, 1400);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
await tester.pumpWidget(const NetQualityApp());
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.byType(PopupMenuButton<String>));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('指标说明'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('没有协议应答'), findsWidgets);
|
||||||
|
await tester.scrollUntilVisible(find.text('选址失败和正式丢包'), 200);
|
||||||
|
expect(find.text('选址失败和正式丢包'), findsOneWidget);
|
||||||
|
await tester.scrollUntilVisible(find.textContaining('RFC 3550'), 200);
|
||||||
|
expect(find.textContaining('RFC 3550'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.pageBack();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.byType(PopupMenuButton<String>));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('更新历史'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('网络质量探测 1.1.2'), findsOneWidget);
|
||||||
|
await tester.scrollUntilVisible(find.text('网络质量探测 1.1.1'), 200);
|
||||||
|
expect(find.text('网络质量探测 1.1.1'), findsOneWidget);
|
||||||
|
expect(find.textContaining('言灸'), findsOneWidget);
|
||||||
|
expect(find.textContaining('v1.1.1'), findsWidgets);
|
||||||
|
expect(find.text('网络质量探测 1.1.0'), findsNothing);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
+31
-2
@@ -44,7 +44,10 @@
|
|||||||
- **普通 TCP**:只记录连接耗时、成功或失败、连续失败。没有自定义帧。
|
- **普通 TCP**:只记录连接耗时、成功或失败、连续失败。没有自定义帧。
|
||||||
- **普通 UDP、DNS、自定义 UDP、基岩版**:没有收到符合协议的包时记为无应答/未知,不叫丢包。内容不对记为协议错误。
|
- **普通 UDP、DNS、自定义 UDP、基岩版**:没有收到符合协议的包时记为无应答/未知,不叫丢包。内容不对记为协议错误。
|
||||||
- **Minecraft Java**:状态握手加上 ping/pong。往返时间只算 ping 到对上 nonce 的 pong。连不上或协议不对记为失败率。
|
- **Minecraft Java**:状态握手加上 ping/pong。往返时间只算 ping 到对上 nonce 的 pong。连不上或协议不对记为失败率。
|
||||||
- **抖动**:RFC 3550。相邻两次成功的往返时间差 `D`,`J = J + (|D| - J) / 16`。
|
- **HTTP**:一次完整的 HTTP 响应算成功,4xx 和 5xx 写在状态码里,不叫丢包。连不上、TLS 失败、或强制的版本不被支持,记为失败率。曲线上的延迟是这一次的总时间。`detail` 另有 `dnsMs`、`connectMs`、`tlsMs`、`ttfbMs`、`totalMs`、`statusCode`、`finalUrl`、`httpVersion`(`1.1` / `2` / `3`)和 `redirects`。HTTP/3 的连接和 TLS 是同一次 QUIC 握手,这两项时间相同。
|
||||||
|
- **抖动**:RFC 3550。相邻两次成功的往返时间差 `D`,`J = J + (|D| - J) / 16`。第一次成功时 J 为 0。
|
||||||
|
- **延迟分布**:只统计成功样本。当前延迟是最近一次成功。最小、最大是极值。平均是算术平均。中位数在奇数个时取排序后的中间值,偶数个时取中间两个的平均。P95 用最近秩,秩 = ceil(0.95 × 次数),用整数 `(95 × 次数 + 99) / 100` 计算,从 1 起计。
|
||||||
|
- **选址**:一个名字解析出多个地址时,还没有任何地址应答之前的失败只用于挑选地址。后面有地址成功时,这些失败不进入已发送、超时和丢包,并在 `detail.fallback` 里说明。选定之后的失败照常计入。每个候选都失败时,这些失败计入正式结果,不能显示成 0% 成功。每条样本的 `detail.address` 和 `detail.family` 是这次实际连通或发包的地址;没有这个字段就表示节点没有报告,不能用解析结果代替。`summary` 另有 `minRttMs`、`meanRttMs`、`medianRttMs`、`p95RttMs`、`maxRttMs` 和 `selectionSkipped`。旧客户端会忽略不认识的字段。
|
||||||
|
|
||||||
## 控制接口
|
## 控制接口
|
||||||
|
|
||||||
@@ -52,7 +55,7 @@
|
|||||||
|
|
||||||
其余接口在配置了 `-node-token` 时都要先带 `Authorization: Bearer`,用常数时间比较。没带或不对就返回 401,并且不会向目标拨号。没配置节点口令时,这些接口公开可用。
|
其余接口在配置了 `-node-token` 时都要先带 `Authorization: Bearer`,用常数时间比较。没带或不对就返回 401,并且不会向目标拨号。没配置节点口令时,这些接口公开可用。
|
||||||
|
|
||||||
- `POST /v1/jobs` 创建一次探测。正文里的 `echoToken` 是反射帧口令,不是节点口令。
|
- `POST /v1/jobs` 创建一次探测。正文里的 `echoToken` 是反射帧口令,不是节点口令。`allowIPv4` 和 `allowIPv6` 省略时都当作打开,这样 1.1.2 的客户端仍然能用。两个都是 false 时返回 400,不会拨号。HTTP 任务再带一个 `http` 对象,字段见下面的类型表。
|
||||||
- `GET /v1/jobs/{id}/stream` 用 Server-Sent Events 推送已经在节点上算好的样本。
|
- `GET /v1/jobs/{id}/stream` 用 Server-Sent Events 推送已经在节点上算好的样本。
|
||||||
- `DELETE /v1/jobs/{id}` 停止。客户端断开结果流时,节点也会停止。任务有绝对到期时间,没人来看也会在大约 15 秒后停掉。
|
- `DELETE /v1/jobs/{id}` 停止。客户端断开结果流时,节点也会停止。任务有绝对到期时间,没人来看也会在大约 15 秒后停掉。
|
||||||
|
|
||||||
@@ -69,6 +72,32 @@
|
|||||||
| `minecraft-java` | 状态握手(协议号 767)加 ping/pong |
|
| `minecraft-java` | 状态握手(协议号 767)加 ping/pong |
|
||||||
| `minecraft-bedrock` | RakNet Unconnected Ping,magic 和时间戳都要对上 |
|
| `minecraft-bedrock` | RakNet Unconnected Ping,magic 和时间戳都要对上 |
|
||||||
| `custom-udp` | 十六进制载荷,可选响应前缀 |
|
| `custom-udp` | 十六进制载荷,可选响应前缀 |
|
||||||
|
| `http` | HTTP/1.1、HTTP/2 或 HTTP/3。`GET /v1/info` 的 `profiles` 里有 `http`,并且 `ipFamily` 为 true。没有这两项的是 1.1.2 节点 |
|
||||||
|
|
||||||
|
`http` 对象:
|
||||||
|
|
||||||
|
| 字段 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `version` | `auto`(默认,HTTP/2,不行再降到 1.1)、`1.1`、`2`、`3`。强制的版本不被支持就失败,不降级。明文强制 2 或 3 会失败,因为那两种需要 HTTPS |
|
||||||
|
| `resolve` | 可选。Host 和 SNI 仍用目标 URL,TCP 或 QUIC 改连这里的 IPv4 或另一个主机名。这不是更换 DNS 服务器 |
|
||||||
|
| `method` | `GET` 或 `POST` |
|
||||||
|
| `body` | 仅 POST。最长 64KB |
|
||||||
|
| `referer` / `userAgent` / `cookies` | 可选,各最长 4KB |
|
||||||
|
| `maxRedirects` | 0 到 20,不写时是 5。301/302/303 改为 GET 并丢掉正文;307/308 保持方法和正文。最终状态码是最后一跳的 |
|
||||||
|
|
||||||
|
目标可以是主机名,也可以是完整的 `http://` 或 `https://` URL。没写端口时,https 用 443,http 用 80。
|
||||||
|
|
||||||
|
本机探测不在 Dart 里另写一套 HTTP。桌面和 Android 都把请求交给同一个 Go 程序的 `-mode helper`,一行 JSON 进、一行结果出。环境变量 `NQ_PROBE_HELPER` 可以指向这个程序;不设置时,客户端在自己的可执行文件旁边找 `netquality-reflector`。
|
||||||
|
|
||||||
|
## 中心
|
||||||
|
|
||||||
|
同一个程序用 `-mode center -center-dir 目录` 当中心,也可以在节点模式上加 `-center-dir`,让一个进程同时提供 `/v1/` 和 `/v1/center/`。中心的控制接口同样要走 HTTPS,不要把明文口令暴露到公网。目录里只保存口令的 `sha256:` 哈希。日志不写口令、密码、Cookie 或请求体。
|
||||||
|
|
||||||
|
- `POST /v1/center/login`,正文 `{account, password}`。密码核对通过后返回一个新的会话口令。这个口令不是原来的长期口令,大约 12 小时有效,只返回这一次。
|
||||||
|
- `GET /v1/center/catalog`,`Authorization: Bearer` 中心口令。返回这个口令所属组能用的服务器。保密服务器只有 `id`、`name` 和 `confidential: true`,没有控制地址,也没有节点口令。非保密服务器带 `controlUrl` 和一条短期凭证,凭证大约 15 分钟有效,不是节点上的长期口令。
|
||||||
|
- `POST /v1/center/servers/{id}/jobs` 以及对应的 `GET .../stream`、`DELETE`。只接受该口令有权使用的服务器。保密节点由中心代为连接,客户端错误里不会出现节点地址。没有权限时返回 403,正文不带那个地址。
|
||||||
|
|
||||||
|
节点要接受中心签发的短期凭证,需要配置和中心相同的 `NQ_CENTER_KEY`,以及和服务器文件 `id` 相同的 `NQ_SERVER_ID`。1.1.2 的节点没有这些接口,只能继续手动添加。
|
||||||
|
|
||||||
## 例子
|
## 例子
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# 网络质量探测 1.1.2
|
||||||
|
|
||||||
|
构建号 5。署名:言灸。许可:GNU Affero General Public License v3.0(AGPL-3.0-only)。
|
||||||
|
|
||||||
|
这一版还没有打 Git 标签,也还没有发布安装包。下面是准备发布的说明。
|
||||||
|
|
||||||
|
## 节点和端口
|
||||||
|
|
||||||
|
- 已有远程节点可以改名称、控制地址和口令。节点编号和当前选择保持不变。
|
||||||
|
- 修改时口令留空表示继续使用已经保存在本机的口令。界面不会把原口令填出来。填写新口令才会替换。
|
||||||
|
- 端口框标明当前探测类型的默认端口。合作反射 TCP 默认 19090,合作反射 UDP 默认 19091。
|
||||||
|
- 只有端口仍是上一种类型的默认值,或者端口是空的,切换类型才会自动更换。自己填过的端口会留下。
|
||||||
|
|
||||||
|
## 实际地址
|
||||||
|
|
||||||
|
- 本机和 1.1.2 节点都会显示这次真正连通或真正发包的 IP,并注明 IPv4 或 IPv6。
|
||||||
|
- 域名解析出的地址单独标成「解析到」,不会被说成已经使用的地址。
|
||||||
|
- 1.1.2 之前的远程节点不会在结果里带地址。界面会写「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。
|
||||||
|
|
||||||
|
## 选址和丢包
|
||||||
|
|
||||||
|
- 还没有任何地址应答时,用来挑选地址的失败(例如 IPv6 没有应答,随后 IPv4 成功)不计入已发送、超时和正式丢包,并单独说明回退。
|
||||||
|
- 某个地址已经应答之后,对它的超时和失败仍然计入,不会因为后来又换地址而被抹掉。
|
||||||
|
- 只有一个地址时,失败从一开始就算正式结果。
|
||||||
|
- 每一个候选都失败时,这些失败计入正式结果。不会显示 0% 成功。
|
||||||
|
- 1.1.1 的节点仍可能把第一次选址失败算进统计。要分开看,节点也需要这一版。
|
||||||
|
|
||||||
|
## 指标和停止
|
||||||
|
|
||||||
|
- 结果给出已发送、已收到、超时、比率、当前/最小/平均/中位/P95/最大延迟、抖动和用时。
|
||||||
|
- 探测无应答 = 超时 ÷(超时 + 成功)。分母只含已经写出的回显尝试。分母为 0 时显示 —,不是 0%。
|
||||||
|
- 普通 TCP 和 Minecraft Java 显示失败率,不显示丢包百分比。
|
||||||
|
- 普通 UDP、DNS、自定义 UDP 和基岩版把沉默记为无应答。UDP 没有应答不能当成已经证实的丢包。
|
||||||
|
- 延迟分布只统计成功样本。P95 用最近秩,秩 = ceil(0.95 × 次数)。抖动沿用 RFC 3550。
|
||||||
|
- 手动停止后保留曲线,并给出开始、结束、用时、目标、来源、实际地址和同一套最终指标。
|
||||||
|
- 停止时还没完成的请求不计入丢包。
|
||||||
|
- 点曲线可以钉住该时刻的延迟和比率,松手后仍然保留。再点另一点会更换。新的一次探测,或该点滚出窗口后,选择不会跳到别的点上。
|
||||||
|
|
||||||
|
应用里增加了「指标说明」和「更新历史」。更新历史只列出仓库里真实存在的标签 v1.1.1,以及这一版。
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# 网络质量探测 1.1.3
|
||||||
|
|
||||||
|
版本名 `1.1.3`,构建号 `6`。应用标识和签名没有改,新的安装包会覆盖原来的程序,不用先卸载。
|
||||||
|
|
||||||
|
## 自更新
|
||||||
|
|
||||||
|
设置里有「自动检查更新」,默认打开。启动时会检查,设置里也可以点「检查更新」。先问 GitHub:
|
||||||
|
|
||||||
|
`https://api.github.com/repos/yanjiu0721/netquality/releases/latest`
|
||||||
|
|
||||||
|
连不上再问言灸的 Git:
|
||||||
|
|
||||||
|
`https://git.yanjiu.ltd/api/v1/repos/YanJiu/netquality/releases/latest`
|
||||||
|
|
||||||
|
有更新而且自动更新开着时,会下载当前系统对应的包。Windows、Linux amd64、Linux arm64,以及 Android 的 arm64-v8a、armeabi-v7a、x86_64 各有一个包。发布里如果有 SHA256SUMS,会先核对,对不上就停止。没有校验和文件时仍会安装,并在界面上说明。
|
||||||
|
|
||||||
|
关掉自动更新以后,启动时不检查,也不会自动下载。手动「检查更新」仍然可用,看到新版本后再点「下载并安装」。
|
||||||
|
|
||||||
|
Windows 和 Linux 把新文件写回当前安装目录,不另起一个程序。设置、节点、口令和探测历史放在应用数据目录,不在安装目录里,覆盖安装不会把它们清掉。Windows 上正在运行的程序文件不能当场替换,会等进程退出后再复制并重新打开。
|
||||||
|
|
||||||
|
Android 必须经过系统的安装确认,程序不能跳过这一步。界面上会写明。
|
||||||
|
|
||||||
|
1.1.2 没有更新器。从 1.1.2 升到 1.1.3 仍然要自己安装。自更新从 1.1.3 这一版才开始。
|
||||||
|
|
||||||
|
没有真正的新版本时,可以用环境变量试这个流程。`NQ_UPDATE_GITHUB_API` 和 `NQ_UPDATE_GITEA_API` 指向一份和上面接口同样格式的 JSON。
|
||||||
|
|
||||||
|
安装包名称:
|
||||||
|
|
||||||
|
- `netquality-client-1.1.3-windows-amd64.zip`
|
||||||
|
- `netquality-client-1.1.3-linux-amd64.tar.gz`
|
||||||
|
- `netquality-client-1.1.3-linux-arm64.tar.gz`
|
||||||
|
- `netquality-client-1.1.3-android-arm64-v8a.apk`
|
||||||
|
- `netquality-client-1.1.3-android-armeabi-v7a.apk`
|
||||||
|
- `netquality-client-1.1.3-android-x86_64.apk`
|
||||||
|
|
||||||
|
名字里带 server 或 reflector 的包不会被客户端选中。
|
||||||
|
|
||||||
|
## 最近目标
|
||||||
|
|
||||||
|
点「开始探测」之后,会记下主机或 IP、端口和探测类型。HTTP 还会记下 URL 和方法。目标框旁边的按钮列出这些记录,点一条会填回表单。每一条可以删除,也可以全部清除。最多保留 40 条。相同的目标只留最新的一条,并放到最上面。
|
||||||
|
|
||||||
|
这份列表只在本机。它不保存节点口令、中心口令、Cookie 或请求体。它和菜单里的「更新历史」不是同一页。
|
||||||
|
|
||||||
|
## IPv4 / IPv6
|
||||||
|
|
||||||
|
设置里两个开关,默认都开着。解析完成以后,只向打开的地址族发包。只开一个就只用那一个。两个都关掉时不会开始,并说明原因。目标本身就是已经关掉的那种地址时,也不会开始。
|
||||||
|
|
||||||
|
远程任务会带上 `allowIPv4` 和 `allowIPv6`。1.1.2 的节点不认识这个开关。两个都开着时,它仍按原来的方式探测。关掉其中一个时,客户端会先看 `/v1/info` 里有没有 `ipFamily: true`,没有就提示需要 1.1.3,而不是让旧节点继续用另一个地址族。结果里的实际地址和地址族,仍是这一次真正用到的那个。
|
||||||
|
|
||||||
|
## HTTP
|
||||||
|
|
||||||
|
新增探测类型「HTTP」。目标可以是主机名,也可以是 `https://example.com/path` 这样的完整地址。没写端口时,https 用 443,http 用 80。切换探测类型时,端口仍按原来的规则:只有当前端口是空的,或仍是上一种类型的默认端口,才会跟着换。离开 HTTP 时,80 和 443 都算默认端口。
|
||||||
|
|
||||||
|
协议默认是 HTTP/2,不行再降到 HTTP/1.1。也可以强制 HTTP/1.1、HTTP/2 或 HTTP/3。强制的版本不被支持就失败,不会悄悄换成另一种。明文连接上强制 HTTP/2 或 HTTP/3 也会失败,因为那两种需要 HTTPS。
|
||||||
|
|
||||||
|
指定解析的写法和 curl `--resolve` 一样:Host 和 SNI 仍用目标网址,TCP 或 QUIC 改连填写的 IPv4 或另一个主机名。这不是把某个地址当成 DNS 服务器。
|
||||||
|
|
||||||
|
方法可以是 GET 或 POST。POST 可以带请求体。Referer、User-Agent、Cookies 都是可选的。最大跳转次数默认 5。最终状态码是最后一跳的,结果里会列出跳转链。301、302、303 会改成 GET 并丢掉正文;307、308 保持原来的方法和正文。
|
||||||
|
|
||||||
|
每一次记下 DNS、连接、TLS、首字节、总时间、状态码、最终 URL,以及实际用到的 HTTP 版本。总时间用作曲线上的延迟。已经收到 HTTP 响应就算成功,4xx 和 5xx 只显示状态码,不叫丢包。
|
||||||
|
|
||||||
|
本机和远程节点用的是同一个 Go 引擎,里面包含 HTTP/3。桌面端把 `netquality-reflector` 放在程序旁边,或设置 `NQ_PROBE_HELPER`。找不到时,本机 HTTP 会说明缺引擎,远程 HTTP 不受影响。Android 如果系统不允许从应用目录启动这个程序,本机 HTTP 同样会说明,而不是改用另一套实现。
|
||||||
|
|
||||||
|
1.1.2 的节点没有 `http` 这个类型。客户端看到 `/v1/info` 里没有它,会提示节点需要升级。
|
||||||
|
|
||||||
|
## 中心
|
||||||
|
|
||||||
|
同一个 Go 程序可以当中心。配置放在一个目录里,示例是 `server/example-center`,口令都是占位。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./netquality-reflector -mode center -center-dir example-center -control-addr 127.0.0.1:8443
|
||||||
|
```
|
||||||
|
|
||||||
|
客户端新增「一键添加服务器」。填写中心地址、账号和口令。中心要求密码、手里还没有口令时,可以填账号和密码,登录后拿到的是一条会话口令,不是原来的长期口令。确认一次,会加入这个口令能用的全部服务器。一个客户端可以保存多个中心口令。展开后能看到名称;非保密节点还会看到地址。点刷新会跟上中心新增和删除的服务器。原来的「管理节点」还在,手动添加的节点和中心下发的节点可以同时存在。中心分配的名称不能在客户端里改。
|
||||||
|
|
||||||
|
保密节点的地址、IP 不会出现在客户端界面和本地保存的数据里,只保留中心分配的名称。对它的探测由中心转发到节点。中心不会把节点的长期口令交给客户端。非保密节点拿到的是大约 15 分钟的短期凭证,客户端用它直接连接。
|
||||||
|
|
||||||
|
中心的控制接口和节点一样,给别人用时要走 HTTPS。目录里只保存哈希。生成方式:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
printf '%s' '换成你自己的口令' | ./netquality-reflector -hash-secret
|
||||||
|
```
|
||||||
|
|
||||||
|
1.1.2 的节点仍可以手动添加。要当中心,或当中心下发的节点,需要 1.1.3 的服务端。节点上要配置和中心相同的 `NQ_CENTER_KEY`,以及和服务器文件 `id` 相同的 `NQ_SERVER_ID`。systemd 和防火墙的例子在 `docs/server-linux.md`。
|
||||||
+38
-1
@@ -63,7 +63,7 @@ ss -lunp | grep 19091
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo mkdir -p /opt/netquality
|
sudo mkdir -p /opt/netquality
|
||||||
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.1-linux-amd64.tar.gz
|
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.3-linux-amd64.tar.gz
|
||||||
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
|
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
|
||||||
sudo systemctl daemon-reload
|
sudo systemctl daemon-reload
|
||||||
sudo systemctl enable --now netquality
|
sudo systemctl enable --now netquality
|
||||||
@@ -192,6 +192,43 @@ probe.example {
|
|||||||
4. 目标地址、端口、类型另填。例如 Minecraft Java 用游戏域名和 `25565`。
|
4. 目标地址、端口、类型另填。例如 Minecraft Java 用游戏域名和 `25565`。
|
||||||
5. 点「开始探测」。延迟是节点到目标的时间。停止后节点会结束任务。
|
5. 点「开始探测」。延迟是节点到目标的时间。停止后节点会结束任务。
|
||||||
|
|
||||||
|
## 7. 把同一程序当成中心
|
||||||
|
|
||||||
|
中心用来一次下发一批探测节点。它不是另一个软件。配置放在一个目录里:
|
||||||
|
|
||||||
|
- `groups.json`:用户组
|
||||||
|
- `tokens.json`:口令和密码的 `sha256:` 哈希,不写原文
|
||||||
|
- `servers/*.json`:中心分配的显示名、节点控制地址、哪些组可以用、是否保密。节点的长期口令只写在这里
|
||||||
|
- `center.key`:签发短期凭证的密钥。第一行非注释内容就是密钥
|
||||||
|
|
||||||
|
生成哈希时,原文从标准输入读,不会出现在命令行参数里:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
printf '%s' '换成你自己的口令' | ./netquality-reflector -hash-secret
|
||||||
|
```
|
||||||
|
|
||||||
|
把打印出来的 `sha256:` 开头那一行写进 `tokens.json`。示例目录在仓库的 `server/example-center`,口令都是占位,不要拿到公网上用。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo mkdir -p /etc/netquality/center
|
||||||
|
sudo cp -a server/example-center/. /etc/netquality/center/
|
||||||
|
# 换成自己的哈希、地址和 center.key 以后再启动
|
||||||
|
./netquality-reflector -mode center -center-dir /etc/netquality/center -control-addr 127.0.0.1:8443
|
||||||
|
```
|
||||||
|
|
||||||
|
对应的环境变量是 `NQ_MODE=center`、`NQ_CENTER_DIR`、`NQ_CENTER_KEY`。节点要认中心签发的短期凭证时,再设 `NQ_SERVER_ID`,值和该节点在中心服务器文件里的 `id` 相同,`NQ_CENTER_KEY` 和中心的密钥相同。
|
||||||
|
|
||||||
|
控制接口会带中心口令,公网必须走 HTTPS,和节点控制端口一样。可以用程序自己的 `-tls-cert` / `-tls-key`,也可以用 Caddy 或 nginx 反代到 `127.0.0.1:8443`。防火墙和安全组只放行 443。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo firewall-cmd --permanent --add-port=443/tcp
|
||||||
|
sudo firewall-cmd --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
systemd 示例是 `deploy/netquality-center.service`。`ProtectSystem=strict` 仍然能读你在服务文件里用 `ReadOnlyPaths` 放行的配置目录。不要把真实口令写进服务文件。
|
||||||
|
|
||||||
|
1.1.2 的节点还能在客户端里手动添加。要当中心,或者要当中心下发的节点,需要 1.1.3 的服务端。
|
||||||
|
|
||||||
## 本机演示补充
|
## 本机演示补充
|
||||||
|
|
||||||
在自己的电脑上同时开反射和节点,并允许它探测本机:
|
在自己的电脑上同时开反射和节点,并允许它探测本机:
|
||||||
|
|||||||
+15
-1
@@ -24,10 +24,12 @@ NQ_UDP_PORT=19091
|
|||||||
# 这和下面的节点口令不是同一个东西。
|
# 这和下面的节点口令不是同一个东西。
|
||||||
NQ_TOKEN=
|
NQ_TOKEN=
|
||||||
|
|
||||||
# 工作模式,三选一:
|
# 工作模式:
|
||||||
# reflector 只做反射:把收到的探测包原样送回去。这是默认。
|
# reflector 只做反射:把收到的探测包原样送回去。这是默认。
|
||||||
# node 只做检测节点:按手机的指令去测别的地址。
|
# node 只做检测节点:按手机的指令去测别的地址。
|
||||||
# both 反射和节点一起开。
|
# both 反射和节点一起开。
|
||||||
|
# center 只做中心:按配置目录里的分组和口令分发节点。需要下面的 NQ_CENTER_DIR。
|
||||||
|
# helper 给本机客户端做 HTTP 探测,不监听端口。
|
||||||
NQ_MODE=reflector
|
NQ_MODE=reflector
|
||||||
|
|
||||||
# 节点控制地址。手机「管理节点」里填的就是这个地址。
|
# 节点控制地址。手机「管理节点」里填的就是这个地址。
|
||||||
@@ -58,3 +60,15 @@ NQ_TLS_KEY=
|
|||||||
# 是否把每一个收发的包都写进日志。只能写 true 或 false。
|
# 是否把每一个收发的包都写进日志。只能写 true 或 false。
|
||||||
# 平常保持 false。排查问题时再改成 true。
|
# 平常保持 false。排查问题时再改成 true。
|
||||||
NQ_VERBOSE=false
|
NQ_VERBOSE=false
|
||||||
|
|
||||||
|
# 中心配置目录。模式是 center 时必填。节点模式也可以同时填写,控制端口会一并提供中心接口。
|
||||||
|
# 留空表示不做中心。目录里放 groups.json、tokens.json、servers/*.json,密钥放 center.key。
|
||||||
|
NQ_CENTER_DIR=
|
||||||
|
|
||||||
|
# 中心用来签发短期凭证的密钥。节点要核对这些凭证时也填同一串。
|
||||||
|
# 留空时,如果填写了中心目录,会改读该目录里的 center.key。
|
||||||
|
# 不要把真实密钥写进仓库,也不要出现在日志里。
|
||||||
|
NQ_CENTER_KEY=
|
||||||
|
|
||||||
|
# 这台节点在中心服务器文件里的编号。要接受中心签发的短期凭证时必填,并且要和服务器文件的 id 一致。
|
||||||
|
NQ_SERVER_ID=
|
||||||
+15
-1
@@ -24,10 +24,12 @@ NQ_UDP_PORT=19091
|
|||||||
# 这和下面的节点口令不是同一个东西。
|
# 这和下面的节点口令不是同一个东西。
|
||||||
NQ_TOKEN=
|
NQ_TOKEN=
|
||||||
|
|
||||||
# 工作模式,三选一:
|
# 工作模式:
|
||||||
# reflector 只做反射:把收到的探测包原样送回去。这是默认。
|
# reflector 只做反射:把收到的探测包原样送回去。这是默认。
|
||||||
# node 只做检测节点:按手机的指令去测别的地址。
|
# node 只做检测节点:按手机的指令去测别的地址。
|
||||||
# both 反射和节点一起开。
|
# both 反射和节点一起开。
|
||||||
|
# center 只做中心:按配置目录里的分组和口令分发节点。需要下面的 NQ_CENTER_DIR。
|
||||||
|
# helper 给本机客户端做 HTTP 探测,不监听端口。
|
||||||
NQ_MODE=reflector
|
NQ_MODE=reflector
|
||||||
|
|
||||||
# 节点控制地址。手机「管理节点」里填的就是这个地址。
|
# 节点控制地址。手机「管理节点」里填的就是这个地址。
|
||||||
@@ -58,3 +60,15 @@ NQ_TLS_KEY=
|
|||||||
# 是否把每一个收发的包都写进日志。只能写 true 或 false。
|
# 是否把每一个收发的包都写进日志。只能写 true 或 false。
|
||||||
# 平常保持 false。排查问题时再改成 true。
|
# 平常保持 false。排查问题时再改成 true。
|
||||||
NQ_VERBOSE=false
|
NQ_VERBOSE=false
|
||||||
|
|
||||||
|
# 中心配置目录。模式是 center 时必填。节点模式也可以同时填写,控制端口会一并提供中心接口。
|
||||||
|
# 留空表示不做中心。目录里放 groups.json、tokens.json、servers/*.json,密钥放 center.key。
|
||||||
|
NQ_CENTER_DIR=
|
||||||
|
|
||||||
|
# 中心用来签发短期凭证的密钥。节点要核对这些凭证时也填同一串。
|
||||||
|
# 留空时,如果填写了中心目录,会改读该目录里的 center.key。
|
||||||
|
# 不要把真实密钥写进仓库,也不要出现在日志里。
|
||||||
|
NQ_CENTER_KEY=
|
||||||
|
|
||||||
|
# 这台节点在中心服务器文件里的编号。要接受中心签发的短期凭证时必填,并且要和服务器文件的 id 一致。
|
||||||
|
NQ_SERVER_ID=
|
||||||
+2
-1
@@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
- **反射**:把探测包原样送回去。手机直接测到这台机器的延迟。
|
- **反射**:把探测包原样送回去。手机直接测到这台机器的延迟。
|
||||||
- **节点**:手机只下指令。这台机器替手机去测别的地址,例如游戏服务器。
|
- **节点**:手机只下指令。这台机器替手机去测别的地址,例如游戏服务器。
|
||||||
|
- **中心**:一个配置目录里放用户组、口令哈希和探测节点。手机填一次中心口令,就能加入这个口令能用的全部节点。说明和示例在仓库的 `example-center/`,以及 `docs/server-linux.md`。
|
||||||
|
|
||||||
压缩包里已经有一份能直接用的 `.env`,默认端口和以前一样:TCP `19090`、UDP `19091`。不改也能用。
|
压缩包里已经有一份能直接用的 `.env`,默认端口和以前一样:TCP `19090`、UDP `19091`。不改也能用。
|
||||||
|
|
||||||
@@ -110,7 +111,7 @@ sudo firewall-cmd --reload
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo mkdir -p /opt/netquality
|
sudo mkdir -p /opt/netquality
|
||||||
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.1-linux-amd64.tar.gz
|
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.3-linux-amd64.tar.gz
|
||||||
sudo chmod 755 /opt/netquality/netquality-reflector
|
sudo chmod 755 /opt/netquality/netquality-reflector
|
||||||
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
|
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
|
||||||
sudo systemctl daemon-reload
|
sudo systemctl daemon-reload
|
||||||
|
|||||||
@@ -0,0 +1,474 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
centerSessionTTL = 12 * time.Hour
|
||||||
|
centerCredTTL = 15 * time.Minute
|
||||||
|
)
|
||||||
|
|
||||||
|
type centerGroup struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type centerToken struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Group string `json:"group"`
|
||||||
|
Account string `json:"account"`
|
||||||
|
TokenHash string `json:"tokenHash"`
|
||||||
|
PasswordHash string `json:"passwordHash"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type centerServer struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
ControlURL string `json:"controlUrl"`
|
||||||
|
Groups []string `json:"groups"`
|
||||||
|
Confidential bool `json:"confidential"`
|
||||||
|
NodeToken string `json:"nodeToken"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type centerConfig struct {
|
||||||
|
groups []centerGroup
|
||||||
|
tokens []centerToken
|
||||||
|
servers []centerServer
|
||||||
|
}
|
||||||
|
|
||||||
|
type centerSession struct {
|
||||||
|
group string
|
||||||
|
account string
|
||||||
|
exp time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Center is the same process as the probe node, serving a directory of
|
||||||
|
// groups, token hashes and servers. Confidential nodes are proxied.
|
||||||
|
// Their addresses are not included in catalog responses.
|
||||||
|
type Center struct {
|
||||||
|
Dir string
|
||||||
|
Key []byte
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
sessions map[string]centerSession
|
||||||
|
client *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func newCenter(dir string, key string) *Center {
|
||||||
|
c := &Center{
|
||||||
|
Dir: dir,
|
||||||
|
sessions: map[string]centerSession{},
|
||||||
|
client: &http.Client{
|
||||||
|
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(key) != "" {
|
||||||
|
c.Key = []byte(strings.TrimSpace(key))
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) Handler() http.Handler {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("POST /v1/center/login", c.login)
|
||||||
|
mux.HandleFunc("GET /v1/center/catalog", c.catalog)
|
||||||
|
mux.HandleFunc("POST /v1/center/servers/{id}/jobs", c.proxyCreate)
|
||||||
|
mux.HandleFunc("GET /v1/center/servers/{id}/jobs/{jobId}", c.proxySnapshot)
|
||||||
|
mux.HandleFunc("GET /v1/center/servers/{id}/jobs/{jobId}/stream", c.proxyStream)
|
||||||
|
mux.HandleFunc("DELETE /v1/center/servers/{id}/jobs/{jobId}", c.proxyDelete)
|
||||||
|
return mux
|
||||||
|
}
|
||||||
|
|
||||||
|
type catalogServer struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Confidential bool `json:"confidential"`
|
||||||
|
ControlURL string `json:"controlUrl,omitempty"`
|
||||||
|
Credential string `json:"credential,omitempty"`
|
||||||
|
CredentialExpiresAt string `json:"credentialExpiresAt,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) login(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req struct {
|
||||||
|
Account string `json:"account"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
dec := json.NewDecoder(io.LimitReader(r.Body, 1<<16))
|
||||||
|
if err := dec.Decode(&req); err != nil {
|
||||||
|
writeErr(w, http.StatusBadRequest, "bad_request", "请求内容无法解析")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg, err := c.load()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("center config: %v", err)
|
||||||
|
writeErr(w, http.StatusInternalServerError, "config", "中心配置无法读取")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
account := strings.TrimSpace(req.Account)
|
||||||
|
var matched *centerToken
|
||||||
|
for i := range cfg.tokens {
|
||||||
|
tok := &cfg.tokens[i]
|
||||||
|
if tok.Account != account || tok.PasswordHash == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if hashEqual(tok.PasswordHash, req.Password) && c.groupKnown(cfg, tok.Group) {
|
||||||
|
matched = tok
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if matched == nil {
|
||||||
|
log.Printf("center login failed")
|
||||||
|
writeErr(w, http.StatusUnauthorized, "unauthorized", "账号或密码不正确")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raw, err := randomToken()
|
||||||
|
if err != nil {
|
||||||
|
writeErr(w, http.StatusInternalServerError, "error", "暂时无法登录")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
exp := time.Now().Add(centerSessionTTL)
|
||||||
|
c.mu.Lock()
|
||||||
|
c.sessions[hashSecret(raw)] = centerSession{group: matched.Group, account: matched.Account, exp: exp}
|
||||||
|
c.mu.Unlock()
|
||||||
|
writeJSON(w, http.StatusOK, map[string]string{
|
||||||
|
"token": raw,
|
||||||
|
"account": matched.Account,
|
||||||
|
"group": matched.Group,
|
||||||
|
"expiresAt": exp.UTC().Format(time.RFC3339),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) catalog(w http.ResponseWriter, r *http.Request) {
|
||||||
|
group, account, ok := c.who(r)
|
||||||
|
if !ok {
|
||||||
|
writeErr(w, http.StatusUnauthorized, "unauthorized", "中心口令不正确或未提供")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cfg, err := c.load()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("center config: %v", err)
|
||||||
|
writeErr(w, http.StatusInternalServerError, "config", "中心配置无法读取")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
items := make([]catalogServer, 0)
|
||||||
|
for _, srv := range cfg.servers {
|
||||||
|
if !containsString(srv.Groups, group) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
item := catalogServer{ID: srv.ID, Name: srv.Name, Confidential: srv.Confidential}
|
||||||
|
if srv.Confidential {
|
||||||
|
items = append(items, item)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(c.Key) == 0 {
|
||||||
|
writeErr(w, http.StatusInternalServerError, "config", "中心没有 center.key,不能给非保密节点签发短期凭证")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
exp := time.Now().Add(centerCredTTL)
|
||||||
|
cred, err := mintCredential(srv.ID, exp, c.Key)
|
||||||
|
if err != nil {
|
||||||
|
writeErr(w, http.StatusInternalServerError, "config", "无法签发短期凭证")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
item.ControlURL = srv.ControlURL
|
||||||
|
item.Credential = cred
|
||||||
|
item.CredentialExpiresAt = exp.UTC().Format(time.RFC3339)
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"account": account,
|
||||||
|
"group": group,
|
||||||
|
"servers": items,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) proxyCreate(w http.ResponseWriter, r *http.Request) {
|
||||||
|
c.proxy(w, r, "/v1/jobs")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) proxySnapshot(w http.ResponseWriter, r *http.Request) {
|
||||||
|
c.proxy(w, r, "/v1/jobs/"+url.PathEscape(r.PathValue("jobId")))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) proxyStream(w http.ResponseWriter, r *http.Request) {
|
||||||
|
c.proxy(w, r, "/v1/jobs/"+url.PathEscape(r.PathValue("jobId"))+"/stream")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) proxyDelete(w http.ResponseWriter, r *http.Request) {
|
||||||
|
c.proxy(w, r, "/v1/jobs/"+url.PathEscape(r.PathValue("jobId")))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) proxy(w http.ResponseWriter, r *http.Request, path string) {
|
||||||
|
srv, ok := c.authorizedServer(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
base, err := url.Parse(srv.ControlURL)
|
||||||
|
if err != nil || base.Host == "" {
|
||||||
|
writeErr(w, http.StatusBadGateway, "node", "连不上节点")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
target := base.ResolveReference(&url.URL{Path: path})
|
||||||
|
body := io.Reader(nil)
|
||||||
|
if r.Body != nil && r.Method != http.MethodGet && r.Method != http.MethodDelete {
|
||||||
|
body = io.LimitReader(r.Body, 1<<16)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(r.Context(), r.Method, target.String(), body)
|
||||||
|
if err != nil {
|
||||||
|
writeErr(w, http.StatusBadGateway, "node", "连不上节点")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if srv.NodeToken != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+srv.NodeToken)
|
||||||
|
}
|
||||||
|
if r.Header.Get("Content-Type") != "" {
|
||||||
|
req.Header.Set("Content-Type", r.Header.Get("Content-Type"))
|
||||||
|
}
|
||||||
|
resp, err := c.client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("center proxy failed server=%s", srv.ID)
|
||||||
|
writeErr(w, http.StatusBadGateway, "node", "连不上节点")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode >= 300 && resp.StatusCode < 400 {
|
||||||
|
writeErr(w, http.StatusBadGateway, "node", "节点地址发生了跳转")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if ct := resp.Header.Get("Content-Type"); ct != "" {
|
||||||
|
w.Header().Set("Content-Type", ct)
|
||||||
|
}
|
||||||
|
if strings.Contains(resp.Header.Get("Content-Type"), "event-stream") {
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
w.Header().Set("X-Accel-Buffering", "no")
|
||||||
|
w.WriteHeader(resp.StatusCode)
|
||||||
|
flusher, _ := w.(http.Flusher)
|
||||||
|
buf := make([]byte, 32*1024)
|
||||||
|
for {
|
||||||
|
n, readErr := resp.Body.Read(buf)
|
||||||
|
if n > 0 {
|
||||||
|
if _, err := w.Write(buf[:n]); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if flusher != nil {
|
||||||
|
flusher.Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if readErr != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.WriteHeader(resp.StatusCode)
|
||||||
|
_, _ = io.Copy(w, resp.Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) authorizedServer(w http.ResponseWriter, r *http.Request) (centerServer, bool) {
|
||||||
|
group, _, ok := c.who(r)
|
||||||
|
if !ok {
|
||||||
|
writeErr(w, http.StatusUnauthorized, "unauthorized", "中心口令不正确或未提供")
|
||||||
|
return centerServer{}, false
|
||||||
|
}
|
||||||
|
cfg, err := c.load()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("center config: %v", err)
|
||||||
|
writeErr(w, http.StatusInternalServerError, "config", "中心配置无法读取")
|
||||||
|
return centerServer{}, false
|
||||||
|
}
|
||||||
|
id := r.PathValue("id")
|
||||||
|
for _, srv := range cfg.servers {
|
||||||
|
if srv.ID != id {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !containsString(srv.Groups, group) {
|
||||||
|
writeErr(w, http.StatusForbidden, "forbidden", "这个口令不能使用该服务器")
|
||||||
|
return centerServer{}, false
|
||||||
|
}
|
||||||
|
return srv, true
|
||||||
|
}
|
||||||
|
writeErr(w, http.StatusNotFound, "not_found", "没有这台服务器")
|
||||||
|
return centerServer{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) who(r *http.Request) (string, string, bool) {
|
||||||
|
raw := bearer(r.Header.Get("Authorization"))
|
||||||
|
if raw == "" {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
sum := hashSecret(raw)
|
||||||
|
now := time.Now()
|
||||||
|
c.mu.Lock()
|
||||||
|
if s, ok := c.sessions[sum]; ok {
|
||||||
|
if now.Before(s.exp) {
|
||||||
|
c.mu.Unlock()
|
||||||
|
return s.group, s.account, true
|
||||||
|
}
|
||||||
|
delete(c.sessions, sum)
|
||||||
|
}
|
||||||
|
c.mu.Unlock()
|
||||||
|
cfg, err := c.load()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("center config: %v", err)
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
for _, tok := range cfg.tokens {
|
||||||
|
if tok.TokenHash == "" || !c.groupKnown(cfg, tok.Group) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if hashEqual(tok.TokenHash, raw) {
|
||||||
|
return tok.Group, tok.Account, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) groupKnown(cfg centerConfig, id string) bool {
|
||||||
|
for _, g := range cfg.groups {
|
||||||
|
if g.ID == id {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Center) load() (centerConfig, error) {
|
||||||
|
var cfg centerConfig
|
||||||
|
var groups struct {
|
||||||
|
Groups []centerGroup `json:"groups"`
|
||||||
|
}
|
||||||
|
if err := readJSONFile(filepath.Join(c.Dir, "groups.json"), &groups); err != nil {
|
||||||
|
return cfg, err
|
||||||
|
}
|
||||||
|
var tokens struct {
|
||||||
|
Tokens []centerToken `json:"tokens"`
|
||||||
|
}
|
||||||
|
if err := readJSONFile(filepath.Join(c.Dir, "tokens.json"), &tokens); err != nil {
|
||||||
|
return cfg, err
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(filepath.Join(c.Dir, "servers"))
|
||||||
|
if err != nil {
|
||||||
|
return cfg, err
|
||||||
|
}
|
||||||
|
seen := map[string]struct{}{}
|
||||||
|
var servers []centerServer
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var srv centerServer
|
||||||
|
if err := readJSONFile(filepath.Join(c.Dir, "servers", entry.Name()), &srv); err != nil {
|
||||||
|
return cfg, err
|
||||||
|
}
|
||||||
|
if err := validateCenterServer(srv); err != nil {
|
||||||
|
return cfg, err
|
||||||
|
}
|
||||||
|
if _, ok := seen[srv.ID]; ok {
|
||||||
|
return cfg, fmt.Errorf("duplicate server id")
|
||||||
|
}
|
||||||
|
seen[srv.ID] = struct{}{}
|
||||||
|
servers = append(servers, srv)
|
||||||
|
}
|
||||||
|
groupIDs := map[string]struct{}{}
|
||||||
|
for _, g := range groups.Groups {
|
||||||
|
if !validServerID(g.ID) {
|
||||||
|
return cfg, fmt.Errorf("bad group id")
|
||||||
|
}
|
||||||
|
if _, ok := groupIDs[g.ID]; ok {
|
||||||
|
return cfg, fmt.Errorf("duplicate group")
|
||||||
|
}
|
||||||
|
groupIDs[g.ID] = struct{}{}
|
||||||
|
}
|
||||||
|
for _, tok := range tokens.Tokens {
|
||||||
|
if _, ok := groupIDs[tok.Group]; !ok {
|
||||||
|
return cfg, fmt.Errorf("token group missing")
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(strings.TrimSpace(tok.TokenHash), "sha256:") {
|
||||||
|
return cfg, fmt.Errorf("token hash missing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, srv := range servers {
|
||||||
|
for _, g := range srv.Groups {
|
||||||
|
if _, ok := groupIDs[g]; !ok {
|
||||||
|
return cfg, fmt.Errorf("server group missing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cfg.groups = groups.Groups
|
||||||
|
cfg.tokens = tokens.Tokens
|
||||||
|
cfg.servers = servers
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateCenterServer(srv centerServer) error {
|
||||||
|
if !validServerID(srv.ID) || strings.TrimSpace(srv.Name) == "" {
|
||||||
|
return fmt.Errorf("bad server")
|
||||||
|
}
|
||||||
|
u, err := url.Parse(strings.TrimSpace(srv.ControlURL))
|
||||||
|
if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") || u.User != nil {
|
||||||
|
return fmt.Errorf("bad control url")
|
||||||
|
}
|
||||||
|
if len(srv.Groups) == 0 {
|
||||||
|
return fmt.Errorf("server has no group")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readJSONFile(path string, dest any) error {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
dec := json.NewDecoder(io.LimitReader(f, 1<<20))
|
||||||
|
if err := dec.Decode(dest); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsString(list []string, want string) bool {
|
||||||
|
for _, item := range list {
|
||||||
|
if item == want {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadCenterKeyFile(dir string) (string, error) {
|
||||||
|
if strings.TrimSpace(dir) == "" {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
b, err := os.ReadFile(filepath.Join(dir, "center.key"))
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
for _, line := range strings.Split(string(b), "\n") {
|
||||||
|
line = strings.TrimSpace(strings.TrimRight(line, "\r"))
|
||||||
|
if line == "" || strings.HasPrefix(line, "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return line, nil
|
||||||
|
}
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,306 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCredentialRoundTrip(t *testing.T) {
|
||||||
|
key := []byte("example-center-key")
|
||||||
|
exp := time.Now().Add(time.Minute)
|
||||||
|
token, err := mintCredential("lab-node", exp, key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !verifyCredential(token, key, "lab-node", time.Now()) {
|
||||||
|
t.Fatal("fresh credential rejected")
|
||||||
|
}
|
||||||
|
if verifyCredential(token, key, "other", time.Now()) {
|
||||||
|
t.Fatal("wrong server accepted")
|
||||||
|
}
|
||||||
|
if verifyCredential(token, []byte("other-key"), "lab-node", time.Now()) {
|
||||||
|
t.Fatal("wrong key accepted")
|
||||||
|
}
|
||||||
|
old, err := mintCredential("lab-node", time.Now().Add(-time.Second), key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if verifyCredential(old, key, "lab-node", time.Now()) {
|
||||||
|
t.Fatal("expired credential accepted")
|
||||||
|
}
|
||||||
|
if hashEqual("example-token", "example-token") {
|
||||||
|
t.Fatal("raw secret was accepted as a stored hash")
|
||||||
|
}
|
||||||
|
if !hashEqual(hashSecret("example-token"), "example-token") {
|
||||||
|
t.Fatal("hash mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCenterGroupsAndConfidentialProxy(t *testing.T) {
|
||||||
|
const nodeToken = "super-secret-node-token"
|
||||||
|
const hiddenHost = "secret-node.internal"
|
||||||
|
node := newNode(nodeToken, true, nil, testLimits())
|
||||||
|
node.ServerID = "lab-node"
|
||||||
|
node.CenterKey = []byte("center-key")
|
||||||
|
nodeSrv := httptest.NewServer(node.Handler())
|
||||||
|
defer nodeSrv.Close()
|
||||||
|
page := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusServiceUnavailable)
|
||||||
|
}))
|
||||||
|
defer page.Close()
|
||||||
|
|
||||||
|
dir := t.TempDir()
|
||||||
|
writeCenterFixture(t, dir, nodeSrv.URL, "https://"+hiddenHost+":8443", nodeToken, "center-key")
|
||||||
|
mustWrite(t, filepath.Join(dir, "servers", "addr.json"), `{
|
||||||
|
"id":"addr-node","name":"带地址的保密节点","controlUrl":"https://203.0.113.55:8443","groups":["lab"],"confidential":true,"nodeToken":"`+nodeToken+`"
|
||||||
|
}`)
|
||||||
|
center := newCenter(dir, "center-key")
|
||||||
|
api := httptest.NewServer(center.Handler())
|
||||||
|
defer api.Close()
|
||||||
|
|
||||||
|
catalog := centerGET(t, api.URL+"/v1/center/catalog", "lab-token")
|
||||||
|
raw, _ := io.ReadAll(catalog.Body)
|
||||||
|
catalog.Body.Close()
|
||||||
|
if catalog.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("catalog %d %s", catalog.StatusCode, raw)
|
||||||
|
}
|
||||||
|
body := string(raw)
|
||||||
|
if strings.Contains(body, hiddenHost) || strings.Contains(body, nodeToken) || strings.Contains(body, "203.0.113.55") {
|
||||||
|
t.Fatalf("catalog leaked a hidden address or token: %s", body)
|
||||||
|
}
|
||||||
|
var parsed struct {
|
||||||
|
Group string `json:"group"`
|
||||||
|
Servers []struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Confidential bool `json:"confidential"`
|
||||||
|
ControlURL string `json:"controlUrl"`
|
||||||
|
Credential string `json:"credential"`
|
||||||
|
} `json:"servers"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &parsed); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if parsed.Group != "lab" || len(parsed.Servers) != 4 {
|
||||||
|
t.Fatalf("parsed %+v", parsed)
|
||||||
|
}
|
||||||
|
var publicCred, secretName string
|
||||||
|
for _, srv := range parsed.Servers {
|
||||||
|
if srv.Confidential {
|
||||||
|
secretName = srv.Name
|
||||||
|
if srv.ControlURL != "" || srv.Credential != "" {
|
||||||
|
t.Fatalf("confidential item %+v", srv)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if srv.ControlURL != nodeSrv.URL || srv.Credential == "" || srv.Credential == nodeToken {
|
||||||
|
t.Fatalf("public item %+v", srv)
|
||||||
|
}
|
||||||
|
publicCred = srv.Credential
|
||||||
|
}
|
||||||
|
if secretName != "保密节点" || publicCred == "" {
|
||||||
|
t.Fatalf("names %+v", parsed.Servers)
|
||||||
|
}
|
||||||
|
if !verifyCredential(publicCred, node.CenterKey, "lab-node", time.Now()) {
|
||||||
|
t.Fatal("catalog credential is not accepted by the node key")
|
||||||
|
}
|
||||||
|
direct := postJSON(t, nodeSrv.URL+"/v1/jobs", `{"target":"127.0.0.1","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":200,"durationSec":1}`)
|
||||||
|
direct.Body.Close()
|
||||||
|
req, _ := http.NewRequest(http.MethodPost, nodeSrv.URL+"/v1/jobs", strings.NewReader(`{"target":"127.0.0.1","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":200,"durationSec":1}`))
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+publicCred)
|
||||||
|
res, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
res.Body.Close()
|
||||||
|
if direct.StatusCode != http.StatusUnauthorized || res.StatusCode != http.StatusCreated {
|
||||||
|
t.Fatalf("direct %d credential %d", direct.StatusCode, res.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
other := centerGET(t, api.URL+"/v1/center/catalog", "ops-token")
|
||||||
|
otherRaw, _ := io.ReadAll(other.Body)
|
||||||
|
other.Body.Close()
|
||||||
|
if other.StatusCode != http.StatusOK || strings.Contains(string(otherRaw), "实验室节点") || strings.Contains(string(otherRaw), hiddenHost) {
|
||||||
|
t.Fatalf("other group %d %s", other.StatusCode, otherRaw)
|
||||||
|
}
|
||||||
|
|
||||||
|
denied := centerPOST(t, api.URL+"/v1/center/servers/secret-node/jobs", "ops-token", `{"target":"127.0.0.1","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":200,"durationSec":1}`)
|
||||||
|
deniedRaw, _ := io.ReadAll(denied.Body)
|
||||||
|
denied.Body.Close()
|
||||||
|
if denied.StatusCode != http.StatusForbidden || strings.Contains(string(deniedRaw), hiddenHost) || strings.Contains(string(deniedRaw), nodeToken) {
|
||||||
|
t.Fatalf("denied %d %s", denied.StatusCode, deniedRaw)
|
||||||
|
}
|
||||||
|
|
||||||
|
jobBody := `{"target":"` + page.URL + `/","port":` + page.URL[strings.LastIndex(page.URL, ":")+1:] + `,"profile":"http","intervalMs":200,"timeoutMs":1500,"durationSec":2,"allowIPv4":true,"allowIPv6":false,"http":{"version":"1.1","method":"GET"}}`
|
||||||
|
created := centerPOST(t, api.URL+"/v1/center/servers/secret-node/jobs", "lab-token", jobBody)
|
||||||
|
createdRaw, _ := io.ReadAll(created.Body)
|
||||||
|
created.Body.Close()
|
||||||
|
if created.StatusCode != http.StatusCreated || strings.Contains(string(createdRaw), hiddenHost) || strings.Contains(string(createdRaw), nodeToken) {
|
||||||
|
t.Fatalf("proxy create %d %s", created.StatusCode, createdRaw)
|
||||||
|
}
|
||||||
|
var job struct {
|
||||||
|
JobID string `json:"jobId"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(createdRaw, &job); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
streamReq, _ := http.NewRequest(http.MethodGet, api.URL+"/v1/center/servers/secret-node/jobs/"+job.JobID+"/stream", nil)
|
||||||
|
streamReq.Header.Set("Authorization", "Bearer lab-token")
|
||||||
|
stream, err := http.DefaultClient.Do(streamReq)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer stream.Body.Close()
|
||||||
|
sample := readSSEMap(t, stream.Body)
|
||||||
|
if sample["status"] != "ok" {
|
||||||
|
t.Fatalf("proxied sample %+v", sample)
|
||||||
|
}
|
||||||
|
note, _ := sample["note"].(string)
|
||||||
|
if !strings.Contains(note, "不是丢包") {
|
||||||
|
t.Fatalf("note %s", note)
|
||||||
|
}
|
||||||
|
|
||||||
|
login := centerPOST(t, api.URL+"/v1/center/login", "", `{"account":"lab","password":"example-password"}`)
|
||||||
|
loginRaw, _ := io.ReadAll(login.Body)
|
||||||
|
login.Body.Close()
|
||||||
|
if login.StatusCode != http.StatusOK || strings.Contains(string(loginRaw), "example-password") {
|
||||||
|
t.Fatalf("login %d %s", login.StatusCode, loginRaw)
|
||||||
|
}
|
||||||
|
var session map[string]string
|
||||||
|
if err := json.Unmarshal(loginRaw, &session); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if session["token"] == "" || session["token"] == "lab-token" {
|
||||||
|
t.Fatalf("session %+v", session)
|
||||||
|
}
|
||||||
|
again := centerGET(t, api.URL+"/v1/center/catalog", session["token"])
|
||||||
|
againRaw, _ := io.ReadAll(again.Body)
|
||||||
|
again.Body.Close()
|
||||||
|
if again.StatusCode != http.StatusOK || strings.Contains(string(againRaw), hiddenHost) {
|
||||||
|
t.Fatalf("session catalog %d %s", again.StatusCode, againRaw)
|
||||||
|
}
|
||||||
|
stored, err := os.ReadFile(filepath.Join(dir, "tokens.json"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Contains(string(stored), "lab-token") || strings.Contains(string(stored), "example-password") {
|
||||||
|
t.Fatalf("token file stored a raw secret: %s", stored)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExampleCenterLoads(t *testing.T) {
|
||||||
|
center := newCenter("example-center", "")
|
||||||
|
key, err := loadCenterKeyFile("example-center")
|
||||||
|
if err != nil || key == "" {
|
||||||
|
t.Fatal(err, key)
|
||||||
|
}
|
||||||
|
center.Key = []byte(key)
|
||||||
|
if _, err := center.load(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
api := httptest.NewServer(center.Handler())
|
||||||
|
defer api.Close()
|
||||||
|
res := centerGET(t, api.URL+"/v1/center/catalog", "example-token")
|
||||||
|
raw, _ := io.ReadAll(res.Body)
|
||||||
|
res.Body.Close()
|
||||||
|
if res.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("example catalog %d %s", res.StatusCode, raw)
|
||||||
|
}
|
||||||
|
if strings.Contains(string(raw), "secret-node.internal") || strings.Contains(string(raw), "example-secret-node-token") || strings.Contains(string(raw), "example-node-token") {
|
||||||
|
t.Fatalf("example catalog leaked: %s", raw)
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(raw), "实验室节点") || !strings.Contains(string(raw), "保密节点") {
|
||||||
|
t.Fatalf("example catalog %s", raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeCenterFixture(t *testing.T, dir, publicURL, secretURL, nodeToken, key string) {
|
||||||
|
t.Helper()
|
||||||
|
mustWrite(t, filepath.Join(dir, "groups.json"), `{"groups":[{"id":"lab","name":"实验室"},{"id":"ops","name":"另一组"}]}`)
|
||||||
|
mustWrite(t, filepath.Join(dir, "tokens.json"), `{"tokens":[`+
|
||||||
|
`{"id":"lab-reader","group":"lab","account":"lab","tokenHash":"`+hashSecret("lab-token")+`","passwordHash":"`+hashSecret("example-password")+`"},`+
|
||||||
|
`{"id":"ops-reader","group":"ops","account":"ops","tokenHash":"`+hashSecret("ops-token")+`"}`+
|
||||||
|
`]}`)
|
||||||
|
if err := os.MkdirAll(filepath.Join(dir, "servers"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
mustWrite(t, filepath.Join(dir, "servers", "lab.json"), `{
|
||||||
|
"id":"lab-node","name":"实验室节点","controlUrl":"`+publicURL+`","groups":["lab"],"confidential":false,"nodeToken":"`+nodeToken+`"
|
||||||
|
}`)
|
||||||
|
mustWrite(t, filepath.Join(dir, "servers", "secret.json"), `{
|
||||||
|
"id":"secret-node","name":"保密节点","controlUrl":"`+publicURL+`","groups":["lab"],"confidential":true,"nodeToken":"`+nodeToken+`"
|
||||||
|
}`)
|
||||||
|
mustWrite(t, filepath.Join(dir, "servers", "hidden.json"), `{
|
||||||
|
"id":"hidden-node","name":"另一台保密节点","controlUrl":"`+secretURL+`","groups":["lab"],"confidential":true,"nodeToken":"`+nodeToken+`"
|
||||||
|
}`)
|
||||||
|
mustWrite(t, filepath.Join(dir, "center.key"), key+"\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func centerGET(t *testing.T, rawURL, token string) *http.Response {
|
||||||
|
t.Helper()
|
||||||
|
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if token != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
}
|
||||||
|
res, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
func centerPOST(t *testing.T, rawURL, token, body string) *http.Response {
|
||||||
|
t.Helper()
|
||||||
|
req, err := http.NewRequest(http.MethodPost, rawURL, strings.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
if token != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
}
|
||||||
|
res, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
func readSSEMap(t *testing.T, r io.Reader) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
sc := bufio.NewScanner(r)
|
||||||
|
var data string
|
||||||
|
for sc.Scan() {
|
||||||
|
line := sc.Text()
|
||||||
|
if strings.HasPrefix(line, "data: ") {
|
||||||
|
data = strings.TrimPrefix(line, "data: ")
|
||||||
|
}
|
||||||
|
if line == "" && data != "" && data != "{}" {
|
||||||
|
var msg map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(data), &msg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if status, _ := msg["status"].(string); status != "" && status != "pending" {
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
data = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("no sample: %v", sc.Err())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+32
-4
@@ -40,6 +40,9 @@ type Config struct {
|
|||||||
TLSCert string
|
TLSCert string
|
||||||
TLSKey string
|
TLSKey string
|
||||||
Verbose bool
|
Verbose bool
|
||||||
|
CenterDir string
|
||||||
|
CenterKey string
|
||||||
|
ServerID string
|
||||||
LoadedFiles []string
|
LoadedFiles []string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,7 +53,7 @@ func (c Config) Summary() string {
|
|||||||
files = strings.Join(c.LoadedFiles, ", ")
|
files = strings.Join(c.LoadedFiles, ", ")
|
||||||
}
|
}
|
||||||
return fmt.Sprintf(
|
return fmt.Sprintf(
|
||||||
"生效配置 mode=%s bind=%s tcp_port=%d udp_port=%d control_addr=%s echo_token=%s node_token=%s allow_private=%t allow_nets=%s tls_cert=%s tls_key=%s verbose=%t 配置文件=%s",
|
"生效配置 mode=%s bind=%s tcp_port=%d udp_port=%d control_addr=%s echo_token=%s node_token=%s allow_private=%t allow_nets=%s tls_cert=%s tls_key=%s verbose=%t center_dir=%s center_key=%s server_id=%s 配置文件=%s",
|
||||||
c.Mode,
|
c.Mode,
|
||||||
c.Bind,
|
c.Bind,
|
||||||
c.TCPPort,
|
c.TCPPort,
|
||||||
@@ -63,6 +66,9 @@ func (c Config) Summary() string {
|
|||||||
pathState(c.TLSCert),
|
pathState(c.TLSCert),
|
||||||
pathState(c.TLSKey),
|
pathState(c.TLSKey),
|
||||||
c.Verbose,
|
c.Verbose,
|
||||||
|
pathState(c.CenterDir),
|
||||||
|
secretState(c.CenterKey),
|
||||||
|
emptyState(c.ServerID),
|
||||||
files,
|
files,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -81,6 +87,13 @@ func pathState(s string) string {
|
|||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func emptyState(s string) string {
|
||||||
|
if strings.TrimSpace(s) == "" {
|
||||||
|
return "未设置"
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
// loadConfig resolves configuration for a real process start.
|
// loadConfig resolves configuration for a real process start.
|
||||||
// A missing .env next to the executable or in the working directory is ignored.
|
// A missing .env next to the executable or in the working directory is ignored.
|
||||||
func loadConfig(args []string, environ []string) (Config, error) {
|
func loadConfig(args []string, environ []string) (Config, error) {
|
||||||
@@ -107,12 +120,15 @@ func loadConfigAt(args []string, environ []string, exeDir, cwd string) (Config,
|
|||||||
udpPort := fs.Int("udp-port", defaultUDPPort, "UDP 反射端口,0 表示关闭,对应 NQ_UDP_PORT")
|
udpPort := fs.Int("udp-port", defaultUDPPort, "UDP 反射端口,0 表示关闭,对应 NQ_UDP_PORT")
|
||||||
token := fs.String("token", "", "回显口令,最长 32 字节,留空不校验,对应 NQ_TOKEN")
|
token := fs.String("token", "", "回显口令,最长 32 字节,留空不校验,对应 NQ_TOKEN")
|
||||||
nodeToken := fs.String("node-token", "", "节点口令,留空则节点公开,对应 NQ_NODE_TOKEN")
|
nodeToken := fs.String("node-token", "", "节点口令,留空则节点公开,对应 NQ_NODE_TOKEN")
|
||||||
mode := fs.String("mode", defaultMode, "reflector、node 或 both,对应 NQ_MODE")
|
mode := fs.String("mode", defaultMode, "reflector、node、both、center 或 helper,对应 NQ_MODE")
|
||||||
controlAddr := fs.String("control-addr", defaultControlAddr, "节点控制地址,对应 NQ_CONTROL_ADDR")
|
controlAddr := fs.String("control-addr", defaultControlAddr, "节点控制地址,对应 NQ_CONTROL_ADDR")
|
||||||
allowPrivate := fs.Bool("allow-private", false, "允许探测本机和局域网,对应 NQ_ALLOW_PRIVATE")
|
allowPrivate := fs.Bool("allow-private", false, "允许探测本机和局域网,对应 NQ_ALLOW_PRIVATE")
|
||||||
allowNets := fs.String("allow-nets", "", "额外允许的网段,逗号分隔,对应 NQ_ALLOW_NETS")
|
allowNets := fs.String("allow-nets", "", "额外允许的网段,逗号分隔,对应 NQ_ALLOW_NETS")
|
||||||
tlsCert := fs.String("tls-cert", "", "控制端口证书,对应 NQ_TLS_CERT")
|
tlsCert := fs.String("tls-cert", "", "控制端口证书,对应 NQ_TLS_CERT")
|
||||||
tlsKey := fs.String("tls-key", "", "控制端口私钥,对应 NQ_TLS_KEY")
|
tlsKey := fs.String("tls-key", "", "控制端口私钥,对应 NQ_TLS_KEY")
|
||||||
|
centerDir := fs.String("center-dir", "", "中心配置目录,对应 NQ_CENTER_DIR")
|
||||||
|
centerKey := fs.String("center-key", "", "中心短期凭证密钥,对应 NQ_CENTER_KEY。不要把真实密钥写进命令历史")
|
||||||
|
serverID := fs.String("server-id", "", "本节点在中心里的编号,对应 NQ_SERVER_ID")
|
||||||
envPath := fs.String("env", "", "额外的 .env 路径,会覆盖其他 .env;文件必须存在")
|
envPath := fs.String("env", "", "额外的 .env 路径,会覆盖其他 .env;文件必须存在")
|
||||||
verbose := fs.Bool("v", false, "打印每一包日志,对应 NQ_VERBOSE")
|
verbose := fs.Bool("v", false, "打印每一包日志,对应 NQ_VERBOSE")
|
||||||
fs.Usage = func() {
|
fs.Usage = func() {
|
||||||
@@ -121,6 +137,9 @@ func loadConfigAt(args []string, environ []string, exeDir, cwd string) (Config,
|
|||||||
优先级:命令行参数 > 环境变量 > .env 文件 > 内置默认值。
|
优先级:命令行参数 > 环境变量 > .env 文件 > 内置默认值。
|
||||||
启动时读取程序所在目录和当前目录下的 .env(路径相同则只读一次)。
|
启动时读取程序所在目录和当前目录下的 .env(路径相同则只读一次)。
|
||||||
找不到这些 .env 不会报错。-env 指定的文件必须存在,并覆盖前面的 .env。
|
找不到这些 .env 不会报错。-env 指定的文件必须存在,并覆盖前面的 .env。
|
||||||
|
-mode 可以是 reflector、node、both、center 或 helper。
|
||||||
|
center 读取 -center-dir。helper 从标准输入读 HTTP 探测,供本机客户端使用。
|
||||||
|
-hash-secret 从标准输入读一行,只打印哈希,不启动服务。
|
||||||
|
|
||||||
`)
|
`)
|
||||||
fs.PrintDefaults()
|
fs.PrintDefaults()
|
||||||
@@ -152,6 +171,9 @@ func loadConfigAt(args []string, environ []string, exeDir, cwd string) (Config,
|
|||||||
cfg.AllowNets = pickString(visited["allow-nets"], *allowNets, "NQ_ALLOW_NETS", real, fileEnv, "")
|
cfg.AllowNets = pickString(visited["allow-nets"], *allowNets, "NQ_ALLOW_NETS", real, fileEnv, "")
|
||||||
cfg.TLSCert = pickString(visited["tls-cert"], *tlsCert, "NQ_TLS_CERT", real, fileEnv, "")
|
cfg.TLSCert = pickString(visited["tls-cert"], *tlsCert, "NQ_TLS_CERT", real, fileEnv, "")
|
||||||
cfg.TLSKey = pickString(visited["tls-key"], *tlsKey, "NQ_TLS_KEY", real, fileEnv, "")
|
cfg.TLSKey = pickString(visited["tls-key"], *tlsKey, "NQ_TLS_KEY", real, fileEnv, "")
|
||||||
|
cfg.CenterDir = pickString(visited["center-dir"], *centerDir, "NQ_CENTER_DIR", real, fileEnv, "")
|
||||||
|
cfg.CenterKey = pickString(visited["center-key"], *centerKey, "NQ_CENTER_KEY", real, fileEnv, "")
|
||||||
|
cfg.ServerID = pickString(visited["server-id"], *serverID, "NQ_SERVER_ID", real, fileEnv, "")
|
||||||
|
|
||||||
tcpRaw := pickString(visited["tcp-port"], strconv.Itoa(*tcpPort), "NQ_TCP_PORT", real, fileEnv, strconv.Itoa(defaultTCPPort))
|
tcpRaw := pickString(visited["tcp-port"], strconv.Itoa(*tcpPort), "NQ_TCP_PORT", real, fileEnv, strconv.Itoa(defaultTCPPort))
|
||||||
udpRaw := pickString(visited["udp-port"], strconv.Itoa(*udpPort), "NQ_UDP_PORT", real, fileEnv, strconv.Itoa(defaultUDPPort))
|
udpRaw := pickString(visited["udp-port"], strconv.Itoa(*udpPort), "NQ_UDP_PORT", real, fileEnv, strconv.Itoa(defaultUDPPort))
|
||||||
@@ -195,9 +217,12 @@ func pickString(fromFlag bool, flagVal, envKey string, real, file map[string]str
|
|||||||
|
|
||||||
func (c Config) validate() error {
|
func (c Config) validate() error {
|
||||||
switch c.Mode {
|
switch c.Mode {
|
||||||
case "reflector", "node", "both":
|
case "reflector", "node", "both", "center", "helper":
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("NQ_MODE 必须是 reflector、node 或 both,当前是 %q", c.Mode)
|
return fmt.Errorf("NQ_MODE 必须是 reflector、node、both、center 或 helper,当前是 %q", c.Mode)
|
||||||
|
}
|
||||||
|
if c.Mode == "center" && strings.TrimSpace(c.CenterDir) == "" {
|
||||||
|
return fmt.Errorf("中心模式需要 NQ_CENTER_DIR 或 -center-dir")
|
||||||
}
|
}
|
||||||
if c.TCPPort < 0 || c.TCPPort > 65535 || c.UDPPort < 0 || c.UDPPort > 65535 {
|
if c.TCPPort < 0 || c.TCPPort > 65535 || c.UDPPort < 0 || c.UDPPort > 65535 {
|
||||||
return fmt.Errorf("端口必须在 0 到 65535 之间")
|
return fmt.Errorf("端口必须在 0 到 65535 之间")
|
||||||
@@ -337,6 +362,9 @@ var knownEnvKeys = map[string]struct{}{
|
|||||||
"NQ_TLS_CERT": {},
|
"NQ_TLS_CERT": {},
|
||||||
"NQ_TLS_KEY": {},
|
"NQ_TLS_KEY": {},
|
||||||
"NQ_VERBOSE": {},
|
"NQ_VERBOSE": {},
|
||||||
|
"NQ_CENTER_DIR": {},
|
||||||
|
"NQ_CENTER_KEY": {},
|
||||||
|
"NQ_SERVER_ID": {},
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseDotEnv(r io.Reader) (map[string]string, error) {
|
func parseDotEnv(r io.Reader) (map[string]string, error) {
|
||||||
|
|||||||
@@ -157,7 +157,7 @@ func TestConfigValidation(t *testing.T) {
|
|||||||
|
|
||||||
func TestSummaryMasksTokens(t *testing.T) {
|
func TestSummaryMasksTokens(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
mustWrite(t, filepath.Join(dir, ".env"), "NQ_TOKEN=super-secret-echo\nNQ_NODE_TOKEN=super-secret-node\nNQ_MODE=both\n")
|
mustWrite(t, filepath.Join(dir, ".env"), "NQ_TOKEN=super-secret-echo\nNQ_NODE_TOKEN=super-secret-node\nNQ_CENTER_KEY=super-secret-center\nNQ_MODE=both\n")
|
||||||
cfg, err := loadConfigAt(nil, nil, dir, t.TempDir())
|
cfg, err := loadConfigAt(nil, nil, dir, t.TempDir())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -166,7 +166,7 @@ func TestSummaryMasksTokens(t *testing.T) {
|
|||||||
if strings.Contains(line, "super-secret") {
|
if strings.Contains(line, "super-secret") {
|
||||||
t.Fatal(line)
|
t.Fatal(line)
|
||||||
}
|
}
|
||||||
if !strings.Contains(line, "echo_token=已设置") || !strings.Contains(line, "node_token=已设置") {
|
if !strings.Contains(line, "echo_token=已设置") || !strings.Contains(line, "node_token=已设置") || !strings.Contains(line, "center_key=已设置") {
|
||||||
t.Fatal(line)
|
t.Fatal(line)
|
||||||
}
|
}
|
||||||
plain, err := loadConfigAt(nil, nil, t.TempDir(), t.TempDir())
|
plain, err := loadConfigAt(nil, nil, t.TempDir(), t.TempDir())
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// hashSecret returns the stored form of a token or password.
|
||||||
|
// Only this hash is written to the center config. The raw value is not.
|
||||||
|
func hashSecret(secret string) string {
|
||||||
|
sum := sha256.Sum256([]byte(secret))
|
||||||
|
return "sha256:" + hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func hashEqual(stored, secret string) bool {
|
||||||
|
stored = strings.TrimSpace(stored)
|
||||||
|
want := hashSecret(secret)
|
||||||
|
if len(stored) != len(want) {
|
||||||
|
subtle.ConstantTimeCompare([]byte(want), []byte(want))
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return subtle.ConstantTimeCompare([]byte(stored), []byte(want)) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomToken() (string, error) {
|
||||||
|
var b [32]byte
|
||||||
|
if _, err := rand.Read(b[:]); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(b[:]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// mintCredential signs a short-lived node credential. It is not the node's
|
||||||
|
// long-lived token. The payload is the server id and an expiry, nothing else.
|
||||||
|
func mintCredential(serverID string, exp time.Time, key []byte) (string, error) {
|
||||||
|
if len(key) == 0 {
|
||||||
|
return "", errors.New("missing center key")
|
||||||
|
}
|
||||||
|
if !validServerID(serverID) {
|
||||||
|
return "", errors.New("bad server id")
|
||||||
|
}
|
||||||
|
payload := serverID + "|" + strconv.FormatInt(exp.Unix(), 10)
|
||||||
|
enc := base64.RawURLEncoding.EncodeToString([]byte(payload))
|
||||||
|
mac := hmac.New(sha256.New, key)
|
||||||
|
_, _ = mac.Write([]byte(enc))
|
||||||
|
sig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||||
|
return "nq1." + enc + "." + sig, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyCredential(token string, key []byte, serverID string, now time.Time) bool {
|
||||||
|
if len(key) == 0 || !validServerID(serverID) || token == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
parts := strings.Split(token, ".")
|
||||||
|
if len(parts) != 3 || parts[0] != "nq1" || parts[1] == "" || parts[2] == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
mac := hmac.New(sha256.New, key)
|
||||||
|
_, _ = mac.Write([]byte(parts[1]))
|
||||||
|
expected := mac.Sum(nil)
|
||||||
|
got, err := base64.RawURLEncoding.DecodeString(parts[2])
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !hmac.Equal(expected, got) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
id, expText, ok := strings.Cut(string(raw), "|")
|
||||||
|
if !ok || id != serverID {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
expUnix, err := strconv.ParseInt(expText, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
exp := time.Unix(expUnix, 0)
|
||||||
|
return now.Before(exp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func validServerID(id string) bool {
|
||||||
|
if id == "" || len(id) > 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range id {
|
||||||
|
switch {
|
||||||
|
case r >= 'a' && r <= 'z':
|
||||||
|
case r >= 'A' && r <= 'Z':
|
||||||
|
case r >= '0' && r <= '9':
|
||||||
|
case r == '.' || r == '_' || r == '-':
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=网络质量探测中心
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=/opt/netquality
|
||||||
|
ExecStart=/opt/netquality/netquality-reflector
|
||||||
|
Environment=NQ_MODE=center
|
||||||
|
Environment=NQ_CENTER_DIR=/etc/netquality/center
|
||||||
|
Environment=NQ_CONTROL_ADDR=127.0.0.1:8443
|
||||||
|
ReadOnlyPaths=/etc/netquality/center
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=2
|
||||||
|
NoNewPrivileges=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=true
|
||||||
|
PrivateTmp=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# 中心配置示例
|
||||||
|
|
||||||
|
这里的口令、密码和密钥都是占位,只能用来在本机看目录长什么样。不要拿到公网上去用。
|
||||||
|
|
||||||
|
目录:
|
||||||
|
|
||||||
|
- `groups.json`:用户组。一个中心可以有很多组。
|
||||||
|
- `tokens.json`:只保存口令和密码的 `sha256:` 哈希,不保存原文。每一条口令只属于一个组。
|
||||||
|
- `servers/*.json`:中心分配的显示名、节点控制地址、哪些组可以用、是否保密。节点的长期口令只写在这里,发给中心用来转发,不会交给客户端。
|
||||||
|
- `center.key`:签发短期凭证的密钥。节点上的 `NQ_CENTER_KEY` 要和它相同,`NQ_SERVER_ID` 要和对应服务器文件的 `id` 相同。
|
||||||
|
|
||||||
|
示例账号 `lab`,口令原文 `example-token`,密码原文 `example-password`。哈希用:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
printf '%s' 'example-token' | ./netquality-reflector -hash-secret
|
||||||
|
```
|
||||||
|
|
||||||
|
`实验室节点` 不是保密的,客户端能看到地址,并用短期凭证直接连接。`保密节点` 的地址只留在这份配置里,目录接口不会把它交出去,探测由中心转发。
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# 这是示例密钥,不能用于真正的部署。换成只有中心和对应节点知道的一长串随机字符。
|
||||||
|
example-center-key
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"groups": [
|
||||||
|
{"id": "lab", "name": "实验室"}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"id": "lab-node",
|
||||||
|
"name": "实验室节点",
|
||||||
|
"controlUrl": "https://127.0.0.1:8443",
|
||||||
|
"groups": ["lab"],
|
||||||
|
"confidential": false,
|
||||||
|
"nodeToken": "example-node-token"
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"id": "secret-node",
|
||||||
|
"name": "保密节点",
|
||||||
|
"controlUrl": "https://secret-node.internal:8443",
|
||||||
|
"groups": ["lab"],
|
||||||
|
"confidential": true,
|
||||||
|
"nodeToken": "example-secret-node-token"
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"tokens": [
|
||||||
|
{
|
||||||
|
"id": "lab-reader",
|
||||||
|
"group": "lab",
|
||||||
|
"account": "lab",
|
||||||
|
"tokenHash": "sha256:4d1566a1d7df42a8517456d60ea06ed284e535cfe4c956aa6ee172dbcdf945f7",
|
||||||
|
"passwordHash": "sha256:a4b7fbda9179055ba005b83fe1d9d558c85e5f6afc2ce4071439ecdab864b98e"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// familyError is a user-facing refusal to use an address family.
|
||||||
|
type familyError struct{ msg string }
|
||||||
|
|
||||||
|
func (e *familyError) Error() string { return e.msg }
|
||||||
|
|
||||||
|
func familyMessage(msg string) error { return &familyError{msg: msg} }
|
||||||
|
|
||||||
|
// filterFamily keeps only the address families the user turned on.
|
||||||
|
// A literal address of a disabled family is refused. When every resolved
|
||||||
|
// address is in a disabled family, the probe does not start.
|
||||||
|
func filterFamily(host string, ips []net.IP, allow4, allow6 bool) ([]net.IP, error) {
|
||||||
|
if !allow4 && !allow6 {
|
||||||
|
return nil, familyMessage("IPv4 和 IPv6 都已关闭,无法开始探测")
|
||||||
|
}
|
||||||
|
literal := net.ParseIP(strings.Trim(strings.TrimSpace(host), "[]"))
|
||||||
|
if literal != nil {
|
||||||
|
if literal.To4() != nil && !allow4 {
|
||||||
|
return nil, familyMessage("目标是 IPv4 地址,但 IPv4 已关闭")
|
||||||
|
}
|
||||||
|
if literal.To4() == nil && !allow6 {
|
||||||
|
return nil, familyMessage("目标是 IPv6 地址,但 IPv6 已关闭")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := make([]net.IP, 0, len(ips))
|
||||||
|
for _, ip := range ips {
|
||||||
|
if ip == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if ip.To4() != nil {
|
||||||
|
if allow4 {
|
||||||
|
out = append(out, ip)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if allow6 {
|
||||||
|
out = append(out, ip)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(out) == 0 {
|
||||||
|
return nil, familyMessage("解析到的地址都不在已打开的地址族里")
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func flagOrDefault(v *bool, fallback bool) bool {
|
||||||
|
if v == nil {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
return *v
|
||||||
|
}
|
||||||
|
|
||||||
|
// preferIP rotates ips so preferred is first when it is one of them.
|
||||||
|
func preferIP(ips []net.IP, preferred net.IP) []net.IP {
|
||||||
|
if preferred == nil || len(ips) == 0 {
|
||||||
|
return ips
|
||||||
|
}
|
||||||
|
for i, ip := range ips {
|
||||||
|
if ip.Equal(preferred) {
|
||||||
|
if i == 0 {
|
||||||
|
return ips
|
||||||
|
}
|
||||||
|
out := make([]net.IP, 0, len(ips))
|
||||||
|
out = append(out, ips[i:]...)
|
||||||
|
out = append(out, ips[:i]...)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ips
|
||||||
|
}
|
||||||
|
|
||||||
|
func asFamily(err error) (*familyError, bool) {
|
||||||
|
var fe *familyError
|
||||||
|
if errors.As(err, &fe) {
|
||||||
|
return fe, true
|
||||||
|
}
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
@@ -1,3 +1,21 @@
|
|||||||
module netquality/server
|
module netquality/server
|
||||||
|
|
||||||
go 1.22
|
go 1.22
|
||||||
|
|
||||||
|
require github.com/quic-go/quic-go v0.49.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
|
||||||
|
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 // indirect
|
||||||
|
github.com/onsi/ginkgo/v2 v2.9.5 // indirect
|
||||||
|
github.com/quic-go/qpack v0.5.1 // indirect
|
||||||
|
go.uber.org/mock v0.5.0 // indirect
|
||||||
|
golang.org/x/crypto v0.26.0 // indirect
|
||||||
|
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
|
||||||
|
golang.org/x/mod v0.18.0 // indirect
|
||||||
|
golang.org/x/net v0.28.0 // indirect
|
||||||
|
golang.org/x/sync v0.8.0 // indirect
|
||||||
|
golang.org/x/sys v0.23.0 // indirect
|
||||||
|
golang.org/x/text v0.17.0 // indirect
|
||||||
|
golang.org/x/tools v0.22.0 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||||
|
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||||
|
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ=
|
||||||
|
github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||||
|
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI=
|
||||||
|
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls=
|
||||||
|
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||||
|
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||||
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
|
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 h1:yAJXTCF9TqKcTiHJAE8dj7HMvPfh66eeA2JYW7eFpSE=
|
||||||
|
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||||
|
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||||
|
github.com/onsi/ginkgo/v2 v2.9.5 h1:+6Hr4uxzP4XIUyAkg61dWBw8lb/gc4/X5luuxN/EC+Q=
|
||||||
|
github.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3RonqW57k=
|
||||||
|
github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE=
|
||||||
|
github.com/onsi/gomega v1.27.6/go.mod h1:PIQNjfQwkP3aQAH7lf7j87O/5FiNr+ZR8+ipb+qQlhg=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||||
|
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||||
|
github.com/quic-go/quic-go v0.49.0 h1:w5iJHXwHxs1QxyBv1EHKuC50GX5to8mJAxvtnttJp94=
|
||||||
|
github.com/quic-go/quic-go v0.49.0/go.mod h1:s2wDnmCdooUQBmQfpUSTCYBl1/D4FcqbULMMkASvR6s=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||||
|
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
|
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||||
|
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||||
|
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
|
||||||
|
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
|
||||||
|
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
|
||||||
|
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
|
||||||
|
golang.org/x/mod v0.18.0 h1:5+9lSbEzPSdWkH32vYPBwEpX8KwDbM52Ud9xBUvNlb0=
|
||||||
|
golang.org/x/mod v0.18.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||||
|
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
|
||||||
|
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
|
||||||
|
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
|
||||||
|
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
|
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM=
|
||||||
|
golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
|
||||||
|
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||||
|
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
|
||||||
|
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||||
|
golang.org/x/tools v0.22.0 h1:gqSGLZqv+AI9lIQzniJ0nZDRG5GBPsSi+DRNHWNz6yA=
|
||||||
|
golang.org/x/tools v0.22.0/go.mod h1:aCwcsjqvq7Yqt6TNyX7QMU2enbQ/Gt0bo6krSeEri+c=
|
||||||
|
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
|
||||||
|
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// runHelper speaks one JSON request per line and writes one JSON outcome.
|
||||||
|
// The Flutter client uses this for local HTTP probes so it runs the same
|
||||||
|
// engine as a remote node. Logs stay off stdout.
|
||||||
|
func runHelper(r io.Reader, w io.Writer) error {
|
||||||
|
sc := bufio.NewScanner(r)
|
||||||
|
sc.Buffer(make([]byte, 64*1024), 1<<20)
|
||||||
|
enc := json.NewEncoder(w)
|
||||||
|
for sc.Scan() {
|
||||||
|
line := strings.TrimSpace(sc.Text())
|
||||||
|
if line == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var req helperRequest
|
||||||
|
if err := json.Unmarshal([]byte(line), &req); err != nil {
|
||||||
|
_ = enc.Encode(outcomeWire(httpFail(statusError, "请求无法解析")))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if req.Profile != "" && req.Profile != "http" {
|
||||||
|
_ = enc.Encode(outcomeWire(httpFail(statusError, "本机引擎目前只负责 HTTP 探测")))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out := probeHTTP(context.Background(), req.ctxInput())
|
||||||
|
_ = enc.Encode(outcomeWire(out))
|
||||||
|
}
|
||||||
|
return sc.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
type helperRequest struct {
|
||||||
|
Profile string `json:"profile"`
|
||||||
|
Target string `json:"target"`
|
||||||
|
Port int `json:"port"`
|
||||||
|
TimeoutMs int `json:"timeoutMs"`
|
||||||
|
AllowIPv4 *bool `json:"allowIPv4"`
|
||||||
|
AllowIPv6 *bool `json:"allowIPv6"`
|
||||||
|
HTTP *httpOptionsReq `json:"http"`
|
||||||
|
Insecure bool `json:"insecure"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type httpOptionsReq struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
Resolve string `json:"resolve"`
|
||||||
|
Method string `json:"method"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
Referer string `json:"referer"`
|
||||||
|
UserAgent string `json:"userAgent"`
|
||||||
|
Cookies string `json:"cookies"`
|
||||||
|
MaxRedirects *int `json:"maxRedirects"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h helperRequest) ctxInput() HTTPInput {
|
||||||
|
in := HTTPInput{
|
||||||
|
Target: h.Target,
|
||||||
|
Port: h.Port,
|
||||||
|
Timeout: 0,
|
||||||
|
Allow4: flagOrDefault(h.AllowIPv4, true),
|
||||||
|
Allow6: flagOrDefault(h.AllowIPv6, true),
|
||||||
|
CheckSafety: false,
|
||||||
|
AllowPrivate: true,
|
||||||
|
Insecure: h.Insecure,
|
||||||
|
}
|
||||||
|
if h.TimeoutMs > 0 {
|
||||||
|
in.Timeout = time.Duration(h.TimeoutMs) * time.Millisecond
|
||||||
|
}
|
||||||
|
applyHTTPOptions(&in, h.HTTP)
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyHTTPOptions(in *HTTPInput, opt *httpOptionsReq) {
|
||||||
|
if opt == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
in.Version = opt.Version
|
||||||
|
in.Resolve = opt.Resolve
|
||||||
|
in.Method = opt.Method
|
||||||
|
in.Body = opt.Body
|
||||||
|
in.Referer = opt.Referer
|
||||||
|
in.UserAgent = opt.UserAgent
|
||||||
|
in.Cookies = opt.Cookies
|
||||||
|
if opt.MaxRedirects != nil {
|
||||||
|
in.MaxRedirects = *opt.MaxRedirects
|
||||||
|
in.MaxSet = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type wireOutcome struct {
|
||||||
|
Status string `json:"status"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
RttMs *float64 `json:"rttMs,omitempty"`
|
||||||
|
Note string `json:"note,omitempty"`
|
||||||
|
Detail map[string]string `json:"detail,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func outcomeWire(o Outcome) wireOutcome {
|
||||||
|
w := wireOutcome{Status: o.Status, Kind: o.Kind, Note: o.Note, Detail: o.Detail}
|
||||||
|
if o.HasRtt {
|
||||||
|
ms := float64(o.Rtt) / float64(1e6)
|
||||||
|
w.RttMs = &ms
|
||||||
|
}
|
||||||
|
return w
|
||||||
|
}
|
||||||
@@ -0,0 +1,646 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptrace"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/quic-go/quic-go"
|
||||||
|
"github.com/quic-go/quic-go/http3"
|
||||||
|
)
|
||||||
|
|
||||||
|
const httpBodyCap = 32 << 10
|
||||||
|
|
||||||
|
// HTTPInput is one HTTP probe. The same function serves the node and the
|
||||||
|
// local helper, so desktop, Android and remote nodes share this engine.
|
||||||
|
type HTTPInput struct {
|
||||||
|
Target string
|
||||||
|
Port int
|
||||||
|
Version string
|
||||||
|
Resolve string
|
||||||
|
Method string
|
||||||
|
Body string
|
||||||
|
Referer string
|
||||||
|
UserAgent string
|
||||||
|
Cookies string
|
||||||
|
MaxRedirects int
|
||||||
|
MaxSet bool
|
||||||
|
Timeout time.Duration
|
||||||
|
Allow4 bool
|
||||||
|
Allow6 bool
|
||||||
|
CheckSafety bool
|
||||||
|
AllowPrivate bool
|
||||||
|
Extra []*net.IPNet
|
||||||
|
Resolver resolver
|
||||||
|
Insecure bool
|
||||||
|
Roots *x509.CertPool
|
||||||
|
Preferred net.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
func probeHTTP(ctx context.Context, in HTTPInput) Outcome {
|
||||||
|
started := time.Now()
|
||||||
|
version, err := normalizeHTTPVersion(in.Version)
|
||||||
|
if err != nil {
|
||||||
|
return httpFail(statusError, err.Error())
|
||||||
|
}
|
||||||
|
method := strings.ToUpper(strings.TrimSpace(in.Method))
|
||||||
|
if method == "" {
|
||||||
|
method = http.MethodGet
|
||||||
|
}
|
||||||
|
if method != http.MethodGet && method != http.MethodPost {
|
||||||
|
return httpFail(statusError, "HTTP 方法只支持 GET 和 POST")
|
||||||
|
}
|
||||||
|
if method != http.MethodPost {
|
||||||
|
in.Body = ""
|
||||||
|
}
|
||||||
|
if len(in.Body) > 64<<10 || len(in.Referer) > 4096 || len(in.UserAgent) > 4096 || len(in.Cookies) > 4096 {
|
||||||
|
return httpFail(statusError, "HTTP 选项超过长度限制")
|
||||||
|
}
|
||||||
|
page, err := buildHTTPURL(in.Target, in.Port)
|
||||||
|
if err != nil {
|
||||||
|
return httpFail(statusError, err.Error())
|
||||||
|
}
|
||||||
|
if (version == "2" || version == "3") && page.Scheme != "https" {
|
||||||
|
name := "HTTP/2"
|
||||||
|
if version == "3" {
|
||||||
|
name = "HTTP/3"
|
||||||
|
}
|
||||||
|
return httpFail(statusError, "强制 "+name+" 需要 HTTPS,不会降级")
|
||||||
|
}
|
||||||
|
maxRedirect := in.MaxRedirects
|
||||||
|
if !in.MaxSet && maxRedirect == 0 {
|
||||||
|
maxRedirect = 5
|
||||||
|
}
|
||||||
|
if maxRedirect < 0 || maxRedirect > 20 {
|
||||||
|
return httpFail(statusError, "跳转次数需要在 0 到 20 之间")
|
||||||
|
}
|
||||||
|
if in.Timeout <= 0 {
|
||||||
|
in.Timeout = 1500 * time.Millisecond
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, in.Timeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
originHost := page.Hostname()
|
||||||
|
var chain []string
|
||||||
|
var dnsSum, connSum, tlsSum time.Duration
|
||||||
|
var used net.IP
|
||||||
|
var gotVersion string
|
||||||
|
var ttfb time.Duration
|
||||||
|
current := page
|
||||||
|
currentMethod := method
|
||||||
|
currentBody := in.Body
|
||||||
|
seen := map[string]int{}
|
||||||
|
|
||||||
|
for followed := 0; ; followed++ {
|
||||||
|
if seen[current.String()] > 2 {
|
||||||
|
return httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, 0, current.String(), chain, statusError, "跳转出现了循环")
|
||||||
|
}
|
||||||
|
seen[current.String()]++
|
||||||
|
resp, hop, err := in.do(ctx, current, currentMethod, currentBody, version, originHost)
|
||||||
|
dnsSum += hop.dns
|
||||||
|
connSum += hop.connect
|
||||||
|
tlsSum += hop.tls
|
||||||
|
if hop.addr != nil {
|
||||||
|
used = hop.addr
|
||||||
|
}
|
||||||
|
if hop.version != "" {
|
||||||
|
gotVersion = hop.version
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil && !errors.Is(err, errForbiddenTarget) {
|
||||||
|
if fe, ok := asFamily(err); ok {
|
||||||
|
return httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, 0, current.String(), chain, statusError, fe.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, 0, current.String(), chain, hop.status, hop.note)
|
||||||
|
}
|
||||||
|
if hop.ttfb > 0 && ttfb == 0 {
|
||||||
|
ttfb = time.Since(started)
|
||||||
|
}
|
||||||
|
if hop.ttfb > 0 {
|
||||||
|
ttfb = time.Since(started)
|
||||||
|
}
|
||||||
|
code := resp.StatusCode
|
||||||
|
finalURL := current.String()
|
||||||
|
if resp.Request != nil && resp.Request.URL != nil {
|
||||||
|
finalURL = resp.Request.URL.String()
|
||||||
|
}
|
||||||
|
chain = append(chain, strconv.Itoa(code)+" "+finalURL)
|
||||||
|
loc := resp.Header.Get("Location")
|
||||||
|
redirect := code >= 300 && code < 400 && loc != ""
|
||||||
|
if !redirect {
|
||||||
|
_, _ = io.CopyN(io.Discard, resp.Body, httpBodyCap)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
note := fmt.Sprintf("HTTP %d", code)
|
||||||
|
if code >= 400 {
|
||||||
|
note += "。这是服务器返回的状态,不是丢包"
|
||||||
|
}
|
||||||
|
out := httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, code, finalURL, chain, statusOK, note)
|
||||||
|
if hop.fallback != "" {
|
||||||
|
out.Detail["fallback"] = hop.fallback
|
||||||
|
}
|
||||||
|
out.HasRtt = true
|
||||||
|
out.Rtt = time.Since(started)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if followed >= maxRedirect {
|
||||||
|
return httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, code, finalURL, chain, statusError, fmt.Sprintf("超过了最多 %d 次跳转", maxRedirect))
|
||||||
|
}
|
||||||
|
next, err := current.Parse(loc)
|
||||||
|
if err != nil || next.Host == "" || (next.Scheme != "http" && next.Scheme != "https") {
|
||||||
|
return httpDone(started, dnsSum, connSum, tlsSum, ttfb, used, gotVersion, code, finalURL, chain, statusError, "跳转地址无效")
|
||||||
|
}
|
||||||
|
current = next
|
||||||
|
if code == http.StatusMovedPermanently || code == http.StatusFound || code == http.StatusSeeOther {
|
||||||
|
currentMethod = http.MethodGet
|
||||||
|
currentBody = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type httpHop struct {
|
||||||
|
dns time.Duration
|
||||||
|
connect time.Duration
|
||||||
|
tls time.Duration
|
||||||
|
ttfb time.Duration
|
||||||
|
addr net.IP
|
||||||
|
version string
|
||||||
|
status string
|
||||||
|
note string
|
||||||
|
fallback string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (in HTTPInput) do(ctx context.Context, page *url.URL, method, body, version, originHost string) (*http.Response, httpHop, error) {
|
||||||
|
connectHost := page.Hostname()
|
||||||
|
if strings.EqualFold(connectHost, originHost) && strings.TrimSpace(in.Resolve) != "" {
|
||||||
|
connectHost = strings.TrimSpace(in.Resolve)
|
||||||
|
}
|
||||||
|
ips, dnsDur, err := in.lookup(ctx, connectHost)
|
||||||
|
hop := httpHop{dns: dnsDur, status: statusError, note: "连接失败"}
|
||||||
|
if err != nil {
|
||||||
|
hop.status, hop.note = classifyHTTPLookup(err, version)
|
||||||
|
return nil, hop, err
|
||||||
|
}
|
||||||
|
ips = preferIP(ips, in.Preferred)
|
||||||
|
var last error
|
||||||
|
var skipped []string
|
||||||
|
for _, ip := range ips {
|
||||||
|
resp, one, err := in.exchange(ctx, page, method, body, version, ip)
|
||||||
|
one.dns = dnsDur
|
||||||
|
if err == nil {
|
||||||
|
if len(skipped) > 0 {
|
||||||
|
one.fallback = "已尝试 " + strings.Join(skipped, "、") + ",随后改用 " + familyOf(ip) + " " + ip.String()
|
||||||
|
}
|
||||||
|
return resp, one, nil
|
||||||
|
}
|
||||||
|
last = err
|
||||||
|
hop = one
|
||||||
|
hop.dns = dnsDur
|
||||||
|
if !retryHTTP(err) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
skipped = append(skipped, familyOf(ip)+" "+ip.String())
|
||||||
|
}
|
||||||
|
if last == nil {
|
||||||
|
last = errors.New("连接失败")
|
||||||
|
}
|
||||||
|
if hop.note == "" || hop.note == "skipped" {
|
||||||
|
hop.status, hop.note = classifyHTTPDial(last, version)
|
||||||
|
}
|
||||||
|
if len(skipped) > 0 && hop.note != "" {
|
||||||
|
hop.note = "已尝试 " + strings.Join(skipped, "、") + "。" + hop.note
|
||||||
|
}
|
||||||
|
return nil, hop, last
|
||||||
|
}
|
||||||
|
|
||||||
|
func (in HTTPInput) exchange(ctx context.Context, page *url.URL, method, body, version string, ip net.IP) (*http.Response, httpHop, error) {
|
||||||
|
hop := httpHop{addr: ip, status: statusError, note: "连接失败"}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, page.String(), strings.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
hop.note = "无法构造 HTTP 请求"
|
||||||
|
return nil, hop, err
|
||||||
|
}
|
||||||
|
if body != "" {
|
||||||
|
req.ContentLength = int64(len(body))
|
||||||
|
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
|
}
|
||||||
|
if in.Referer != "" {
|
||||||
|
req.Header.Set("Referer", in.Referer)
|
||||||
|
}
|
||||||
|
if in.UserAgent != "" {
|
||||||
|
req.Header.Set("User-Agent", in.UserAgent)
|
||||||
|
}
|
||||||
|
if in.Cookies != "" {
|
||||||
|
req.Header.Set("Cookie", in.Cookies)
|
||||||
|
}
|
||||||
|
var connectDur, tlsDur time.Duration
|
||||||
|
var connectStart, tlsStart time.Time
|
||||||
|
trace := &httptrace.ClientTrace{
|
||||||
|
ConnectStart: func(string, string) { connectStart = time.Now() },
|
||||||
|
ConnectDone: func(string, string, error) {
|
||||||
|
if !connectStart.IsZero() {
|
||||||
|
connectDur = time.Since(connectStart)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
TLSHandshakeStart: func() { tlsStart = time.Now() },
|
||||||
|
TLSHandshakeDone: func(tls.ConnectionState, error) {
|
||||||
|
if !tlsStart.IsZero() {
|
||||||
|
tlsDur = time.Since(tlsStart)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
GotFirstResponseByte: func() { hop.ttfb = time.Nanosecond },
|
||||||
|
}
|
||||||
|
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
|
||||||
|
|
||||||
|
var resp *http.Response
|
||||||
|
switch version {
|
||||||
|
case "3":
|
||||||
|
t0 := time.Now()
|
||||||
|
resp, err = in.roundTripH3(req, ip)
|
||||||
|
elapsed := time.Since(t0)
|
||||||
|
// QUIC finishes the UDP association and the TLS handshake together.
|
||||||
|
connectDur = elapsed
|
||||||
|
tlsDur = elapsed
|
||||||
|
default:
|
||||||
|
resp, err = in.roundTripTCP(req, ip, version)
|
||||||
|
}
|
||||||
|
hop.connect = connectDur
|
||||||
|
hop.tls = tlsDur
|
||||||
|
if err != nil {
|
||||||
|
hop.status, hop.note = classifyHTTPDial(err, version)
|
||||||
|
return nil, hop, err
|
||||||
|
}
|
||||||
|
got := canonicalProto(resp.Proto)
|
||||||
|
if version == "1.1" && got != "1.1" {
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
hop.note = "服务器没有使用 HTTP/1.1,已按设置失败,没有降级"
|
||||||
|
return nil, hop, errors.New(hop.note)
|
||||||
|
}
|
||||||
|
if version == "2" && got != "2" {
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
hop.note = "服务器不支持 HTTP/2,已按设置失败,没有降级"
|
||||||
|
return nil, hop, errors.New(hop.note)
|
||||||
|
}
|
||||||
|
if version == "3" && got != "3" {
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
hop.note = "服务器不支持 HTTP/3,已按设置失败,没有降级"
|
||||||
|
return nil, hop, errors.New(hop.note)
|
||||||
|
}
|
||||||
|
hop.version = got
|
||||||
|
hop.status = statusOK
|
||||||
|
hop.note = ""
|
||||||
|
return resp, hop, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (in HTTPInput) roundTripTCP(req *http.Request, ip net.IP, version string) (*http.Response, error) {
|
||||||
|
port := req.URL.Port()
|
||||||
|
if port == "" {
|
||||||
|
if req.URL.Scheme == "https" {
|
||||||
|
port = "443"
|
||||||
|
} else {
|
||||||
|
port = "80"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dialAddr := net.JoinHostPort(ip.String(), port)
|
||||||
|
tlsConf := &tls.Config{
|
||||||
|
ServerName: req.URL.Hostname(),
|
||||||
|
InsecureSkipVerify: in.Insecure,
|
||||||
|
RootCAs: in.Roots,
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
}
|
||||||
|
switch version {
|
||||||
|
case "1.1":
|
||||||
|
tlsConf.NextProtos = []string{"http/1.1"}
|
||||||
|
case "2":
|
||||||
|
tlsConf.NextProtos = []string{"h2"}
|
||||||
|
default:
|
||||||
|
tlsConf.NextProtos = []string{"h2", "http/1.1"}
|
||||||
|
}
|
||||||
|
transport := &http.Transport{
|
||||||
|
Proxy: nil,
|
||||||
|
ForceAttemptHTTP2: version != "1.1",
|
||||||
|
TLSClientConfig: tlsConf,
|
||||||
|
DisableKeepAlives: true,
|
||||||
|
DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
|
||||||
|
d := net.Dialer{}
|
||||||
|
use := "tcp4"
|
||||||
|
if ip.To4() == nil {
|
||||||
|
use = "tcp6"
|
||||||
|
}
|
||||||
|
return d.DialContext(ctx, use, dialAddr)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if version == "1.1" {
|
||||||
|
transport.ForceAttemptHTTP2 = false
|
||||||
|
transport.TLSNextProto = map[string]func(string, *tls.Conn) http.RoundTripper{}
|
||||||
|
}
|
||||||
|
defer transport.CloseIdleConnections()
|
||||||
|
client := &http.Client{
|
||||||
|
Transport: transport,
|
||||||
|
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return client.Do(req)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (in HTTPInput) roundTripH3(req *http.Request, ip net.IP) (*http.Response, error) {
|
||||||
|
port := req.URL.Port()
|
||||||
|
if port == "" {
|
||||||
|
port = "443"
|
||||||
|
}
|
||||||
|
addr := net.JoinHostPort(ip.String(), port)
|
||||||
|
tlsConf := &tls.Config{
|
||||||
|
ServerName: req.URL.Hostname(),
|
||||||
|
InsecureSkipVerify: in.Insecure,
|
||||||
|
RootCAs: in.Roots,
|
||||||
|
NextProtos: []string{http3.NextProtoH3},
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
}
|
||||||
|
rt := &http3.Transport{
|
||||||
|
TLSClientConfig: tlsConf,
|
||||||
|
Dial: func(ctx context.Context, _ string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error) {
|
||||||
|
if cfg == nil {
|
||||||
|
cfg = &quic.Config{}
|
||||||
|
} else {
|
||||||
|
cfg = cfg.Clone()
|
||||||
|
}
|
||||||
|
if cfg.HandshakeIdleTimeout == 0 || cfg.HandshakeIdleTimeout > time.Second {
|
||||||
|
cfg.HandshakeIdleTimeout = time.Second
|
||||||
|
}
|
||||||
|
return quic.DialAddrEarly(ctx, addr, tlsCfg, cfg)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
defer rt.Close()
|
||||||
|
client := &http.Client{
|
||||||
|
Transport: rt,
|
||||||
|
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||||
|
return http.ErrUseLastResponse
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return client.Do(req)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (in HTTPInput) lookup(ctx context.Context, host string) ([]net.IP, time.Duration, error) {
|
||||||
|
host = strings.TrimSpace(host)
|
||||||
|
host = strings.Trim(host, "[]")
|
||||||
|
if host == "" {
|
||||||
|
return nil, 0, errors.New("empty host")
|
||||||
|
}
|
||||||
|
if !in.Allow4 && !in.Allow6 {
|
||||||
|
return nil, 0, familyMessage("IPv4 和 IPv6 都已关闭,无法开始探测")
|
||||||
|
}
|
||||||
|
if ip := net.ParseIP(host); ip != nil {
|
||||||
|
filtered, err := filterFamily(host, []net.IP{ip}, in.Allow4, in.Allow6)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
if in.CheckSafety && !ipAllowed(ip, in.AllowPrivate, in.Extra) {
|
||||||
|
return nil, 0, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String())
|
||||||
|
}
|
||||||
|
return filtered, 0, nil
|
||||||
|
}
|
||||||
|
start := time.Now()
|
||||||
|
var ips []net.IP
|
||||||
|
var err error
|
||||||
|
if in.CheckSafety {
|
||||||
|
ips, err = resolveTargets(ctx, in.Resolver, host, in.AllowPrivate, in.Extra)
|
||||||
|
} else {
|
||||||
|
ips, err = lookupPlain(ctx, in.Resolver, host)
|
||||||
|
}
|
||||||
|
elapsed := time.Since(start)
|
||||||
|
if err != nil {
|
||||||
|
return nil, elapsed, err
|
||||||
|
}
|
||||||
|
filtered, err := filterFamily(host, ips, in.Allow4, in.Allow6)
|
||||||
|
if err != nil {
|
||||||
|
return nil, elapsed, err
|
||||||
|
}
|
||||||
|
return filtered, elapsed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupPlain(ctx context.Context, r resolver, host string) ([]net.IP, error) {
|
||||||
|
if r == nil {
|
||||||
|
r = net.DefaultResolver
|
||||||
|
}
|
||||||
|
lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
addrs, err := r.LookupIPAddr(lookupCtx, host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(addrs) == 0 {
|
||||||
|
return nil, &net.DNSError{Err: "no addresses", Name: host, IsNotFound: true}
|
||||||
|
}
|
||||||
|
out := make([]net.IP, 0, len(addrs))
|
||||||
|
for _, addr := range addrs {
|
||||||
|
out = append(out, addr.IP)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildHTTPURL(target string, port int) (*url.URL, error) {
|
||||||
|
target = strings.TrimSpace(target)
|
||||||
|
if target == "" {
|
||||||
|
return nil, errors.New("请填写目标地址")
|
||||||
|
}
|
||||||
|
raw := target
|
||||||
|
if !strings.Contains(raw, "://") {
|
||||||
|
scheme := "https"
|
||||||
|
if port == 80 {
|
||||||
|
scheme = "http"
|
||||||
|
}
|
||||||
|
hostpart := raw
|
||||||
|
path := ""
|
||||||
|
if i := strings.Index(raw, "/"); i >= 0 {
|
||||||
|
hostpart, path = raw[:i], raw[i:]
|
||||||
|
}
|
||||||
|
if strings.Count(hostpart, ":") >= 2 && !strings.HasPrefix(hostpart, "[") {
|
||||||
|
hostpart = "[" + hostpart + "]"
|
||||||
|
}
|
||||||
|
raw = scheme + "://" + hostpart + path
|
||||||
|
}
|
||||||
|
u, err := url.Parse(raw)
|
||||||
|
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") {
|
||||||
|
return nil, errors.New("HTTP 目标需要是主机名或 http/https 网址")
|
||||||
|
}
|
||||||
|
if u.Port() == "" {
|
||||||
|
if port < 1 || port > 65535 {
|
||||||
|
return nil, errors.New("端口需要在 1 到 65535 之间")
|
||||||
|
}
|
||||||
|
u.Host = net.JoinHostPort(u.Hostname(), strconv.Itoa(port))
|
||||||
|
}
|
||||||
|
if u.Path == "" {
|
||||||
|
u.Path = "/"
|
||||||
|
}
|
||||||
|
return u, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeHTTPVersion(v string) (string, error) {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(v)) {
|
||||||
|
case "", "auto":
|
||||||
|
return "auto", nil
|
||||||
|
case "1.1", "http/1.1":
|
||||||
|
return "1.1", nil
|
||||||
|
case "2", "http/2":
|
||||||
|
return "2", nil
|
||||||
|
case "3", "http/3":
|
||||||
|
return "3", nil
|
||||||
|
default:
|
||||||
|
return "", errors.New("HTTP 版本需要是自动、1.1、2 或 3")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func canonicalProto(proto string) string {
|
||||||
|
p := strings.ToUpper(strings.TrimSpace(proto))
|
||||||
|
switch {
|
||||||
|
case strings.Contains(p, "3"):
|
||||||
|
return "3"
|
||||||
|
case strings.Contains(p, "2"):
|
||||||
|
return "2"
|
||||||
|
case strings.Contains(p, "1.1"):
|
||||||
|
return "1.1"
|
||||||
|
case strings.Contains(p, "1.0"):
|
||||||
|
return "1.0"
|
||||||
|
default:
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func classifyHTTPLookup(err error, version string) (string, string) {
|
||||||
|
if fe, ok := asFamily(err); ok {
|
||||||
|
return statusError, fe.Error()
|
||||||
|
}
|
||||||
|
if errors.Is(err, errForbiddenTarget) {
|
||||||
|
return statusError, "远程节点默认不探测本机、内网、链路本地或云元数据地址。管理员开放局域网后才能测这些地址"
|
||||||
|
}
|
||||||
|
var dnsErr *net.DNSError
|
||||||
|
if errors.As(err, &dnsErr) {
|
||||||
|
return statusDNS, "域名无法解析"
|
||||||
|
}
|
||||||
|
return classifyHTTPDial(err, version)
|
||||||
|
}
|
||||||
|
|
||||||
|
func classifyHTTPDial(err error, version string) (string, string) {
|
||||||
|
if err == nil {
|
||||||
|
return statusError, "连接失败"
|
||||||
|
}
|
||||||
|
if fe, ok := asFamily(err); ok {
|
||||||
|
return statusError, fe.Error()
|
||||||
|
}
|
||||||
|
if errors.Is(err, errForbiddenTarget) {
|
||||||
|
return statusError, "远程节点默认不探测本机、内网、链路本地或云元数据地址。管理员开放局域网后才能测这些地址"
|
||||||
|
}
|
||||||
|
var dnsErr *net.DNSError
|
||||||
|
if errors.As(err, &dnsErr) {
|
||||||
|
return statusDNS, "域名无法解析"
|
||||||
|
}
|
||||||
|
msg := err.Error()
|
||||||
|
if strings.Contains(msg, "没有使用 HTTP/1.1") || strings.Contains(msg, "不支持 HTTP/2") || strings.Contains(msg, "不支持 HTTP/3") {
|
||||||
|
return statusError, msg
|
||||||
|
}
|
||||||
|
out := classifyDial(err)
|
||||||
|
if out.Note == "" {
|
||||||
|
out.Note = "连接失败"
|
||||||
|
}
|
||||||
|
if version == "2" || version == "3" {
|
||||||
|
if out.Status == statusTimeout || out.Status == statusRefused || out.Status == statusDNS {
|
||||||
|
return out.Status, out.Note
|
||||||
|
}
|
||||||
|
name := "HTTP/2"
|
||||||
|
if version == "3" {
|
||||||
|
name = "HTTP/3"
|
||||||
|
}
|
||||||
|
return statusError, "服务器不支持 " + name + ",已按设置失败,没有降级"
|
||||||
|
}
|
||||||
|
return out.Status, out.Note
|
||||||
|
}
|
||||||
|
|
||||||
|
func retryHTTP(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if _, ok := asFamily(err); ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if errors.Is(err, errForbiddenTarget) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
var dnsErr *net.DNSError
|
||||||
|
return !errors.As(err, &dnsErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func httpFail(status, note string) Outcome {
|
||||||
|
return Outcome{Status: status, Kind: kindQuery, Note: note}
|
||||||
|
}
|
||||||
|
|
||||||
|
func httpDone(started time.Time, dns, conn, tls, ttfb time.Duration, ip net.IP, version string, code int, final string, chain []string, status, note string) Outcome {
|
||||||
|
detail := map[string]string{}
|
||||||
|
putMs(detail, "dnsMs", dns)
|
||||||
|
putMs(detail, "connectMs", conn)
|
||||||
|
putMs(detail, "tlsMs", tls)
|
||||||
|
putMs(detail, "ttfbMs", ttfb)
|
||||||
|
putMs(detail, "totalMs", time.Since(started))
|
||||||
|
if version != "" {
|
||||||
|
detail["httpVersion"] = version
|
||||||
|
}
|
||||||
|
if code > 0 {
|
||||||
|
detail["statusCode"] = strconv.Itoa(code)
|
||||||
|
}
|
||||||
|
if final != "" {
|
||||||
|
detail["finalUrl"] = final
|
||||||
|
}
|
||||||
|
if len(chain) > 0 {
|
||||||
|
detail["redirects"] = strings.Join(chain, " -> ")
|
||||||
|
}
|
||||||
|
out := Outcome{Status: status, Kind: kindQuery, Note: note, Detail: detail}
|
||||||
|
if ip != nil {
|
||||||
|
out = stampIP(out, ip)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
type httpProbe struct {
|
||||||
|
spec jobSpec
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *httpProbe) Close() error { return nil }
|
||||||
|
|
||||||
|
func (p *httpProbe) Probe(ctx context.Context) Outcome {
|
||||||
|
in := p.spec.HTTP
|
||||||
|
in.Preferred = p.spec.dialIP()
|
||||||
|
out := probeHTTP(ctx, in)
|
||||||
|
if p.spec.state != nil {
|
||||||
|
p.spec.state.used = nil
|
||||||
|
if out.Status == statusOK {
|
||||||
|
if ip := net.ParseIP(out.Detail["address"]); ip != nil {
|
||||||
|
p.spec.state.used = append(net.IP(nil), ip...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func putMs(detail map[string]string, key string, d time.Duration) {
|
||||||
|
if d < 0 {
|
||||||
|
d = 0
|
||||||
|
}
|
||||||
|
detail[key] = strconv.FormatFloat(float64(d)/float64(time.Millisecond), 'f', 3, 64)
|
||||||
|
}
|
||||||
@@ -0,0 +1,445 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"math/big"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/quic-go/quic-go/http3"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFilterFamily(t *testing.T) {
|
||||||
|
v4 := net.ParseIP("1.1.1.1")
|
||||||
|
v6 := net.ParseIP("2001:db8::1")
|
||||||
|
both := []net.IP{v4, v6}
|
||||||
|
only4, err := filterFamily("example.com", both, true, false)
|
||||||
|
if err != nil || len(only4) != 1 || !only4[0].Equal(v4) {
|
||||||
|
t.Fatalf("v4 only: %v %v", only4, err)
|
||||||
|
}
|
||||||
|
only6, err := filterFamily("example.com", both, false, true)
|
||||||
|
if err != nil || len(only6) != 1 || !only6[0].Equal(v6) {
|
||||||
|
t.Fatalf("v6 only: %v %v", only6, err)
|
||||||
|
}
|
||||||
|
if _, err := filterFamily("example.com", both, false, false); err == nil || !strings.Contains(err.Error(), "都已关闭") {
|
||||||
|
t.Fatalf("both off: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := filterFamily("1.1.1.1", []net.IP{v4}, false, true); err == nil || !strings.Contains(err.Error(), "IPv4") {
|
||||||
|
t.Fatalf("literal v4: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := filterFamily("2001:db8::1", []net.IP{v6}, true, false); err == nil || !strings.Contains(err.Error(), "IPv6") {
|
||||||
|
t.Fatalf("literal v6: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHTTPRedirectStatusIsNotLoss(t *testing.T) {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Redirect(w, r, "/b", http.StatusFound)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("/b", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.Redirect(w, r, "/c", http.StatusMovedPermanently)
|
||||||
|
})
|
||||||
|
mux.HandleFunc("/c", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodGet {
|
||||||
|
t.Errorf("method %s", r.Method)
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
_, _ = w.Write([]byte("missing"))
|
||||||
|
})
|
||||||
|
srv := httptest.NewServer(mux)
|
||||||
|
defer srv.Close()
|
||||||
|
port := mustPort(t, srv.URL)
|
||||||
|
out := probeHTTP(context.Background(), HTTPInput{
|
||||||
|
Target: srv.URL + "/a", Port: port, Version: "1.1", Method: "POST", Body: "ignored-after-redirect",
|
||||||
|
Allow4: true, Allow6: true, Timeout: 3 * time.Second, MaxSet: true, MaxRedirects: 5,
|
||||||
|
})
|
||||||
|
if out.Status != statusOK {
|
||||||
|
t.Fatalf("status %s note %s", out.Status, out.Note)
|
||||||
|
}
|
||||||
|
if strings.Contains(out.Note, "丢包") && !strings.Contains(out.Note, "不是丢包") {
|
||||||
|
t.Fatalf("note treats 404 as loss: %s", out.Note)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out.Note, "不是丢包") || out.Detail["statusCode"] != "404" {
|
||||||
|
t.Fatalf("note/detail %+v %s", out.Detail, out.Note)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out.Detail["finalUrl"], "/c") || !strings.Contains(out.Detail["redirects"], "/a") || !strings.Contains(out.Detail["redirects"], "/b") {
|
||||||
|
t.Fatalf("chain %+v", out.Detail)
|
||||||
|
}
|
||||||
|
if out.Detail["httpVersion"] != "1.1" || !out.HasRtt {
|
||||||
|
t.Fatalf("version/rtt %+v", out)
|
||||||
|
}
|
||||||
|
for _, key := range []string{"dnsMs", "connectMs", "tlsMs", "ttfbMs", "totalMs"} {
|
||||||
|
if _, err := strconv.ParseFloat(out.Detail[key], 64); err != nil {
|
||||||
|
t.Fatalf("%s: %v", key, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHTTPPostHeadersAndResolve(t *testing.T) {
|
||||||
|
var gotHost, gotBody, gotRef, gotUA, gotCookie string
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotHost = r.Host
|
||||||
|
raw, _ := io.ReadAll(r.Body)
|
||||||
|
gotBody = string(raw)
|
||||||
|
gotRef = r.Referer()
|
||||||
|
gotUA = r.UserAgent()
|
||||||
|
gotCookie = r.Header.Get("Cookie")
|
||||||
|
if r.URL.Path != "/only" {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
port := mustPort(t, srv.URL)
|
||||||
|
out := probeHTTP(context.Background(), HTTPInput{
|
||||||
|
Target: "http://example.com/only", Port: port, Version: "1.1", Method: "POST", Body: "hello",
|
||||||
|
Referer: "https://from.example/a", UserAgent: "nq-test", Cookies: "a=b",
|
||||||
|
Resolve: "cdn.test", Resolver: stubResolver{[]net.IP{net.ParseIP("127.0.0.1")}},
|
||||||
|
Allow4: true, Allow6: true, Timeout: 3 * time.Second,
|
||||||
|
})
|
||||||
|
if out.Status != statusOK || out.Detail["statusCode"] != "201" {
|
||||||
|
t.Fatalf("%s %s %+v", out.Status, out.Note, out.Detail)
|
||||||
|
}
|
||||||
|
if gotHost != "example.com:"+strconv.Itoa(port) {
|
||||||
|
t.Fatalf("host %q", gotHost)
|
||||||
|
}
|
||||||
|
if gotBody != "hello" || gotRef != "https://from.example/a" || gotUA != "nq-test" || gotCookie != "a=b" {
|
||||||
|
t.Fatalf("body %q ref %q ua %q cookie %q", gotBody, gotRef, gotUA, gotCookie)
|
||||||
|
}
|
||||||
|
if out.Detail["address"] != "127.0.0.1" || out.Detail["family"] != "IPv4" {
|
||||||
|
t.Fatalf("address %+v", out.Detail)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHTTPForceVersionAndSNI(t *testing.T) {
|
||||||
|
cert, pool := testCert(t)
|
||||||
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.TLS == nil || r.TLS.ServerName != "example.com" {
|
||||||
|
http.Error(w, "bad sni", http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(r.Host, "example.com") {
|
||||||
|
http.Error(w, "bad host", http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
})
|
||||||
|
h2addr, h2close := serveTLS(t, handler, []string{"h2", "http/1.1"}, true, cert)
|
||||||
|
defer h2close()
|
||||||
|
h1addr, h1close := serveTLS(t, handler, []string{"http/1.1"}, false, cert)
|
||||||
|
defer h1close()
|
||||||
|
h2port := mustPort(t, "https://"+h2addr)
|
||||||
|
h1port := mustPort(t, "https://"+h1addr)
|
||||||
|
|
||||||
|
auto := probeHTTP(context.Background(), tlsInput("https://example.com/path", h2port, "auto", pool))
|
||||||
|
if auto.Status != statusOK || auto.Detail["httpVersion"] != "2" || auto.Detail["statusCode"] != "204" {
|
||||||
|
t.Fatalf("auto h2: %s %s %+v", auto.Status, auto.Note, auto.Detail)
|
||||||
|
}
|
||||||
|
forced1 := probeHTTP(context.Background(), tlsInput("https://example.com/path", h2port, "1.1", pool))
|
||||||
|
if forced1.Status != statusOK || forced1.Detail["httpVersion"] != "1.1" {
|
||||||
|
t.Fatalf("force 1.1: %s %s %+v", forced1.Status, forced1.Note, forced1.Detail)
|
||||||
|
}
|
||||||
|
forced2 := probeHTTP(context.Background(), tlsInput("https://example.com/path", h1port, "2", pool))
|
||||||
|
if forced2.Status == statusOK || !strings.Contains(forced2.Note, "HTTP/2") || strings.Contains(forced2.Note, "降级到") {
|
||||||
|
t.Fatalf("force 2 should fail closed: %s %s", forced2.Status, forced2.Note)
|
||||||
|
}
|
||||||
|
plain := probeHTTP(context.Background(), HTTPInput{
|
||||||
|
Target: "http://127.0.0.1/x", Port: 9, Version: "3", Allow4: true, Allow6: true, Timeout: time.Second,
|
||||||
|
})
|
||||||
|
if plain.Status == statusOK || !strings.Contains(plain.Note, "需要 HTTPS") {
|
||||||
|
t.Fatalf("cleartext h3: %s %s", plain.Status, plain.Note)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHTTP3(t *testing.T) {
|
||||||
|
cert, pool := testCert(t)
|
||||||
|
udp, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.ParseIP("127.0.0.1")})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer udp.Close()
|
||||||
|
h3 := &http3.Server{
|
||||||
|
TLSConfig: &tls.Config{Certificates: []tls.Certificate{cert}},
|
||||||
|
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.TLS == nil || r.TLS.ServerName != "example.com" {
|
||||||
|
http.Error(w, "bad sni", http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(r.Host, "example.com") {
|
||||||
|
http.Error(w, "bad host "+r.Host, http.StatusBadGateway)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = io.WriteString(w, "h3")
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
go h3.Serve(udp)
|
||||||
|
defer h3.Close()
|
||||||
|
port := udp.LocalAddr().(*net.UDPAddr).Port
|
||||||
|
out := probeHTTP(context.Background(), tlsInput("https://example.com/h3", port, "3", pool))
|
||||||
|
if out.Status != statusOK || out.Detail["httpVersion"] != "3" || out.Detail["statusCode"] != "200" {
|
||||||
|
t.Fatalf("h3: %s %s %+v", out.Status, out.Note, out.Detail)
|
||||||
|
}
|
||||||
|
if out.Detail["address"] != "127.0.0.1" {
|
||||||
|
t.Fatalf("address %+v", out.Detail)
|
||||||
|
}
|
||||||
|
tcpAddr, closeTCP := serveTLS(t, http.NotFoundHandler(), []string{"h2", "http/1.1"}, true, cert)
|
||||||
|
defer closeTCP()
|
||||||
|
failed := probeHTTP(context.Background(), tlsInput("https://example.com/nope", mustPort(t, "https://"+tcpAddr), "3", pool))
|
||||||
|
if failed.Status == statusOK || strings.Contains(failed.Note, "降到") {
|
||||||
|
t.Fatalf("h3 against tcp: %s %s", failed.Status, failed.Note)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHTTPFamilyRefusal(t *testing.T) {
|
||||||
|
out := probeHTTP(context.Background(), HTTPInput{
|
||||||
|
Target: "127.0.0.1", Port: 80, Allow4: false, Allow6: true, Timeout: time.Second,
|
||||||
|
})
|
||||||
|
if out.Status == statusOK || !strings.Contains(out.Note, "IPv4") {
|
||||||
|
t.Fatalf("%s %s", out.Status, out.Note)
|
||||||
|
}
|
||||||
|
both := probeHTTP(context.Background(), HTTPInput{
|
||||||
|
Target: "example.com", Port: 443, Allow4: false, Allow6: false, Timeout: time.Second,
|
||||||
|
})
|
||||||
|
if !strings.Contains(both.Note, "都已关闭") {
|
||||||
|
t.Fatal(both.Note)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeHonorsFamilyAndHTTP(t *testing.T) {
|
||||||
|
page := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusBadGateway)
|
||||||
|
}))
|
||||||
|
defer page.Close()
|
||||||
|
port := mustPort(t, page.URL)
|
||||||
|
node := newNode("", true, nil, testLimits())
|
||||||
|
node.Resolver = stubResolver{[]net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}}
|
||||||
|
ts := httptest.NewServer(node.Handler())
|
||||||
|
defer ts.Close()
|
||||||
|
|
||||||
|
bad := postJSON(t, ts.URL+"/v1/jobs", `{"target":"127.0.0.1","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":300,"durationSec":1,"allowIPv4":false,"allowIPv6":true}`)
|
||||||
|
if bad.StatusCode != http.StatusBadRequest {
|
||||||
|
t.Fatalf("literal v4 status %d", bad.StatusCode)
|
||||||
|
}
|
||||||
|
badBody, _ := io.ReadAll(bad.Body)
|
||||||
|
bad.Body.Close()
|
||||||
|
if !strings.Contains(string(badBody), "IPv4") {
|
||||||
|
t.Fatalf("body %s", badBody)
|
||||||
|
}
|
||||||
|
both := postJSON(t, ts.URL+"/v1/jobs", `{"target":"127.0.0.1","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":300,"durationSec":1,"allowIPv4":false,"allowIPv6":false}`)
|
||||||
|
both.Body.Close()
|
||||||
|
if both.StatusCode != http.StatusBadRequest {
|
||||||
|
t.Fatalf("both off %d", both.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
created := postJSON(t, ts.URL+"/v1/jobs", `{"target":"example.test","port":1,"profile":"tcp-connect","intervalMs":200,"timeoutMs":300,"durationSec":1,"allowIPv4":false,"allowIPv6":true}`)
|
||||||
|
defer created.Body.Close()
|
||||||
|
if created.StatusCode != http.StatusCreated {
|
||||||
|
raw, _ := io.ReadAll(created.Body)
|
||||||
|
t.Fatalf("family filter create %d %s", created.StatusCode, raw)
|
||||||
|
}
|
||||||
|
var createdBody map[string]any
|
||||||
|
if err := json.NewDecoder(created.Body).Decode(&createdBody); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
resolved, _ := createdBody["resolved"].([]any)
|
||||||
|
if len(resolved) != 1 {
|
||||||
|
t.Fatalf("resolved %+v", createdBody["resolved"])
|
||||||
|
}
|
||||||
|
first, _ := resolved[0].(map[string]any)
|
||||||
|
if first["address"] != "::1" || first["family"] != "IPv6" {
|
||||||
|
t.Fatalf("resolved %+v", first)
|
||||||
|
}
|
||||||
|
|
||||||
|
httpJob := postJSON(t, ts.URL+"/v1/jobs", `{"target":"`+page.URL+`/","port":`+strconv.Itoa(port)+`,"profile":"http","intervalMs":200,"timeoutMs":1500,"durationSec":2,"http":{"version":"1.1","method":"GET","maxRedirects":5}}`)
|
||||||
|
defer httpJob.Body.Close()
|
||||||
|
if httpJob.StatusCode != http.StatusCreated {
|
||||||
|
raw, _ := io.ReadAll(httpJob.Body)
|
||||||
|
t.Fatalf("http create %d %s", httpJob.StatusCode, raw)
|
||||||
|
}
|
||||||
|
var job map[string]any
|
||||||
|
if err := json.NewDecoder(httpJob.Body).Decode(&job); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
id, _ := job["jobId"].(string)
|
||||||
|
sample := readSampleURL(t, ts.URL+"/v1/jobs/"+id+"/stream")
|
||||||
|
if sample["status"] != statusOK {
|
||||||
|
t.Fatalf("sample %+v", sample)
|
||||||
|
}
|
||||||
|
detail, _ := sample["detail"].(map[string]any)
|
||||||
|
if detail["statusCode"] != "502" {
|
||||||
|
t.Fatalf("detail %+v", detail)
|
||||||
|
}
|
||||||
|
note, _ := sample["note"].(string)
|
||||||
|
if !strings.Contains(note, "不是丢包") {
|
||||||
|
t.Fatalf("note %s", note)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHelperSpeaksHTTPEngine(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}))
|
||||||
|
defer srv.Close()
|
||||||
|
port := mustPort(t, srv.URL)
|
||||||
|
var in bytes.Buffer
|
||||||
|
req, _ := json.Marshal(map[string]any{
|
||||||
|
"profile": "http", "target": srv.URL + "/", "port": port, "timeoutMs": 2000,
|
||||||
|
"allowIPv4": true, "allowIPv6": false,
|
||||||
|
"http": map[string]any{"version": "1.1", "method": "GET"},
|
||||||
|
})
|
||||||
|
in.Write(req)
|
||||||
|
in.WriteByte('\n')
|
||||||
|
var out bytes.Buffer
|
||||||
|
if err := runHelper(&in, &out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sc := bufio.NewScanner(&out)
|
||||||
|
if !sc.Scan() {
|
||||||
|
t.Fatal("no output")
|
||||||
|
}
|
||||||
|
var body map[string]any
|
||||||
|
if err := json.Unmarshal(sc.Bytes(), &body); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if body["status"] != statusOK {
|
||||||
|
t.Fatalf("%+v", body)
|
||||||
|
}
|
||||||
|
detail, _ := body["detail"].(map[string]any)
|
||||||
|
if detail["httpVersion"] != "1.1" || detail["statusCode"] != "204" {
|
||||||
|
t.Fatalf("%+v", detail)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func tlsInput(target string, port int, version string, pool *x509.CertPool) HTTPInput {
|
||||||
|
return HTTPInput{
|
||||||
|
Target: target, Port: port, Version: version, Resolve: "127.0.0.1",
|
||||||
|
Allow4: true, Allow6: true, Timeout: 4 * time.Second, Roots: pool,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCert(t *testing.T) (tls.Certificate, *x509.CertPool) {
|
||||||
|
t.Helper()
|
||||||
|
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
tmpl := &x509.Certificate{
|
||||||
|
SerialNumber: big.NewInt(1),
|
||||||
|
Subject: pkix.Name{CommonName: "example.com"},
|
||||||
|
NotBefore: time.Now().Add(-time.Hour),
|
||||||
|
NotAfter: time.Now().Add(time.Hour),
|
||||||
|
DNSNames: []string{"example.com"},
|
||||||
|
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||||
|
}
|
||||||
|
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
leaf, err := x509.ParseCertificate(der)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
pool := x509.NewCertPool()
|
||||||
|
pool.AddCert(leaf)
|
||||||
|
return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key}, pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func serveTLS(t *testing.T, handler http.Handler, protos []string, h2 bool, cert tls.Certificate) (string, func()) {
|
||||||
|
t.Helper()
|
||||||
|
ln, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{
|
||||||
|
Certificates: []tls.Certificate{cert},
|
||||||
|
NextProtos: protos,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
srv := &http.Server{Handler: handler, ReadHeaderTimeout: 5 * time.Second}
|
||||||
|
if !h2 {
|
||||||
|
srv.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
|
||||||
|
}
|
||||||
|
go srv.Serve(ln)
|
||||||
|
return ln.Addr().String(), func() { _ = srv.Close() }
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustPort(t *testing.T, raw string) int {
|
||||||
|
t.Helper()
|
||||||
|
if !strings.Contains(raw, "://") {
|
||||||
|
raw = "https://" + raw
|
||||||
|
}
|
||||||
|
u, err := url.Parse(raw)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
port, err := strconv.Atoi(u.Port())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return port
|
||||||
|
}
|
||||||
|
|
||||||
|
func postJSON(t *testing.T, url, body string) *http.Response {
|
||||||
|
t.Helper()
|
||||||
|
res, err := http.Post(url, "application/json", strings.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
func readSampleURL(t *testing.T, rawURL string) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
client := &http.Client{Timeout: 5 * time.Second}
|
||||||
|
res, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer res.Body.Close()
|
||||||
|
sc := bufio.NewScanner(res.Body)
|
||||||
|
var data string
|
||||||
|
for sc.Scan() {
|
||||||
|
line := sc.Text()
|
||||||
|
if strings.HasPrefix(line, "data: ") {
|
||||||
|
data = strings.TrimPrefix(line, "data: ")
|
||||||
|
}
|
||||||
|
if line == "" && data != "" && data != "{}" {
|
||||||
|
var msg map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(data), &msg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if msg["status"] != "" && msg["status"] != "pending" {
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
data = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatal("no sample")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+87
-6
@@ -1,12 +1,14 @@
|
|||||||
// Copyright (C) 2026 灸 言
|
// Copyright (C) 2026 言灸
|
||||||
// SPDX-License-Identifier: AGPL-3.0-only
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -19,6 +21,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
if hashRequested(os.Args[1:]) {
|
||||||
|
if err := printHash(os.Stdin); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
cfg, err := loadConfig(os.Args[1:], os.Environ())
|
cfg, err := loadConfig(os.Args[1:], os.Environ())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, errHelp) {
|
if errors.Is(err, errHelp) {
|
||||||
@@ -26,6 +34,20 @@ func main() {
|
|||||||
}
|
}
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
if cfg.CenterKey == "" && cfg.CenterDir != "" {
|
||||||
|
key, err := loadCenterKeyFile(cfg.CenterDir)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg.CenterKey = key
|
||||||
|
}
|
||||||
|
if cfg.Mode == "helper" {
|
||||||
|
if err := runHelper(os.Stdin, os.Stdout); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("netquality %s", appVersion)
|
||||||
log.Printf("%s", cfg.Summary())
|
log.Printf("%s", cfg.Summary())
|
||||||
|
|
||||||
tok, err := tokenBytes(cfg.Token)
|
tok, err := tokenBytes(cfg.Token)
|
||||||
@@ -50,11 +72,27 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var httpSrv *http.Server
|
var httpSrv *http.Server
|
||||||
|
var node *Node
|
||||||
if cfg.Mode == "node" || cfg.Mode == "both" {
|
if cfg.Mode == "node" || cfg.Mode == "both" {
|
||||||
node := newNode(cfg.NodeToken, cfg.AllowPrivate, extra, defaultLimits())
|
node = newNode(cfg.NodeToken, cfg.AllowPrivate, extra, defaultLimits())
|
||||||
|
node.CenterKey = []byte(cfg.CenterKey)
|
||||||
|
node.ServerID = strings.TrimSpace(cfg.ServerID)
|
||||||
|
if cfg.CenterKey != "" && node.ServerID == "" {
|
||||||
|
log.Printf("设置了中心密钥但没有 NQ_SERVER_ID,将不接受中心签发的短期凭证")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var center *Center
|
||||||
|
if strings.TrimSpace(cfg.CenterDir) != "" && cfg.Mode != "reflector" {
|
||||||
|
center = newCenter(cfg.CenterDir, cfg.CenterKey)
|
||||||
|
if _, err := center.load(); err != nil {
|
||||||
|
log.Fatalf("中心配置无法读取: %v", err)
|
||||||
|
}
|
||||||
|
log.Printf("center directory %s", cfg.CenterDir)
|
||||||
|
}
|
||||||
|
if node != nil || center != nil {
|
||||||
httpSrv = &http.Server{
|
httpSrv = &http.Server{
|
||||||
Addr: cfg.ControlAddr,
|
Addr: cfg.ControlAddr,
|
||||||
Handler: node.Handler(),
|
Handler: controlHandler(node, center),
|
||||||
ReadHeaderTimeout: 5 * time.Second,
|
ReadHeaderTimeout: 5 * time.Second,
|
||||||
IdleTimeout: 2 * time.Minute,
|
IdleTimeout: 2 * time.Minute,
|
||||||
}
|
}
|
||||||
@@ -75,14 +113,17 @@ func main() {
|
|||||||
errCh <- serveErr
|
errCh <- serveErr
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
if node.Public() && !loopbackHost(cfg.ControlAddr) {
|
if node != nil && node.Public() && !loopbackHost(cfg.ControlAddr) {
|
||||||
log.Printf("WARNING: this node is PUBLIC. Anyone who can reach %s can start bounded probes. Set NQ_NODE_TOKEN or -node-token to require a control token. Caps stay on: jobs=%d duration=%s interval>=%s probes/s=%d bandwidth=%dB/s",
|
log.Printf("WARNING: this node is PUBLIC. Anyone who can reach %s can start bounded probes. Set NQ_NODE_TOKEN or -node-token to require a control token. Caps stay on: jobs=%d duration=%s interval>=%s probes/s=%d bandwidth=%dB/s",
|
||||||
cfg.ControlAddr, node.Limits.MaxJobs, node.Limits.MaxDuration, node.Limits.MinInterval, node.Limits.MaxProbePerSec, node.Limits.MaxBytesPerSec)
|
cfg.ControlAddr, node.Limits.MaxJobs, node.Limits.MaxDuration, node.Limits.MinInterval, node.Limits.MaxProbePerSec, node.Limits.MaxBytesPerSec)
|
||||||
} else if node.Public() {
|
} else if node != nil && node.Public() {
|
||||||
log.Printf("node is public and bound to loopback; no control token is required")
|
log.Printf("node is public and bound to loopback; no control token is required")
|
||||||
} else {
|
} else if node != nil {
|
||||||
log.Printf("node is private; a control token is required and is not logged")
|
log.Printf("node is private; a control token is required and is not logged")
|
||||||
}
|
}
|
||||||
|
if center != nil {
|
||||||
|
log.Printf("center API is on the control port; use HTTPS before exposing it")
|
||||||
|
}
|
||||||
if cfg.AllowPrivate {
|
if cfg.AllowPrivate {
|
||||||
log.Printf("private and loopback targets are allowed; metadata addresses stay blocked")
|
log.Printf("private and loopback targets are allowed; metadata addresses stay blocked")
|
||||||
}
|
}
|
||||||
@@ -188,6 +229,46 @@ func parseNets(s string) ([]*net.IPNet, error) {
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func controlHandler(node *Node, center *Center) http.Handler {
|
||||||
|
switch {
|
||||||
|
case node != nil && center == nil:
|
||||||
|
return node.Handler()
|
||||||
|
case node == nil && center != nil:
|
||||||
|
return center.Handler()
|
||||||
|
default:
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.Handle("/v1/center/", center.Handler())
|
||||||
|
mux.Handle("/v1/", node.Handler())
|
||||||
|
return mux
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func hashRequested(args []string) bool {
|
||||||
|
for _, arg := range args {
|
||||||
|
if arg == "-hash-secret" || arg == "--hash-secret" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func printHash(r io.Reader) error {
|
||||||
|
sc := bufio.NewScanner(r)
|
||||||
|
sc.Buffer(make([]byte, 64*1024), 1<<20)
|
||||||
|
if !sc.Scan() {
|
||||||
|
if err := sc.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return errors.New("请从标准输入传入一行要计算哈希的内容")
|
||||||
|
}
|
||||||
|
line := strings.TrimRight(sc.Text(), "\r")
|
||||||
|
if strings.TrimSpace(line) == "" {
|
||||||
|
return errors.New("内容是空的")
|
||||||
|
}
|
||||||
|
fmt.Println(hashSecret(line))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func loopbackHost(addr string) bool {
|
func loopbackHost(addr string) bool {
|
||||||
host, _, err := net.SplitHostPort(addr)
|
host, _, err := net.SplitHostPort(addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
+31
-12
@@ -19,13 +19,14 @@ const (
|
|||||||
// Outcome is one finished attempt. Pending attempts are never turned into
|
// Outcome is one finished attempt. Pending attempts are never turned into
|
||||||
// a sample, so a chart cannot show a fake 100% before the probe completes.
|
// a sample, so a chart cannot show a fake 100% before the probe completes.
|
||||||
type Outcome struct {
|
type Outcome struct {
|
||||||
Status string
|
Status string
|
||||||
Kind string
|
Kind string
|
||||||
Rtt time.Duration
|
Rtt time.Duration
|
||||||
HasRtt bool
|
HasRtt bool
|
||||||
Note string
|
Note string
|
||||||
Detail map[string]string
|
Detail map[string]string
|
||||||
Reconnect bool
|
Reconnect bool
|
||||||
|
SelectionSkipped int
|
||||||
}
|
}
|
||||||
|
|
||||||
type jitter struct {
|
type jitter struct {
|
||||||
@@ -64,15 +65,18 @@ type sampleBook struct {
|
|||||||
reconnect int
|
reconnect int
|
||||||
consecutive int
|
consecutive int
|
||||||
|
|
||||||
lastRttMs *float64
|
lastRttMs *float64
|
||||||
jitter jitter
|
jitter jitter
|
||||||
lastNote string
|
rtts []float64
|
||||||
detail map[string]string
|
selectionSkipped int
|
||||||
|
lastNote string
|
||||||
|
detail map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *sampleBook) add(o Outcome) {
|
func (b *sampleBook) add(o Outcome) {
|
||||||
b.sent++
|
b.sent++
|
||||||
b.completed++
|
b.completed++
|
||||||
|
b.selectionSkipped += o.SelectionSkipped
|
||||||
if o.Reconnect {
|
if o.Reconnect {
|
||||||
b.reconnect++
|
b.reconnect++
|
||||||
}
|
}
|
||||||
@@ -94,6 +98,7 @@ func (b *sampleBook) add(o Outcome) {
|
|||||||
if o.HasRtt {
|
if o.HasRtt {
|
||||||
ms := float64(o.Rtt) / float64(time.Millisecond)
|
ms := float64(o.Rtt) / float64(time.Millisecond)
|
||||||
b.lastRttMs = &ms
|
b.lastRttMs = &ms
|
||||||
|
b.rtts = append(b.rtts, ms)
|
||||||
b.jitter.push(ms)
|
b.jitter.push(ms)
|
||||||
}
|
}
|
||||||
case statusTimeout:
|
case statusTimeout:
|
||||||
@@ -138,6 +143,14 @@ func (b *sampleBook) summary() summaryMsg {
|
|||||||
ConsecutiveFailures: b.consecutive,
|
ConsecutiveFailures: b.consecutive,
|
||||||
LastNote: b.lastNote,
|
LastNote: b.lastNote,
|
||||||
Detail: b.detail,
|
Detail: b.detail,
|
||||||
|
SelectionSkipped: b.selectionSkipped,
|
||||||
|
}
|
||||||
|
if min, mean, median, p95, max, ok := latencyOf(b.rtts); ok {
|
||||||
|
s.MinRttMs = &min
|
||||||
|
s.MeanRttMs = &mean
|
||||||
|
s.MedianRttMs = &median
|
||||||
|
s.P95RttMs = &p95
|
||||||
|
s.MaxRttMs = &max
|
||||||
}
|
}
|
||||||
if b.lastRttMs != nil {
|
if b.lastRttMs != nil {
|
||||||
v := *b.lastRttMs
|
v := *b.lastRttMs
|
||||||
@@ -159,7 +172,7 @@ func (b *sampleBook) summary() summaryMsg {
|
|||||||
v := float64(b.timeout) * 100 / float64(b.timeout+b.ok)
|
v := float64(b.timeout) * 100 / float64(b.timeout+b.ok)
|
||||||
s.ProbeLossPct = &v
|
s.ProbeLossPct = &v
|
||||||
}
|
}
|
||||||
case "tcp-connect", "minecraft-java":
|
case "tcp-connect", "minecraft-java", "http":
|
||||||
denom := b.ok + b.timeout + b.refused + b.dns + b.protocol + b.other
|
denom := b.ok + b.timeout + b.refused + b.dns + b.protocol + b.other
|
||||||
if denom > 0 {
|
if denom > 0 {
|
||||||
v := float64(denom-b.ok) * 100 / float64(denom)
|
v := float64(denom-b.ok) * 100 / float64(denom)
|
||||||
@@ -197,6 +210,12 @@ type summaryMsg struct {
|
|||||||
ProbeLossPct *float64 `json:"probeLossPct,omitempty"`
|
ProbeLossPct *float64 `json:"probeLossPct,omitempty"`
|
||||||
FailurePct *float64 `json:"failurePct,omitempty"`
|
FailurePct *float64 `json:"failurePct,omitempty"`
|
||||||
UnknownPct *float64 `json:"unknownPct,omitempty"`
|
UnknownPct *float64 `json:"unknownPct,omitempty"`
|
||||||
|
MinRttMs *float64 `json:"minRttMs,omitempty"`
|
||||||
|
MeanRttMs *float64 `json:"meanRttMs,omitempty"`
|
||||||
|
MedianRttMs *float64 `json:"medianRttMs,omitempty"`
|
||||||
|
P95RttMs *float64 `json:"p95RttMs,omitempty"`
|
||||||
|
MaxRttMs *float64 `json:"maxRttMs,omitempty"`
|
||||||
|
SelectionSkipped int `json:"selectionSkipped,omitempty"`
|
||||||
LastNote string `json:"lastNote,omitempty"`
|
LastNote string `json:"lastNote,omitempty"`
|
||||||
Detail map[string]string `json:"detail,omitempty"`
|
Detail map[string]string `json:"detail,omitempty"`
|
||||||
}
|
}
|
||||||
+106
-15
@@ -21,6 +21,7 @@ type jobSpec struct {
|
|||||||
Port int
|
Port int
|
||||||
Profile string
|
Profile string
|
||||||
IP net.IP
|
IP net.IP
|
||||||
|
state *dialState
|
||||||
Interval time.Duration
|
Interval time.Duration
|
||||||
Timeout time.Duration
|
Timeout time.Duration
|
||||||
Duration time.Duration
|
Duration time.Duration
|
||||||
@@ -29,6 +30,9 @@ type jobSpec struct {
|
|||||||
DNSName string
|
DNSName string
|
||||||
Payload []byte
|
Payload []byte
|
||||||
Expect []byte
|
Expect []byte
|
||||||
|
Allow4 bool
|
||||||
|
Allow6 bool
|
||||||
|
HTTP HTTPInput
|
||||||
}
|
}
|
||||||
|
|
||||||
type Limits struct {
|
type Limits struct {
|
||||||
@@ -68,6 +72,8 @@ type Node struct {
|
|||||||
ExtraNets []*net.IPNet
|
ExtraNets []*net.IPNet
|
||||||
Limits Limits
|
Limits Limits
|
||||||
Resolver resolver
|
Resolver resolver
|
||||||
|
CenterKey []byte
|
||||||
|
ServerID string
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
jobs map[string]*probeJob
|
jobs map[string]*probeJob
|
||||||
@@ -92,7 +98,7 @@ func newNode(token string, allowPrivate bool, extra []*net.IPNet, limits Limits)
|
|||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
|
|
||||||
func (n *Node) Public() bool { return n.Token == "" }
|
func (n *Node) Public() bool { return n.Token == "" && len(n.CenterKey) == 0 }
|
||||||
|
|
||||||
func (n *Node) Handler() http.Handler {
|
func (n *Node) Handler() http.Handler {
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
@@ -110,12 +116,14 @@ func (n *Node) info(w http.ResponseWriter, _ *http.Request) {
|
|||||||
vis = "public"
|
vis = "public"
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]any{
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"version": appVersion,
|
||||||
"visibility": vis,
|
"visibility": vis,
|
||||||
"authRequired": !n.Public(),
|
"authRequired": !n.Public(),
|
||||||
"profiles": []string{
|
"profiles": []string{
|
||||||
"nq-tcp", "nq-udp", "tcp-connect", "udp-generic", "dns",
|
"nq-tcp", "nq-udp", "tcp-connect", "udp-generic", "dns",
|
||||||
"minecraft-java", "minecraft-bedrock", "custom-udp",
|
"minecraft-java", "minecraft-bedrock", "custom-udp", "http",
|
||||||
},
|
},
|
||||||
|
"ipFamily": true,
|
||||||
"limits": map[string]int{
|
"limits": map[string]int{
|
||||||
"maxJobs": n.Limits.MaxJobs,
|
"maxJobs": n.Limits.MaxJobs,
|
||||||
"maxDurationSec": int(n.Limits.MaxDuration / time.Second),
|
"maxDurationSec": int(n.Limits.MaxDuration / time.Second),
|
||||||
@@ -129,16 +137,20 @@ func (n *Node) info(w http.ResponseWriter, _ *http.Request) {
|
|||||||
|
|
||||||
func (n *Node) auth(next http.HandlerFunc) http.HandlerFunc {
|
func (n *Node) auth(next http.HandlerFunc) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
if n.Token == "" {
|
if n.Public() {
|
||||||
next(w, r)
|
next(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
got := bearer(r.Header.Get("Authorization"))
|
got := bearer(r.Header.Get("Authorization"))
|
||||||
if got == "" || subtle.ConstantTimeCompare([]byte(got), []byte(n.Token)) != 1 {
|
if n.Token != "" && got != "" && subtle.ConstantTimeCompare([]byte(got), []byte(n.Token)) == 1 {
|
||||||
writeErr(w, http.StatusUnauthorized, "unauthorized", "节点口令不正确或未提供")
|
next(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
next(w, r)
|
if verifyCredential(got, n.CenterKey, n.ServerID, time.Now()) {
|
||||||
|
next(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeErr(w, http.StatusUnauthorized, "unauthorized", "节点口令不正确或未提供")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,10 +162,13 @@ type createReq struct {
|
|||||||
TimeoutMs int `json:"timeoutMs"`
|
TimeoutMs int `json:"timeoutMs"`
|
||||||
DurationSec int `json:"durationSec"`
|
DurationSec int `json:"durationSec"`
|
||||||
PacketSize int `json:"packetSize"`
|
PacketSize int `json:"packetSize"`
|
||||||
EchoToken string `json:"echoToken"`
|
EchoToken string `json:"echoToken"`
|
||||||
DNSName string `json:"dnsName"`
|
DNSName string `json:"dnsName"`
|
||||||
PayloadHex string `json:"payloadHex"`
|
PayloadHex string `json:"payloadHex"`
|
||||||
ExpectHex string `json:"expectHex"`
|
ExpectHex string `json:"expectHex"`
|
||||||
|
AllowIPv4 *bool `json:"allowIPv4"`
|
||||||
|
AllowIPv6 *bool `json:"allowIPv6"`
|
||||||
|
HTTP *httpOptionsReq `json:"http"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (n *Node) create(w http.ResponseWriter, r *http.Request) {
|
func (n *Node) create(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -185,19 +200,30 @@ func (n *Node) create(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeErr(w, http.StatusInternalServerError, "error", "任务没有启动")
|
writeErr(w, http.StatusInternalServerError, "error", "任务没有启动")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
resolved := make([]map[string]string, 0, len(spec.candidates()))
|
||||||
|
for _, ip := range spec.candidates() {
|
||||||
|
resolved = append(resolved, map[string]string{
|
||||||
|
"address": ip.String(),
|
||||||
|
"family": familyOf(ip),
|
||||||
|
})
|
||||||
|
}
|
||||||
writeJSON(w, http.StatusCreated, map[string]any{
|
writeJSON(w, http.StatusCreated, map[string]any{
|
||||||
"jobId": job.id,
|
"jobId": job.id,
|
||||||
"expiresAt": job.expires.UTC().Format(time.RFC3339),
|
"expiresAt": job.expires.UTC().Format(time.RFC3339),
|
||||||
"visibility": map[bool]string{true: "public", false: "private"}[n.Public()],
|
"visibility": map[bool]string{true: "public", false: "private"}[n.Public()],
|
||||||
|
"version": appVersion,
|
||||||
|
"resolved": resolved,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
|
func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
|
||||||
switch req.Profile {
|
switch req.Profile {
|
||||||
case "nq-tcp", "nq-udp", "tcp-connect", "udp-generic", "dns", "minecraft-java", "minecraft-bedrock", "custom-udp":
|
case "nq-tcp", "nq-udp", "tcp-connect", "udp-generic", "dns", "minecraft-java", "minecraft-bedrock", "custom-udp", "http":
|
||||||
default:
|
default:
|
||||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", "不支持的探测类型"}
|
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", "不支持的探测类型"}
|
||||||
}
|
}
|
||||||
|
allow4 := flagOrDefault(req.AllowIPv4, true)
|
||||||
|
allow6 := flagOrDefault(req.AllowIPv6, true)
|
||||||
if req.Port < 1 || req.Port > 65535 {
|
if req.Port < 1 || req.Port > 65535 {
|
||||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_port", "端口需要在 1 到 65535 之间"}
|
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_port", "端口需要在 1 到 65535 之间"}
|
||||||
}
|
}
|
||||||
@@ -246,7 +272,31 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ip, err := targetOK(ctx, n.Resolver, req.Target, n.AllowPrivate, n.ExtraNets)
|
httpIn := HTTPInput{
|
||||||
|
Target: req.Target, Port: req.Port, Timeout: timeout,
|
||||||
|
Allow4: allow4, Allow6: allow6, CheckSafety: true,
|
||||||
|
AllowPrivate: n.AllowPrivate, Extra: n.ExtraNets, Resolver: n.Resolver,
|
||||||
|
}
|
||||||
|
applyHTTPOptions(&httpIn, req.HTTP)
|
||||||
|
lookupHost := req.Target
|
||||||
|
if req.Profile == "http" {
|
||||||
|
page, err := buildHTTPURL(req.Target, req.Port)
|
||||||
|
if err != nil {
|
||||||
|
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", err.Error()}
|
||||||
|
}
|
||||||
|
if _, err := normalizeHTTPVersion(httpIn.Version); err != nil {
|
||||||
|
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", err.Error()}
|
||||||
|
}
|
||||||
|
method := strings.ToUpper(strings.TrimSpace(httpIn.Method))
|
||||||
|
if method != "" && method != "GET" && method != "POST" {
|
||||||
|
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_request", "HTTP 方法只支持 GET 和 POST"}
|
||||||
|
}
|
||||||
|
lookupHost = page.Hostname()
|
||||||
|
if strings.TrimSpace(httpIn.Resolve) != "" {
|
||||||
|
lookupHost = strings.TrimSpace(httpIn.Resolve)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ips, err := resolveTargets(ctx, n.Resolver, lookupHost, n.AllowPrivate, n.ExtraNets)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var dnsErr *net.DNSError
|
var dnsErr *net.DNSError
|
||||||
if errors.As(err, &dnsErr) {
|
if errors.As(err, &dnsErr) {
|
||||||
@@ -257,10 +307,19 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
|
|||||||
}
|
}
|
||||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", "目标地址无效"}
|
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", "目标地址无效"}
|
||||||
}
|
}
|
||||||
|
ips, err = filterFamily(lookupHost, ips, allow4, allow6)
|
||||||
|
if err != nil {
|
||||||
|
if fe, ok := asFamily(err); ok {
|
||||||
|
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_family", fe.Error()}
|
||||||
|
}
|
||||||
|
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_family", "地址族不被允许"}
|
||||||
|
}
|
||||||
return jobSpec{
|
return jobSpec{
|
||||||
Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ip,
|
Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ips[0],
|
||||||
|
state: &dialState{picker: newEndpointPicker(ips)},
|
||||||
Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size,
|
Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size,
|
||||||
Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect,
|
Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect,
|
||||||
|
Allow4: allow4, Allow6: allow6, HTTP: httpIn,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,18 +393,50 @@ func (n *Node) run(ctx context.Context, job *probeJob, spec jobSpec, p prober) {
|
|||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ledger := &selectionLedger{candidates: len(spec.candidates())}
|
||||||
|
datagram := datagramProfile(spec.Profile)
|
||||||
for {
|
for {
|
||||||
if err := n.pace.wait(ctx, spec.PacketSize); err != nil {
|
if err := n.pace.wait(ctx, spec.PacketSize); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
started := time.Now()
|
started := time.Now()
|
||||||
pctx, cancel := context.WithTimeout(ctx, spec.Timeout)
|
budget := spec.Timeout
|
||||||
|
if budget <= 0 {
|
||||||
|
budget = 1500 * time.Millisecond
|
||||||
|
}
|
||||||
|
if !datagram && spec.state != nil && spec.state.picker != nil && !spec.state.picker.locked && len(spec.state.picker.ips) > 1 {
|
||||||
|
budget *= time.Duration(len(spec.state.picker.ips))
|
||||||
|
}
|
||||||
|
if datagram && spec.state != nil {
|
||||||
|
if ip := spec.dialIP(); ip != nil {
|
||||||
|
spec.state.used = append(net.IP(nil), ip...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pctx, cancel := context.WithTimeout(ctx, budget)
|
||||||
out := p.Probe(pctx)
|
out := p.Probe(pctx)
|
||||||
cancel()
|
cancel()
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
emit(out)
|
out = spec.decorate(out)
|
||||||
|
var commit []Outcome
|
||||||
|
if datagram && spec.state != nil && spec.state.picker != nil {
|
||||||
|
responded := selectionResponded(out.Status)
|
||||||
|
wasMeasuring := ledger.measuring
|
||||||
|
changed := spec.state.picker.record(responded)
|
||||||
|
commit, _ = ledger.take(out, responded)
|
||||||
|
if wasMeasuring && changed {
|
||||||
|
ledger.measuring = false
|
||||||
|
}
|
||||||
|
if len(commit) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
commit = []Outcome{out}
|
||||||
|
}
|
||||||
|
for _, item := range commit {
|
||||||
|
emit(item)
|
||||||
|
}
|
||||||
wait := spec.Interval - time.Since(started)
|
wait := spec.Interval - time.Since(started)
|
||||||
if wait < 0 {
|
if wait < 0 {
|
||||||
wait = 0
|
wait = 0
|
||||||
|
|||||||
+17
-1
@@ -79,9 +79,19 @@ func TestPublicAndPrivateAuth(t *testing.T) {
|
|||||||
if err := json.NewDecoder(info.Body).Decode(&body); err != nil {
|
if err := json.NewDecoder(info.Body).Decode(&body); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if body["visibility"] != "public" || body["authRequired"] != false {
|
if body["visibility"] != "public" || body["authRequired"] != false || body["ipFamily"] != true {
|
||||||
t.Fatalf("info %+v", body)
|
t.Fatalf("info %+v", body)
|
||||||
}
|
}
|
||||||
|
profiles, _ := body["profiles"].([]any)
|
||||||
|
seenHTTP := false
|
||||||
|
for _, item := range profiles {
|
||||||
|
if item == "http" {
|
||||||
|
seenHTTP = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !seenHTTP {
|
||||||
|
t.Fatalf("info profiles %+v", body["profiles"])
|
||||||
|
}
|
||||||
|
|
||||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -163,6 +173,12 @@ func TestNodeNQAndTCPAndUDP(t *testing.T) {
|
|||||||
if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 {
|
if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 {
|
||||||
t.Fatalf("nq tcp %+v", sample)
|
t.Fatalf("nq tcp %+v", sample)
|
||||||
}
|
}
|
||||||
|
if sample.Detail["address"] != "127.0.0.1" || sample.Detail["family"] != "IPv4" {
|
||||||
|
t.Fatalf("tcp did not report the connected address %+v", sample.Detail)
|
||||||
|
}
|
||||||
|
if sample.Summary.MinRttMs == nil || sample.Summary.P95RttMs == nil {
|
||||||
|
t.Fatalf("latency stats missing %+v", sample.Summary)
|
||||||
|
}
|
||||||
if sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 {
|
if sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 {
|
||||||
t.Fatalf("loss %+v", sample.Summary)
|
t.Fatalf("loss %+v", sample.Summary)
|
||||||
}
|
}
|
||||||
|
|||||||
+25
-25
@@ -38,6 +38,8 @@ func newProber(spec jobSpec) (prober, error) {
|
|||||||
return &mcJava{spec: spec}, nil
|
return &mcJava{spec: spec}, nil
|
||||||
case "minecraft-bedrock":
|
case "minecraft-bedrock":
|
||||||
return &mcBedrock{spec: spec}, nil
|
return &mcBedrock{spec: spec}, nil
|
||||||
|
case "http":
|
||||||
|
return &httpProbe{spec: spec}, nil
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unknown profile %q", spec.Profile)
|
return nil, fmt.Errorf("unknown profile %q", spec.Profile)
|
||||||
}
|
}
|
||||||
@@ -127,7 +129,7 @@ func (p *nqTCP) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *nqTCP) dial(ctx context.Context) error {
|
func (p *nqTCP) dial(ctx context.Context) error {
|
||||||
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
|
conn, err := dialSpecTCP(ctx, &p.spec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -208,11 +210,9 @@ func (p *nqUDP) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *nqUDP) ensure() error {
|
func (p *nqUDP) ensure() error {
|
||||||
if p.conn != nil {
|
c, err := ensureUDP(p.conn, p.spec)
|
||||||
return nil
|
|
||||||
}
|
|
||||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
p.conn = nil
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
p.conn = c
|
p.conn = c
|
||||||
@@ -273,7 +273,7 @@ func (p *tcpConnect) Close() error { return nil }
|
|||||||
|
|
||||||
func (p *tcpConnect) Probe(ctx context.Context) Outcome {
|
func (p *tcpConnect) Probe(ctx context.Context) Outcome {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
|
conn, err := dialSpecTCP(ctx, &p.spec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return classifyDial(err)
|
return classifyDial(err)
|
||||||
}
|
}
|
||||||
@@ -297,13 +297,12 @@ func (p *udpQuery) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *udpQuery) Probe(ctx context.Context) Outcome {
|
func (p *udpQuery) Probe(ctx context.Context) Outcome {
|
||||||
if p.conn == nil {
|
c, err := ensureUDP(p.conn, p.spec)
|
||||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
if err != nil {
|
||||||
if err != nil {
|
p.conn = nil
|
||||||
return classifyDial(err)
|
return classifyDial(err)
|
||||||
}
|
|
||||||
p.conn = c
|
|
||||||
}
|
}
|
||||||
|
p.conn = c
|
||||||
payload := p.spec.Payload
|
payload := p.spec.Payload
|
||||||
if p.generic {
|
if p.generic {
|
||||||
n := p.spec.PacketSize
|
n := p.spec.PacketSize
|
||||||
@@ -358,13 +357,12 @@ func (p *dnsQuery) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *dnsQuery) Probe(ctx context.Context) Outcome {
|
func (p *dnsQuery) Probe(ctx context.Context) Outcome {
|
||||||
if p.conn == nil {
|
c, err := ensureUDP(p.conn, p.spec)
|
||||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
if err != nil {
|
||||||
if err != nil {
|
p.conn = nil
|
||||||
return classifyDial(err)
|
return classifyDial(err)
|
||||||
}
|
|
||||||
p.conn = c
|
|
||||||
}
|
}
|
||||||
|
p.conn = c
|
||||||
p.id++
|
p.id++
|
||||||
if p.id == 0 {
|
if p.id == 0 {
|
||||||
p.id = 1
|
p.id = 1
|
||||||
@@ -449,12 +447,14 @@ func (p *mcBedrock) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *mcBedrock) Probe(ctx context.Context) Outcome {
|
func (p *mcBedrock) Probe(ctx context.Context) Outcome {
|
||||||
if p.conn == nil {
|
fresh := p.conn == nil
|
||||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
c, err := ensureUDP(p.conn, p.spec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return classifyDial(err)
|
p.conn = nil
|
||||||
}
|
return classifyDial(err)
|
||||||
p.conn = c
|
}
|
||||||
|
p.conn = c
|
||||||
|
if fresh || p.guid == 0 {
|
||||||
p.guid = uint64(time.Now().UnixNano())
|
p.guid = uint64(time.Now().UnixNano())
|
||||||
}
|
}
|
||||||
ts := uint64(time.Now().UnixNano())
|
ts := uint64(time.Now().UnixNano())
|
||||||
@@ -529,7 +529,7 @@ type mcJava struct{ spec jobSpec }
|
|||||||
func (p *mcJava) Close() error { return nil }
|
func (p *mcJava) Close() error { return nil }
|
||||||
|
|
||||||
func (p *mcJava) Probe(ctx context.Context) Outcome {
|
func (p *mcJava) Probe(ctx context.Context) Outcome {
|
||||||
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
|
conn, err := dialSpecTCP(ctx, &p.spec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return classifyDial(err)
|
return classifyDial(err)
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-3
@@ -25,8 +25,17 @@ var metadataIP = net.ParseIP("169.254.169.254")
|
|||||||
// Loopback, private, link-local and cloud metadata are rejected unless
|
// Loopback, private, link-local and cloud metadata are rejected unless
|
||||||
// allowPrivate is set. Metadata addresses stay blocked either way.
|
// allowPrivate is set. Metadata addresses stay blocked either way.
|
||||||
// Every resolved address is checked so a later DNS answer cannot rebind
|
// Every resolved address is checked so a later DNS answer cannot rebind
|
||||||
// the dial onto a forbidden IP; the caller dials only the returned IP.
|
// the dial onto a forbidden IP. targetOK returns the first allowed address;
|
||||||
|
// resolveTargets returns every allowed address in resolver order.
|
||||||
func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) (net.IP, error) {
|
func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) (net.IP, error) {
|
||||||
|
ips, err := resolveTargets(ctx, resolver, host, allowPrivate, extra)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ips[0], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveTargets(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) ([]net.IP, error) {
|
||||||
host = strings.TrimSpace(host)
|
host = strings.TrimSpace(host)
|
||||||
host = strings.Trim(host, "[]")
|
host = strings.Trim(host, "[]")
|
||||||
if host == "" {
|
if host == "" {
|
||||||
@@ -39,7 +48,7 @@ func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate
|
|||||||
if !ipAllowed(ip, allowPrivate, extra) {
|
if !ipAllowed(ip, allowPrivate, extra) {
|
||||||
return nil, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String())
|
return nil, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String())
|
||||||
}
|
}
|
||||||
return ip, nil
|
return []net.IP{ip}, nil
|
||||||
}
|
}
|
||||||
if resolver == nil {
|
if resolver == nil {
|
||||||
resolver = net.DefaultResolver
|
resolver = net.DefaultResolver
|
||||||
@@ -65,7 +74,7 @@ func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate
|
|||||||
if len(allowed) != len(addrs) {
|
if len(allowed) != len(addrs) {
|
||||||
return nil, fmt.Errorf("%w: %s resolved to a mix of public and blocked addresses", errForbiddenTarget, host)
|
return nil, fmt.Errorf("%w: %s resolved to a mix of public and blocked addresses", errForbiddenTarget, host)
|
||||||
}
|
}
|
||||||
return allowed[0], nil
|
return allowed, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ipAllowed(ip net.IP, allowPrivate bool, extra []*net.IPNet) bool {
|
func ipAllowed(ip net.IP, allowPrivate bool, extra []*net.IPNet) bool {
|
||||||
|
|||||||
@@ -0,0 +1,368 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const appVersion = "1.1.3"
|
||||||
|
|
||||||
|
// dialState is shared by the job runner and the prober. Both hold a copy of
|
||||||
|
// jobSpec, so the mutable address choice has to live behind a pointer.
|
||||||
|
type dialState struct {
|
||||||
|
picker *endpointPicker
|
||||||
|
used net.IP
|
||||||
|
fallback string
|
||||||
|
skipped int
|
||||||
|
}
|
||||||
|
|
||||||
|
type endpointPicker struct {
|
||||||
|
ips []net.IP
|
||||||
|
index int
|
||||||
|
misses int
|
||||||
|
locked bool
|
||||||
|
sticky int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newEndpointPicker(ips []net.IP) *endpointPicker {
|
||||||
|
return &endpointPicker{ips: append([]net.IP(nil), ips...), sticky: 3}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *endpointPicker) current() net.IP {
|
||||||
|
if p == nil || len(p.ips) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return p.ips[p.index]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *endpointPicker) lock(ip net.IP) {
|
||||||
|
for i, cand := range p.ips {
|
||||||
|
if cand.Equal(ip) {
|
||||||
|
p.index = i
|
||||||
|
p.locked = true
|
||||||
|
p.misses = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// record matches the client EndpointPicker: one miss rotates until some
|
||||||
|
// address has answered; after that, sticky misses are required.
|
||||||
|
func (p *endpointPicker) record(responded bool) bool {
|
||||||
|
if responded {
|
||||||
|
p.locked = true
|
||||||
|
p.misses = 0
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
p.misses++
|
||||||
|
limit := 1
|
||||||
|
if p.locked {
|
||||||
|
limit = p.sticky
|
||||||
|
}
|
||||||
|
if len(p.ips) < 2 || p.misses < limit {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
p.misses = 0
|
||||||
|
p.locked = false
|
||||||
|
p.index = (p.index + 1) % len(p.ips)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s jobSpec) candidates() []net.IP {
|
||||||
|
if s.state != nil && s.state.picker != nil && len(s.state.picker.ips) > 0 {
|
||||||
|
return s.state.picker.ips
|
||||||
|
}
|
||||||
|
if s.IP != nil {
|
||||||
|
return []net.IP{s.IP}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s jobSpec) dialIP() net.IP {
|
||||||
|
if s.state != nil && s.state.picker != nil {
|
||||||
|
if ip := s.state.picker.current(); ip != nil {
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.IP != nil {
|
||||||
|
return s.IP
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func familyOf(ip net.IP) string {
|
||||||
|
if ip == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if ip.To4() != nil {
|
||||||
|
return "IPv4"
|
||||||
|
}
|
||||||
|
return "IPv6"
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyDetail(in map[string]string) map[string]string {
|
||||||
|
out := make(map[string]string, len(in)+2)
|
||||||
|
for k, v := range in {
|
||||||
|
out[k] = v
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func stampIP(o Outcome, ip net.IP) Outcome {
|
||||||
|
if ip == nil {
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
o.Detail = copyDetail(o.Detail)
|
||||||
|
o.Detail["address"] = ip.String()
|
||||||
|
o.Detail["family"] = familyOf(ip)
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// decorate attaches the address actually dialed. Candidate-connect failures
|
||||||
|
// that were skipped in favor of a working address are copied onto this one
|
||||||
|
// outcome and then cleared, so they are not repeated on later probes.
|
||||||
|
func (s jobSpec) decorate(o Outcome) Outcome {
|
||||||
|
if s.state == nil {
|
||||||
|
if s.IP != nil {
|
||||||
|
return stampIP(o, s.IP)
|
||||||
|
}
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
if s.state.used != nil {
|
||||||
|
o = stampIP(o, s.state.used)
|
||||||
|
}
|
||||||
|
if s.state.fallback != "" {
|
||||||
|
o.Detail = copyDetail(o.Detail)
|
||||||
|
o.Detail["fallback"] = s.state.fallback
|
||||||
|
s.state.fallback = ""
|
||||||
|
}
|
||||||
|
if s.state.skipped > 0 {
|
||||||
|
o.SelectionSkipped += s.state.skipped
|
||||||
|
s.state.skipped = 0
|
||||||
|
}
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectionResponded(status string) bool {
|
||||||
|
switch status {
|
||||||
|
case statusOK, statusProtocol, statusRefused:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func datagramProfile(profile string) bool {
|
||||||
|
switch profile {
|
||||||
|
case "nq-udp", "udp-generic", "custom-udp", "dns", "minecraft-bedrock":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type selectionLedger struct {
|
||||||
|
candidates int
|
||||||
|
measuring bool
|
||||||
|
held []Outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *selectionLedger) take(o Outcome, responded bool) (commit []Outcome, skipped int) {
|
||||||
|
if l.candidates <= 1 {
|
||||||
|
if responded {
|
||||||
|
l.measuring = true
|
||||||
|
}
|
||||||
|
return []Outcome{o}, 0
|
||||||
|
}
|
||||||
|
if l.measuring {
|
||||||
|
return []Outcome{o}, 0
|
||||||
|
}
|
||||||
|
if responded {
|
||||||
|
skipped = len(l.held)
|
||||||
|
if skipped > 0 {
|
||||||
|
o.Detail = copyDetail(o.Detail)
|
||||||
|
o.Detail["fallback"] = fallbackFromHeld(l.held, o)
|
||||||
|
o.SelectionSkipped += skipped
|
||||||
|
}
|
||||||
|
l.held = nil
|
||||||
|
l.measuring = true
|
||||||
|
return []Outcome{o}, skipped
|
||||||
|
}
|
||||||
|
l.held = append(l.held, o)
|
||||||
|
if len(l.held) >= l.candidates {
|
||||||
|
commit = append([]Outcome(nil), l.held...)
|
||||||
|
l.held = nil
|
||||||
|
return commit, 0
|
||||||
|
}
|
||||||
|
return nil, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func fallbackFromHeld(held []Outcome, success Outcome) string {
|
||||||
|
parts := make([]string, 0, len(held))
|
||||||
|
for _, o := range held {
|
||||||
|
addr := ""
|
||||||
|
fam := ""
|
||||||
|
if o.Detail != nil {
|
||||||
|
addr = o.Detail["address"]
|
||||||
|
fam = o.Detail["family"]
|
||||||
|
}
|
||||||
|
where := "未知地址"
|
||||||
|
if addr != "" {
|
||||||
|
where = addr
|
||||||
|
if fam != "" {
|
||||||
|
where = addr + "(" + fam + ")"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
why := o.Note
|
||||||
|
if why == "" {
|
||||||
|
why = "没有成功"
|
||||||
|
}
|
||||||
|
parts = append(parts, where+":"+why)
|
||||||
|
}
|
||||||
|
used := ""
|
||||||
|
usedFam := ""
|
||||||
|
if success.Detail != nil {
|
||||||
|
used = success.Detail["address"]
|
||||||
|
usedFam = success.Detail["family"]
|
||||||
|
}
|
||||||
|
usedText := "另一个地址"
|
||||||
|
if used != "" {
|
||||||
|
usedText = used
|
||||||
|
if usedFam != "" {
|
||||||
|
usedText = used + "(" + usedFam + ")"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "候选未成功:" + strings.Join(parts, ";") + "。已改用 " + usedText + "。这些失败没有计入正式丢包或失败率。"
|
||||||
|
}
|
||||||
|
|
||||||
|
type dialFunc func(context.Context, net.IP) (net.Conn, error)
|
||||||
|
|
||||||
|
// dialFirst tries each address with its own timeout. A failure is described
|
||||||
|
// and not returned as a separate measured attempt. If a later address
|
||||||
|
// connects, the skipped notes are returned for the diagnostic. If every
|
||||||
|
// address fails, err is the last error. A cancelled parent context does not
|
||||||
|
// become a measured timeout.
|
||||||
|
func dialFirst(ctx context.Context, ips []net.IP, timeout time.Duration, dial dialFunc) (net.Conn, net.IP, []string, error) {
|
||||||
|
if len(ips) == 0 {
|
||||||
|
return nil, nil, nil, errors.New("no address")
|
||||||
|
}
|
||||||
|
if timeout <= 0 {
|
||||||
|
timeout = 1500 * time.Millisecond
|
||||||
|
}
|
||||||
|
var skipped []string
|
||||||
|
var last error
|
||||||
|
for _, ip := range ips {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, nil, skipped, err
|
||||||
|
}
|
||||||
|
dialCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
conn, err := dial(dialCtx, ip)
|
||||||
|
cancel()
|
||||||
|
if err == nil {
|
||||||
|
return conn, ip, skipped, nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.Canceled) && ctx.Err() != nil {
|
||||||
|
return nil, nil, skipped, ctx.Err()
|
||||||
|
}
|
||||||
|
skipped = append(skipped, fmt.Sprintf("%s %s %s", familyOf(ip), ip.String(), classifyDial(err).Note))
|
||||||
|
last = err
|
||||||
|
}
|
||||||
|
if last == nil {
|
||||||
|
last = errors.New("连接失败")
|
||||||
|
}
|
||||||
|
return nil, nil, skipped, last
|
||||||
|
}
|
||||||
|
|
||||||
|
func dialSpecTCP(ctx context.Context, spec *jobSpec) (net.Conn, error) {
|
||||||
|
ips := spec.candidates()
|
||||||
|
start := 0
|
||||||
|
if spec.state != nil && spec.state.picker != nil {
|
||||||
|
start = spec.state.picker.index
|
||||||
|
}
|
||||||
|
rotated := make([]net.IP, 0, len(ips))
|
||||||
|
for n := 0; n < len(ips); n++ {
|
||||||
|
rotated = append(rotated, ips[(start+n)%len(ips)])
|
||||||
|
}
|
||||||
|
conn, ip, skipped, err := dialFirst(ctx, rotated, spec.Timeout, func(ctx context.Context, ip net.IP) (net.Conn, error) {
|
||||||
|
return dialTCP(ctx, ip, spec.Port)
|
||||||
|
})
|
||||||
|
if spec.state != nil {
|
||||||
|
spec.state.used = nil
|
||||||
|
spec.state.fallback = ""
|
||||||
|
spec.state.skipped = 0
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if spec.state != nil && len(skipped) > 0 && !errors.Is(err, context.Canceled) {
|
||||||
|
spec.state.fallback = "已尝试 " + strings.Join(skipped, ";") + "。没有地址连通,这次记为失败。"
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if spec.state != nil {
|
||||||
|
if spec.state.picker != nil {
|
||||||
|
spec.state.picker.lock(ip)
|
||||||
|
}
|
||||||
|
spec.state.used = append(net.IP(nil), ip...)
|
||||||
|
if len(skipped) > 0 {
|
||||||
|
spec.state.skipped = len(skipped)
|
||||||
|
spec.state.fallback = "候选未连通:" + strings.Join(skipped, ";") + "。已改用 " + ip.String() + "(" + familyOf(ip) + ")。这些失败没有计入正式丢包或失败率。"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureUDP(conn *net.UDPConn, spec jobSpec) (*net.UDPConn, error) {
|
||||||
|
want := spec.dialIP()
|
||||||
|
if want == nil {
|
||||||
|
return nil, errors.New("no address")
|
||||||
|
}
|
||||||
|
if conn != nil {
|
||||||
|
if ra, ok := conn.RemoteAddr().(*net.UDPAddr); ok && ra.IP.Equal(want) {
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
_ = conn.Close()
|
||||||
|
}
|
||||||
|
return dialUDP(want, spec.Port)
|
||||||
|
}
|
||||||
|
|
||||||
|
// nearestRank95 is ceil(0.95*n) in integer arithmetic.
|
||||||
|
func nearestRank95(n int) int {
|
||||||
|
if n <= 1 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
rank := (95*n + 99) / 100
|
||||||
|
if rank < 1 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if rank > n {
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
return rank
|
||||||
|
}
|
||||||
|
|
||||||
|
func latencyOf(samples []float64) (min, mean, median, p95, max float64, ok bool) {
|
||||||
|
if len(samples) == 0 {
|
||||||
|
return 0, 0, 0, 0, 0, false
|
||||||
|
}
|
||||||
|
sorted := append([]float64(nil), samples...)
|
||||||
|
sort.Float64s(sorted)
|
||||||
|
var sum float64
|
||||||
|
for _, v := range sorted {
|
||||||
|
sum += v
|
||||||
|
}
|
||||||
|
n := len(sorted)
|
||||||
|
if n%2 == 1 {
|
||||||
|
median = sorted[n/2]
|
||||||
|
} else {
|
||||||
|
median = (sorted[n/2-1] + sorted[n/2]) / 2
|
||||||
|
}
|
||||||
|
rank := nearestRank95(n)
|
||||||
|
return sorted[0], sum / float64(n), median, sorted[rank-1], sorted[n-1], true
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSelectionLedgerDoesNotCountFallback(t *testing.T) {
|
||||||
|
ledger := &selectionLedger{candidates: 2}
|
||||||
|
miss := Outcome{
|
||||||
|
Status: statusTimeout,
|
||||||
|
Kind: kindProbe,
|
||||||
|
Note: "未收到回显",
|
||||||
|
Detail: map[string]string{"address": "2001:db8::1", "family": "IPv6"},
|
||||||
|
}
|
||||||
|
commit, skipped := ledger.take(miss, false)
|
||||||
|
if commit != nil || skipped != 0 {
|
||||||
|
t.Fatalf("held failure was counted: %+v %d", commit, skipped)
|
||||||
|
}
|
||||||
|
ok := Outcome{
|
||||||
|
Status: statusOK,
|
||||||
|
Kind: kindProbe,
|
||||||
|
HasRtt: true,
|
||||||
|
Rtt: 5 * time.Millisecond,
|
||||||
|
Note: "收到回显",
|
||||||
|
Detail: map[string]string{"address": "203.0.113.5", "family": "IPv4"},
|
||||||
|
}
|
||||||
|
commit, skipped = ledger.take(ok, true)
|
||||||
|
if skipped != 1 || len(commit) != 1 || commit[0].SelectionSkipped != 1 {
|
||||||
|
t.Fatalf("success %+v skipped %d", commit, skipped)
|
||||||
|
}
|
||||||
|
if commit[0].Detail["fallback"] == "" || !containsAll(commit[0].Detail["fallback"], "2001:db8::1", "203.0.113.5", "没有计入") {
|
||||||
|
t.Fatalf("fallback %q", commit[0].Detail["fallback"])
|
||||||
|
}
|
||||||
|
book := &sampleBook{profile: "nq-udp"}
|
||||||
|
book.add(commit[0])
|
||||||
|
summary := book.summary()
|
||||||
|
if summary.Sent != 1 || summary.OK != 1 || summary.Timeout != 0 || summary.ProbeLossPct == nil || *summary.ProbeLossPct != 0 {
|
||||||
|
t.Fatalf("summary %+v", summary)
|
||||||
|
}
|
||||||
|
if summary.SelectionSkipped != 1 || summary.MinRttMs == nil || *summary.MinRttMs != 5 || summary.P95RttMs == nil || *summary.P95RttMs != 5 {
|
||||||
|
t.Fatalf("stats %+v", summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectionLedgerCommitsTotalFailure(t *testing.T) {
|
||||||
|
ledger := &selectionLedger{candidates: 2}
|
||||||
|
first := Outcome{Status: statusTimeout, Kind: kindProbe, Detail: map[string]string{"address": "2001:db8::1", "family": "IPv6"}}
|
||||||
|
second := Outcome{Status: statusTimeout, Kind: kindProbe, Detail: map[string]string{"address": "203.0.113.5", "family": "IPv4"}}
|
||||||
|
if commit, _ := ledger.take(first, false); commit != nil {
|
||||||
|
t.Fatal("first failure committed early")
|
||||||
|
}
|
||||||
|
commit, _ := ledger.take(second, false)
|
||||||
|
if len(commit) != 2 {
|
||||||
|
t.Fatalf("commit %+v", commit)
|
||||||
|
}
|
||||||
|
book := &sampleBook{profile: "nq-udp"}
|
||||||
|
for _, outcome := range commit {
|
||||||
|
book.add(outcome)
|
||||||
|
}
|
||||||
|
summary := book.summary()
|
||||||
|
if summary.OK != 0 || summary.Sent != 2 || summary.ProbeLossPct == nil || *summary.ProbeLossPct != 100 {
|
||||||
|
t.Fatalf("summary %+v", summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMeasuredTimeoutStillCounts(t *testing.T) {
|
||||||
|
ledger := &selectionLedger{candidates: 2}
|
||||||
|
ok := Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: 4 * time.Millisecond}
|
||||||
|
if commit, _ := ledger.take(ok, true); len(commit) != 1 {
|
||||||
|
t.Fatal(commit)
|
||||||
|
}
|
||||||
|
miss := Outcome{Status: statusTimeout, Kind: kindProbe}
|
||||||
|
commit, _ := ledger.take(miss, false)
|
||||||
|
if len(commit) != 1 || commit[0].Status != statusTimeout {
|
||||||
|
t.Fatalf("post-selection miss hidden: %+v", commit)
|
||||||
|
}
|
||||||
|
book := &sampleBook{profile: "nq-udp"}
|
||||||
|
book.add(ok)
|
||||||
|
book.add(commit[0])
|
||||||
|
summary := book.summary()
|
||||||
|
if summary.ProbeLossPct == nil || *summary.ProbeLossPct != 50 || summary.Sent != 2 {
|
||||||
|
t.Fatalf("summary %+v", summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLatencyRanks(t *testing.T) {
|
||||||
|
if nearestRank95(1) != 1 || nearestRank95(2) != 2 || nearestRank95(4) != 4 || nearestRank95(5) != 5 || nearestRank95(20) != 19 {
|
||||||
|
t.Fatalf("ranks %d %d %d %d %d", nearestRank95(1), nearestRank95(2), nearestRank95(4), nearestRank95(5), nearestRank95(20))
|
||||||
|
}
|
||||||
|
min, mean, median, p95, max, ok := latencyOf([]float64{1, 2, 3, 4})
|
||||||
|
if !ok || min != 1 || mean != 2.5 || median != 2.5 || p95 != 4 || max != 4 {
|
||||||
|
t.Fatalf("four %v %v %v %v %v", min, mean, median, p95, max)
|
||||||
|
}
|
||||||
|
_, _, median, p95, _, ok = latencyOf([]float64{1, 2, 3, 4, 10})
|
||||||
|
if !ok || median != 3 || p95 != 10 {
|
||||||
|
t.Fatalf("five median %v p95 %v", median, p95)
|
||||||
|
}
|
||||||
|
_, _, _, _, _, ok = latencyOf(nil)
|
||||||
|
if ok {
|
||||||
|
t.Fatal("empty latency")
|
||||||
|
}
|
||||||
|
book := &sampleBook{profile: "nq-udp"}
|
||||||
|
book.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: time.Millisecond})
|
||||||
|
book.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: 4 * time.Millisecond})
|
||||||
|
summary := book.summary()
|
||||||
|
if summary.MinRttMs == nil || *summary.MinRttMs != 1 || summary.MaxRttMs == nil || *summary.MaxRttMs != 4 || summary.MedianRttMs == nil || *summary.MedianRttMs != 2.5 {
|
||||||
|
t.Fatalf("aliased latency %+v", summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDialFirstSkipsFailedCandidate(t *testing.T) {
|
||||||
|
good, bad := net.Pipe()
|
||||||
|
defer good.Close()
|
||||||
|
defer bad.Close()
|
||||||
|
v6 := net.ParseIP("2001:db8::1")
|
||||||
|
v4 := net.ParseIP("203.0.113.5")
|
||||||
|
calls := 0
|
||||||
|
conn, used, skipped, err := dialFirst(context.Background(), []net.IP{v6, v4}, time.Second, func(ctx context.Context, ip net.IP) (net.Conn, error) {
|
||||||
|
calls++
|
||||||
|
if ip.Equal(v6) {
|
||||||
|
return nil, errors.New("network unreachable")
|
||||||
|
}
|
||||||
|
return good, nil
|
||||||
|
})
|
||||||
|
if err != nil || !used.Equal(v4) || len(skipped) != 1 || calls != 2 {
|
||||||
|
t.Fatalf("used %v skipped %v err %v calls %d", used, skipped, err, calls)
|
||||||
|
}
|
||||||
|
_ = conn.Close()
|
||||||
|
|
||||||
|
_, _, skipped, err = dialFirst(context.Background(), []net.IP{v6, v4}, time.Second, func(context.Context, net.IP) (net.Conn, error) {
|
||||||
|
return nil, context.DeadlineExceeded
|
||||||
|
})
|
||||||
|
if err == nil || len(skipped) != 2 {
|
||||||
|
t.Fatalf("all-fail err %v skipped %v", err, skipped)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
_, _, _, err = dialFirst(ctx, []net.IP{v6, v4}, time.Second, func(context.Context, net.IP) (net.Conn, error) {
|
||||||
|
t.Fatal("dialled after cancel")
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("cancel err %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveTargetsKeepsOrder(t *testing.T) {
|
||||||
|
resolver := stubResolver{[]net.IP{net.ParseIP("2001:db8::1"), net.ParseIP("203.0.113.5")}}
|
||||||
|
ips, err := resolveTargets(context.Background(), resolver, "example.com", false, nil)
|
||||||
|
if err != nil || len(ips) != 2 || ips[0].String() != "2001:db8::1" || ips[1].String() != "203.0.113.5" {
|
||||||
|
t.Fatalf("ips %v err %v", ips, err)
|
||||||
|
}
|
||||||
|
first, err := targetOK(context.Background(), resolver, "example.com", false, nil)
|
||||||
|
if err != nil || first.String() != "2001:db8::1" {
|
||||||
|
t.Fatalf("first %v err %v", first, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStopDoesNotRecordInFlight(t *testing.T) {
|
||||||
|
blackhole, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer blackhole.Close()
|
||||||
|
node := newNode("", true, nil, testLimits())
|
||||||
|
srv := httptest.NewServer(node.Handler())
|
||||||
|
defer srv.Close()
|
||||||
|
id := createJob(t, srv.URL, "", map[string]any{
|
||||||
|
"target": "127.0.0.1", "port": blackhole.LocalAddr().(*net.UDPAddr).Port,
|
||||||
|
"profile": "nq-udp", "intervalMs": 200, "timeoutMs": 4000, "durationSec": 5, "packetSize": 80,
|
||||||
|
})
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
req, err := http.NewRequest(http.MethodDelete, srv.URL+"/v1/jobs/"+id, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
res, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
res.Body.Close()
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
snapReq, err := http.NewRequest(http.MethodGet, srv.URL+"/v1/jobs/"+id, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
snapRes, err := http.DefaultClient.Do(snapReq)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer snapRes.Body.Close()
|
||||||
|
if snapRes.StatusCode == http.StatusNotFound {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, _ := io.ReadAll(snapRes.Body)
|
||||||
|
var msg sampleMsg
|
||||||
|
if err := json.Unmarshal(body, &msg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if msg.Summary.Sent > 0 || msg.Status == statusTimeout || msg.Status == statusUnknown {
|
||||||
|
t.Fatalf("cancelled probe counted %s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeUDPFallbackIsNotLoss(t *testing.T) {
|
||||||
|
drop, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.2")})
|
||||||
|
if err != nil {
|
||||||
|
t.Skipf("127.0.0.2 unavailable: %v", err)
|
||||||
|
}
|
||||||
|
defer drop.Close()
|
||||||
|
go func() {
|
||||||
|
buf := make([]byte, 2048)
|
||||||
|
for {
|
||||||
|
if _, _, err := drop.ReadFromUDP(buf); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
port := drop.LocalAddr().(*net.UDPAddr).Port
|
||||||
|
echo, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port})
|
||||||
|
if err != nil {
|
||||||
|
t.Skipf("paired echo: %v", err)
|
||||||
|
}
|
||||||
|
defer echo.Close()
|
||||||
|
reflector := &Server{}
|
||||||
|
go reflector.ServeUDP(echo)
|
||||||
|
defer reflector.Close()
|
||||||
|
|
||||||
|
node := newNode("", true, nil, testLimits())
|
||||||
|
node.Resolver = stubResolver{[]net.IP{net.ParseIP("127.0.0.2"), net.ParseIP("127.0.0.1")}}
|
||||||
|
srv := httptest.NewServer(node.Handler())
|
||||||
|
defer srv.Close()
|
||||||
|
id := createJob(t, srv.URL, "", map[string]any{
|
||||||
|
"target": "example.test", "port": port, "profile": "nq-udp",
|
||||||
|
"intervalMs": 200, "timeoutMs": 300, "durationSec": 5, "packetSize": 80,
|
||||||
|
})
|
||||||
|
sample := readOneSample(t, srv.URL, "", id)
|
||||||
|
if sample.Status != statusOK || sample.Detail["address"] != "127.0.0.1" || sample.Detail["family"] != "IPv4" {
|
||||||
|
t.Fatalf("sample %+v", sample)
|
||||||
|
}
|
||||||
|
if sample.Summary.Sent != 1 || sample.Summary.Timeout != 0 || sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 || sample.Summary.SelectionSkipped != 1 {
|
||||||
|
t.Fatalf("loss polluted %+v", sample.Summary)
|
||||||
|
}
|
||||||
|
if !strings.Contains(sample.Detail["fallback"], "127.0.0.2") || !strings.Contains(sample.Detail["fallback"], "没有计入") {
|
||||||
|
t.Fatalf("fallback %q", sample.Detail["fallback"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsAll(text string, parts ...string) bool {
|
||||||
|
for _, part := range parts {
|
||||||
|
if !strings.Contains(text, part) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
Reference in new issue
Block a user