Import netquality 1.1.1

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

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

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
.DS_Store
*.exe
server/netquality-reflector
+99 -1
View File
@@ -1 +1,99 @@
# netquality
# 网络质量探测
看一条路径质量的小工具。可以在 Windows、Linux 和 Android 上用。
有两种发包方式:
- **本机**:这台手机或电脑直接向目标发包,自己计算往返时间。
- **远程节点**:手机只负责选择目标和看结果。真正发包的是你自己的一台 Linux 节点,延迟在节点上用单调时钟量好再传回来,不包含手机到节点的控制通道耗时。
目标可以是合作的 NetQuality 反射器,也可以是已经在跑的业务端口。Minecraft Java(TCP 25565)和基岩版(UDP 19132)有专门的握手。端口都能改。
数字和曲线只来自已经完成的探测。没有内置假样本,也不会在还没探完时画出 100%。
## 为什么结果要分开看
合作反射器会把探测包送回来,这时可以算「探测无应答」:发出去了,超时前没有对上序号的回显。TCP 会自己重传,所以这个数字不是网卡上的物理丢包。
普通 TCP 只看能不能连上、连接花了多久、失败了几次。它不使用自定义探测帧。
普通 UDP、DNS、基岩版如果根本没有协议应答,记为「无应答 / 未知」,不能当成已经证实的丢包。收到了包但内容不对,记为协议错误。
域名解析失败、连接被拒绝、超时、节点口令错误、协议不符,界面上会用短句分开说明。
## 仓库里有什么
| 路径 | 内容 |
| --- | --- |
| `server/` | 同一个 Go 程序。可以只做反射器、只做探测节点,或两个一起开 |
| `client/` | Flutter 客户端。Windows、Linux 桌面和 Android |
| `docs/PROTOCOL.md` | 反射帧、控制接口和各探测类型 |
| `docs/server-linux.md` | 安装、systemd、防火墙、公开节点和口令节点、HTTPS |
## 本地演示
需要 Go 1.22+。桌面客户端需要 Flutter(本仓库用 3.47 开发)。Linux 桌面还需要 `clang`、`cmake`、`ninja`、`pkg-config` 和 GTK 3。
终端 1:
```bash
cd server
go build -o netquality-reflector .
./netquality-reflector
```
默认只做反射器:TCP `19090`、UDP `19091`。
终端 2:
```bash
cd client
flutter pub get
flutter run -d linux
```
来源选「本机」,目标保持 `127.0.0.1`,类型选「合作反射 TCP」或「合作反射 UDP」,点「开始探测」。延迟应是零点几毫秒这一量级。点「停止探测」后不再发包。
本机演示只能证明程序在工作。要看真实线路,把反射器装到服务器上,或者让一台节点去测你的业务端口。
## 在 App 里选节点和目标
1. 「探测来源」选「本机」或「远程节点」。
2. 远程时点「管理节点」。名称自定。地址写成 `https://你的域名:8443` 这种控制地址,不要把口令写进地址。公开节点的口令留空;私有节点把节点口令填在这一栏。它和目标回显口令不是同一个。
3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。
4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。
本机的 UDP 探测会记下这次解析出的每个地址。结果上的「发往」是当前实际在用的地址。还没有哪个地址应答时,一个超时就换下一个;已经有应答之后,要连续三次没有应答才换,中途开关 VPN 不会把还在应答的地址丢掉。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。
节点口令保存在本机应用目录里,权限尽量收成只有自己能读,不会写进网址或日志。
## 装到自己的 Linux 服务器
步骤、公开/口令两种例子、防火墙和 HTTPS 在 [docs/server-linux.md](docs/server-linux.md)。不要把真实口令写进仓库或命令历史以外的公开地方。
只做反射,给本机或节点回显用:
```bash
cd server
go build -o netquality-reflector .
./netquality-reflector -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091
```
同一台机器既回显、又替手机探测别的目标:
```bash
./netquality-reflector -mode both -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091 -control-addr 127.0.0.1:8443
```
控制端口默认只听本机。放到公网前,用 HTTPS 反向代理,或加上 `-tls-cert` 和 `-tls-key`。没设置 `-node-token` 时节点是公开的,谁能连上谁就能发起有上限的探测,程序启动时会警告。设置了节点口令以后,所有创建、停止、查看和结果流都会先校验,不对就不会向目标发包。
远程节点默认不探测本机、内网、链路本地和云元数据地址。要在机房里故意测局域网时,才加 `-allow-private`。元数据地址仍然禁止。
## 开发
```bash
cd server && go test -race ./...
cd client && flutter analyze && flutter test
```
Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.1`。
+48
View File
@@ -0,0 +1,48 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins-dependencies
.pub-cache/
.pub/
/build/
/coverage/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
# Widget Preview related
.widget_preview/
+36
View File
@@ -0,0 +1,36 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "c197ca5199e9ee5661e865596c9c07294dfab51c"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
base_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
- platform: android
create_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
base_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
- platform: linux
create_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
base_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
- platform: windows
create_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
base_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
+10
View File
@@ -0,0 +1,10 @@
# 客户端
Flutter 应用,支持 Linux、Windows 桌面和 Android。用法、节点安装和协议说明见仓库根目录的 [README.md](../README.md)。
```bash
flutter pub get
flutter run -d linux
```
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。
+35
View File
@@ -0,0 +1,35 @@
# This file configures the analyzer, which statically analyzes Dart code to
# check for errors, warnings, and lints.
#
# The issues identified by the analyzer are surfaced in the UI of Dart-enabled
# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be
# invoked from the command line by running `flutter analyze`.
# The following line activates a set of recommended lints for Flutter apps,
# packages, and plugins designed to encourage good coding practices.
include: package:flutter_lints/flutter.yaml
analyzer:
exclude:
- build/**
- android/**
- windows/**
- linux/**
linter:
# The lint rules applied to this project can be customized in the
# section below to disable rules from the `package:flutter_lints/flutter.yaml`
# included above or to enable additional rules. A list of all available lints
# and their documentation is published at https://dart.dev/lints.
#
# Instead of disabling a lint rule for the entire project in the
# section below, it can also be suppressed for a single line of code
# or a specific dart file by using the `// ignore: name_of_lint` and
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
+14
View File
@@ -0,0 +1,14 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
.cxx/
# Remember to never publicly share your keystore.
# See https://flutter.dev/to/reference-keystore
key.properties
**/*.keystore
**/*.jks
+49
View File
@@ -0,0 +1,49 @@
plugins {
id("com.android.application")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
android {
namespace = "dev.netquality.netquality"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "dev.netquality.netquality"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
// Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION
// is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions)
// You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true`
// flag during build.
versionCode = flutter.versionCode
versionName = flutter.versionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.getByName("debug")
}
}
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
}
}
flutter {
source = "../.."
}
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
@@ -0,0 +1,46 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:label="网络质量探测"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
</queries>
</manifest>
@@ -0,0 +1,5 @@
package dev.netquality.netquality
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity()
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
Binary file not shown.

After

Width:  |  Height:  |  Size: 544 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
+24
View File
@@ -0,0 +1,24 @@
allprojects {
repositories {
google()
mavenCentral()
}
}
val newBuildDir: Directory =
rootProject.layout.buildDirectory
.dir("../../build")
.get()
rootProject.layout.buildDirectory.value(newBuildDir)
subprojects {
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
project.layout.buildDirectory.value(newSubprojectBuildDir)
}
subprojects {
project.evaluationDependsOn(":app")
}
tasks.register<Delete>("clean") {
delete(rootProject.layout.buildDirectory)
}
+6
View File
@@ -0,0 +1,6 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
# This newDsl flag was added by the Flutter template
android.newDsl=false
# This builtInKotlin flag was added by the Flutter template
android.builtInKotlin=false
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip
+26
View File
@@ -0,0 +1,26 @@
pluginManagement {
val flutterSdkPath =
run {
val properties = java.util.Properties()
file("local.properties").inputStream().use { properties.load(it) }
val flutterSdkPath = properties.getProperty("flutter.sdk")
require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
flutterSdkPath
}
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "9.1.0" apply false
id("org.jetbrains.kotlin.android") version "2.4.0" apply false
}
include(":app")
+7
View File
@@ -0,0 +1,7 @@
WenQuanYi Micro Hei (subset)
Copyright 2008-2009 The WenQuanYi Project Board of Trustees
Copyright 2006-2008 Google Corporation
Copyright 2006-2008 Steve Matteson, Ascender Corp.
This subset is licensed under the Apache License, Version 2.0.
http://www.apache.org/licenses/LICENSE-2.0
Binary file not shown.
+50
View File
@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'ui/home_page.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const NetQualityApp());
}
class NetQualityApp extends StatelessWidget {
const NetQualityApp({super.key});
@override
Widget build(BuildContext context) {
const paper = Color(0xFFF3F1EC);
final scheme = ColorScheme.fromSeed(
seedColor: const Color(0xFF1F4E79),
surface: paper,
);
return MaterialApp(
title: '网络质量探测',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: scheme,
scaffoldBackgroundColor: paper,
useMaterial3: true,
fontFamilyFallback: const [
'NetQualityCJK',
'Noto Sans CJK SC',
'Noto Sans SC',
'PingFang SC',
'Microsoft YaHei',
'Droid Sans Fallback',
],
inputDecorationTheme: const InputDecorationTheme(
filled: true,
fillColor: Color(0xFFFFFCF7),
isDense: true,
border: OutlineInputBorder(),
),
cardTheme: const CardThemeData(
elevation: 0,
color: Color(0xFFFFFCF7),
margin: EdgeInsets.zero,
),
),
home: const HomePage(),
);
}
}
+331
View File
@@ -0,0 +1,331 @@
class Outcome {
const Outcome({
required this.status,
required this.kind,
this.rttMs,
this.note = '',
this.detail = const {},
this.reconnect = false,
});
final String status;
final String kind;
final double? rttMs;
final String note;
final Map<String, String> detail;
final bool reconnect;
static const ok = 'ok';
static const timeout = 'timeout';
static const unknown = 'unknown';
static const refused = 'refused';
static const dns = 'dns';
static const protocol = 'protocol';
static const error = 'error';
static const connect = 'connect';
static const probe = 'probe';
static const query = 'query';
}
class ProbeSummary {
const ProbeSummary({
required this.sent,
required this.completed,
required this.ok,
required this.timeout,
required this.unknown,
required this.refused,
required this.dns,
required this.protocol,
required this.other,
required this.reconnects,
required this.consecutiveFailures,
required this.rttMs,
required this.jitterMs,
required this.probeLossPct,
required this.failurePct,
required this.unknownPct,
required this.lastNote,
required this.detail,
});
final int sent;
final int completed;
final int ok;
final int timeout;
final int unknown;
final int refused;
final int dns;
final int protocol;
final int other;
final int reconnects;
final int consecutiveFailures;
final double? rttMs;
final double? jitterMs;
final double? probeLossPct;
final double? failurePct;
final double? unknownPct;
final String lastNote;
final Map<String, String> detail;
static const empty = ProbeSummary(
sent: 0,
completed: 0,
ok: 0,
timeout: 0,
unknown: 0,
refused: 0,
dns: 0,
protocol: 0,
other: 0,
reconnects: 0,
consecutiveFailures: 0,
rttMs: null,
jitterMs: null,
probeLossPct: null,
failurePct: null,
unknownPct: null,
lastNote: '',
detail: {},
);
factory ProbeSummary.fromJson(Map<String, dynamic> json) {
return ProbeSummary(
sent: _int(json['sent']),
completed: _int(json['completed']),
ok: _int(json['ok']),
timeout: _int(json['timeout']),
unknown: _int(json['unknown']),
refused: _int(json['refused']),
dns: _int(json['dns']),
protocol: _int(json['protocol']),
other: _int(json['other']),
reconnects: _int(json['reconnects']),
consecutiveFailures: _int(json['consecutiveFailures']),
rttMs: _double(json['rttMs']),
jitterMs: _double(json['jitterMs']),
probeLossPct: _double(json['probeLossPct']),
failurePct: _double(json['failurePct']),
unknownPct: _double(json['unknownPct']),
lastNote: json['lastNote'] is String ? json['lastNote'] as String : '',
detail: _detail(json['detail']),
);
}
}
class ProbeSample {
const ProbeSample({
required this.seq,
required this.status,
required this.kind,
required this.rttMs,
required this.jitterMs,
required this.note,
required this.detail,
required this.summary,
});
final int seq;
final String status;
final String kind;
final double? rttMs;
final double? jitterMs;
final String note;
final Map<String, String> detail;
final ProbeSummary summary;
factory ProbeSample.fromJson(Map<String, dynamic> json) {
final summary = json['summary'] is Map
? ProbeSummary.fromJson(Map<String, dynamic>.from(json['summary'] as Map))
: ProbeSummary.empty;
return ProbeSample(
seq: _int(json['seq']),
status: json['status'] is String ? json['status'] as String : '',
kind: json['kind'] is String ? json['kind'] as String : '',
rttMs: _double(json['rttMs']),
jitterMs: _double(json['jitterMs']),
note: json['note'] is String ? json['note'] as String : '',
detail: _detail(json['detail']),
summary: summary,
);
}
}
class SampleBook {
SampleBook(this.profile);
final String profile;
int sent = 0;
int completed = 0;
int ok = 0;
int timeout = 0;
int unknown = 0;
int refused = 0;
int dns = 0;
int protocol = 0;
int other = 0;
int reconnects = 0;
int consecutive = 0;
double? lastRttMs;
double jitterMs = 0;
bool _hasJitter = false;
double _lastTransit = 0;
String lastNote = '';
Map<String, String> detail = {};
void add(Outcome outcome) {
sent += 1;
completed += 1;
if (outcome.reconnect) {
reconnects += 1;
}
if (outcome.note.isNotEmpty) {
lastNote = outcome.note;
}
if (outcome.detail.isNotEmpty) {
detail = {...detail, ...outcome.detail};
}
switch (outcome.status) {
case Outcome.ok:
ok += 1;
consecutive = 0;
final rtt = outcome.rttMs;
if (rtt != null) {
lastRttMs = rtt;
if (_hasJitter) {
final delta = (rtt - _lastTransit).abs();
jitterMs += (delta - jitterMs) / 16;
}
_lastTransit = rtt;
_hasJitter = true;
}
case Outcome.timeout:
if (outcome.kind == Outcome.probe) {
timeout += 1;
} else {
other += 1;
}
consecutive += 1;
case Outcome.unknown:
unknown += 1;
case Outcome.refused:
refused += 1;
consecutive += 1;
case Outcome.dns:
dns += 1;
consecutive += 1;
case Outcome.protocol:
protocol += 1;
consecutive += 1;
default:
other += 1;
consecutive += 1;
}
}
ProbeSummary summary() {
double? probeLoss;
double? failure;
double? unknownPct;
if (completed > 0) {
if (profile == 'nq-tcp' || profile == 'nq-udp') {
final denom = timeout + ok;
if (denom > 0) {
probeLoss = timeout * 100 / denom;
}
} else if (profile == 'tcp-connect' || profile == 'minecraft-java') {
final denom = ok + timeout + refused + dns + protocol + other;
if (denom > 0) {
failure = (denom - ok) * 100 / denom;
}
} else {
final denom = ok + protocol + refused + dns + other;
if (denom > 0) {
failure = (denom - ok) * 100 / denom;
}
final known = unknown + ok + protocol;
if (known > 0) {
unknownPct = unknown * 100 / completed;
}
}
}
return ProbeSummary(
sent: sent,
completed: completed,
ok: ok,
timeout: timeout,
unknown: unknown,
refused: refused,
dns: dns,
protocol: protocol,
other: other,
reconnects: reconnects,
consecutiveFailures: consecutive,
rttMs: lastRttMs,
jitterMs: _hasJitter ? jitterMs : null,
probeLossPct: probeLoss,
failurePct: failure,
unknownPct: unknownPct,
lastNote: lastNote,
detail: detail,
);
}
ProbeSample sample(int seq, Outcome outcome) {
final folded = summary();
return ProbeSample(
seq: seq,
status: outcome.status,
kind: outcome.kind,
rttMs: outcome.rttMs,
jitterMs: outcome.status == Outcome.ok ? folded.jitterMs : null,
note: outcome.note,
detail: outcome.detail,
summary: folded,
);
}
}
double? chartRate(String profile, ProbeSummary summary) {
switch (profile) {
case 'nq-tcp':
case 'nq-udp':
return summary.probeLossPct;
case 'tcp-connect':
case 'minecraft-java':
return summary.failurePct;
default:
return summary.unknownPct;
}
}
int _int(Object? value) {
if (value is int) {
return value;
}
if (value is num) {
return value.toInt();
}
return 0;
}
double? _double(Object? value) {
if (value is num) {
return value.toDouble();
}
return null;
}
Map<String, String> _detail(Object? value) {
if (value is! Map) {
return const {};
}
final out = <String, String>{};
value.forEach((key, item) {
if (key is String && item is String) {
out[key] = item;
}
});
return out;
}
+103
View File
@@ -0,0 +1,103 @@
class ProbeProfile {
const ProbeProfile({
required this.id,
required this.label,
required this.port,
required this.blurb,
required this.rateLabel,
});
final String id;
final String label;
final int port;
final String blurb;
/// Name of the chart that is honest for this profile.
final String rateLabel;
static const nqTcp = ProbeProfile(
id: 'nq-tcp',
label: '合作反射 TCP',
port: 19090,
blurb: '和 NetQuality 反射器保持一条 TCP 长连接,按回显计算往返时间。超时只表示探测没有应答,不是物理丢包。',
rateLabel: '探测无应答',
);
static const nqUdp = ProbeProfile(
id: 'nq-udp',
label: '合作反射 UDP',
port: 19091,
blurb: '向 NetQuality 反射器发 UDP,收到对应序号的回显才算成功。',
rateLabel: '探测无应答',
);
static const tcpConnect = ProbeProfile(
id: 'tcp-connect',
label: '普通 TCP 连通',
port: 80,
blurb: '只测量能否连上以及连接耗时,不发送自定义探测帧。',
rateLabel: '失败率',
);
static const udpGeneric = ProbeProfile(
id: 'udp-generic',
label: '普通 UDP',
port: 9,
blurb: '发出 UDP 后如果没有协议应答,记为无应答/未知,不能当成丢包。',
rateLabel: '无应答(未知)',
);
static const dns = ProbeProfile(
id: 'dns',
label: 'DNS',
port: 53,
blurb: '发送标准 DNS 查询,序号和应答标志都对上才算成功。',
rateLabel: '无应答(未知)',
);
static const minecraftJava = ProbeProfile(
id: 'minecraft-java',
label: 'Minecraft Java',
port: 25565,
blurb: '按 Java 版状态握手读取 MOTD,再用 ping/pong 计算往返时间。',
rateLabel: '失败率',
);
static const minecraftBedrock = ProbeProfile(
id: 'minecraft-bedrock',
label: 'Minecraft 基岩版',
port: 19132,
blurb: '发送 RakNet Unconnected Ping,校验 magic 和原时间戳。',
rateLabel: '无应答(未知)',
);
static const customUdp = ProbeProfile(
id: 'custom-udp',
label: '自定义 UDP',
port: 19132,
blurb: '发送你填写的十六进制载荷。可以要求响应以前若干字节开头。',
rateLabel: '无应答(未知)',
);
static const all = <ProbeProfile>[
nqTcp,
nqUdp,
tcpConnect,
udpGeneric,
dns,
minecraftJava,
minecraftBedrock,
customUdp,
];
static ProbeProfile byId(String id) {
for (final profile in all) {
if (profile.id == id) {
return profile;
}
}
return nqTcp;
}
bool get needsPacketSize =>
id == 'nq-tcp' || id == 'nq-udp' || id == 'udp-generic';
bool get needsEchoToken => id == 'nq-tcp' || id == 'nq-udp';
bool get isNq => needsEchoToken;
}
String rateLabelFor(String profileId) => ProbeProfile.byId(profileId).rateLabel;
+291
View File
@@ -0,0 +1,291 @@
import 'dart:convert';
import '../protocol/probe_packet.dart';
import 'probe_profile.dart';
class RemoteNode {
const RemoteNode({
required this.id,
required this.name,
required this.baseUrl,
this.visibility = '',
});
final String id;
final String name;
final String baseUrl;
final String visibility;
RemoteNode copyWith({String? name, String? baseUrl, String? visibility}) {
return RemoteNode(
id: id,
name: name ?? this.name,
baseUrl: baseUrl ?? this.baseUrl,
visibility: visibility ?? this.visibility,
);
}
Map<String, Object?> toJson() => {
'id': id,
'name': name,
'baseUrl': baseUrl,
'visibility': visibility,
};
factory RemoteNode.fromJson(Map<String, dynamic> json) {
return RemoteNode(
id: json['id'] is String ? json['id'] as String : '',
name: json['name'] is String ? json['name'] as String : '未命名节点',
baseUrl: json['baseUrl'] is String ? json['baseUrl'] as String : '',
visibility: json['visibility'] is String ? json['visibility'] as String : '',
);
}
}
class SessionConfig {
const SessionConfig({
required this.remote,
required this.nodeId,
required this.nodes,
required this.host,
required this.port,
required this.profileId,
required this.intervalMs,
required this.timeoutMs,
required this.durationSec,
required this.packetSize,
required this.dnsName,
required this.payloadHex,
required this.expectHex,
});
static const defaults = SessionConfig(
remote: false,
nodeId: '',
nodes: [],
host: '127.0.0.1',
port: 19090,
profileId: 'nq-tcp',
intervalMs: 300,
timeoutMs: 1000,
durationSec: 60,
packetSize: 128,
dnsName: 'example.com',
payloadHex: '',
expectHex: '',
);
final bool remote;
final String nodeId;
final List<RemoteNode> nodes;
final String host;
final int port;
final String profileId;
final int intervalMs;
final int timeoutMs;
final int durationSec;
final int packetSize;
final String dnsName;
final String payloadHex;
final String expectHex;
ProbeProfile get profile => ProbeProfile.byId(profileId);
RemoteNode? get node {
for (final item in nodes) {
if (item.id == nodeId) {
return item;
}
}
return null;
}
String? validate() {
if (host.trim().isEmpty) {
return '请填写目标地址';
}
if (port < 1 || port > 65535) {
return '端口需要在 1 到 65535 之间';
}
final minInterval = remote ? 200 : 100;
if (intervalMs < minInterval || intervalMs > 30000) {
return remote
? '远程节点的发送间隔需要在 200 到 30000 毫秒之间'
: '发送间隔需要在 100 到 30000 毫秒之间';
}
if (timeoutMs < 100 || timeoutMs > 15000) {
return '超时需要在 100 到 15000 毫秒之间';
}
if (remote && (durationSec < 1 || durationSec > 300)) {
return '远程探测时长需要在 1 到 300 秒之间,节点还会再加自己的上限';
}
if (profile.needsPacketSize &&
(packetSize < ProbePacket.headerSize || packetSize > 1400)) {
if (profileId == 'udp-generic' && (packetSize < 1 || packetSize > 1400)) {
return '报文大小需要在 1 到 1400 字节之间';
}
if (profileId != 'udp-generic') {
return '报文大小需要在 ${ProbePacket.headerSize} 到 1400 字节之间';
}
}
if (profileId == 'dns' && dnsName.trim().isEmpty) {
return '请填写要查询的域名';
}
if (profileId == 'custom-udp') {
final payload = _hexError(payloadHex, allowEmpty: false);
if (payload != null) {
return '自定义载荷$payload';
}
final expect = _hexError(expectHex, allowEmpty: true);
if (expect != null) {
return '预期响应$expect';
}
}
if (remote) {
final selected = node;
if (selected == null) {
return '请先添加并选择一个远程节点';
}
if (normalizeNodeUrl(selected.baseUrl) == null) {
return '节点地址需要是 http 或 https,且不能把口令写在地址里';
}
}
return null;
}
Map<String, Object?> toJson() => {
'remote': remote,
'nodeId': nodeId,
'nodes': nodes.map((node) => node.toJson()).toList(),
'host': host,
'port': port,
'profileId': profileId,
'intervalMs': intervalMs,
'timeoutMs': timeoutMs,
'durationSec': durationSec,
'packetSize': packetSize,
'dnsName': dnsName,
'payloadHex': payloadHex,
'expectHex': expectHex,
};
factory SessionConfig.fromJson(Map<String, dynamic> json) {
final rawNodes = json['nodes'];
final nodes = <RemoteNode>[];
if (rawNodes is List) {
for (final item in rawNodes) {
if (item is Map) {
nodes.add(RemoteNode.fromJson(Map<String, dynamic>.from(item)));
}
}
}
return SessionConfig(
remote: json['remote'] == true,
nodeId: json['nodeId'] is String ? json['nodeId'] as String : '',
nodes: nodes,
host: json['host'] is String ? json['host'] as String : defaults.host,
port: _asInt(json['port'], defaults.port),
profileId: json['profileId'] is String
? json['profileId'] as String
: defaults.profileId,
intervalMs: _asInt(json['intervalMs'], defaults.intervalMs),
timeoutMs: _asInt(json['timeoutMs'], defaults.timeoutMs),
durationSec: _asInt(json['durationSec'], defaults.durationSec),
packetSize: _asInt(json['packetSize'], defaults.packetSize),
dnsName: json['dnsName'] is String
? json['dnsName'] as String
: defaults.dnsName,
payloadHex: json['payloadHex'] is String ? json['payloadHex'] as String : '',
expectHex: json['expectHex'] is String ? json['expectHex'] as String : '',
);
}
static int _asInt(Object? value, int fallback) {
if (value is int) {
return value;
}
if (value is num) {
return value.toInt();
}
if (value is String) {
return int.tryParse(value) ?? fallback;
}
return fallback;
}
}
String? _hexError(String raw, {required bool allowEmpty}) {
final text = raw.replaceAll(RegExp(r'\s'), '');
if (text.isEmpty) {
return allowEmpty ? null : '需要是十六进制';
}
if (text.length.isOdd || !RegExp(r'^[0-9a-fA-F]+$').hasMatch(text)) {
return '需要是偶数位的十六进制';
}
if (text.length > 2800) {
return '太长了';
}
return null;
}
/// Accepts an operator control URL and refuses credentials embedded in it.
String? normalizeNodeUrl(String input) {
final trimmed = input.trim();
final uri = Uri.tryParse(trimmed);
if (uri == null || !uri.hasScheme || uri.host.isEmpty) {
return null;
}
if (uri.scheme != 'http' && uri.scheme != 'https') {
return null;
}
if (uri.userInfo.isNotEmpty) {
return null;
}
final port = uri.hasPort ? ':${uri.port}' : '';
final path = uri.path.isEmpty || uri.path == '/' ? '' : uri.path;
return '${uri.scheme}://${uri.host}$port$path';
}
bool nodeUrlLooksPublic(String url) {
final uri = Uri.tryParse(url);
if (uri == null) {
return false;
}
final host = uri.host.toLowerCase();
return host != 'localhost' &&
host != '127.0.0.1' &&
host != '::1' &&
uri.scheme == 'http';
}
/// Legacy v1 settings stored the echo token beside the host. Migrate the
/// non-secret fields and return the token so the caller can move it out.
({SessionConfig config, String echoToken}) migrateV1(String raw) {
final json = jsonDecode(raw);
if (json is! Map) {
return (config: SessionConfig.defaults, echoToken: '');
}
final map = Map<String, dynamic>.from(json);
final token = map['token'] is String ? map['token'] as String : '';
final tcp = SessionConfig._asInt(map['tcpPort'], 19090);
final udp = SessionConfig._asInt(map['udpPort'], 19091);
final enableTcp = map['enableTcp'] != false;
return (
config: SessionConfig(
remote: false,
nodeId: '',
nodes: const [],
host: map['host'] is String ? map['host'] as String : '127.0.0.1',
port: enableTcp ? tcp : udp,
profileId: enableTcp ? 'nq-tcp' : 'nq-udp',
intervalMs: SessionConfig._asInt(map['intervalMs'], 300),
timeoutMs: SessionConfig._asInt(map['timeoutMs'], 1000),
durationSec: 60,
packetSize: SessionConfig._asInt(map['packetSize'], 128),
dnsName: 'example.com',
payloadHex: '',
expectHex: '',
),
echoToken: token,
);
}
+76
View File
@@ -0,0 +1,76 @@
import 'dart:io';
/// How many misses a working address may have before another address is tried.
const stickyMissThreshold = 3;
const clashFakeIpNote = '这是 VPN 的假地址,只有这个 VPN 开着时才能用';
/// Clash and similar VPNs hand out addresses in 198.18.0.0/15.
bool isClashFakeIp(InternetAddress address) {
final raw = address.rawAddress;
if (raw.length != 4) {
return false;
}
return raw[0] == 198 && (raw[1] == 18 || raw[1] == 19);
}
/// Picks which resolved address to send to.
///
/// Before any address has answered, one miss is enough to try the next.
/// After an address has answered, it is kept until [stickyMissThreshold]
/// misses in a row. The list is the one resolved at the start of the run;
/// nothing here looks the name up again.
class EndpointPicker {
EndpointPicker(this.candidates, {this.stickyMisses = stickyMissThreshold}) {
if (candidates.isEmpty) {
throw ArgumentError.value(candidates, 'candidates', 'empty');
}
}
final List<InternetAddress> candidates;
final int stickyMisses;
var _index = 0;
var _misses = 0;
var _locked = false;
InternetAddress get current => candidates[_index];
bool get hasAnswered => _locked;
/// Records one finished attempt. Returns true when [current] changed.
bool record(bool gotResponse) {
if (gotResponse) {
_locked = true;
_misses = 0;
return false;
}
_misses += 1;
final limit = _locked ? stickyMisses : 1;
if (candidates.length < 2 || _misses < limit) {
return false;
}
_misses = 0;
_locked = false;
_index = (_index + 1) % candidates.length;
return true;
}
}
Future<List<InternetAddress>> lookupAll(String host) async {
final parsed = InternetAddress.tryParse(host.trim());
if (parsed != null) {
return [parsed];
}
final found = await InternetAddress.lookup(host.trim());
if (found.isEmpty) {
throw const SocketException('Failed host lookup');
}
final seen = <String>{};
final unique = <InternetAddress>[];
for (final address in found) {
if (seen.add('${address.type.name} ${address.address}')) {
unique.add(address);
}
}
return unique;
}
+243
View File
@@ -0,0 +1,243 @@
import 'dart:convert';
import 'dart:typed_data';
const rakMagic = <int>[
0x00,
0xff,
0xff,
0x00,
0xfe,
0xfe,
0xfe,
0xfe,
0xfd,
0xfd,
0xfd,
0xfd,
0x12,
0x34,
0x56,
0x78,
];
Uint8List encodeVarInt(int value) {
final out = <int>[];
var u = value;
while (true) {
if ((u & ~0x7f) == 0) {
out.add(u);
return Uint8List.fromList(out);
}
out.add((u & 0x7f) | 0x80);
u >>= 7;
}
}
int? decodeVarInt(Uint8List bytes, int offset, void Function(int next) onNext) {
var n = 0;
for (var i = 0; i < 5; i++) {
if (offset + i >= bytes.length) {
return null;
}
final by = bytes[offset + i];
n |= (by & 0x7f) << (7 * i);
if ((by & 0x80) == 0) {
onNext(offset + i + 1);
return n;
}
}
throw const FormatException('varint');
}
Uint8List mcString(String value) {
final raw = utf8.encode(value);
final out = BytesBuilder(copy: false);
out.add(encodeVarInt(raw.length));
out.add(raw);
return out.toBytes();
}
Uint8List mcPacket(List<int> payload) {
final out = BytesBuilder(copy: false);
out.add(encodeVarInt(payload.length));
out.add(payload);
return out.toBytes();
}
/// Handshake for status state. Protocol 767 is Minecraft 1.21.x.
Uint8List javaHandshake(String host, int port) {
final payload = BytesBuilder(copy: false);
payload.addByte(0x00);
payload.add(encodeVarInt(767));
payload.add(mcString(host));
final data = ByteData(2)..setUint16(0, port);
payload.add(data.buffer.asUint8List());
payload.add(encodeVarInt(1));
return mcPacket(payload.toBytes());
}
Uint8List javaStatusRequest() => mcPacket(const [0x00]);
Uint8List javaPing(int nonce) {
final data = ByteData(9);
data.setUint8(0, 0x01);
data.setUint64(1, nonce);
return mcPacket(data.buffer.asUint8List());
}
/// Returns the payload of one length-prefixed packet, and how many bytes it used.
({Uint8List payload, int used})? takeMcPacket(Uint8List bytes) {
var offset = 0;
final length = decodeVarInt(bytes, 0, (next) => offset = next);
if (length == null || length < 1 || length > 1 << 20) {
return null;
}
if (bytes.length < offset + length) {
return null;
}
return (
payload: Uint8List.sublistView(bytes, offset, offset + length),
used: offset + length,
);
}
Map<String, String> minecraftStatusDetail(String raw) {
final decoded = jsonDecode(raw);
if (decoded is! Map) {
return const {};
}
final out = <String, String>{};
final version = decoded['version'];
if (version is Map && version['name'] is String) {
out['version'] = version['name'] as String;
}
final players = decoded['players'];
if (players is Map) {
final online = players['online'];
final max = players['max'];
if (online is num && max is num) {
out['players'] = '${online.toInt()}/${max.toInt()}';
}
}
final description = decoded['description'];
final text = motdText(description);
if (text.isNotEmpty) {
out['motd'] = text;
}
return out;
}
String motdText(Object? value) {
if (value is String) {
return value;
}
if (value is Map) {
final buf = StringBuffer();
if (value['text'] is String) {
buf.write(value['text']);
}
final extra = value['extra'];
if (extra is List) {
for (final item in extra) {
buf.write(motdText(item));
}
}
return buf.toString();
}
return '';
}
String? readMcString(Uint8List payload, int offset) {
var next = offset;
final length = decodeVarInt(payload, offset, (value) => next = value);
if (length == null || length < 0 || next + length > payload.length) {
return null;
}
return utf8.decode(payload.sublist(next, next + length), allowMalformed: true);
}
Uint8List bedrockPing(int timestamp, int guid) {
final data = ByteData(1 + 8 + 16 + 8);
data.setUint8(0, 0x01);
data.setUint64(1, timestamp);
final bytes = data.buffer.asUint8List();
bytes.setRange(9, 25, rakMagic);
data.setUint64(25, guid);
return bytes;
}
Map<String, String>? parseRakPong(Uint8List packet, int timestamp) {
if (packet.length < 35 || packet[0] != 0x1c) {
return null;
}
final data = ByteData.sublistView(packet);
if (data.getUint64(1) != timestamp) {
return null;
}
for (var i = 0; i < rakMagic.length; i++) {
if (packet[17 + i] != rakMagic[i]) {
return null;
}
}
final strlen = data.getUint16(33);
if (35 + strlen > packet.length) {
return null;
}
final text = utf8.decode(packet.sublist(35, 35 + strlen), allowMalformed: true);
final parts = text.split(';');
final detail = <String, String>{};
if (parts.length > 1) {
detail['motd'] = parts[1];
}
if (parts.length > 3) {
detail['version'] = parts[3];
}
if (parts.length > 5) {
detail['players'] = '${parts[4]}/${parts[5]}';
}
return detail;
}
Uint8List dnsQuery(int id, String name) {
final body = BytesBuilder(copy: false);
for (final label in name.split('.')) {
if (label.isEmpty) {
continue;
}
final raw = utf8.encode(label);
if (raw.length > 63) {
throw const FormatException('label');
}
body.addByte(raw.length);
body.add(raw);
}
body.add(const [0, 0, 1, 0, 1]);
final question = body.toBytes();
final msg = Uint8List(12 + question.length);
final data = ByteData.sublistView(msg);
data.setUint16(0, id);
data.setUint16(2, 0x0100);
data.setUint16(4, 1);
msg.setRange(12, msg.length, question);
return msg;
}
bool dnsResponseMatches(Uint8List packet, int id) {
if (packet.length < 12) {
return false;
}
final data = ByteData.sublistView(packet);
return data.getUint16(0) == id && (packet[2] & 0x80) != 0;
}
Uint8List decodeHex(String raw) {
final text = raw.replaceAll(RegExp(r'\s'), '');
if (text.isEmpty || text.length.isOdd) {
throw const FormatException('hex');
}
final out = Uint8List(text.length ~/ 2);
for (var i = 0; i < out.length; i++) {
out[i] = int.parse(text.substring(i * 2, i * 2 + 2), radix: 16);
}
return out;
}
+288
View File
@@ -0,0 +1,288 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../metrics/sample_book.dart';
import '../models/probe_profile.dart';
import '../models/session_config.dart';
import 'endpoint_picker.dart';
import 'probe_loop.dart';
import 'remote_client.dart';
class ChartSample {
const ChartSample({required this.sec, required this.rttMs, required this.ratePct});
final double sec;
final double? rttMs;
final double? ratePct;
}
class ProbeView {
const ProbeView({
required this.running,
required this.phase,
required this.banner,
required this.note,
required this.detail,
required this.summary,
required this.samples,
required this.rateLabel,
required this.sourceLabel,
this.targetAddress,
this.targetIsFake = false,
});
static const initial = ProbeView(
running: false,
phase: '未开始',
banner: null,
note: '',
detail: {},
summary: ProbeSummary.empty,
samples: [],
rateLabel: '探测无应答',
sourceLabel: '本机',
);
final bool running;
final String phase;
final String? banner;
final String note;
final Map<String, String> detail;
final ProbeSummary summary;
final List<ChartSample> samples;
final String rateLabel;
final String sourceLabel;
final String? targetAddress;
final bool targetIsFake;
ProbeView copyWith({
bool? running,
String? phase,
String? banner,
bool clearBanner = false,
String? note,
Map<String, String>? detail,
ProbeSummary? summary,
List<ChartSample>? samples,
String? rateLabel,
String? sourceLabel,
String? targetAddress,
bool? targetIsFake,
}) {
return ProbeView(
running: running ?? this.running,
phase: phase ?? this.phase,
banner: clearBanner ? null : banner ?? this.banner,
note: note ?? this.note,
detail: detail ?? this.detail,
summary: summary ?? this.summary,
samples: samples ?? this.samples,
rateLabel: rateLabel ?? this.rateLabel,
sourceLabel: sourceLabel ?? this.sourceLabel,
targetAddress: targetAddress ?? this.targetAddress,
targetIsFake: targetIsFake ?? this.targetIsFake,
);
}
}
class ProbeController extends ChangeNotifier {
ProbeView view = ProbeView.initial;
final Stopwatch _clock = Stopwatch();
ProbeLoop? _local;
RemoteProbe? _remote;
String _nodeToken = '';
var _token = 0;
Future<void> start(SessionConfig config, {required String nodeToken, required String echoToken}) async {
final problem = config.validate();
if (problem != null) {
view = view.copyWith(banner: problem, phase: '无法开始');
notifyListeners();
return;
}
final echoProblem = _echoProblem(config.profileId, echoToken);
if (echoProblem != null) {
view = view.copyWith(banner: echoProblem, phase: '无法开始');
notifyListeners();
return;
}
await stop();
_nodeToken = nodeToken;
final generation = ++_token;
_clock
..reset()
..start();
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
view = ProbeView(
running: true,
phase: '探测中',
banner: null,
note: config.remote ? '正在让节点向目标发包' : '正在从本机向目标发包',
detail: const {},
summary: ProbeSummary.empty,
samples: const [],
rateLabel: rateLabelFor(config.profileId),
sourceLabel: source,
);
notifyListeners();
bool cancelled() => generation != _token;
try {
if (config.remote) {
final remote = RemoteProbe();
_remote = remote;
await remote.run(
baseUrl: config.node!.baseUrl,
nodeToken: nodeToken,
body: ProbeBody(
target: config.host.trim(),
port: config.port,
profile: config.profileId,
intervalMs: config.intervalMs,
timeoutMs: config.timeoutMs,
durationSec: config.durationSec,
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
);
} else {
final loop = ProbeLoop(
onEndpoint: (address) {
if (generation != _token) {
return;
}
view = view.copyWith(
targetAddress: address.address,
targetIsFake: isClashFakeIp(address),
);
notifyListeners();
},
);
_local = loop;
await loop.run(
request: ProbeRequest(
host: config.host.trim(),
port: config.port,
profileId: config.profileId,
interval: Duration(milliseconds: config.intervalMs),
timeout: Duration(milliseconds: config.timeoutMs),
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
);
}
if (generation == _token) {
view = view.copyWith(running: false, phase: '已停止');
notifyListeners();
}
} on RemoteException catch (error) {
if (generation == _token) {
view = view.copyWith(running: false, phase: '出错', banner: error.message);
notifyListeners();
}
} on Object {
if (generation == _token) {
view = view.copyWith(running: false, phase: '出错', banner: '探测中断');
notifyListeners();
}
} finally {
if (generation == _token) {
_local = null;
_remote = null;
}
}
}
Future<void> stop() async {
_token += 1;
final local = _local;
final remote = _remote;
_local = null;
_remote = null;
if (local != null) {
await local.close();
}
if (remote != null) {
await remote.stop(_nodeToken);
_nodeToken = '';
}
if (view.running) {
view = view.copyWith(running: false, phase: '已停止');
notifyListeners();
}
}
void _accept(int generation, ProbeSample sample) {
if (generation != _token) {
return;
}
final samples = [...view.samples];
if (samples.length >= 180) {
samples.removeAt(0);
}
final double? rate;
switch (view.rateLabel) {
case '探测无应答':
rate = sample.summary.probeLossPct;
case '失败率':
rate = sample.summary.failurePct;
default:
rate = sample.summary.unknownPct;
}
samples.add(
ChartSample(
sec: _clock.elapsedMilliseconds / 1000,
rttMs: sample.status == Outcome.ok ? sample.rttMs : null,
ratePct: rate,
),
);
view = view.copyWith(
phase: phaseFor(sample.status),
note: sample.note,
detail: sample.detail.isEmpty ? sample.summary.detail : sample.detail,
summary: sample.summary,
samples: samples,
clearBanner: true,
);
notifyListeners();
}
}
String? _echoProblem(String profileId, String echoToken) {
if (profileId != 'nq-tcp' && profileId != 'nq-udp') {
return null;
}
if (echoToken.length > 32) {
return '目标回显口令最长 32 字节';
}
return null;
}
String phaseFor(String status) {
switch (status) {
case Outcome.ok:
return '有应答';
case Outcome.timeout:
return '超时';
case Outcome.unknown:
return '无应答';
case Outcome.refused:
return '被拒绝';
case Outcome.dns:
return '域名失败';
case Outcome.protocol:
return '协议不符';
default:
return '出错';
}
}
+841
View File
@@ -0,0 +1,841 @@
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import '../metrics/sample_book.dart';
import '../protocol/probe_packet.dart';
import 'endpoint_picker.dart';
import 'game_codec.dart';
class ProbeRequest {
const ProbeRequest({
required this.host,
required this.port,
required this.profileId,
required this.interval,
required this.timeout,
required this.packetSize,
required this.echoToken,
required this.dnsName,
required this.payloadHex,
required this.expectHex,
});
final String host;
final int port;
final String profileId;
final Duration interval;
final Duration timeout;
final int packetSize;
final String echoToken;
final String dnsName;
final String payloadHex;
final String expectHex;
}
/// Sends one probe at a time from this device. A cancelled attempt is not
/// recorded, so stopping cannot paint a fake loss sample.
class ProbeLoop {
ProbeLoop({
this.lookup,
this.onEndpoint,
});
/// Replaces [lookupAll] in tests.
final Future<List<InternetAddress>> Function(String host)? lookup;
/// Fires when the address about to be used is chosen or changed.
final void Function(InternetAddress address)? onEndpoint;
_TcpPipe? _tcp;
_UdpPipe? _udp;
EndpointPicker? _picker;
InternetAddress? _announced;
int _seq = 0;
int _dnsId = 1;
final int _guid = DateTime.now().microsecondsSinceEpoch;
Future<void> run({
required ProbeRequest request,
required void Function(ProbeSample sample) onSample,
required bool Function() cancelled,
}) async {
final book = SampleBook(request.profileId);
try {
while (!cancelled()) {
final started = DateTime.now();
final outcome = await _once(request, cancelled);
if (cancelled() || outcome == null) {
break;
}
if (_usesDatagram(request.profileId)) {
final responded = outcome.status == Outcome.ok ||
outcome.status == Outcome.protocol ||
outcome.status == Outcome.refused;
if (_picker != null && _picker!.record(responded)) {
await _dropUdp();
_announce(_picker!.current);
}
}
book.add(outcome);
onSample(book.sample(book.sent, outcome));
final spent = DateTime.now().difference(started);
final rest = request.interval - spent;
if (!cancelled() && rest > Duration.zero) {
await Future<void>.delayed(rest);
}
}
} finally {
await close();
}
}
Future<void> close() async {
final tcp = _tcp;
_tcp = null;
if (tcp != null) {
await tcp.close();
}
final udp = _udp;
_udp = null;
if (udp != null) {
await udp.close();
}
}
Future<Outcome?> _once(ProbeRequest request, bool Function() cancelled) async {
try {
final outcome = await _dispatch(request, cancelled);
final peer = _udp?.peer;
if (peer != null && _usesDatagram(request.profileId)) {
return _stampAddress(outcome, peer);
}
return outcome;
} on SocketException catch (error) {
if (cancelled()) {
return null;
}
return classifySocket(error);
} on TimeoutException {
if (cancelled()) {
return null;
}
return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '连接超时',
);
}
}
Future<Outcome> _dispatch(ProbeRequest request, bool Function() cancelled) {
switch (request.profileId) {
case 'nq-tcp':
return _nqTcp(request, cancelled);
case 'nq-udp':
return _nqUdp(request, cancelled);
case 'tcp-connect':
return _tcpConnect(request, cancelled);
case 'udp-generic':
case 'custom-udp':
return _udpQuery(request, cancelled);
case 'dns':
return _dns(request, cancelled);
case 'minecraft-java':
return _java(request, cancelled);
case 'minecraft-bedrock':
return _bedrock(request, cancelled);
default:
return Future.value(
const Outcome(
status: Outcome.error,
kind: Outcome.query,
note: '不支持的探测类型',
),
);
}
}
Future<Outcome> _tcpConnect(
ProbeRequest request,
bool Function() cancelled,
) async {
final watch = Stopwatch()..start();
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
watch.stop();
await socket.close();
if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
}
return Outcome(
status: Outcome.ok,
kind: Outcome.connect,
rttMs: watch.elapsedMicroseconds / 1000,
note: 'TCP 已连通',
);
}
Future<Outcome> _nqTcp(ProbeRequest request, bool Function() cancelled) async {
if (_tcp == null) {
try {
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
socket.setOption(SocketOption.tcpNoDelay, true);
_tcp = _TcpPipe(socket);
} on SocketException catch (error) {
return classifySocket(error, reconnect: true);
} on TimeoutException {
return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
reconnect: true,
note: '连接超时,将重试',
);
}
}
final pipe = _tcp!;
_seq += 1;
final seq = _seq;
final packet = ProbePacket(
type: ProbePacket.typeRequest,
sequence: seq,
clientSendUnixNano: DateTime.now().microsecondsSinceEpoch * 1000,
token: ProbePacket.encodeToken(request.echoToken),
payload: Uint8List(request.packetSize - ProbePacket.headerSize),
);
pipe.socket.add(packet.encode());
try {
await pipe.socket.flush();
} on SocketException {
await _dropTcp();
return const Outcome(
status: Outcome.error,
kind: Outcome.connect,
reconnect: true,
note: '发送失败,连接将重连',
);
}
final watch = Stopwatch()..start();
final matched = await pipe.waitMatch(request.timeout, (frame) {
try {
final reply = ProbePacket.decode(frame);
return reply.isReply && reply.sequence == seq;
} on ProbePacketException {
return false;
}
});
if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
}
if (matched == null) {
await _dropTcp();
return const Outcome(
status: Outcome.timeout,
kind: Outcome.probe,
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.probe,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到回显',
);
}
Future<void> _dropTcp() async {
final tcp = _tcp;
_tcp = null;
if (tcp != null) {
await tcp.close();
}
}
Future<Outcome> _nqUdp(ProbeRequest request, bool Function() cancelled) async {
final pipe = await _datagram(request);
_seq += 1;
final seq = _seq;
final packet = ProbePacket(
type: ProbePacket.typeRequest,
sequence: seq,
clientSendUnixNano: DateTime.now().microsecondsSinceEpoch * 1000,
token: ProbePacket.encodeToken(request.echoToken),
payload: Uint8List(request.packetSize - ProbePacket.headerSize),
);
final watch = Stopwatch()..start();
pipe.send(packet.encode(), request.port);
var sawInvalid = false;
final reply = await pipe.waitMatch(request.timeout, (data) {
try {
final parsed = ProbePacket.decode(data);
if (!parsed.isReply) {
sawInvalid = true;
return false;
}
return parsed.sequence == seq;
} on ProbePacketException {
sawInvalid = true;
return false;
}
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
if (sawInvalid) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.probe,
note: '收到的 UDP 包不是有效回显',
);
}
return const Outcome(
status: Outcome.timeout,
kind: Outcome.probe,
note: '未收到回显。这是探测没有应答,不是网卡上的物理丢包计数',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.probe,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到回显',
);
}
Future<Outcome> _udpQuery(
ProbeRequest request,
bool Function() cancelled,
) async {
final pipe = await _datagram(request);
late final Uint8List payload;
Uint8List? expect;
if (request.profileId == 'udp-generic') {
payload = Uint8List(request.packetSize.clamp(1, 1400));
} else {
payload = decodeHex(request.payloadHex);
if (request.expectHex.trim().isNotEmpty) {
expect = decodeHex(request.expectHex);
}
}
final watch = Stopwatch()..start();
pipe.send(payload, request.port);
final reply = await pipe.waitMatch(request.timeout, (_) => true);
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '没有收到 UDP 应答,不能据此断定物理丢包',
);
}
final wanted = expect;
if (wanted != null && (reply.length < wanted.length || !_prefix(reply, wanted))) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '收到了数据,但和预期的响应不一致',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 UDP 响应',
);
}
Future<Outcome> _dns(ProbeRequest request, bool Function() cancelled) async {
final pipe = await _datagram(request);
_dnsId = _dnsId == 65535 ? 1 : _dnsId + 1;
final id = _dnsId;
final name = request.dnsName.trim().isEmpty ? 'example.com' : request.dnsName.trim();
final watch = Stopwatch()..start();
pipe.send(dnsQuery(id, name), request.port);
var malformed = false;
final reply = await pipe.waitMatch(request.timeout, (data) {
if (data.length < 12) {
malformed = true;
return false;
}
final got = ByteData.sublistView(data).getUint16(0);
if (got != id) {
return false;
}
if ((data[2] & 0x80) == 0) {
malformed = true;
return false;
}
return true;
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
if (malformed) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '收到的包不是 DNS 应答',
);
}
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '没有收到 DNS 应答,不能据此断定物理丢包',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 DNS 应答',
);
}
Future<Outcome> _bedrock(
ProbeRequest request,
bool Function() cancelled,
) async {
final pipe = await _datagram(request);
final timestamp = DateTime.now().microsecondsSinceEpoch;
final watch = Stopwatch()..start();
pipe.send(bedrockPing(timestamp, _guid), request.port);
Map<String, String>? detail;
var sawInvalid = false;
final reply = await pipe.waitMatch(request.timeout, (data) {
final parsed = parseRakPong(data, timestamp);
if (parsed == null) {
sawInvalid = true;
return false;
}
detail = parsed;
return true;
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
if (sawInvalid) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '收到的包不是有效的 RakNet Pong',
);
}
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '未收到 RakNet 应答,不能据此断定物理丢包',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 Bedrock 应答',
detail: detail ?? const {},
);
}
Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async {
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
final reader = _BytePipe(socket);
try {
socket.add(javaHandshake(request.host, request.port));
socket.add(javaStatusRequest());
await socket.flush();
final status = await reader.nextPacket(request.timeout);
if (status == null || status.isEmpty || status[0] != 0x00) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft 状态响应无效',
);
}
final jsonText = readMcString(status, 1);
if (jsonText == null) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft 状态内容无法解析',
);
}
final detail = minecraftStatusDetail(jsonText);
final nonce = DateTime.now().microsecondsSinceEpoch;
final watch = Stopwatch()..start();
socket.add(javaPing(nonce));
await socket.flush();
final pong = await reader.nextPacket(request.timeout);
if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
}
if (pong == null || pong.length != 9 || pong[0] != 0x01) {
return Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '没有收到有效的 Minecraft pong',
detail: detail,
);
}
if (ByteData.sublistView(pong).getUint64(1) != nonce) {
return Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft pong 的时间戳不匹配',
detail: detail,
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 Minecraft 状态和 ping 应答',
detail: detail,
);
} finally {
await reader.close();
await socket.close();
}
}
Future<_UdpPipe> _datagram(ProbeRequest request) async {
_picker ??= EndpointPicker(await (lookup ?? lookupAll)(request.host));
final want = _picker!.current;
final existing = _udp;
if (existing != null && existing.peer.address == want.address) {
return existing;
}
if (existing != null) {
await existing.close();
_udp = null;
}
final socket = await RawDatagramSocket.bind(
want.type == InternetAddressType.IPv6
? InternetAddress.anyIPv6
: InternetAddress.anyIPv4,
0,
);
final pipe = _UdpPipe(socket, want);
_udp = pipe;
_announce(want);
return pipe;
}
void _announce(InternetAddress address) {
if (_announced != null && _announced!.address == address.address) {
return;
}
_announced = address;
onEndpoint?.call(address);
}
Future<void> _dropUdp() async {
final udp = _udp;
_udp = null;
if (udp != null) {
await udp.close();
}
}
}
bool _usesDatagram(String profileId) {
switch (profileId) {
case 'nq-udp':
case 'udp-generic':
case 'custom-udp':
case 'dns':
case 'minecraft-bedrock':
return true;
default:
return false;
}
}
Outcome _stampAddress(Outcome outcome, InternetAddress peer) {
return Outcome(
status: outcome.status,
kind: outcome.kind,
rttMs: outcome.rttMs,
note: outcome.note,
reconnect: outcome.reconnect,
detail: {...outcome.detail, 'address': peer.address},
);
}
Outcome classifySocket(SocketException error, {bool reconnect = false}) {
final text = '${error.message} ${error.osError?.message ?? ''}'.toLowerCase();
final code = error.osError?.errorCode;
if (text.contains('timed out') || text.contains('timeout')) {
return Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
reconnect: reconnect,
note: reconnect ? '连接超时,将重试' : '连接超时',
);
}
if (text.contains('failed host lookup') ||
text.contains('name or service not known') ||
text.contains('nodename nor servname') ||
text.contains('no address associated')) {
return const Outcome(
status: Outcome.dns,
kind: Outcome.connect,
note: '域名无法解析',
);
}
if (code == 111 ||
code == 61 ||
code == 10061 ||
text.contains('connection refused') ||
text.contains('actively refused')) {
return Outcome(
status: Outcome.refused,
kind: Outcome.connect,
reconnect: reconnect,
note: '连接被拒绝',
);
}
return Outcome(
status: Outcome.error,
kind: Outcome.connect,
reconnect: reconnect,
note: '连接失败',
);
}
bool _prefix(Uint8List data, Uint8List prefix) {
for (var i = 0; i < prefix.length; i++) {
if (data[i] != prefix[i]) {
return false;
}
}
return true;
}
class _TcpPipe {
_TcpPipe(this.socket) {
_sub = socket.listen(
(data) {
try {
_frames.addAll(_buffer.add(data));
} on ProbePacketException {
_failed = true;
}
_signal();
},
onError: (Object _) {
_failed = true;
_signal();
},
onDone: () {
_failed = true;
_signal();
},
cancelOnError: true,
);
}
final Socket socket;
final FrameBuffer _buffer = FrameBuffer();
final List<Uint8List> _frames = [];
late final StreamSubscription<Uint8List> _sub;
Completer<void>? _pending;
bool _failed = false;
var _cursor = 0;
void _signal() {
final pending = _pending;
_pending = null;
if (pending != null && !pending.isCompleted) {
pending.complete();
}
}
Future<Uint8List?> waitMatch(
Duration timeout,
bool Function(Uint8List frame) match,
) async {
final deadline = DateTime.now().add(timeout);
while (true) {
while (_cursor < _frames.length) {
final frame = _frames[_cursor];
_cursor += 1;
if (match(frame)) {
return frame;
}
}
if (_failed) {
return null;
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (_cursor < _frames.length || _failed) {
_signal();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
if (identical(_pending, waiter)) {
_pending = null;
}
return null;
}
}
}
Future<void> close() async {
await _sub.cancel();
await socket.close();
_signal();
}
}
class _UdpPipe {
_UdpPipe(this.socket, this.peer) {
_sub = socket.listen((event) {
if (event != RawSocketEvent.read) {
return;
}
while (true) {
final datagram = socket.receive();
if (datagram == null) {
return;
}
_queue.add(Uint8List.fromList(datagram.data));
_signal();
}
});
}
final RawDatagramSocket socket;
final InternetAddress peer;
final List<Uint8List> _queue = [];
late final StreamSubscription<RawSocketEvent> _sub;
Completer<void>? _pending;
var _cursor = 0;
void send(List<int> bytes, int port) {
socket.send(bytes, peer, port);
}
void _signal() {
final pending = _pending;
_pending = null;
if (pending != null && !pending.isCompleted) {
pending.complete();
}
}
Future<Uint8List?> waitMatch(
Duration timeout,
bool Function(Uint8List data) match,
) async {
final deadline = DateTime.now().add(timeout);
while (true) {
while (_cursor < _queue.length) {
final data = _queue[_cursor];
_cursor += 1;
if (match(data)) {
return data;
}
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (_cursor < _queue.length) {
_signal();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
if (identical(_pending, waiter)) {
_pending = null;
}
return null;
}
}
}
Future<void> close() async {
await _sub.cancel();
socket.close();
_signal();
}
}
class _BytePipe {
_BytePipe(this.socket) {
_sub = socket.listen((data) {
_buf.add(data);
_signal();
});
}
final Socket socket;
final BytesBuilder _buf = BytesBuilder(copy: false);
late final StreamSubscription<Uint8List> _sub;
Completer<void>? _pending;
void _signal() {
final pending = _pending;
_pending = null;
if (pending != null && !pending.isCompleted) {
pending.complete();
}
}
Future<Uint8List?> nextPacket(Duration timeout) async {
final deadline = DateTime.now().add(timeout);
while (true) {
final bytes = _buf.toBytes();
final packet = takeMcPacket(bytes);
if (packet != null) {
_buf.clear();
if (packet.used < bytes.length) {
_buf.add(Uint8List.sublistView(bytes, packet.used));
}
return packet.payload;
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (takeMcPacket(_buf.toBytes()) != null) {
_signal();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
if (identical(_pending, waiter)) {
_pending = null;
}
return null;
}
}
}
Future<void> close() => _sub.cancel();
}
+281
View File
@@ -0,0 +1,281 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import '../metrics/sample_book.dart';
import '../models/session_config.dart';
class RemoteProbe {
HttpClient? _client;
String? _jobId;
Uri? _base;
Future<void> run({
required String baseUrl,
required String nodeToken,
required ProbeBody body,
required void Function(ProbeSample sample) onSample,
required bool Function() cancelled,
}) async {
final normalized = normalizeNodeUrl(baseUrl);
if (normalized == null) {
throw RemoteException('节点地址需要是 http 或 https,且不能把口令写在地址里');
}
_base = Uri.parse(normalized);
final client = HttpClient();
_client = client;
try {
final created = await _send(
client,
'POST',
_base!.resolve('/v1/jobs'),
nodeToken,
utf8.encode(jsonEncode(body.toJson())),
);
if (created.status >= 300 && created.status < 400) {
throw RemoteException('节点地址发生了跳转。请填写最终地址,不要在地址里带口令');
}
if (created.status == 401) {
throw RemoteException('节点口令不正确或未提供');
}
if (created.status == 429) {
throw RemoteException('节点同时探测的任务已达上限');
}
if (created.status == 403 || created.status == 400) {
throw RemoteException(_message(created.body) ?? '节点拒绝了这次探测');
}
if (created.status != 201) {
throw RemoteException('节点没有接受探测(${created.status})');
}
final parsed = jsonDecode(created.body);
if (parsed is! Map || parsed['jobId'] is! String) {
throw RemoteException('节点返回的任务无效');
}
_jobId = parsed['jobId'] as String;
if (cancelled()) {
return;
}
await _stream(client, nodeToken, onSample, cancelled);
} on RemoteException {
rethrow;
} on SocketException {
if (!cancelled()) {
throw RemoteException('连不上节点。请检查地址、端口和防火墙');
}
} on HandshakeException {
throw RemoteException('TLS 握手失败。请检查证书,或改用正确的 HTTPS 地址');
} on RedirectException {
throw RemoteException('节点地址发生了跳转。请填写最终地址,不要在地址里带口令');
} on HttpException {
if (!cancelled()) {
throw RemoteException('节点连接中断');
}
} on TimeoutException {
if (!cancelled()) {
throw RemoteException('节点没有及时响应');
}
} finally {
await stop(nodeToken);
}
}
Future<void> stop(String nodeToken) async {
final client = _client;
final id = _jobId;
final base = _base;
_jobId = null;
if (client != null && id != null && base != null) {
try {
await _send(client, 'DELETE', base.resolve('/v1/jobs/$id'), nodeToken, const []);
} on Object {
// The stream ending already asks the node to drop the job.
}
}
client?.close(force: true);
_client = null;
}
Future<void> _stream(
HttpClient client,
String nodeToken,
void Function(ProbeSample sample) onSample,
bool Function() cancelled,
) async {
final request = await client.getUrl(_base!.resolve('/v1/jobs/$_jobId/stream'));
request.followRedirects = false;
_auth(request, nodeToken);
final response = await request.close().timeout(const Duration(seconds: 20));
if (response.statusCode == 401) {
throw RemoteException('节点口令不正确或未提供');
}
if (response.statusCode != 200) {
throw RemoteException('无法接收节点上的探测结果');
}
var buffer = '';
await for (final chunk in response.transform(utf8.decoder)) {
if (cancelled()) {
return;
}
buffer += chunk;
while (buffer.contains('\n\n')) {
final split = buffer.indexOf('\n\n');
final block = buffer.substring(0, split);
buffer = buffer.substring(split + 2);
final sample = _sampleFromBlock(block);
if (sample != null) {
onSample(sample);
}
}
}
}
}
class ProbeBody {
const ProbeBody({
required this.target,
required this.port,
required this.profile,
required this.intervalMs,
required this.timeoutMs,
required this.durationSec,
required this.packetSize,
required this.echoToken,
required this.dnsName,
required this.payloadHex,
required this.expectHex,
});
final String target;
final int port;
final String profile;
final int intervalMs;
final int timeoutMs;
final int durationSec;
final int packetSize;
final String echoToken;
final String dnsName;
final String payloadHex;
final String expectHex;
Map<String, Object?> toJson() => {
'target': target,
'port': port,
'profile': profile,
'intervalMs': intervalMs,
'timeoutMs': timeoutMs,
'durationSec': durationSec,
'packetSize': packetSize,
'echoToken': echoToken,
'dnsName': dnsName,
'payloadHex': payloadHex,
'expectHex': expectHex,
};
}
class RemoteException implements Exception {
RemoteException(this.message);
final String message;
@override
String toString() => message;
}
class NodeInfo {
const NodeInfo({required this.visibility, required this.authRequired});
final String visibility;
final bool authRequired;
}
Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
final normalized = normalizeNodeUrl(baseUrl);
if (normalized == null) {
throw RemoteException('节点地址需要是 http 或 https,且不能把口令写在地址里');
}
final client = HttpClient();
try {
final request = await client.getUrl(Uri.parse(normalized).resolve('/v1/info'));
request.followRedirects = false;
final response = await request.close().timeout(const Duration(seconds: 8));
final body = await response.transform(utf8.decoder).join();
if (response.statusCode != 200) {
throw RemoteException('读不到节点信息');
}
final json = jsonDecode(body);
if (json is! Map) {
throw RemoteException('节点信息无效');
}
return NodeInfo(
visibility: json['visibility'] is String ? json['visibility'] as String : '',
authRequired: json['authRequired'] == true,
);
} on RemoteException {
rethrow;
} on SocketException {
throw RemoteException('连不上节点');
} on HandshakeException {
throw RemoteException('TLS 握手失败');
} finally {
client.close(force: true);
}
}
Future<({int status, String body})> _send(
HttpClient client,
String method,
Uri uri,
String nodeToken,
List<int> bytes,
) async {
final request = await client.openUrl(method, uri);
request.followRedirects = false;
request.headers.contentType = ContentType.json;
_auth(request, nodeToken);
request.add(bytes);
final response = await request.close().timeout(const Duration(seconds: 15));
final body = await response.transform(utf8.decoder).join();
return (status: response.statusCode, body: body);
}
void _auth(HttpClientRequest request, String nodeToken) {
if (nodeToken.isNotEmpty) {
request.headers.set(HttpHeaders.authorizationHeader, 'Bearer $nodeToken');
}
}
String? _message(String body) {
try {
final json = jsonDecode(body);
if (json is Map && json['message'] is String) {
return json['message'] as String;
}
} on FormatException {
return null;
}
return null;
}
ProbeSample? _sampleFromBlock(String block) {
String? data;
for (final line in block.split('\n')) {
if (line.startsWith('data: ')) {
data = line.substring(6);
}
}
if (data == null || data == '{}') {
return null;
}
try {
final json = jsonDecode(data);
if (json is! Map) {
return null;
}
final sample = ProbeSample.fromJson(Map<String, dynamic>.from(json));
if (sample.status.isEmpty || sample.status == 'pending') {
return null;
}
return sample;
} on FormatException {
return null;
}
}
+165
View File
@@ -0,0 +1,165 @@
import 'dart:convert';
import 'dart:typed_data';
/// Wire format shared by TCP frames and UDP datagrams.
///
/// See docs/PROTOCOL.md. Header is 62 bytes, little-endian.
/// A TCP stream is a sequence of these frames. A UDP datagram is exactly one.
class ProbePacket {
ProbePacket({
required this.type,
required this.sequence,
required this.clientSendUnixNano,
this.serverUnixNano = 0,
Uint8List? token,
Uint8List? payload,
this.version = version1,
}) : token = token ?? Uint8List(tokenLength),
payload = payload ?? Uint8List(0);
static const version1 = 1;
static const headerSize = 62;
static const tokenLength = 32;
static const tokenOffset = 28;
static const maxPayload = 2048;
static const typeRequest = 1;
static const typeReply = 2;
static const magic0 = 0x4e; // N
static const magic1 = 0x51; // Q
static const magic2 = 0x30; // 0
static const magic3 = 0x31; // 1
final int version;
final int type;
final int sequence;
final int clientSendUnixNano;
final int serverUnixNano;
final Uint8List token;
final Uint8List payload;
bool get isReply => type == typeReply;
Uint8List encode() {
if (token.length != tokenLength) {
throw ProbePacketException('token must be $tokenLength bytes');
}
if (payload.length > maxPayload) {
throw ProbePacketException('payload too large');
}
final out = Uint8List(headerSize + payload.length);
final data = ByteData.sublistView(out);
out[0] = magic0;
out[1] = magic1;
out[2] = magic2;
out[3] = magic3;
data.setUint8(4, version);
data.setUint8(5, type);
data.setUint8(6, 0);
data.setUint8(7, 0);
data.setUint32(8, sequence, Endian.little);
data.setUint64(12, clientSendUnixNano, Endian.little);
data.setUint64(20, serverUnixNano, Endian.little);
out.setRange(tokenOffset, tokenOffset + tokenLength, token);
data.setUint16(60, payload.length, Endian.little);
out.setRange(headerSize, out.length, payload);
return out;
}
static ProbePacket decode(Uint8List bytes) {
if (bytes.length < headerSize) {
throw ProbePacketException('packet shorter than header');
}
if (bytes[0] != magic0 ||
bytes[1] != magic1 ||
bytes[2] != magic2 ||
bytes[3] != magic3) {
throw ProbePacketException('bad magic');
}
final data = ByteData.sublistView(bytes);
final version = data.getUint8(4);
if (version != version1) {
throw ProbePacketException('unsupported version $version');
}
final type = data.getUint8(5);
if (type != typeRequest && type != typeReply) {
throw ProbePacketException('unsupported type $type');
}
final payloadLen = data.getUint16(60, Endian.little);
if (payloadLen > maxPayload) {
throw ProbePacketException('payload too large');
}
final total = headerSize + payloadLen;
if (bytes.length != total) {
throw ProbePacketException(
'length mismatch: have ${bytes.length}, want $total',
);
}
return ProbePacket(
version: version,
type: type,
sequence: data.getUint32(8, Endian.little),
clientSendUnixNano: data.getUint64(12, Endian.little),
serverUnixNano: data.getUint64(20, Endian.little),
token: Uint8List.sublistView(bytes, tokenOffset, tokenOffset + tokenLength),
payload: payloadLen == 0
? Uint8List(0)
: Uint8List.sublistView(bytes, headerSize, total),
);
}
/// UTF-8 token padded with zeros. Empty string is 32 zero bytes.
static Uint8List encodeToken(String token) {
final raw = utf8.encode(token);
if (raw.length > tokenLength) {
throw ProbePacketException('口令最长 $tokenLength 字节');
}
final out = Uint8List(tokenLength);
out.setRange(0, raw.length, raw);
return out;
}
}
class ProbePacketException implements Exception {
ProbePacketException(this.message);
final String message;
@override
String toString() => message;
}
/// Reassembles TCP frames. UDP datagrams are already one frame and do not
/// need this buffer.
class FrameBuffer {
final BytesBuilder _buf = BytesBuilder(copy: false);
List<Uint8List> add(List<int> chunk) {
_buf.add(chunk);
final bytes = _buf.toBytes();
var offset = 0;
final frames = <Uint8List>[];
while (bytes.length - offset >= ProbePacket.headerSize) {
final view = ByteData.sublistView(bytes, offset);
final payloadLen = view.getUint16(60, Endian.little);
if (payloadLen > ProbePacket.maxPayload) {
_buf.clear();
throw ProbePacketException('payload too large');
}
final total = ProbePacket.headerSize + payloadLen;
if (bytes.length - offset < total) {
break;
}
frames.add(Uint8List.sublistView(bytes, offset, offset + total));
offset += total;
}
_buf.clear();
if (offset < bytes.length) {
_buf.add(Uint8List.sublistView(bytes, offset));
}
return frames;
}
void clear() {
_buf.clear();
}
}
+59
View File
@@ -0,0 +1,59 @@
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/session_config.dart';
import 'token_vault.dart';
class AppStore {
static const _key = 'netquality.settings.v2';
static const _legacy = 'netquality.settings.v1';
Future<({SessionConfig config, String legacyEcho})> load() async {
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString(_key);
if (raw != null && raw.isNotEmpty) {
try {
final decoded = jsonDecode(raw);
if (decoded is Map) {
return (
config: SessionConfig.fromJson(Map<String, dynamic>.from(decoded)),
legacyEcho: '',
);
}
} on FormatException {
return (config: SessionConfig.defaults, legacyEcho: '');
}
}
final legacy = prefs.getString(_legacy);
if (legacy != null && legacy.isNotEmpty) {
try {
final migrated = migrateV1(legacy);
await save(migrated.config);
await prefs.remove(_legacy);
return (config: migrated.config, legacyEcho: migrated.echoToken);
} on FormatException {
return (config: SessionConfig.defaults, legacyEcho: '');
}
}
return (config: SessionConfig.defaults, legacyEcho: '');
}
Future<void> save(SessionConfig config) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_key, jsonEncode(config.toJson()));
}
}
Future<TokenVault> openTokenVault() async {
try {
final dir = await getApplicationSupportDirectory();
final vault = FileTokenVault(File('${dir.path}/node-tokens.json'));
await vault.load();
return vault;
} on Object {
return MemoryTokenVault();
}
}
+103
View File
@@ -0,0 +1,103 @@
import 'dart:convert';
import 'dart:io';
/// Stores node-control tokens and the target echo token outside preferences.
///
/// The file lives in the app's private support directory. On Unix it is
/// created with mode 0600. Tokens are never written into URLs or logs.
abstract class TokenVault {
Future<String?> read(String key);
Future<void> write(String key, String value);
Future<void> delete(String key);
}
class MemoryTokenVault implements TokenVault {
final Map<String, String> _values = {};
@override
Future<void> delete(String key) async {
_values.remove(key);
}
@override
Future<String?> read(String key) async => _values[key];
@override
Future<void> write(String key, String value) async {
if (value.isEmpty) {
_values.remove(key);
return;
}
_values[key] = value;
}
}
class FileTokenVault implements TokenVault {
FileTokenVault(this.file);
final File file;
final Map<String, String> _values = {};
bool _loaded = false;
Future<void> load() async {
if (_loaded) {
return;
}
_loaded = true;
if (!await file.exists()) {
return;
}
try {
final decoded = jsonDecode(await file.readAsString());
if (decoded is Map) {
decoded.forEach((key, value) {
if (key is String && value is String && value.isNotEmpty) {
_values[key] = value;
}
});
}
} on FormatException {
_values.clear();
}
}
@override
Future<void> delete(String key) async {
await load();
_values.remove(key);
await _flush();
}
@override
Future<String?> read(String key) async {
await load();
return _values[key];
}
@override
Future<void> write(String key, String value) async {
await load();
if (value.isEmpty) {
_values.remove(key);
} else {
_values[key] = value;
}
await _flush();
}
Future<void> _flush() async {
await file.parent.create(recursive: true);
await file.writeAsString(jsonEncode(_values), flush: true);
if (!Platform.isWindows) {
try {
await Process.run('chmod', ['600', file.path]);
} on ProcessException {
// The app directory is already private on Android.
}
}
}
}
const echoTokenKey = 'target-echo-token';
String nodeTokenKey(String nodeId) => 'node-token.$nodeId';
+76
View File
@@ -0,0 +1,76 @@
import '../metrics/sample_book.dart';
String formatMs(double? ms) {
if (ms == null) {
return '—';
}
if (ms < 1) {
return '${ms.toStringAsFixed(3)} ms';
}
if (ms < 10) {
return '${ms.toStringAsFixed(2)} ms';
}
if (ms < 100) {
return '${ms.toStringAsFixed(1)} ms';
}
return '${ms.toStringAsFixed(0)} ms';
}
String formatPct(double? pct) {
if (pct == null) {
return '—';
}
if (pct == 0) {
return '0%';
}
if (pct < 10) {
return '${pct.toStringAsFixed(1)}%';
}
return '${pct.toStringAsFixed(0)}%';
}
String visibilityLabel(String visibility) {
switch (visibility) {
case 'public':
return '公开';
case 'private':
return '需要口令';
default:
return '未检查';
}
}
String summaryLine(ProbeSummary summary) {
if (summary.completed == 0) {
return '还没有完成的探测';
}
final parts = <String>[
'完成 ${summary.completed}',
'成功 ${summary.ok}',
];
if (summary.timeout > 0) {
parts.add('超时 ${summary.timeout}');
}
if (summary.unknown > 0) {
parts.add('无应答 ${summary.unknown}');
}
if (summary.refused > 0) {
parts.add('拒绝 ${summary.refused}');
}
if (summary.dns > 0) {
parts.add('域名 ${summary.dns}');
}
if (summary.protocol > 0) {
parts.add('协议 ${summary.protocol}');
}
if (summary.other > 0) {
parts.add('其他失败 ${summary.other}');
}
if (summary.reconnects > 0) {
parts.add('重连 ${summary.reconnects}');
}
if (summary.consecutiveFailures > 0) {
parts.add('连续失败 ${summary.consecutiveFailures}');
}
return parts.join(' · ');
}
+631
View File
@@ -0,0 +1,631 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../models/probe_profile.dart';
import '../models/session_config.dart';
import '../probe/endpoint_picker.dart';
import '../probe/probe_controller.dart';
import '../probe/remote_client.dart';
import '../storage/app_store.dart';
import '../storage/token_vault.dart';
import 'format.dart';
import 'quality_charts.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _controller = ProbeController();
final _store = AppStore();
TokenVault _vault = MemoryTokenVault();
final _host = TextEditingController(text: SessionConfig.defaults.host);
final _port = TextEditingController(text: '${SessionConfig.defaults.port}');
final _interval = TextEditingController(text: '300');
final _timeout = TextEditingController(text: '1000');
final _duration = TextEditingController(text: '60');
final _size = TextEditingController(text: '128');
final _echo = TextEditingController();
final _dns = TextEditingController(text: 'example.com');
final _payload = TextEditingController();
final _expect = TextEditingController();
var _remote = false;
var _profileId = ProbeProfile.nqTcp.id;
var _nodeId = '';
var _nodes = <RemoteNode>[];
var _ready = false;
@override
void initState() {
super.initState();
_controller.addListener(_rebuild);
_load();
}
Future<void> _load() async {
_vault = await openTokenVault();
final loaded = await _store.load();
final echo = await _vault.read(echoTokenKey);
if (!mounted) {
return;
}
final config = loaded.config;
setState(() {
_remote = config.remote;
_nodeId = config.nodeId;
_nodes = config.nodes;
_profileId = config.profileId;
_host.text = config.host;
_port.text = '${config.port}';
_interval.text = '${config.intervalMs}';
_timeout.text = '${config.timeoutMs}';
_duration.text = '${config.durationSec}';
_size.text = '${config.packetSize}';
_dns.text = config.dnsName;
_payload.text = config.payloadHex;
_expect.text = config.expectHex;
_echo.text = (echo == null || echo.isEmpty) ? loaded.legacyEcho : echo;
_ready = true;
});
if (loaded.legacyEcho.isNotEmpty && (echo == null || echo.isEmpty)) {
await _vault.write(echoTokenKey, loaded.legacyEcho);
}
}
void _rebuild() {
if (mounted) {
setState(() {});
}
}
@override
void dispose() {
unawaited(_controller.stop());
unawaited(_persist());
_controller.removeListener(_rebuild);
_controller.dispose();
for (final field in [
_host,
_port,
_interval,
_timeout,
_duration,
_size,
_echo,
_dns,
_payload,
_expect,
]) {
field.dispose();
}
super.dispose();
}
SessionConfig _config() {
return SessionConfig(
remote: _remote,
nodeId: _nodeId,
nodes: _nodes,
host: _host.text.trim(),
port: int.tryParse(_port.text.trim()) ?? 0,
profileId: _profileId,
intervalMs: int.tryParse(_interval.text.trim()) ?? 0,
timeoutMs: int.tryParse(_timeout.text.trim()) ?? 0,
durationSec: int.tryParse(_duration.text.trim()) ?? 0,
packetSize: int.tryParse(_size.text.trim()) ?? 0,
dnsName: _dns.text.trim(),
payloadHex: _payload.text.trim(),
expectHex: _expect.text.trim(),
);
}
Future<void> _persist() async {
await _store.save(_config());
await _vault.write(echoTokenKey, _echo.text);
}
Future<void> _start() async {
await _persist();
final config = _config();
final nodeToken = config.node == null
? ''
: (await _vault.read(nodeTokenKey(config.node!.id)) ?? '');
await _controller.start(config, nodeToken: nodeToken, echoToken: _echo.text);
}
void _changeProfile(String? id) {
if (id == null) {
return;
}
final previous = ProbeProfile.byId(_profileId);
final next = ProbeProfile.byId(id);
setState(() {
if (_port.text.trim() == '${previous.port}') {
_port.text = '${next.port}';
}
_profileId = id;
});
}
@override
Widget build(BuildContext context) {
final view = _controller.view;
final profile = ProbeProfile.byId(_profileId);
final wide = MediaQuery.sizeOf(context).width >= 720;
return Scaffold(
appBar: AppBar(
title: const Text('网络质量探测'),
backgroundColor: const Color(0xFFF3F1EC),
),
body: SafeArea(
child: Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 880),
child: ListView(
padding: EdgeInsets.fromLTRB(wide ? 24 : 12, 8, wide ? 24 : 12, 28),
children: [
_card(
title: '探测来源',
child: _source(view, wide),
),
_card(
title: '目标',
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_pair(
wide,
_field(_host, '目标地址', '域名或 IP'),
_field(_port, '端口', '1–65535'),
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
key: const Key('profile'),
initialValue: _profileId,
decoration: const InputDecoration(labelText: '探测类型'),
items: [
for (final item in ProbeProfile.all)
DropdownMenuItem(value: item.id, child: Text(item.label)),
],
onChanged: view.running ? null : _changeProfile,
),
const SizedBox(height: 8),
Text(profile.blurb, style: const TextStyle(color: muted, fontSize: 13)),
],
),
),
_card(
title: '参数',
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_pair(
wide,
_field(_interval, '间隔(毫秒)', _remote ? '至少 200' : '至少 100'),
_field(_timeout, '超时(毫秒)', '100–15000'),
),
if (profile.needsPacketSize) ...[
const SizedBox(height: 12),
_field(_size, '报文大小(字节)', '最大 1400'),
],
if (_remote) ...[
const SizedBox(height: 12),
_field(_duration, '时长(秒)', '到点后节点会停止'),
],
if (profile.needsEchoToken) ...[
const SizedBox(height: 12),
_field(
_echo,
'目标回显口令',
'可选,只放进探测包,和节点口令不是同一个',
secret: true,
),
],
if (profile.id == 'dns') ...[
const SizedBox(height: 12),
_field(_dns, '查询域名', '例如 example.com'),
],
if (profile.id == 'custom-udp') ...[
const SizedBox(height: 12),
_field(_payload, '载荷(十六进制)', '例如 0102'),
const SizedBox(height: 12),
_field(_expect, '响应需以此开头(十六进制,可空)', '不填则任意响应都算成功'),
],
],
),
),
FilledButton(
onPressed: !_ready
? null
: view.running
? _controller.stop
: _start,
child: Text(view.running ? '停止探测' : '开始探测'),
),
if (view.banner != null) ...[
const SizedBox(height: 12),
_banner(view.banner!),
],
const SizedBox(height: 12),
_card(title: '结果', child: _result(view)),
QualityCharts(
samples: view.samples,
rateLabel: view.rateLabel,
running: view.running,
),
const Text(
'延迟用发包一侧的单调时钟计算。远程探测时,这个时间在节点上量好再传回来,不包含手机到节点的控制通道耗时。TCP 超时不是物理丢包。没有协议应答的 UDP 记为无应答/未知,不会在探测完成前显示 100%。',
style: TextStyle(color: muted, fontSize: 12, height: 1.4),
),
],
),
),
),
),
);
}
Widget _source(ProbeView view, bool wide) {
final selected = _nodes.cast<RemoteNode?>().followedBy(const [null]).firstWhere(
(node) => node?.id == _nodeId,
orElse: () => null,
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SegmentedButton<bool>(
segments: const [
ButtonSegment(value: false, label: Text('本机'), icon: Icon(Icons.phone_android)),
ButtonSegment(value: true, label: Text('远程节点'), icon: Icon(Icons.dns_outlined)),
],
selected: {_remote},
onSelectionChanged: view.running
? null
: (value) => setState(() => _remote = value.first),
),
const SizedBox(height: 8),
Text(
_remote
? '由选中的节点向目标发包,这台设备只负责控制和显示。'
: '由这台设备直接向目标发包。可以探测本机上的反射器。',
style: const TextStyle(color: muted, fontSize: 13),
),
if (_remote) ...[
const SizedBox(height: 12),
_pair(
wide,
DropdownButtonFormField<String>(
key: const Key('node-selector'),
initialValue: selected == null ? '' : selected.id,
decoration: const InputDecoration(labelText: '节点'),
items: [
const DropdownMenuItem(value: '', child: Text('未选择')),
for (final node in _nodes)
DropdownMenuItem(
value: node.id,
child: Text(_nodeLabel(node)),
),
],
onChanged: view.running
? null
: (value) => setState(() => _nodeId = value ?? ''),
),
OutlinedButton(
onPressed: view.running ? null : _manageNodes,
child: const Text('管理节点'),
),
),
if (selected != null && nodeUrlLooksPublic(selected.baseUrl))
const Padding(
padding: EdgeInsets.only(top: 8),
child: Text(
'这个控制地址没有使用 HTTPS。口令会暴露在链路上,请改用 TLS 或 HTTPS 反向代理。',
style: TextStyle(color: Color(0xFF9A3412), fontSize: 12),
),
),
],
],
);
}
String _nodeLabel(RemoteNode node) {
final vis = visibilityLabel(node.visibility);
return '${node.name} · $vis';
}
Widget _result(ProbeView view) {
final summary = view.summary;
final rate = view.rateLabel == '探测无应答'
? summary.probeLossPct
: view.rateLabel == '失败率'
? summary.failurePct
: summary.unknownPct;
final motd = view.detail['motd'];
final version = view.detail['version'];
final players = view.detail['players'];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Wrap(
spacing: 8,
runSpacing: 8,
children: [
_chip(view.phase),
_chip('来源 ${view.sourceLabel}'),
if (view.targetAddress != null) _chip('发往 ${view.targetAddress}'),
_chip('延迟 ${formatMs(summary.rttMs)}'),
_chip('抖动 ${formatMs(summary.jitterMs)}'),
_chip('${view.rateLabel} ${formatPct(rate)}'),
],
),
if (view.targetIsFake) ...[
const SizedBox(height: 8),
const Text(
clashFakeIpNote,
style: TextStyle(color: Color(0xFF9A3412), fontSize: 13),
),
],
if (view.note.isNotEmpty) ...[
const SizedBox(height: 8),
Text(view.note, style: const TextStyle(color: ink)),
],
if (motd != null || version != null || players != null) ...[
const SizedBox(height: 8),
Text(
[
if (motd != null) 'MOTD $motd',
if (version != null) '版本 $version',
if (players != null) '人数 $players',
].join(' · '),
style: const TextStyle(color: ink),
),
],
const SizedBox(height: 8),
Text(summaryLine(summary), style: const TextStyle(color: muted, fontSize: 13)),
],
);
}
Future<void> _manageNodes() async {
await showDialog<void>(
context: context,
builder: (context) => _NodeDialog(
nodes: _nodes,
vault: _vault,
onChanged: (nodes, selected) {
setState(() {
_nodes = nodes;
if (selected != null) {
_nodeId = selected;
_remote = true;
} else if (_nodes.every((node) => node.id != _nodeId)) {
_nodeId = '';
}
});
unawaited(_persist());
},
),
);
}
}
class _NodeDialog extends StatefulWidget {
const _NodeDialog({
required this.nodes,
required this.vault,
required this.onChanged,
});
final List<RemoteNode> nodes;
final TokenVault vault;
final void Function(List<RemoteNode> nodes, String? selected) onChanged;
@override
State<_NodeDialog> createState() => _NodeDialogState();
}
class _NodeDialogState extends State<_NodeDialog> {
late List<RemoteNode> _nodes = [...widget.nodes];
final _name = TextEditingController();
final _url = TextEditingController();
final _token = TextEditingController();
String? _hint;
@override
void dispose() {
_name.dispose();
_url.dispose();
_token.dispose();
super.dispose();
}
Future<void> _save() async {
final url = normalizeNodeUrl(_url.text);
if (_name.text.trim().isEmpty || url == null) {
setState(() => _hint = '请填写名称,以及不带口令的 http 或 https 地址');
return;
}
final id = DateTime.now().microsecondsSinceEpoch.toString();
final node = RemoteNode(id: id, name: _name.text.trim(), baseUrl: url);
await widget.vault.write(nodeTokenKey(id), _token.text.trim());
setState(() {
_nodes = [..._nodes, node];
_hint = '已保存。口令只留在本机。';
_name.clear();
_url.clear();
_token.clear();
});
widget.onChanged(_nodes, id);
}
Future<void> _check(RemoteNode node) async {
try {
final info = await fetchNodeInfo(node.baseUrl);
final next = [
for (final item in _nodes)
if (item.id == node.id)
item.copyWith(visibility: info.visibility)
else
item,
];
setState(() {
_nodes = next;
_hint = info.authRequired
? '这个节点是私有的,请求必须带正确的节点口令,否则不会向目标发包。'
: '这个节点是公开的,不需要口令。它仍然有并发、时长和带宽上限。';
});
widget.onChanged(next, node.id);
} on RemoteException catch (error) {
setState(() => _hint = error.message);
}
}
Future<void> _delete(RemoteNode node) async {
await widget.vault.delete(nodeTokenKey(node.id));
final next = [for (final item in _nodes) if (item.id != node.id) item];
setState(() => _nodes = next);
widget.onChanged(next, null);
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('远程节点'),
content: SizedBox(
width: 460,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'节点口令和目标回显口令是两回事。服务器没配置节点口令时,它是公开节点;配置了就必须校验,错误口令不会发出任何探测。',
style: TextStyle(fontSize: 13, color: muted),
),
const SizedBox(height: 12),
for (final node in _nodes)
ListTile(
contentPadding: EdgeInsets.zero,
title: Text(_nodes.isEmpty ? '' : '${node.name} · ${visibilityLabel(node.visibility)}'),
subtitle: Text(node.baseUrl, maxLines: 1, overflow: TextOverflow.ellipsis),
trailing: Wrap(
spacing: 4,
children: [
TextButton(onPressed: () => _check(node), child: const Text('检查')),
TextButton(onPressed: () => _delete(node), child: const Text('删除')),
],
),
),
TextField(
controller: _name,
decoration: const InputDecoration(labelText: '名称'),
),
const SizedBox(height: 8),
TextField(
controller: _url,
decoration: const InputDecoration(
labelText: '节点地址',
hintText: 'https://probe.example:8443',
),
),
const SizedBox(height: 8),
TextField(
controller: _token,
obscureText: true,
decoration: const InputDecoration(
labelText: '节点口令(公开节点留空)',
),
),
if (_hint != null) ...[
const SizedBox(height: 8),
Text(_hint!, style: const TextStyle(fontSize: 13)),
],
],
),
),
),
actions: [
TextButton(onPressed: _save, child: const Text('添加节点')),
TextButton(onPressed: () => Navigator.pop(context), child: const Text('完成')),
],
);
}
}
Widget _card({required String title, required Widget child}) {
return Card(
margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: line),
),
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(title, style: const TextStyle(fontWeight: FontWeight.w700, color: ink)),
const SizedBox(height: 10),
child,
],
),
),
);
}
Widget _field(
TextEditingController controller,
String label,
String hint, {
bool secret = false,
}) {
return TextField(
controller: controller,
obscureText: secret,
decoration: InputDecoration(labelText: label, hintText: hint),
);
}
Widget _pair(bool wide, Widget left, Widget right) {
if (!wide) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [left, const SizedBox(height: 12), right],
);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: left),
const SizedBox(width: 12),
Expanded(child: right),
],
);
}
Widget _chip(String text) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFFE7EEF5),
borderRadius: BorderRadius.circular(99),
),
child: Text(text, style: const TextStyle(fontSize: 12, color: ink)),
);
}
Widget _banner(String text) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0xFFFFF1E8),
borderRadius: BorderRadius.circular(10),
border: Border.all(color: const Color(0xFFF0C9B0)),
),
child: Text(text, style: const TextStyle(color: Color(0xFF9A3412))),
);
}
+284
View File
@@ -0,0 +1,284 @@
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import '../probe/probe_controller.dart';
const rttColor = Color(0xFF1F4E79);
const rateColor = Color(0xFF9A3412);
const ink = Color(0xFF1C2430);
const muted = Color(0xFF5E6872);
const line = Color(0xFFE4DFD4);
class QualityCharts extends StatelessWidget {
const QualityCharts({
super.key,
required this.samples,
required this.rateLabel,
required this.running,
});
final List<ChartSample> samples;
final String rateLabel;
final bool running;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Row(
children: [
_Swatch(color: rttColor, label: '往返时间'),
SizedBox(width: 16),
_Swatch(color: rateColor, label: '比率'),
],
),
const SizedBox(height: 8),
_ChartCard(
title: '延迟',
unit: 'ms',
samples: samples,
read: (sample) => sample.rttMs,
color: rttColor,
floor: 1,
running: running,
),
_ChartCard(
title: rateLabel,
unit: '%',
samples: samples,
read: (sample) => sample.ratePct,
color: rateColor,
floor: 10,
running: running,
),
],
);
}
}
class _Swatch extends StatelessWidget {
const _Swatch({required this.color, required this.label});
final Color color;
final String label;
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 14,
height: 3,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(width: 6),
Text(label, style: const TextStyle(color: muted, fontSize: 12)),
],
);
}
}
class _ChartCard extends StatelessWidget {
const _ChartCard({
required this.title,
required this.unit,
required this.samples,
required this.read,
required this.color,
required this.floor,
required this.running,
});
final String title;
final String unit;
final List<ChartSample> samples;
final double? Function(ChartSample sample) read;
final Color color;
final double floor;
final bool running;
@override
Widget build(BuildContext context) {
final spots = _spots();
final hasData = spots.any((spot) => !spot.isNull());
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: line),
),
margin: const EdgeInsets.only(bottom: 12),
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'$title($unit)',
style: const TextStyle(
color: ink,
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
const SizedBox(height: 8),
SizedBox(
height: 168,
child: hasData
? _lineChart(spots)
: Center(
child: Text(
running
? '正在等待第一次完成的探测。未完成的不会画成 100%。'
: '暂无已完成的探测',
style: const TextStyle(color: muted),
textAlign: TextAlign.center,
),
),
),
],
),
),
);
}
List<FlSpot> _spots() {
final spots = <FlSpot>[];
for (final sample in samples) {
final value = read(sample);
if (value == null) {
if (spots.isNotEmpty && !spots.last.isNull()) {
spots.add(FlSpot.nullSpot);
}
} else {
spots.add(FlSpot(sample.sec, value));
}
}
if (spots.isNotEmpty && spots.last.isNull()) {
spots.removeLast();
}
return spots;
}
Widget _lineChart(List<FlSpot> spots) {
final minX = samples.first.sec;
var maxX = samples.last.sec;
if (maxX - minX < 1) {
maxX = minX + 1;
}
var maxY = floor;
for (final spot in spots) {
if (!spot.isNull() && spot.y > maxY) {
maxY = spot.y;
}
}
maxY = maxY * 1.2;
final yInterval = _yInterval(maxY);
final xInterval = _xInterval(maxX - minX);
return LineChart(
LineChartData(
minX: minX,
maxX: maxX,
minY: 0,
maxY: maxY,
clipData: const FlClipData.all(),
gridData: FlGridData(
show: true,
drawVerticalLine: false,
horizontalInterval: yInterval,
getDrawingHorizontalLine: (_) => const FlLine(color: line, strokeWidth: 1),
),
borderData: FlBorderData(
show: true,
border: const Border(
left: BorderSide(color: line),
bottom: BorderSide(color: line),
),
),
titlesData: FlTitlesData(
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
leftTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 40,
interval: yInterval,
getTitlesWidget: (value, meta) => _axisLabel(_formatTick(value, maxY)),
),
),
bottomTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 26,
interval: xInterval,
getTitlesWidget: (value, meta) =>
_axisLabel('${value.toStringAsFixed(0)}s'),
),
),
),
lineTouchData: const LineTouchData(handleBuiltInTouches: true),
lineBarsData: [
LineChartBarData(
spots: spots,
isCurved: false,
color: color,
barWidth: 2,
dotData: const FlDotData(show: false),
belowBarData: BarAreaData(show: true, color: color.withValues(alpha: 0.10)),
),
],
),
duration: Duration.zero,
);
}
}
Widget _axisLabel(String text) {
return Padding(
padding: const EdgeInsets.only(right: 4),
child: Text(text, style: const TextStyle(color: muted, fontSize: 10)),
);
}
double _yInterval(double maxY) {
if (maxY <= 1) {
return 0.25;
}
if (maxY <= 5) {
return 1;
}
if (maxY <= 20) {
return 5;
}
if (maxY <= 50) {
return 10;
}
if (maxY <= 120) {
return 20;
}
if (maxY <= 300) {
return 50;
}
return 100;
}
double _xInterval(double span) {
if (span <= 15) {
return 5;
}
if (span <= 40) {
return 10;
}
return 15;
}
String _formatTick(double value, double maxY) {
if (maxY < 5) {
return value.toStringAsFixed(value < 1 ? 2 : 1);
}
return value.toStringAsFixed(0);
}
+1
View File
@@ -0,0 +1 @@
flutter/ephemeral
+128
View File
@@ -0,0 +1,128 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "netquality")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
set(APPLICATION_ID "dev.netquality.netquality")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(SET CMP0063 NEW)
# Load bundled libraries from the lib/ directory relative to the binary.
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Root filesystem for cross-building.
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
# Define build configuration options.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_14)
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
# Only the install-generated bundle's copy of the executable will launch
# correctly, since the resources must in the right relative locations. To avoid
# people trying to run the unbundled copy, put it in a subdirectory instead of
# the default top-level location.
set_target_properties(${BINARY_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# By default, "installing" just makes a relocatable bundle in the build
# directory.
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
# Start with a clean build bundle directory every time.
install(CODE "
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
" COMPONENT Runtime)
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endforeach(bundled_library)
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
+88
View File
@@ -0,0 +1,88 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.10)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
# which isn't available in 3.10.
function(list_prepend LIST_NAME PREFIX)
set(NEW_LIST "")
foreach(element ${${LIST_NAME}})
list(APPEND NEW_LIST "${PREFIX}${element}")
endforeach(element)
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
endfunction()
# === Flutter Library ===
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"fl_basic_message_channel.h"
"fl_binary_codec.h"
"fl_binary_messenger.h"
"fl_dart_project.h"
"fl_engine.h"
"fl_json_message_codec.h"
"fl_json_method_codec.h"
"fl_message_codec.h"
"fl_method_call.h"
"fl_method_channel.h"
"fl_method_codec.h"
"fl_method_response.h"
"fl_plugin_registrar.h"
"fl_plugin_registry.h"
"fl_standard_message_codec.h"
"fl_standard_method_codec.h"
"fl_string_codec.h"
"fl_value.h"
"fl_view.h"
"flutter_linux.h"
)
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
target_link_libraries(flutter INTERFACE
PkgConfig::GTK
PkgConfig::GLIB
PkgConfig::GIO
)
add_dependencies(flutter flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CMAKE_CURRENT_BINARY_DIR}/_phony_
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
)
@@ -0,0 +1,11 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
void fl_register_plugins(FlPluginRegistry* registry) {
}
@@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter_linux/flutter_linux.h>
// Registers Flutter plugins.
void fl_register_plugins(FlPluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_
@@ -0,0 +1,24 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
+26
View File
@@ -0,0 +1,26 @@
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME}
"main.cc"
"my_application.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the application ID.
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
# Add dependency libraries. Add any application-specific dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
+6
View File
@@ -0,0 +1,6 @@
#include "my_application.h"
int main(int argc, char** argv) {
g_autoptr(MyApplication) app = my_application_new();
return g_application_run(G_APPLICATION(app), argc, argv);
}
+148
View File
@@ -0,0 +1,148 @@
#include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Called when first Flutter frame received.
static void first_frame_cb(MyApplication* self, FlView* view) {
gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view)));
}
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen* screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "网络质量探测");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
} else {
gtk_window_set_title(window, "网络质量探测");
}
gtk_window_set_default_size(window, 1180, 800);
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(
project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
GdkRGBA background_color;
// Background defaults to black, override it here if necessary, e.g. #00000000
// for transparent.
gdk_rgba_parse(&background_color, "#F3F1EC");
fl_view_set_background_color(view, &background_color);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
// Show the window when Flutter renders.
// Requires the view to be realized so we can start rendering.
g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb),
self);
gtk_widget_realize(GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application,
gchar*** arguments,
int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GApplication::startup.
static void my_application_startup(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application startup.
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
}
// Implements GApplication::shutdown.
static void my_application_shutdown(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application shutdown.
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line =
my_application_local_command_line;
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
// Set the program name to the application ID, which helps various systems
// like GTK and desktop environments map this running application to its
// corresponding .desktop file. This ensures better integration by allowing
// the application to be recognized beyond its binary name.
g_set_prgname(APPLICATION_ID);
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID, "flags",
G_APPLICATION_NON_UNIQUE, nullptr));
}
+21
View File
@@ -0,0 +1,21 @@
#ifndef FLUTTER_MY_APPLICATION_H_
#define FLUTTER_MY_APPLICATION_H_
#include <gtk/gtk.h>
G_DECLARE_FINAL_TYPE(MyApplication,
my_application,
MY,
APPLICATION,
GtkApplication)
/**
* my_application_new:
*
* Creates a new Flutter-based application.
*
* Returns: a new #MyApplication.
*/
MyApplication* my_application_new();
#endif // FLUTTER_MY_APPLICATION_H_
+490
View File
@@ -0,0 +1,490 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
args:
dependency: transitive
description:
name: args
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
url: "https://pub.dev"
source: hosted
version: "2.7.0"
async:
dependency: transitive
description:
name: async
sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
url: "https://pub.dev"
source: hosted
version: "2.13.1"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
characters:
dependency: transitive
description:
name: characters
sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
url: "https://pub.dev"
source: hosted
version: "1.4.1"
clock:
dependency: transitive
description:
name: clock
sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e
url: "https://pub.dev"
source: hosted
version: "1.1.3"
code_assets:
dependency: transitive
description:
name: code_assets
sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8
url: "https://pub.dev"
source: hosted
version: "1.2.1"
collection:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
url: "https://pub.dev"
source: hosted
version: "1.19.1"
crypto:
dependency: transitive
description:
name: crypto
sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4
url: "https://pub.dev"
source: hosted
version: "3.0.8"
cupertino_icons:
dependency: "direct main"
description:
name: cupertino_icons
sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd"
url: "https://pub.dev"
source: hosted
version: "1.0.9"
equatable:
dependency: transitive
description:
name: equatable
sha256: ea36e500cbf0ec18361deabca755434f73e42fe53c5130021c7e2d6b5ebe1702
url: "https://pub.dev"
source: hosted
version: "3.0.0"
fake_async:
dependency: transitive
description:
name: fake_async
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
url: "https://pub.dev"
source: hosted
version: "1.3.3"
ffi:
dependency: transitive
description:
name: ffi
sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
url: "https://pub.dev"
source: hosted
version: "2.2.0"
file:
dependency: transitive
description:
name: file
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
url: "https://pub.dev"
source: hosted
version: "7.0.1"
fl_chart:
dependency: "direct main"
description:
name: fl_chart
sha256: "5ed69b8be550c6276c8f0bc25c09704fb061018ed1b1681867ad18fcf477e7b7"
url: "https://pub.dev"
source: hosted
version: "1.3.0"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_lints:
dependency: "direct dev"
description:
name: flutter_lints
sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1"
url: "https://pub.dev"
source: hosted
version: "6.0.0"
flutter_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
flutter_web_plugins:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
hooks:
dependency: transitive
description:
name: hooks
sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
jni:
dependency: transitive
description:
name: jni
sha256: "2e91e6087291affd10b31b6c872f3e3ac7dc5d93b51b5ba485d930c8f08bde6c"
url: "https://pub.dev"
source: hosted
version: "1.1.2"
jni_flutter:
dependency: transitive
description:
name: jni_flutter
sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191"
url: "https://pub.dev"
source: hosted
version: "1.0.4+1"
jni_util:
dependency: transitive
description:
name: jni_util
sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
leak_tracker:
dependency: transitive
description:
name: leak_tracker
sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
url: "https://pub.dev"
source: hosted
version: "11.0.2"
leak_tracker_flutter_testing:
dependency: transitive
description:
name: leak_tracker_flutter_testing
sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
url: "https://pub.dev"
source: hosted
version: "3.0.10"
leak_tracker_testing:
dependency: transitive
description:
name: leak_tracker_testing
sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
url: "https://pub.dev"
source: hosted
version: "3.0.2"
lints:
dependency: transitive
description:
name: lints
sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df"
url: "https://pub.dev"
source: hosted
version: "6.1.0"
logging:
dependency: transitive
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
matcher:
dependency: transitive
description:
name: matcher
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
url: "https://pub.dev"
source: hosted
version: "0.13.0"
meta:
dependency: transitive
description:
name: meta
sha256: c82594181e3312f3d0695fc95aaaf7758d75b8d4ae2bbecf223b9fd5109a059d
url: "https://pub.dev"
source: hosted
version: "1.18.3"
objective_c:
dependency: transitive
description:
name: objective_c
sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e
url: "https://pub.dev"
source: hosted
version: "9.5.0"
package_config:
dependency: transitive
description:
name: package_config
sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d
url: "https://pub.dev"
source: hosted
version: "3.0.0"
path:
dependency: transitive
description:
name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path_provider:
dependency: "direct main"
description:
name: path_provider
sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
url: "https://pub.dev"
source: hosted
version: "2.1.6"
path_provider_android:
dependency: transitive
description:
name: path_provider_android
sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd"
url: "https://pub.dev"
source: hosted
version: "2.3.1"
path_provider_foundation:
dependency: transitive
description:
name: path_provider_foundation
sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699"
url: "https://pub.dev"
source: hosted
version: "2.6.0"
path_provider_linux:
dependency: transitive
description:
name: path_provider_linux
sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
url: "https://pub.dev"
source: hosted
version: "2.2.2"
path_provider_platform_interface:
dependency: transitive
description:
name: path_provider_platform_interface
sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"
url: "https://pub.dev"
source: hosted
version: "2.1.3"
path_provider_windows:
dependency: transitive
description:
name: path_provider_windows
sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
url: "https://pub.dev"
source: hosted
version: "2.3.0"
platform:
dependency: transitive
description:
name: platform
sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec
url: "https://pub.dev"
source: hosted
version: "3.2.0"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
url: "https://pub.dev"
source: hosted
version: "2.1.8"
pub_semver:
dependency: transitive
description:
name: pub_semver
sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24"
url: "https://pub.dev"
source: hosted
version: "2.2.1"
record_use:
dependency: transitive
description:
name: record_use
sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed"
url: "https://pub.dev"
source: hosted
version: "0.6.0"
shared_preferences:
dependency: "direct main"
description:
name: shared_preferences
sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f"
url: "https://pub.dev"
source: hosted
version: "2.5.6"
shared_preferences_android:
dependency: transitive
description:
name: shared_preferences_android
sha256: "33b38b07d9ac7d16aff0426c61418752fd3e7a8c7dc8be786c875d6ce673b002"
url: "https://pub.dev"
source: hosted
version: "2.5.4"
shared_preferences_foundation:
dependency: transitive
description:
name: shared_preferences_foundation
sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea"
url: "https://pub.dev"
source: hosted
version: "2.5.7"
shared_preferences_linux:
dependency: transitive
description:
name: shared_preferences_linux
sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
shared_preferences_platform_interface:
dependency: transitive
description:
name: shared_preferences_platform_interface
sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9"
url: "https://pub.dev"
source: hosted
version: "2.4.2"
shared_preferences_web:
dependency: transitive
description:
name: shared_preferences_web
sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019
url: "https://pub.dev"
source: hosted
version: "2.4.3"
shared_preferences_windows:
dependency: transitive
description:
name: shared_preferences_windows
sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
sky_engine:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
source_span:
dependency: transitive
description:
name: source_span
sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
url: "https://pub.dev"
source: hosted
version: "1.10.2"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490"
url: "https://pub.dev"
source: hosted
version: "1.12.2"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
string_scanner:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
url: "https://pub.dev"
source: hosted
version: "1.2.2"
test_api:
dependency: transitive
description:
name: test_api
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev"
source: hosted
version: "0.7.12"
vector_math:
dependency: transitive
description:
name: vector_math
sha256: "1d774bbdf6b72a0b12122fc1560c9c2d2a67db5a4a4cc2bd8a5c990ab20e3188"
url: "https://pub.dev"
source: hosted
version: "2.4.0"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78"
url: "https://pub.dev"
source: hosted
version: "15.4.0"
web:
dependency: transitive
description:
name: web
sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b
url: "https://pub.dev"
source: hosted
version: "1.1.2"
xdg_directories:
dependency: transitive
description:
name: xdg_directories
sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
yaml:
dependency: transitive
description:
name: yaml
sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
url: "https://pub.dev"
source: hosted
version: "3.1.4"
sdks:
dart: ">=3.13.7 <4.0.0"
flutter: ">=3.44.0"
+97
View File
@@ -0,0 +1,97 @@
name: netquality
description: "UDP/TCP connection quality probe"
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# 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
# of the product and file versions while build-number is used as the build suffix.
version: 1.1.1+4
environment:
sdk: ^3.13.7
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
fl_chart: ^1.3.0
path_provider: ^2.1.5
shared_preferences: ^2.5.6
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^6.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
fonts:
- family: NetQualityCJK
fonts:
- asset: assets/fonts/wqy-subset.ttf
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/to/resolution-aware-images
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/to/asset-from-package
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/to/font-from-package
+50
View File
@@ -0,0 +1,50 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/probe/endpoint_picker.dart';
void main() {
test('a miss before any answer tries the next address', () {
final v6 = InternetAddress('2001:db8::1');
final v4 = InternetAddress('203.0.113.5');
final picker = EndpointPicker([v6, v4]);
expect(picker.current, v6);
expect(picker.record(false), isTrue);
expect(picker.current, v4);
expect(picker.record(true), isFalse);
expect(picker.current, v4);
expect(picker.hasAnswered, isTrue);
});
test('a working address survives two misses and leaves on the third', () {
final v4 = InternetAddress('203.0.113.5');
final v6 = InternetAddress('2001:db8::1');
final picker = EndpointPicker([v4, v6]);
expect(picker.record(true), isFalse);
expect(picker.record(false), isFalse);
expect(picker.record(false), isFalse);
expect(picker.current, v4);
expect(picker.record(false), isTrue);
expect(picker.current, v6);
expect(picker.hasAnswered, isFalse);
expect(picker.record(false), isTrue);
expect(picker.current, v4);
});
test('one address is never abandoned', () {
final only = InternetAddress('203.0.113.9');
final picker = EndpointPicker([only]);
expect(picker.record(false), isFalse);
expect(picker.record(false), isFalse);
expect(picker.current, only);
});
test('198.18.0.0/15 is treated as a VPN fake address', () {
expect(isClashFakeIp(InternetAddress('198.18.0.1')), isTrue);
expect(isClashFakeIp(InternetAddress('198.19.255.254')), isTrue);
expect(isClashFakeIp(InternetAddress('198.17.255.255')), isFalse);
expect(isClashFakeIp(InternetAddress('198.20.0.1')), isFalse);
expect(isClashFakeIp(InternetAddress('180.172.93.226')), isFalse);
expect(isClashFakeIp(InternetAddress('2001:db8::1')), isFalse);
});
}
+498
View File
@@ -0,0 +1,498 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/metrics/sample_book.dart';
import 'package:netquality/probe/game_codec.dart';
import 'package:netquality/probe/probe_loop.dart';
import 'package:netquality/probe/remote_client.dart';
late String binary;
void main() {
setUpAll(() async {
final dir = await Directory.systemTemp.createTemp('nq-node');
binary = '${dir.path}/netquality-reflector';
final serverDir = Directory('server').existsSync() ? 'server' : '../server';
final build = await Process.run('go', [
'build',
'-o',
binary,
'.',
], workingDirectory: serverDir);
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 {
final reflector = await _reflector();
addTearDown(() => reflector.process.kill());
final tcp = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: reflector.tcp,
profileId: 'nq-tcp',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 800),
packetSize: 80,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 2,
);
expect(tcp.last.status, Outcome.ok);
expect(tcp.last.rttMs, greaterThan(0));
expect(tcp.last.summary.probeLossPct, 0);
final udp = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: reflector.udp,
profileId: 'nq-udp',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 800),
packetSize: 80,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(udp.single.status, Outcome.ok);
expect(udp.single.summary.probeLossPct, 0);
final refused = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: 1,
profileId: 'tcp-connect',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 400),
packetSize: 64,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(refused.single.status, Outcome.refused);
expect(refused.single.summary.failurePct, 100);
expect(refused.single.summary.probeLossPct, isNull);
});
test('silence is unknown, games answer, and a remote node measures rtt', () async {
final hole = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(hole.close);
hole.listen((event) {
if (event == RawSocketEvent.read) {
hole.receive();
}
});
final unknown = await _collect(
ProbeRequest(
host: '127.0.0.1',
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();
}
}
}());
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('plain udp leaves a silent address and keeps one that 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;
}
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 seen = <String>[];
final samples = await _collect(
ProbeRequest(
host: 'example.test',
port: port,
profileId: 'udp-generic',
interval: const Duration(milliseconds: 40),
timeout: const Duration(milliseconds: 250),
packetSize: 16,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 2,
loop: ProbeLoop(
lookup: (host) async {
expect(host, 'example.test');
return [InternetAddress('127.0.0.1'), InternetAddress('::1')];
},
onEndpoint: (address) => seen.add(address.address),
),
);
expect(samples.first.status, Outcome.unknown);
expect(samples.first.detail['address'], '127.0.0.1');
expect(samples.last.status, Outcome.ok);
expect(samples.last.detail['address'], '::1');
expect(seen, ['127.0.0.1', '::1']);
});
test('a responding address is not replaced while it still answers', () 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: '',
),
count: 3,
loop: ProbeLoop(
lookup: (_) async => [
InternetAddress('127.0.0.1'),
InternetAddress('2001:db8::1'),
],
),
);
expect(samples.map((sample) => sample.status), everyElement(Outcome.ok));
expect(samples.map((sample) => sample.detail['address']), everyElement('127.0.0.1'));
});
}
Future<List<ProbeSample>> _collect(
ProbeRequest request, {
required int count,
ProbeLoop? loop,
}) async {
final probe = loop ?? ProbeLoop();
final samples = <ProbeSample>[];
var stop = false;
await probe
.run(
request: request,
onSample: (sample) {
samples.add(sample);
if (samples.length >= count) {
stop = true;
}
},
cancelled: () => stop,
)
.timeout(const Duration(seconds: 6));
return samples;
}
Future<({Process process, int tcp, int udp})> _reflector() async {
final tcp = await _freeTcp();
final udp = await _freeUdp();
final process = await Process.start(binary, [
'-bind',
'127.0.0.1',
'-tcp-port',
'$tcp',
'-udp-port',
'$udp',
'-mode',
'reflector',
]);
await _waitListen(process);
return (process: process, tcp: tcp, udp: udp);
}
Future<({Process process, int control, int udp, void Function() kill})> _node() async {
final udp = await _freeUdp();
final control = await _freeTcp();
final process = await Process.start(binary, [
'-bind',
'127.0.0.1',
'-tcp-port',
'0',
'-udp-port',
'$udp',
'-mode',
'both',
'-control-addr',
'127.0.0.1:$control',
'-allow-private',
]);
final ready = Completer<void>();
process.stderr.transform(utf8.decoder).listen((text) {
if (text.contains('node control listening') && !ready.isCompleted) {
ready.complete();
}
});
process.stdout.transform(utf8.decoder).listen((_) {});
await ready.future.timeout(const Duration(seconds: 3));
return (
process: process,
control: control,
udp: udp,
kill: () {
process.kill();
},
);
}
Future<void> _waitListen(Process process) async {
final ready = Completer<void>();
process.stderr.transform(utf8.decoder).listen((text) {
if (text.contains('listening') && !ready.isCompleted) {
ready.complete();
}
});
process.stdout.transform(utf8.decoder).listen((_) {});
await ready.future.timeout(const Duration(seconds: 3));
}
Future<int> _freeTcp() async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = server.port;
await server.close();
return port;
}
Future<int> _freeUdp() async {
final socket = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = socket.port;
socket.close();
return port;
}
Future<({int port, Future<void> Function() close})> _javaServer() async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final sub = server.listen((socket) async {
final reader = _Reader(socket);
await reader.next();
await reader.next();
const status =
'{"version":{"name":"1.21.1","protocol":767},"players":{"online":3,"max":20},"description":{"text":"Hello"}}';
final payload = BytesBuilder(copy: false)
..addByte(0x00)
..add(mcString(status));
socket.add(mcPacket(payload.toBytes()));
final ping = await reader.next();
if (ping != null) {
socket.add(mcPacket(ping));
}
await socket.close();
});
return (
port: server.port,
close: () async {
await sub.cancel();
await server.close();
},
);
}
Future<({int port, void Function() close})> _bedrockServer() async {
final socket = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
final sub = socket.listen((event) {
if (event != RawSocketEvent.read) {
return;
}
final datagram = socket.receive();
if (datagram == null || datagram.data.length < 9) {
return;
}
final ts = datagram.data.sublist(1, 9);
const motd = 'MCPE;Bed;844;1.21.50;1;10;0;world;Survival;1;19132;0;';
final body = BytesBuilder(copy: false)
..addByte(0x1c)
..add(ts)
..add(const [0, 0, 0, 0, 0, 0, 0, 99])
..add(rakMagic)
..addByte(0)
..addByte(motd.length)
..add(motd.codeUnits);
socket.send(body.toBytes(), datagram.address, datagram.port);
});
return (
port: socket.port,
close: () {
sub.cancel();
socket.close();
},
);
}
class _Reader {
_Reader(this.socket) {
socket.listen((data) {
_buf.add(data);
_pending?.complete();
_pending = null;
});
}
final Socket socket;
final BytesBuilder _buf = BytesBuilder(copy: false);
Completer<void>? _pending;
Future<Uint8List?> next() async {
final deadline = DateTime.now().add(const Duration(seconds: 2));
while (true) {
final bytes = _buf.toBytes();
final packet = takeMcPacket(bytes);
if (packet != null) {
_buf.clear();
if (packet.used < bytes.length) {
_buf.add(Uint8List.sublistView(bytes, packet.used));
}
return packet.payload;
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (takeMcPacket(_buf.toBytes()) != null) {
waiter.complete();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
return null;
}
}
}
}
+75
View File
@@ -0,0 +1,75 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/protocol/probe_packet.dart';
void main() {
test('golden request matches the server fixture', () {
final packet = ProbePacket(
type: ProbePacket.typeRequest,
sequence: 1,
clientSendUnixNano: 1000,
payload: Uint8List.fromList([1, 2, 3, 4]),
);
final hex = packet
.encode()
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
.join();
expect(
hex,
'4e5130310101000001000000e803000000000000'
'0000000000000000000000000000000000000000'
'0000000000000000000000000000000000000000'
'040001020304',
);
final back = ProbePacket.decode(packet.encode());
expect(back.sequence, 1);
expect(back.clientSendUnixNano, 1000);
expect(back.type, ProbePacket.typeRequest);
expect(back.payload, [1, 2, 3, 4]);
});
test('token is zero padded in the header', () {
final token = ProbePacket.encodeToken('demo');
expect(token, hasLength(32));
expect(token.sublist(0, 4), [0x64, 0x65, 0x6d, 0x6f]);
expect(token.sublist(4), everyElement(0));
expect(() => ProbePacket.encodeToken('x' * 33), throwsA(isA<ProbePacketException>()));
});
test('frame buffer splits partial and concatenated TCP frames', () {
final packet = ProbePacket(
type: ProbePacket.typeReply,
sequence: 9,
clientSendUnixNano: 50,
serverUnixNano: 80,
payload: Uint8List.fromList([9, 8, 7]),
).encode();
final buffer = FrameBuffer();
expect(buffer.add(packet.sublist(0, 20)), isEmpty);
expect(buffer.add(packet.sublist(20, 40)), isEmpty);
final one = buffer.add(packet.sublist(40));
expect(one, hasLength(1));
expect(ProbePacket.decode(one.single).sequence, 9);
expect(ProbePacket.decode(one.single).serverUnixNano, 80);
final both = Uint8List.fromList([...packet, ...packet]);
final two = FrameBuffer().add(both);
expect(two, hasLength(2));
expect(ProbePacket.decode(two[1]).payload, [9, 8, 7]);
});
test('rejects a short or trailing datagram', () {
final packet = ProbePacket(
type: ProbePacket.typeRequest,
sequence: 1,
clientSendUnixNano: 1,
).encode();
expect(
() => ProbePacket.decode(Uint8List.sublistView(packet, 0, 10)),
throwsA(isA<ProbePacketException>()),
);
final extra = Uint8List(packet.length + 1)..setRange(0, packet.length, packet);
expect(() => ProbePacket.decode(extra), throwsA(isA<ProbePacketException>()));
});
}
+96
View File
@@ -0,0 +1,96 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/metrics/sample_book.dart';
import 'package:netquality/models/session_config.dart';
import 'package:netquality/probe/game_codec.dart';
import 'package:netquality/probe/remote_client.dart';
void main() {
test('pending work is not a rate, and connect failure is not probe loss', () {
final book = SampleBook('nq-tcp');
expect(book.summary().probeLossPct, isNull);
expect(book.summary().completed, 0);
book.add(
const Outcome(status: Outcome.refused, kind: Outcome.connect, reconnect: true),
);
expect(book.summary().probeLossPct, isNull);
expect(book.summary().reconnects, 1);
book.add(const Outcome(status: Outcome.timeout, kind: Outcome.probe));
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: 1.5));
expect(book.summary().probeLossPct, 25);
expect(book.summary().jitterMs, closeTo(0.08984375, 0.000001));
});
test('generic udp silence is unknown, not loss', () {
final book = SampleBook('udp-generic');
book.add(const Outcome(status: Outcome.unknown, kind: Outcome.query));
final summary = book.summary();
expect(summary.probeLossPct, isNull);
expect(summary.unknownPct, 100);
});
test('node url rejects embedded secrets and job body keeps tokens apart', () {
expect(normalizeNodeUrl('https://user:secret@probe.example/node'), isNull);
expect(
normalizeNodeUrl('https://probe.example:8443/nq?token=secret'),
'https://probe.example:8443/nq',
);
expect(normalizeNodeUrl('http://127.0.0.1:8443'), 'http://127.0.0.1:8443');
const body = ProbeBody(
target: '203.0.113.10',
port: 19090,
profile: 'nq-tcp',
intervalMs: 300,
timeoutMs: 1000,
durationSec: 30,
packetSize: 128,
echoToken: 'echo-secret',
dnsName: '',
payloadHex: '',
expectHex: '',
);
final json = body.toJson();
expect(json.containsKey('nodeToken'), isFalse);
expect(json['echoToken'], 'echo-secret');
expect(jsonEncodeContainsToken(json), isFalse);
});
test('minecraft and raknet builders match the protocol', () {
final handshake = javaHandshake('127.0.0.1', 25565);
expect(handshake.sublist(2, 4), [0xff, 0x05]);
final status = minecraftStatusDetail(
'{"version":{"name":"1.21.1"},"players":{"online":3,"max":20},"description":{"text":"Hello","extra":[{"text":"!"}]}}',
);
expect(status['motd'], 'Hello!');
expect(status['version'], '1.21.1');
expect(status['players'], '3/20');
const motd = 'MCPE;Bed;844;1.21.50;1;10;0;';
final pong = Uint8List.fromList([
0x1c,
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
0, 0, 0, 0, 0, 0, 0, 99,
...rakMagic,
0, motd.length,
...motd.codeUnits,
]);
final detail = parseRakPong(pong, 0x1122334455667788);
expect(detail?['motd'], 'Bed');
expect(detail?['version'], '1.21.50');
expect(detail?['players'], '1/10');
final bad = Uint8List.fromList(pong);
bad[17] = 0x11;
expect(parseRakPong(bad, 0x1122334455667788), isNull);
final query = dnsQuery(7, 'example.com');
expect(query[0], 0);
expect(query[1], 7);
expect((query[2] & 0x80), 0);
});
}
bool jsonEncodeContainsToken(Map<String, Object?> json) {
return json.keys.contains('nodeToken') || json.values.contains('node-control-secret');
}
+50
View File
@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/main.dart';
import 'package:netquality/models/session_config.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
testWidgets('opens on local source with an empty chart', (tester) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(1280, 1400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const NetQualityApp());
await tester.pumpAndSettle();
expect(find.text('网络质量探测'), findsOneWidget);
expect(find.text('探测来源'), findsOneWidget);
expect(find.text('本机'), findsWidgets);
expect(find.text('远程节点'), findsWidgets);
expect(find.text('开始探测'), findsOneWidget);
expect(find.text('暂无已完成的探测'), findsNWidgets(2));
expect(find.textContaining('127.0.0.1'), findsWidgets);
});
test('settings round trip keeps the node and drops nothing secret into json keys', () {
const config = SessionConfig(
remote: true,
nodeId: 'n1',
nodes: [RemoteNode(id: 'n1', name: '机房', baseUrl: 'https://probe.example:8443')],
host: '203.0.113.8',
port: 25565,
profileId: 'minecraft-java',
intervalMs: 300,
timeoutMs: 1000,
durationSec: 60,
packetSize: 128,
dnsName: 'example.com',
payloadHex: '',
expectHex: '',
);
final again = SessionConfig.fromJson(config.toJson());
expect(again.host, '203.0.113.8');
expect(again.profileId, 'minecraft-java');
expect(again.node?.name, '机房');
expect(again.toJson().containsKey('token'), isFalse);
expect(again.toJson().containsKey('nodeToken'), isFalse);
expect(SessionConfig.defaults.validate(), isNull);
});
}
+17
View File
@@ -0,0 +1,17 @@
flutter/ephemeral/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
+108
View File
@@ -0,0 +1,108 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.14)
project(netquality LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "netquality")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(VERSION 3.14...3.25)
# Define build configuration option.
get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(IS_MULTICONFIG)
set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
CACHE STRING "" FORCE)
else()
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
endif()
# Define settings for the Profile build mode.
set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
# Use Unicode for all projects.
add_definitions(-DUNICODE -D_UNICODE)
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_17)
target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100")
target_compile_options(${TARGET} PRIVATE /EHsc)
target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")
target_compile_definitions(${TARGET} PRIVATE "$<$<CONFIG:Debug>:_DEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# Support files are copied into place next to the executable, so that it can
# run in place. This is done instead of making a separate bundle (as on Linux)
# so that building and running from within Visual Studio will work.
set(BUILD_BUNDLE_DIR "$<TARGET_FILE_DIR:${BINARY_NAME}>")
# Make the "install" step default, as it's required to run.
set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
if(PLUGIN_BUNDLED_LIBRARIES)
install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
CONFIGURATIONS Profile;Release
COMPONENT Runtime)
+109
View File
@@ -0,0 +1,109 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.14)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")
# Set fallback configurations for older versions of the flutter tool.
if (NOT DEFINED FLUTTER_TARGET_PLATFORM)
set(FLUTTER_TARGET_PLATFORM "windows-x64")
endif()
# === Flutter Library ===
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"flutter_export.h"
"flutter_windows.h"
"flutter_messenger.h"
"flutter_plugin_registrar.h"
"flutter_texture_registrar.h"
)
list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")
add_dependencies(flutter flutter_assemble)
# === Wrapper ===
list(APPEND CPP_WRAPPER_SOURCES_CORE
"core_implementations.cc"
"standard_codec.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")
list(APPEND CPP_WRAPPER_SOURCES_PLUGIN
"plugin_registrar.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")
list(APPEND CPP_WRAPPER_SOURCES_APP
"flutter_engine.cc"
"flutter_view_controller.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")
# Wrapper sources needed for a plugin.
add_library(flutter_wrapper_plugin STATIC
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_PLUGIN}
)
apply_standard_settings(flutter_wrapper_plugin)
set_target_properties(flutter_wrapper_plugin PROPERTIES
POSITION_INDEPENDENT_CODE ON)
set_target_properties(flutter_wrapper_plugin PROPERTIES
CXX_VISIBILITY_PRESET hidden)
target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)
target_include_directories(flutter_wrapper_plugin PUBLIC
"${WRAPPER_ROOT}/include"
)
add_dependencies(flutter_wrapper_plugin flutter_assemble)
# Wrapper sources needed for the runner.
add_library(flutter_wrapper_app STATIC
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_APP}
)
apply_standard_settings(flutter_wrapper_app)
target_link_libraries(flutter_wrapper_app PUBLIC flutter)
target_include_directories(flutter_wrapper_app PUBLIC
"${WRAPPER_ROOT}/include"
)
add_dependencies(flutter_wrapper_app flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")
set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}
${CPP_WRAPPER_SOURCES_APP}
${PHONY_OUTPUT}
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"
${FLUTTER_TARGET_PLATFORM} $<CONFIG>
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_PLUGIN}
${CPP_WRAPPER_SOURCES_APP}
)
@@ -0,0 +1,11 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
void RegisterPlugins(flutter::PluginRegistry* registry) {
}
@@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter/plugin_registry.h>
// Registers Flutter plugins.
void RegisterPlugins(flutter::PluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_
@@ -0,0 +1,24 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
+40
View File
@@ -0,0 +1,40 @@
cmake_minimum_required(VERSION 3.14)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME} WIN32
"flutter_window.cpp"
"main.cpp"
"utils.cpp"
"win32_window.cpp"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
"Runner.rc"
"runner.exe.manifest"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the build version.
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}")
# Disable Windows macros that collide with C++ standard library functions.
target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
# Add dependency libraries and include directories. Add any application-specific
# dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
+121
View File
@@ -0,0 +1,121 @@
// Microsoft Visual C++ generated resource script.
//
#pragma code_page(65001)
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_APP_ICON ICON "resources\\app_icon.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)
#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD
#else
#define VERSION_AS_NUMBER 1,0,0,0
#endif
#if defined(FLUTTER_VERSION)
#define VERSION_AS_STRING FLUTTER_VERSION
#else
#define VERSION_AS_STRING "1.0.0"
#endif
VS_VERSION_INFO VERSIONINFO
FILEVERSION VERSION_AS_NUMBER
PRODUCTVERSION VERSION_AS_NUMBER
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
#ifdef _DEBUG
FILEFLAGS VS_FF_DEBUG
#else
FILEFLAGS 0x0L
#endif
FILEOS VOS__WINDOWS32
FILETYPE VFT_APP
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "dev.netquality" "\0"
VALUE "FileDescription", "netquality" "\0"
VALUE "FileVersion", VERSION_AS_STRING "\0"
VALUE "InternalName", "netquality" "\0"
VALUE "LegalCopyright", "Copyright (C) 2026 dev.netquality. All rights reserved." "\0"
VALUE "OriginalFilename", "netquality.exe" "\0"
VALUE "ProductName", "netquality" "\0"
VALUE "ProductVersion", VERSION_AS_STRING "\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
+71
View File
@@ -0,0 +1,71 @@
#include "flutter_window.h"
#include <optional>
#include "flutter/generated_plugin_registrant.h"
FlutterWindow::FlutterWindow(const flutter::DartProject& project)
: project_(project) {}
FlutterWindow::~FlutterWindow() {}
bool FlutterWindow::OnCreate() {
if (!Win32Window::OnCreate()) {
return false;
}
RECT frame = GetClientArea();
// The size here must match the window dimensions to avoid unnecessary surface
// creation / destruction in the startup path.
flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
frame.right - frame.left, frame.bottom - frame.top, project_);
// Ensure that basic setup of the controller was successful.
if (!flutter_controller_->engine() || !flutter_controller_->view()) {
return false;
}
RegisterPlugins(flutter_controller_->engine());
SetChildContent(flutter_controller_->view()->GetNativeWindow());
flutter_controller_->engine()->SetNextFrameCallback([&]() {
this->Show();
});
// Flutter can complete the first frame before the "show window" callback is
// registered. The following call ensures a frame is pending to ensure the
// window is shown. It is a no-op if the first frame hasn't completed yet.
flutter_controller_->ForceRedraw();
return true;
}
void FlutterWindow::OnDestroy() {
if (flutter_controller_) {
flutter_controller_ = nullptr;
}
Win32Window::OnDestroy();
}
LRESULT
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
// Give Flutter, including plugins, an opportunity to handle window messages.
if (flutter_controller_) {
std::optional<LRESULT> result =
flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
lparam);
if (result) {
return *result;
}
}
switch (message) {
case WM_FONTCHANGE:
flutter_controller_->engine()->ReloadSystemFonts();
break;
}
return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
}
+33
View File
@@ -0,0 +1,33 @@
#ifndef RUNNER_FLUTTER_WINDOW_H_
#define RUNNER_FLUTTER_WINDOW_H_
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <memory>
#include "win32_window.h"
// A window that does nothing but host a Flutter view.
class FlutterWindow : public Win32Window {
public:
// Creates a new FlutterWindow hosting a Flutter view running |project|.
explicit FlutterWindow(const flutter::DartProject& project);
virtual ~FlutterWindow();
protected:
// Win32Window:
bool OnCreate() override;
void OnDestroy() override;
LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,
LPARAM const lparam) noexcept override;
private:
// The project to run.
flutter::DartProject project_;
// The Flutter instance hosted by this window.
std::unique_ptr<flutter::FlutterViewController> flutter_controller_;
};
#endif // RUNNER_FLUTTER_WINDOW_H_
+43
View File
@@ -0,0 +1,43 @@
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.Create(L"\x7f51\x7edc\x8d28\x91cf\x63a2\x6d4b", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}
+16
View File
@@ -0,0 +1,16 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Runner.rc
//
#define IDI_APP_ICON 101
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 and Windows 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
</assembly>
+69
View File
@@ -0,0 +1,69 @@
#include "utils.h"
#include <flutter_windows.h>
#include <io.h>
#include <stdio.h>
#include <windows.h>
#include <iostream>
void CreateAndAttachConsole() {
if (::AllocConsole()) {
FILE *unused;
if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
_dup2(_fileno(stdout), 1);
}
if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
_dup2(_fileno(stdout), 2);
}
std::ios::sync_with_stdio();
FlutterDesktopResyncOutputStreams();
}
}
std::vector<std::string> GetCommandLineArguments() {
// Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
int argc;
wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
if (argv == nullptr) {
return std::vector<std::string>();
}
std::vector<std::string> command_line_arguments;
// Skip the first argument as it's the binary name.
for (int i = 1; i < argc; i++) {
command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
}
::LocalFree(argv);
return command_line_arguments;
}
std::string Utf8FromUtf16(const wchar_t* utf16_string) {
if (utf16_string == nullptr) {
return std::string();
}
// First, find the length of the string with a safe upper bound (CWE-126).
// UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.
int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));
// Now use that bounded length to determine the required buffer size.
// When an explicit length is passed, WideCharToMultiByte does not include
// the null terminator in its returned size.
int target_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
input_length, nullptr, 0, nullptr, nullptr);
std::string utf8_string;
if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {
return utf8_string;
}
utf8_string.resize(target_length);
int converted_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
input_length, utf8_string.data(), target_length, nullptr, nullptr);
if (converted_length == 0) {
return std::string();
}
return utf8_string;
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef RUNNER_UTILS_H_
#define RUNNER_UTILS_H_
#include <string>
#include <vector>
// Creates a console for the process, and redirects stdout and stderr to
// it for both the runner and the Flutter library.
void CreateAndAttachConsole();
// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string
// encoded in UTF-8. Returns an empty std::string on failure.
std::string Utf8FromUtf16(const wchar_t* utf16_string);
// Gets the command line arguments passed in as a std::vector<std::string>,
// encoded in UTF-8. Returns an empty std::vector<std::string> on failure.
std::vector<std::string> GetCommandLineArguments();
#endif // RUNNER_UTILS_H_
+288
View File
@@ -0,0 +1,288 @@
#include "win32_window.h"
#include <dwmapi.h>
#include <flutter_windows.h>
#include "resource.h"
namespace {
/// Window attribute that enables dark mode window decorations.
///
/// Redefined in case the developer's machine has a Windows SDK older than
/// version 10.0.22000.0.
/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
#endif
constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW";
/// Registry key for app theme preference.
///
/// A value of 0 indicates apps should use dark mode. A non-zero or missing
/// value indicates apps should use light mode.
constexpr const wchar_t kGetPreferredBrightnessRegKey[] =
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme";
// The number of Win32Window objects that currently exist.
static int g_active_window_count = 0;
using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);
// Scale helper to convert logical scaler values to physical using passed in
// scale factor
int Scale(int source, double scale_factor) {
return static_cast<int>(source * scale_factor);
}
// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module.
// This API is only needed for PerMonitor V1 awareness mode.
void EnableFullDpiSupportIfAvailable(HWND hwnd) {
HMODULE user32_module = LoadLibraryA("User32.dll");
if (!user32_module) {
return;
}
auto enable_non_client_dpi_scaling =
reinterpret_cast<EnableNonClientDpiScaling*>(
GetProcAddress(user32_module, "EnableNonClientDpiScaling"));
if (enable_non_client_dpi_scaling != nullptr) {
enable_non_client_dpi_scaling(hwnd);
}
FreeLibrary(user32_module);
}
} // namespace
// Manages the Win32Window's window class registration.
class WindowClassRegistrar {
public:
~WindowClassRegistrar() = default;
// Returns the singleton registrar instance.
static WindowClassRegistrar* GetInstance() {
if (!instance_) {
instance_ = new WindowClassRegistrar();
}
return instance_;
}
// Returns the name of the window class, registering the class if it hasn't
// previously been registered.
const wchar_t* GetWindowClass();
// Unregisters the window class. Should only be called if there are no
// instances of the window.
void UnregisterWindowClass();
private:
WindowClassRegistrar() = default;
static WindowClassRegistrar* instance_;
bool class_registered_ = false;
};
WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr;
const wchar_t* WindowClassRegistrar::GetWindowClass() {
if (!class_registered_) {
WNDCLASS window_class{};
window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
window_class.lpszClassName = kWindowClassName;
window_class.style = CS_HREDRAW | CS_VREDRAW;
window_class.cbClsExtra = 0;
window_class.cbWndExtra = 0;
window_class.hInstance = GetModuleHandle(nullptr);
window_class.hIcon =
LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
window_class.hbrBackground = 0;
window_class.lpszMenuName = nullptr;
window_class.lpfnWndProc = Win32Window::WndProc;
RegisterClass(&window_class);
class_registered_ = true;
}
return kWindowClassName;
}
void WindowClassRegistrar::UnregisterWindowClass() {
UnregisterClass(kWindowClassName, nullptr);
class_registered_ = false;
}
Win32Window::Win32Window() {
++g_active_window_count;
}
Win32Window::~Win32Window() {
--g_active_window_count;
Destroy();
}
bool Win32Window::Create(const std::wstring& title,
const Point& origin,
const Size& size) {
Destroy();
const wchar_t* window_class =
WindowClassRegistrar::GetInstance()->GetWindowClass();
const POINT target_point = {static_cast<LONG>(origin.x),
static_cast<LONG>(origin.y)};
HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
double scale_factor = dpi / 96.0;
HWND window = CreateWindow(
window_class, title.c_str(), WS_OVERLAPPEDWINDOW,
Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
Scale(size.width, scale_factor), Scale(size.height, scale_factor),
nullptr, nullptr, GetModuleHandle(nullptr), this);
if (!window) {
return false;
}
UpdateTheme(window);
return OnCreate();
}
bool Win32Window::Show() {
return ShowWindow(window_handle_, SW_SHOWNORMAL);
}
// static
LRESULT CALLBACK Win32Window::WndProc(HWND const window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
if (message == WM_NCCREATE) {
auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);
SetWindowLongPtr(window, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));
auto that = static_cast<Win32Window*>(window_struct->lpCreateParams);
EnableFullDpiSupportIfAvailable(window);
that->window_handle_ = window;
} else if (Win32Window* that = GetThisFromHandle(window)) {
return that->MessageHandler(window, message, wparam, lparam);
}
return DefWindowProc(window, message, wparam, lparam);
}
LRESULT
Win32Window::MessageHandler(HWND hwnd,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
switch (message) {
case WM_DESTROY:
window_handle_ = nullptr;
Destroy();
if (quit_on_close_) {
PostQuitMessage(0);
}
return 0;
case WM_DPICHANGED: {
auto newRectSize = reinterpret_cast<RECT*>(lparam);
LONG newWidth = newRectSize->right - newRectSize->left;
LONG newHeight = newRectSize->bottom - newRectSize->top;
SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth,
newHeight, SWP_NOZORDER | SWP_NOACTIVATE);
return 0;
}
case WM_SIZE: {
RECT rect = GetClientArea();
if (child_content_ != nullptr) {
// Size and position the child window.
MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,
rect.bottom - rect.top, TRUE);
}
return 0;
}
case WM_ACTIVATE:
if (child_content_ != nullptr) {
SetFocus(child_content_);
}
return 0;
case WM_DWMCOLORIZATIONCOLORCHANGED:
UpdateTheme(hwnd);
return 0;
}
return DefWindowProc(window_handle_, message, wparam, lparam);
}
void Win32Window::Destroy() {
OnDestroy();
if (window_handle_) {
DestroyWindow(window_handle_);
window_handle_ = nullptr;
}
if (g_active_window_count == 0) {
WindowClassRegistrar::GetInstance()->UnregisterWindowClass();
}
}
Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {
return reinterpret_cast<Win32Window*>(
GetWindowLongPtr(window, GWLP_USERDATA));
}
void Win32Window::SetChildContent(HWND content) {
child_content_ = content;
SetParent(content, window_handle_);
RECT frame = GetClientArea();
MoveWindow(content, frame.left, frame.top, frame.right - frame.left,
frame.bottom - frame.top, true);
SetFocus(child_content_);
}
RECT Win32Window::GetClientArea() {
RECT frame;
GetClientRect(window_handle_, &frame);
return frame;
}
HWND Win32Window::GetHandle() {
return window_handle_;
}
void Win32Window::SetQuitOnClose(bool quit_on_close) {
quit_on_close_ = quit_on_close;
}
bool Win32Window::OnCreate() {
// No-op; provided for subclasses.
return true;
}
void Win32Window::OnDestroy() {
// No-op; provided for subclasses.
}
void Win32Window::UpdateTheme(HWND const window) {
DWORD light_mode;
DWORD light_mode_size = sizeof(light_mode);
LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,
kGetPreferredBrightnessRegValue,
RRF_RT_REG_DWORD, nullptr, &light_mode,
&light_mode_size);
if (result == ERROR_SUCCESS) {
BOOL enable_dark_mode = light_mode == 0;
DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE,
&enable_dark_mode, sizeof(enable_dark_mode));
}
}
+102
View File
@@ -0,0 +1,102 @@
#ifndef RUNNER_WIN32_WINDOW_H_
#define RUNNER_WIN32_WINDOW_H_
#include <windows.h>
#include <functional>
#include <memory>
#include <string>
// A class abstraction for a high DPI-aware Win32 Window. Intended to be
// inherited from by classes that wish to specialize with custom
// rendering and input handling
class Win32Window {
public:
struct Point {
unsigned int x;
unsigned int y;
Point(unsigned int x, unsigned int y) : x(x), y(y) {}
};
struct Size {
unsigned int width;
unsigned int height;
Size(unsigned int width, unsigned int height)
: width(width), height(height) {}
};
Win32Window();
virtual ~Win32Window();
// Creates a win32 window with |title| that is positioned and sized using
// |origin| and |size|. New windows are created on the default monitor. Window
// sizes are specified to the OS in physical pixels, hence to ensure a
// consistent size this function will scale the inputted width and height as
// as appropriate for the default monitor. The window is invisible until
// |Show| is called. Returns true if the window was created successfully.
bool Create(const std::wstring& title, const Point& origin, const Size& size);
// Show the current window. Returns true if the window was successfully shown.
bool Show();
// Release OS resources associated with window.
void Destroy();
// Inserts |content| into the window tree.
void SetChildContent(HWND content);
// Returns the backing Window handle to enable clients to set icon and other
// window properties. Returns nullptr if the window has been destroyed.
HWND GetHandle();
// If true, closing this window will quit the application.
void SetQuitOnClose(bool quit_on_close);
// Return a RECT representing the bounds of the current client area.
RECT GetClientArea();
protected:
// Processes and route salient window messages for mouse handling,
// size change and DPI. Delegates handling of these to member overloads that
// inheriting classes can handle.
virtual LRESULT MessageHandler(HWND window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept;
// Called when CreateAndShow is called, allowing subclass window-related
// setup. Subclasses should return false if setup fails.
virtual bool OnCreate();
// Called when Destroy is called.
virtual void OnDestroy();
private:
friend class WindowClassRegistrar;
// OS callback called by message pump. Handles the WM_NCCREATE message which
// is passed when the non-client area is being created and enables automatic
// non-client DPI scaling so that the non-client area automatically
// responds to changes in DPI. All other messages are handled by
// MessageHandler.
static LRESULT CALLBACK WndProc(HWND const window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept;
// Retrieves a class instance pointer for |window|
static Win32Window* GetThisFromHandle(HWND const window) noexcept;
// Update the window frame's theme to match the system theme.
static void UpdateTheme(HWND const window);
bool quit_on_close_ = false;
// window handle for top level window.
HWND window_handle_ = nullptr;
// window handle for hosted content.
HWND child_content_ = nullptr;
};
#endif // RUNNER_WIN32_WINDOW_H_
+86
View File
@@ -0,0 +1,86 @@
# 探测协议 NQ01
客户端和反射服务器使用同一套二进制格式。TCP 和 UDP 都用它。
- UDP:一个数据报就是一帧,长度必须刚好等于这一帧,多一个字节也会被丢掉。
- TCP:字节流里连续放多帧。没有额外的长度前缀,靠帧里的 `PayloadLen` 切分。
多字节整数都是小端(little-endian)。
## 帧布局
| 偏移 | 长度 | 字段 | 说明 |
| --- | --- | --- | --- |
| 0 | 4 | Magic | ASCII `NQ01` |
| 4 | 1 | Version | 目前只能是 `1` |
| 5 | 1 | Type | `1` 请求,`2` 应答 |
| 6 | 1 | Flags | 保留,发送 `0` |
| 7 | 1 | Reserved | `0` |
| 8 | 4 | Sequence | `uint32`,由客户端递增,到 `2^32-1` 后回到 0 |
| 12 | 8 | ClientSendUnixNano | `uint64`,客户端发送时的 Unix 纳秒时间 |
| 20 | 8 | ServerUnixNano | `uint64`,请求里填 0;服务器填收到该包的时间 |
| 28 | 32 | Token | UTF-8 口令,不足补 0。不用口令时 32 个 0 |
| 60 | 2 | PayloadLen | `uint16`,后面负载的字节数 |
| 62 | N | Payload | 原样回显。服务器拒绝大于 2048 的负载 |
固定头长度是 **62** 字节。
客户端建议把整帧控制在 1400 字节以内,这样 UDP 不会被 IP 分片。默认整帧 128 字节。
## 服务器怎么处理
1. 校验 Magic、Version,以及长度是否刚好一帧。
2. 只回答 `Type = 1` 的请求。
3. 如果启动时配置了口令,Token 必须完全一致(包含补 0)。不一致就丢弃,不回包。没配置口令则不检查。
4. 把 Type 改成 `2`,填上 `ServerUnixNano`,序号、客户端时间、口令和负载都原样返回。
应答长度和请求相同,所以这不是放大反射。
## 客户端怎么算指标
延迟不要用服务器时间来减,也不要用「手机收到这条结果的时刻」去减。远程探测时,往返时间在节点发出探测包的那一侧用单调时钟量好,再放进结果里。
- **合作反射 TCP / UDP**:写出一帧之后,超时内没有对上序号的回显,记为探测无应答。百分比的分母只算已经完成的回显尝试。还在路上的不计入。连接失败、连接超时和重连单独计数,不算进这个百分比。晚到的旧序号直接忽略。TCP 会重传,所以这不是物理丢包。
- **普通 TCP**:只记录连接耗时、成功或失败、连续失败。没有自定义帧。
- **普通 UDP、DNS、自定义 UDP、基岩版**:没有收到符合协议的包时记为无应答/未知,不叫丢包。内容不对记为协议错误。
- **Minecraft Java**:状态握手加上 ping/pong。往返时间只算 ping 到对上 nonce 的 pong。连不上或协议不对记为失败率。
- **抖动**:RFC 3550。相邻两次成功的往返时间差 `D`,`J = J + (|D| - J) / 16`。
## 控制接口
节点用 HTTP。`GET /v1/info` 不需要口令,只说明自己是公开还是私有、支持哪些类型、上限是多少,不返回任何口令。
其余接口在配置了 `-node-token` 时都要先带 `Authorization: Bearer`,用常数时间比较。没带或不对就返回 401,并且不会向目标拨号。没配置节点口令时,这些接口公开可用。
- `POST /v1/jobs` 创建一次探测。正文里的 `echoToken` 是反射帧口令,不是节点口令。
- `GET /v1/jobs/{id}/stream` 用 Server-Sent Events 推送已经在节点上算好的样本。
- `DELETE /v1/jobs/{id}` 停止。客户端断开结果流时,节点也会停止。任务有绝对到期时间,没人来看也会在大约 15 秒后停掉。
节点同时只跑有限个任务,并限制单次时长、最小间隔、每秒次数和带宽。默认不拨号到回环、私网、链路本地和云元数据;解析域名后还会检查真正要拨的地址,混有内网地址就拒绝。`-allow-private` 只放开你明确要测的局域网,元数据仍然禁止。
## 探测类型
| profile | 含义 |
| --- | --- |
| `nq-tcp` / `nq-udp` | 上面的 NQ01 帧 |
| `tcp-connect` | 只建立 TCP 连接 |
| `udp-generic` | 发出 UDP,没有协议应答就是未知 |
| `dns` | 标准查询,核对 ID 和应答标志 |
| `minecraft-java` | 状态握手(协议号 767)加 ping/pong |
| `minecraft-bedrock` | RakNet Unconnected Ping,magic 和时间戳都要对上 |
| `custom-udp` | 十六进制载荷,可选响应前缀 |
## 例子
请求:序号 1,客户端时间 1000 纳秒,无口令,负载 `01 02 03 04`。
```text
4e513031 01010000 01000000 e803000000000000
0000000000000000
0000000000000000000000000000000000000000000000000000000000000000
0400 01020304
```
上面第二行是 8 字节的服务器时间(请求里为 0),第三行是 32 字节口令。应答只是把 Type 改成 `02`,并填上服务器时间。
Go 和 Dart 的单元测试都锁了这组字节。实现另一套客户端时,先对上这组字节再谈连上服务器。
+207
View File
@@ -0,0 +1,207 @@
# 在 Linux 服务器上安装反射服务
反射服务是一个小程序。它不做账号、不存数据,只把探测包原样送回去。请装在你自己的机器上。
下面假设系统是 Ubuntu 或 Debian,已经能用 `sudo`。其他发行版把安装 Go 的那一步换成自己的包管理器即可。
## 1. 安装 Go
需要 Go 1.22 或更新的版本。
```bash
sudo apt update
sudo apt install -y golang-go
go version
```
如果发行版自带的 Go 太旧,到 [https://go.dev/dl/](https://go.dev/dl/) 下载官方包。
## 2. 编译并前台运行(先确认能通)
把本仓库的 `server` 目录拷到服务器,例如 `/opt/netquality/server`。在该目录执行:
```bash
cd /opt/netquality/server
go build -o netquality-reflector .
./netquality-reflector
```
默认监听:
- TCP `0.0.0.0:19090`
- UDP `0.0.0.0:19091`
看到两行 `listening` 就说明起来了。另开一个终端可以看端口:
```bash
ss -ltnp | grep 19090
ss -lunp | grep 19091
```
用 `Ctrl+C` 停止。确认客户端能连上之后,再做成开机自启。
常用参数:
```bash
./netquality-reflector -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091
./netquality-reflector -tcp-port 0 # 只开 UDP
./netquality-reflector -token '一段口令' # 口令最长 32 字节
./netquality-reflector -h
```
也可以用环境变量:`NQ_BIND`、`NQ_TCP_PORT`、`NQ_UDP_PORT`、`NQ_TOKEN`(回显口令)、`NQ_MODE`、`NQ_CONTROL_ADDR`、`NQ_NODE_TOKEN`(节点口令)、`NQ_ALLOW_PRIVATE`、`NQ_TLS_CERT`、`NQ_TLS_KEY`。
## 3. 做成系统服务
```bash
cd /opt/netquality/server
go build -o netquality-reflector .
sudo install -m 0755 netquality-reflector /usr/local/bin/netquality-reflector
sudo cp deploy/netquality-reflector.service /etc/systemd/system/netquality-reflector.service
sudo systemctl daemon-reload
sudo systemctl enable --now netquality-reflector
sudo systemctl status netquality-reflector
```
日志:
```bash
journalctl -u netquality-reflector -f
```
大约每分钟会打一行统计:收到多少请求、回了多少、拒绝了多少。
要加口令时,编辑服务文件,去掉 `NQ_TOKEN` 那一行的注释并写成你自己的口令,然后:
```bash
sudo systemctl daemon-reload
sudo systemctl restart netquality-reflector
```
App 里的「口令」必须和这里完全一致。口令是明文写在探测包里的,只能挡住无关的随机访问,不能当密码学上的加密。
## 4. 放行防火墙
只放行你实际使用的端口。
ufw:
```bash
sudo ufw allow 19090/tcp
sudo ufw allow 19091/udp
sudo ufw status
```
firewalld:
```bash
sudo firewall-cmd --permanent --add-port=19090/tcp
sudo firewall-cmd --permanent --add-port=19091/udp
sudo firewall-cmd --reload
```
如果服务器在阿里云、腾讯云、AWS 或其他云上,安全组里也要放行同样的端口。只放系统防火墙、不放安全组,外网还是连不上。
不需要的协议就不要放行。只想测 UDP 时,可以让服务以 `-tcp-port 0` 启动,并且只开放 UDP。
## 5. 让这台机器替手机去测别的目标
反射器只把自己收到的探测包送回去。如果手机要测的是别的业务端口,例如游戏服务器,应让这台机器作为节点去发包。手机只下指令、看结果。
同一个程序有三种模式:
```bash
./netquality-reflector -mode reflector
./netquality-reflector -mode node -control-addr 127.0.0.1:8443
./netquality-reflector -mode both -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091 -control-addr 127.0.0.1:8443
```
`both` 会同时提供反射和节点。控制地址默认只听本机,这样不会一启动就把探测能力暴露到公网。
### 公开节点
不设置 `-node-token` 就是公开节点。谁能访问控制端口,谁就能在上限内发起探测。程序会在日志里写一行警告。上限包括同时任务数、单次时长、最小间隔、每秒次数和带宽。这不是开放代理:默认不去拨本机、内网、链路本地和云元数据。
```bash
./netquality-reflector -mode node -control-addr 127.0.0.1:8443
```
### 私有节点
设置了节点口令以后,创建任务、看结果、看流、停止任务都会先校验。口令不对,不会向目标发包。把下面的占位文字换成你自己的口令,不要把真实口令发到聊天或提交到仓库。
```bash
./netquality-reflector -mode node -control-addr 127.0.0.1:8443 -node-token '换成你自己的节点口令'
```
`-token` 是另一回事,它写进反射帧,只在别人来连你的 19090/19091 时使用。App 里对应「目标回显口令」。节点口令对应「管理节点」里的那一栏。
要开机启动节点,可以用 `deploy/netquality-node.service`。编辑里面的环境变量注释,再:
```bash
sudo cp deploy/netquality-node.service /etc/systemd/system/netquality-node.service
sudo systemctl daemon-reload
sudo systemctl enable --now netquality-node
```
故意测机房局域网时加 `-allow-private`。云厂商的元数据地址即使加了这个参数也不会放行。
### HTTPS
控制通道会带节点口令,不要直接把明文 HTTP 暴露到公网。两种做法:
用程序自己的证书:
```bash
./netquality-reflector -mode node -control-addr 0.0.0.0:8443 -tls-cert /etc/netquality/fullchain.pem -tls-key /etc/netquality/privkey.pem -node-token '换成你自己的节点口令'
```
或让 Caddy / nginx 终止 HTTPS,再反代到 `127.0.0.1:8443`。Caddy 的站点可以写成:
```text
probe.example {
reverse_proxy 127.0.0.1:8443
}
```
防火墙和安全组只放行 443,不要把 8443 直接敞开。反射端口 19090/19091 仍然是普通 TCP/UDP,和这个 HTTPS 控制端口是分开的。
## 6. 在 App 里填写
本机直接测反射器:
- 来源:本机
- 目标:服务器的公网 IP 或域名,不要在手机上填 `127.0.0.1`
- 类型:合作反射 TCP 或 UDP
- 端口:`19090` 或 `19091`
- 目标回显口令:和服务器的 `-token` 相同;服务器没设就留空
让节点去测:
1. 来源选「远程节点」,点「管理节点」。
2. 地址填 `https://你的域名`(或你实际反代后的地址)。不要把口令写在地址里。
3. 节点口令:私有节点填写,公开节点留空。可以点「检查」,看到「公开」或「需要口令」。
4. 目标地址、端口、类型另填。例如 Minecraft Java 用游戏域名和 `25565`。
5. 点「开始探测」。延迟是节点到目标的时间。停止后节点会结束任务。
## 本机演示补充
在自己的电脑上同时开反射和节点,并允许它探测本机:
```bash
./netquality-reflector -mode both -bind 127.0.0.1 -tcp-port 19090 -udp-port 19091 -control-addr 127.0.0.1:8443 -allow-private
```
App 里添加节点 `http://127.0.0.1:8443`,口令留空,目标填 `127.0.0.1` 和对应端口。这只适合确认功能,不代表公网质量。
## 只开反射器的本机演示
不想先买服务器时,在自己的电脑上运行同一个程序即可:
```bash
cd server
go build -o netquality-reflector .
./netquality-reflector
```
App 保持默认的 `127.0.0.1`,直接点开始。这只能证明程序工作正常。延迟会接近 0,不代表宽带或移动网络的质量。
+1
View File
@@ -0,0 +1 @@
/netquality-reflector
+10
View File
@@ -0,0 +1,10 @@
.PHONY: build run test
build:
go build -o netquality-reflector .
run: build
./netquality-reflector
test:
go test ./...
+23
View File
@@ -0,0 +1,23 @@
[Unit]
Description=NetQuality probe node and reflector
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/local/bin/netquality-reflector -mode both -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091 -control-addr 127.0.0.1:8443
Restart=on-failure
RestartSec=2
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
# 二选一,不要把真实口令提交到仓库。
# 留空或不设置 NQ_NODE_TOKEN:公开节点,任何人都能用,但有并发和时长上限。
# Environment=NQ_NODE_TOKEN=replace-with-your-own-node-token
# 下面这个是反射帧里的回显口令,和节点口令不是同一个。
# Environment=NQ_TOKEN=replace-with-your-own-echo-token
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,20 @@
[Unit]
Description=NetQuality UDP/TCP reflector
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/local/bin/netquality-reflector -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091
Restart=on-failure
RestartSec=2
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
# Optional shared token. Uncomment and set a short passphrase (max 32 bytes).
# Environment=NQ_TOKEN=replace-me
[Install]
WantedBy=multi-user.target
+205
View File
@@ -0,0 +1,205 @@
package main
import (
"bufio"
"errors"
"io"
"log"
"net"
"sync"
"sync/atomic"
"time"
)
// Server is a TCP and UDP echo reflector for probe frames.
type Server struct {
Token [tokenLen]byte
Required bool
Verbose bool
requests atomic.Uint64
replies atomic.Uint64
rejected atomic.Uint64
lisMu sync.Mutex
tcpListener net.Listener
udpConn *net.UDPConn
wg sync.WaitGroup
}
// HandlePacket validates a request and returns the reply bytes.
// Invalid packets return ok=false and are not answered.
func (s *Server) HandlePacket(p Packet, now time.Time) ([]byte, bool) {
s.requests.Add(1)
if p.Type != typeRequest || p.Version != protocolVer {
s.rejected.Add(1)
return nil, false
}
if !tokenMatches(p.Token, s.Token, s.Required) {
s.rejected.Add(1)
if s.Verbose {
log.Printf("reject seq=%d: token mismatch", p.Sequence)
}
return nil, false
}
p.Type = typeReply
p.ServerUnixNano = uint64(now.UnixNano())
buf, err := p.Marshal()
if err != nil {
s.rejected.Add(1)
return nil, false
}
s.replies.Add(1)
if s.Verbose {
log.Printf("echo seq=%d bytes=%d", p.Sequence, len(buf))
}
return buf, true
}
func (s *Server) Stats() (requests, replies, rejected uint64) {
return s.requests.Load(), s.replies.Load(), s.rejected.Load()
}
// ServeTCP accepts connections until the listener is closed.
func (s *Server) ServeTCP(ln net.Listener) {
s.lisMu.Lock()
s.tcpListener = ln
s.lisMu.Unlock()
for {
conn, err := ln.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
log.Printf("tcp accept: %v", err)
continue
}
s.wg.Add(1)
go func() {
defer s.wg.Done()
s.handleTCPConn(conn)
}()
}
}
func (s *Server) handleTCPConn(conn net.Conn) {
defer conn.Close()
if tc, ok := conn.(*net.TCPConn); ok {
// Go already defaults NoDelay to true; keep it explicit so echoes are
// not held by Nagle and RTT stays honest.
_ = tc.SetNoDelay(true)
_ = tc.SetKeepAlive(true)
_ = tc.SetKeepAlivePeriod(30 * time.Second)
}
remote := conn.RemoteAddr().String()
if s.Verbose {
log.Printf("tcp connected %s", remote)
}
r := bufio.NewReaderSize(conn, headerSize+maxPayloadSize)
for {
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
pkt, err := readFrame(r)
if err != nil {
if !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) && s.Verbose {
log.Printf("tcp %s read: %v", remote, err)
}
return
}
reply, ok := s.HandlePacket(pkt, time.Now())
if !ok {
continue
}
_ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
if _, err := conn.Write(reply); err != nil {
if s.Verbose {
log.Printf("tcp %s write: %v", remote, err)
}
return
}
}
}
// readFrame reads exactly one frame from a TCP stream.
func readFrame(r *bufio.Reader) (Packet, error) {
hdr := make([]byte, headerSize)
if _, err := io.ReadFull(r, hdr); err != nil {
return Packet{}, err
}
if string(hdr[0:4]) != magic {
return Packet{}, errBadMagic
}
if hdr[4] != protocolVer {
return Packet{}, errBadVersion
}
payloadLen := int(binaryUint16(hdr[payloadLenOff : payloadLenOff+2]))
if payloadLen > maxPayloadSize {
return Packet{}, errBadPayloadLen
}
buf := make([]byte, headerSize+payloadLen)
copy(buf, hdr)
if payloadLen > 0 {
if _, err := io.ReadFull(r, buf[headerSize:]); err != nil {
return Packet{}, err
}
}
return ParsePacket(buf)
}
func binaryUint16(b []byte) uint16 {
return uint16(b[0]) | uint16(b[1])<<8
}
// ServeUDP reads datagrams until the socket is closed.
func (s *Server) ServeUDP(conn *net.UDPConn) {
s.lisMu.Lock()
s.udpConn = conn
s.lisMu.Unlock()
buf := make([]byte, headerSize+maxPayloadSize+64)
for {
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Minute))
n, addr, err := conn.ReadFromUDP(buf)
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
var ne net.Error
if errors.As(err, &ne) && ne.Timeout() {
continue
}
log.Printf("udp read: %v", err)
continue
}
pkt, err := ParsePacket(buf[:n])
if err != nil {
s.requests.Add(1)
s.rejected.Add(1)
if s.Verbose {
log.Printf("udp %s bad packet: %v", addr, err)
}
continue
}
reply, ok := s.HandlePacket(pkt, time.Now())
if !ok {
continue
}
_ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
if _, err := conn.WriteToUDP(reply, addr); err != nil && s.Verbose {
log.Printf("udp %s write: %v", addr, err)
}
}
}
// Close stops listeners. Existing TCP handlers exit on their next I/O error.
func (s *Server) Close() {
s.lisMu.Lock()
tcp := s.tcpListener
udp := s.udpConn
s.lisMu.Unlock()
if tcp != nil {
_ = tcp.Close()
}
if udp != nil {
_ = udp.Close()
}
}
+3
View File
@@ -0,0 +1,3 @@
module netquality/server
go 1.22
+250
View File
@@ -0,0 +1,250 @@
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
)
func main() {
bind := flag.String("bind", envStr("NQ_BIND", "0.0.0.0"), "reflector bind address")
tcpPort := flag.Int("tcp-port", envInt("NQ_TCP_PORT", 19090), "TCP echo port (0 disables)")
udpPort := flag.Int("udp-port", envInt("NQ_UDP_PORT", 19091), "UDP echo port (0 disables)")
tokenFlag := flag.String("token", envStr("NQ_TOKEN", ""), "optional echo token written into NQ frames, max 32 bytes; empty accepts any echo token")
nodeToken := flag.String("node-token", envStr("NQ_NODE_TOKEN", ""), "optional control-plane token; empty makes the node public")
mode := flag.String("mode", envStr("NQ_MODE", "reflector"), "reflector, node, or both")
controlAddr := flag.String("control-addr", envStr("NQ_CONTROL_ADDR", "127.0.0.1:8443"), "node control listen address")
allowPrivate := flag.Bool("allow-private", envBool("NQ_ALLOW_PRIVATE", false), "let the node probe loopback and private addresses (metadata stays blocked)")
allowNets := flag.String("allow-nets", envStr("NQ_ALLOW_NETS", ""), "comma-separated extra CIDRs the node may probe")
tlsCert := flag.String("tls-cert", envStr("NQ_TLS_CERT", ""), "TLS certificate for the control API")
tlsKey := flag.String("tls-key", envStr("NQ_TLS_KEY", ""), "TLS private key for the control API")
verbose := flag.Bool("v", false, "log each echoed packet")
flag.Parse()
switch *mode {
case "reflector", "node", "both":
default:
log.Fatal("-mode must be reflector, node, or both")
}
if *tcpPort < 0 || *tcpPort > 65535 || *udpPort < 0 || *udpPort > 65535 {
log.Fatal("ports must be between 0 and 65535")
}
if (*mode == "reflector" || *mode == "both") && *tcpPort == 0 && *udpPort == 0 {
log.Fatal("reflector mode needs -tcp-port and/or -udp-port")
}
if (*tlsCert == "") != (*tlsKey == "") {
log.Fatal("-tls-cert and -tls-key must be set together")
}
tok, err := tokenBytes(*tokenFlag)
if err != nil {
log.Fatal(err)
}
extra, err := parseNets(*allowNets)
if err != nil {
log.Fatal(err)
}
errCh := make(chan error, 4)
var srv *Server
if *mode == "reflector" || *mode == "both" {
srv = &Server{Token: tok, Required: *tokenFlag != "", Verbose: *verbose}
startReflector(srv, *bind, *tcpPort, *udpPort, errCh)
if srv.Required {
log.Printf("echo token check enabled")
} else {
log.Printf("echo token check disabled")
}
}
var httpSrv *http.Server
if *mode == "node" || *mode == "both" {
node := newNode(*nodeToken, *allowPrivate, extra, defaultLimits())
httpSrv = &http.Server{
Addr: *controlAddr,
Handler: node.Handler(),
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 2 * time.Minute,
}
ln, err := net.Listen("tcp", *controlAddr)
if err != nil {
log.Fatalf("control listen %s: %v", *controlAddr, err)
}
go func() {
var serveErr error
if *tlsCert != "" {
log.Printf("node control listening with TLS on %s", ln.Addr())
serveErr = httpSrv.ServeTLS(ln, *tlsCert, *tlsKey)
} else {
log.Printf("node control listening on %s (no TLS; put an HTTPS reverse proxy in front if this is reachable from the internet)", ln.Addr())
serveErr = httpSrv.Serve(ln)
}
if serveErr != nil && serveErr != http.ErrServerClosed {
errCh <- serveErr
}
}()
if node.Public() && !loopbackHost(*controlAddr) {
log.Printf("WARNING: this node is PUBLIC. Anyone who can reach %s can start bounded probes. Set -node-token to require a control token. Caps stay on: jobs=%d duration=%s interval>=%s probes/s=%d bandwidth=%dB/s",
*controlAddr, node.Limits.MaxJobs, node.Limits.MaxDuration, node.Limits.MinInterval, node.Limits.MaxProbePerSec, node.Limits.MaxBytesPerSec)
} else if node.Public() {
log.Printf("node is public and bound to loopback; no control token is required")
} else {
log.Printf("node is private; a control token is required and is not logged")
}
if *allowPrivate {
log.Printf("private and loopback targets are allowed; metadata addresses stay blocked")
}
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
ticker := time.NewTicker(60 * time.Second)
defer ticker.Stop()
for {
select {
case <-sig:
log.Printf("shutting down")
if srv != nil {
srv.Close()
}
if httpSrv != nil {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
_ = httpSrv.Shutdown(ctx)
cancel()
}
return
case err := <-errCh:
log.Printf("listener stopped: %v", err)
if srv != nil {
srv.Close()
}
if httpSrv != nil {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
_ = httpSrv.Shutdown(ctx)
cancel()
}
os.Exit(1)
case <-ticker.C:
if srv != nil {
req, rep, rej := srv.Stats()
log.Printf("stats requests=%d replies=%d rejected=%d", req, rep, rej)
}
}
}
}
func startReflector(srv *Server, bind string, tcpPort, udpPort int, errCh chan error) {
if tcpPort > 0 {
addr := net.JoinHostPort(bind, strconv.Itoa(tcpPort))
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Fatalf("tcp listen %s: %v", addr, err)
}
log.Printf("TCP reflector listening on %s", ln.Addr())
go func() {
srv.ServeTCP(ln)
errCh <- fmt.Errorf("tcp listener closed")
}()
}
if udpPort > 0 {
addr := net.JoinHostPort(bind, strconv.Itoa(udpPort))
udpAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
log.Fatalf("udp resolve %s: %v", addr, err)
}
conn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
log.Fatalf("udp listen %s: %v", addr, err)
}
log.Printf("UDP reflector listening on %s", conn.LocalAddr())
go func() {
srv.ServeUDP(conn)
errCh <- fmt.Errorf("udp listener closed")
}()
}
}
func parseNets(s string) ([]*net.IPNet, error) {
s = strings.TrimSpace(s)
if s == "" {
return nil, nil
}
var out []*net.IPNet
for _, part := range strings.Split(s, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
if !strings.Contains(part, "/") {
ip := net.ParseIP(part)
if ip == nil {
return nil, fmt.Errorf("bad allow entry %q", part)
}
bits := 32
if ip.To4() == nil {
bits = 128
}
part = ip.String() + "/" + strconv.Itoa(bits)
}
_, n, err := net.ParseCIDR(part)
if err != nil {
return nil, fmt.Errorf("bad allow entry %q: %w", part, err)
}
out = append(out, n)
}
return out, nil
}
func loopbackHost(addr string) bool {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return false
}
host = strings.Trim(host, "[]")
ip := net.ParseIP(host)
return ip != nil && ip.IsLoopback()
}
func envStr(key, fallback string) string {
if v, ok := os.LookupEnv(key); ok && v != "" {
return v
}
return fallback
}
func envInt(key string, fallback int) int {
v, ok := os.LookupEnv(key)
if !ok || v == "" {
return fallback
}
n, err := strconv.Atoi(v)
if err != nil {
return fallback
}
return n
}
func envBool(key string, fallback bool) bool {
v, ok := os.LookupEnv(key)
if !ok || v == "" {
return fallback
}
switch strings.ToLower(v) {
case "1", "true", "yes", "on":
return true
case "0", "false", "no", "off":
return false
default:
return fallback
}
}
+202
View File
@@ -0,0 +1,202 @@
package main
import "time"
const (
statusOK = "ok"
statusTimeout = "timeout"
statusUnknown = "unknown"
statusRefused = "refused"
statusDNS = "dns"
statusProtocol = "protocol"
statusError = "error"
kindConnect = "connect"
kindProbe = "probe"
kindQuery = "query"
)
// 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.
type Outcome struct {
Status string
Kind string
Rtt time.Duration
HasRtt bool
Note string
Detail map[string]string
Reconnect bool
}
type jitter struct {
has bool
last float64
value float64
}
func (j *jitter) push(rttMs float64) float64 {
if j.has {
d := rttMs - j.last
if d < 0 {
d = -d
}
j.value += (d - j.value) / 16
}
j.last = rttMs
j.has = true
return j.value
}
// sampleBook folds finished outcomes. Rates use only completed attempts.
// "unknown" (no protocol reply) is not counted as proven packet loss.
type sampleBook struct {
profile string
sent int
completed int
ok int
timeout int
unknown int
refused int
dns int
protocol int
other int
reconnect int
consecutive int
lastRttMs *float64
jitter jitter
lastNote string
detail map[string]string
}
func (b *sampleBook) add(o Outcome) {
b.sent++
b.completed++
if o.Reconnect {
b.reconnect++
}
if o.Note != "" {
b.lastNote = o.Note
}
if len(o.Detail) > 0 {
if b.detail == nil {
b.detail = map[string]string{}
}
for k, v := range o.Detail {
b.detail[k] = v
}
}
switch o.Status {
case statusOK:
b.ok++
b.consecutive = 0
if o.HasRtt {
ms := float64(o.Rtt) / float64(time.Millisecond)
b.lastRttMs = &ms
b.jitter.push(ms)
}
case statusTimeout:
// Only a written NQ probe that never returned is probe-response loss.
// A TCP connect timeout is a failed attempt, not a lost echo.
if o.Kind == kindProbe {
b.timeout++
} else {
b.other++
}
b.consecutive++
case statusUnknown:
b.unknown++
case statusRefused:
b.refused++
b.consecutive++
case statusDNS:
b.dns++
b.consecutive++
case statusProtocol:
b.protocol++
b.consecutive++
default:
b.other++
b.consecutive++
}
}
func (b *sampleBook) summary() summaryMsg {
s := summaryMsg{
Sent: b.sent,
Pending: 0,
Completed: b.completed,
OK: b.ok,
Timeout: b.timeout,
Unknown: b.unknown,
Refused: b.refused,
DNS: b.dns,
Protocol: b.protocol,
Other: b.other,
Reconnects: b.reconnect,
ConsecutiveFailures: b.consecutive,
LastNote: b.lastNote,
Detail: b.detail,
}
if b.lastRttMs != nil {
v := *b.lastRttMs
s.RttMs = &v
}
if b.jitter.has {
v := b.jitter.value
s.JitterMs = &v
}
if b.completed == 0 {
return s
}
switch b.profile {
case "nq-tcp", "nq-udp":
// Echo was requested and did not come back. This is probe-response
// loss, not a NIC packet-loss counter. TCP timeouts still land here
// only after a frame was written; connect failures use other statuses.
if b.timeout+b.ok > 0 {
v := float64(b.timeout) * 100 / float64(b.timeout+b.ok)
s.ProbeLossPct = &v
}
case "tcp-connect", "minecraft-java":
denom := b.ok + b.timeout + b.refused + b.dns + b.protocol + b.other
if denom > 0 {
v := float64(denom-b.ok) * 100 / float64(denom)
s.FailurePct = &v
}
default:
denom := b.ok + b.protocol + b.refused + b.dns + b.other
if denom > 0 {
v := float64(denom-b.ok) * 100 / float64(denom)
s.FailurePct = &v
}
if b.unknown+b.ok+b.protocol > 0 {
v := float64(b.unknown) * 100 / float64(b.completed)
s.UnknownPct = &v
}
}
return s
}
type summaryMsg struct {
Sent int `json:"sent"`
Pending int `json:"pending"`
Completed int `json:"completed"`
OK int `json:"ok"`
Timeout int `json:"timeout"`
Unknown int `json:"unknown"`
Refused int `json:"refused"`
DNS int `json:"dns"`
Protocol int `json:"protocol"`
Other int `json:"other"`
Reconnects int `json:"reconnects"`
ConsecutiveFailures int `json:"consecutiveFailures"`
RttMs *float64 `json:"rttMs,omitempty"`
JitterMs *float64 `json:"jitterMs,omitempty"`
ProbeLossPct *float64 `json:"probeLossPct,omitempty"`
FailurePct *float64 `json:"failurePct,omitempty"`
UnknownPct *float64 `json:"unknownPct,omitempty"`
LastNote string `json:"lastNote,omitempty"`
Detail map[string]string `json:"detail,omitempty"`
}
+568
View File
@@ -0,0 +1,568 @@
package main
import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strings"
"sync"
"time"
)
type jobSpec struct {
Host string
Port int
Profile string
IP net.IP
Interval time.Duration
Timeout time.Duration
Duration time.Duration
PacketSize int
Echo [tokenLen]byte
DNSName string
Payload []byte
Expect []byte
}
type Limits struct {
MaxJobs int
MaxDuration time.Duration
MinInterval time.Duration
MaxProbePerSec int
MaxBytesPerSec int
MaxPacket int
}
func defaultLimits() Limits {
return Limits{
MaxJobs: 4,
MaxDuration: 120 * time.Second,
MinInterval: 200 * time.Millisecond,
MaxProbePerSec: 20,
MaxBytesPerSec: 256 * 1024,
MaxPacket: 1400,
}
}
type sampleMsg struct {
Seq int `json:"seq"`
Status string `json:"status"`
Kind string `json:"kind"`
RttMs *float64 `json:"rttMs,omitempty"`
JitterMs *float64 `json:"jitterMs,omitempty"`
Note string `json:"note,omitempty"`
Detail map[string]string `json:"detail,omitempty"`
Summary summaryMsg `json:"summary"`
}
type Node struct {
Token string
AllowPrivate bool
ExtraNets []*net.IPNet
Limits Limits
Resolver resolver
mu sync.Mutex
jobs map[string]*probeJob
sem chan struct{}
pace *paced
}
func newNode(token string, allowPrivate bool, extra []*net.IPNet, limits Limits) *Node {
if limits.MaxJobs <= 0 {
limits = defaultLimits()
}
n := &Node{
Token: token,
AllowPrivate: allowPrivate,
ExtraNets: extra,
Limits: limits,
jobs: map[string]*probeJob{},
sem: make(chan struct{}, limits.MaxJobs),
pace: newPaced(limits.MaxProbePerSec, limits.MaxBytesPerSec),
}
go n.reap()
return n
}
func (n *Node) Public() bool { return n.Token == "" }
func (n *Node) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/info", n.info)
mux.HandleFunc("POST /v1/jobs", n.auth(n.create))
mux.HandleFunc("GET /v1/jobs/{id}", n.auth(n.snapshot))
mux.HandleFunc("GET /v1/jobs/{id}/stream", n.auth(n.stream))
mux.HandleFunc("DELETE /v1/jobs/{id}", n.auth(n.remove))
return mux
}
func (n *Node) info(w http.ResponseWriter, _ *http.Request) {
vis := "private"
if n.Public() {
vis = "public"
}
writeJSON(w, http.StatusOK, map[string]any{
"visibility": vis,
"authRequired": !n.Public(),
"profiles": []string{
"nq-tcp", "nq-udp", "tcp-connect", "udp-generic", "dns",
"minecraft-java", "minecraft-bedrock", "custom-udp",
},
"limits": map[string]int{
"maxJobs": n.Limits.MaxJobs,
"maxDurationSec": int(n.Limits.MaxDuration / time.Second),
"minIntervalMs": int(n.Limits.MinInterval / time.Millisecond),
"maxPacketBytes": n.Limits.MaxPacket,
"maxBytesPerSec": n.Limits.MaxBytesPerSec,
"maxProbePerSec": n.Limits.MaxProbePerSec,
},
})
}
func (n *Node) auth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if n.Token == "" {
next(w, r)
return
}
got := bearer(r.Header.Get("Authorization"))
if got == "" || subtle.ConstantTimeCompare([]byte(got), []byte(n.Token)) != 1 {
writeErr(w, http.StatusUnauthorized, "unauthorized", "节点口令不正确或未提供")
return
}
next(w, r)
}
}
type createReq struct {
Target string `json:"target"`
Port int `json:"port"`
Profile string `json:"profile"`
IntervalMs int `json:"intervalMs"`
TimeoutMs int `json:"timeoutMs"`
DurationSec int `json:"durationSec"`
PacketSize int `json:"packetSize"`
EchoToken string `json:"echoToken"`
DNSName string `json:"dnsName"`
PayloadHex string `json:"payloadHex"`
ExpectHex string `json:"expectHex"`
}
func (n *Node) create(w http.ResponseWriter, r *http.Request) {
var req createReq
dec := json.NewDecoder(io.LimitReader(r.Body, 1<<16))
if err := dec.Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, "bad_request", "请求内容无法解析")
return
}
spec, err := n.prepare(r.Context(), req)
if err != nil {
var ae *apiError
if errors.As(err, &ae) {
writeErr(w, ae.status, ae.code, ae.msg)
return
}
writeErr(w, http.StatusBadRequest, "bad_request", "无法创建探测任务")
return
}
select {
case n.sem <- struct{}{}:
default:
writeErr(w, http.StatusTooManyRequests, "busy", "节点同时探测的任务已达上限")
return
}
job, err := n.start(spec)
if err != nil {
<-n.sem
writeErr(w, http.StatusInternalServerError, "error", "任务没有启动")
return
}
writeJSON(w, http.StatusCreated, map[string]any{
"jobId": job.id,
"expiresAt": job.expires.UTC().Format(time.RFC3339),
"visibility": map[bool]string{true: "public", false: "private"}[n.Public()],
})
}
func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
switch req.Profile {
case "nq-tcp", "nq-udp", "tcp-connect", "udp-generic", "dns", "minecraft-java", "minecraft-bedrock", "custom-udp":
default:
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", "不支持的探测类型"}
}
if req.Port < 1 || req.Port > 65535 {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_port", "端口需要在 1 到 65535 之间"}
}
interval := time.Duration(req.IntervalMs) * time.Millisecond
if req.IntervalMs == 0 {
interval = 500 * time.Millisecond
}
if interval < n.Limits.MinInterval || interval > 30*time.Second {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_interval", "发送间隔超出节点允许的范围"}
}
timeout := time.Duration(req.TimeoutMs) * time.Millisecond
if req.TimeoutMs == 0 {
timeout = 1500 * time.Millisecond
}
if timeout < 100*time.Millisecond || timeout > 15*time.Second {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_timeout", "超时超出节点允许的范围"}
}
duration := time.Duration(req.DurationSec) * time.Second
if req.DurationSec == 0 {
duration = 60 * time.Second
}
if duration < time.Second || duration > n.Limits.MaxDuration {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_duration", "探测时长超出节点允许的范围"}
}
size := req.PacketSize
if size == 0 {
size = 128
}
if size > n.Limits.MaxPacket {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_size", "报文超过节点允许的大小"}
}
echo, err := tokenBytes(req.EchoToken)
if err != nil {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_token", "目标回显口令最长 32 字节"}
}
var payload, expect []byte
if req.Profile == "custom-udp" {
payload, err = decodeHex(req.PayloadHex)
if err != nil || len(payload) == 0 || len(payload) > n.Limits.MaxPacket {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_payload", "自定义载荷需要是不超过上限的十六进制"}
}
if req.ExpectHex != "" {
expect, err = decodeHex(req.ExpectHex)
if err != nil {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_payload", "预期响应需要是十六进制"}
}
}
}
ip, err := targetOK(ctx, n.Resolver, req.Target, n.AllowPrivate, n.ExtraNets)
if err != nil {
var dnsErr *net.DNSError
if errors.As(err, &dnsErr) {
return jobSpec{}, &apiError{http.StatusBadRequest, "dns", "域名无法解析"}
}
if errors.Is(err, errForbiddenTarget) {
return jobSpec{}, &apiError{http.StatusForbidden, "forbidden_target", "远程节点默认不探测本机、内网、链路本地或云元数据地址。管理员开放局域网后才能测这些地址"}
}
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", "目标地址无效"}
}
return jobSpec{
Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ip,
Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size,
Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect,
}, nil
}
func (n *Node) start(spec jobSpec) (*probeJob, error) {
p, err := newProber(spec)
if err != nil {
return nil, err
}
id, err := newID()
if err != nil {
_ = p.Close()
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), spec.Duration)
job := &probeJob{
id: id,
expires: time.Now().Add(spec.Duration),
cancel: cancel,
events: make(chan sampleMsg, 64),
attach: make(chan struct{}),
done: make(chan struct{}),
}
n.mu.Lock()
n.jobs[id] = job
n.mu.Unlock()
go n.run(ctx, job, spec, p)
go n.attachDeadline(job)
return job, nil
}
func (n *Node) attachDeadline(job *probeJob) {
select {
case <-job.attach:
case <-job.done:
case <-time.After(15 * time.Second):
n.Stop(job.id)
}
}
func (n *Node) run(ctx context.Context, job *probeJob, spec jobSpec, p prober) {
defer func() {
_ = p.Close()
job.finish()
n.mu.Lock()
delete(n.jobs, job.id)
n.mu.Unlock()
<-n.sem
}()
book := &sampleBook{profile: spec.Profile}
seq := 0
emit := func(o Outcome) {
book.add(o)
seq++
msg := sampleMsg{
Seq: seq, Status: o.Status, Kind: o.Kind, Note: o.Note,
Detail: o.Detail, Summary: book.summary(),
}
if o.HasRtt {
ms := float64(o.Rtt) / float64(time.Millisecond)
msg.RttMs = &ms
}
if book.jitter.has && o.Status == statusOK {
v := book.jitter.value
msg.JitterMs = &v
}
job.mu.Lock()
job.last = msg
job.mu.Unlock()
select {
case job.events <- msg:
case <-ctx.Done():
}
}
for {
if err := n.pace.wait(ctx, spec.PacketSize); err != nil {
return
}
started := time.Now()
pctx, cancel := context.WithTimeout(ctx, spec.Timeout)
out := p.Probe(pctx)
cancel()
if ctx.Err() != nil {
return
}
emit(out)
wait := spec.Interval - time.Since(started)
if wait < 0 {
wait = 0
}
timer := time.NewTimer(wait)
select {
case <-ctx.Done():
timer.Stop()
return
case <-timer.C:
}
}
}
func (n *Node) snapshot(w http.ResponseWriter, r *http.Request) {
job := n.get(r.PathValue("id"))
if job == nil {
writeErr(w, http.StatusNotFound, "not_found", "任务不存在或已结束")
return
}
job.mu.Lock()
last := job.last
job.mu.Unlock()
if last.Seq == 0 && last.Status == "" {
last = sampleMsg{Status: "pending", Summary: summaryMsg{Pending: 1}}
}
writeJSON(w, http.StatusOK, last)
}
func (n *Node) stream(w http.ResponseWriter, r *http.Request) {
job := n.get(r.PathValue("id"))
if job == nil {
writeErr(w, http.StatusNotFound, "not_found", "任务不存在或已结束")
return
}
flusher, ok := w.(http.Flusher)
if !ok {
writeErr(w, http.StatusInternalServerError, "error", "服务器不支持流式输出")
return
}
job.attachOnce.Do(func() { close(job.attach) })
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("X-Accel-Buffering", "no")
defer n.Stop(job.id)
for {
select {
case <-r.Context().Done():
return
case msg, open := <-job.events:
if !open {
fmt.Fprintf(w, "event: end\ndata: {}\n\n")
flusher.Flush()
return
}
raw, _ := json.Marshal(msg)
fmt.Fprintf(w, "event: sample\ndata: %s\n\n", raw)
flusher.Flush()
}
}
}
func (n *Node) remove(w http.ResponseWriter, r *http.Request) {
if !n.Stop(r.PathValue("id")) {
writeErr(w, http.StatusNotFound, "not_found", "任务不存在或已结束")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (n *Node) get(id string) *probeJob {
n.mu.Lock()
defer n.mu.Unlock()
return n.jobs[id]
}
func (n *Node) Stop(id string) bool {
n.mu.Lock()
job := n.jobs[id]
n.mu.Unlock()
if job == nil {
return false
}
job.cancel()
return true
}
func (n *Node) reap() {
t := time.NewTicker(time.Second)
defer t.Stop()
for range t.C {
now := time.Now()
n.mu.Lock()
var expired []string
for id, job := range n.jobs {
if now.After(job.expires) {
expired = append(expired, id)
}
}
n.mu.Unlock()
for _, id := range expired {
n.Stop(id)
}
}
}
func (n *Node) jobCount() int {
n.mu.Lock()
defer n.mu.Unlock()
return len(n.jobs)
}
type probeJob struct {
id string
expires time.Time
cancel context.CancelFunc
events chan sampleMsg
attach chan struct{}
attachOnce sync.Once
mu sync.Mutex
last sampleMsg
once sync.Once
done chan struct{}
}
func (j *probeJob) finish() {
j.once.Do(func() {
close(j.events)
close(j.done)
})
}
func newID() (string, error) {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return hex.EncodeToString(b[:]), nil
}
func bearer(h string) string {
const p = "Bearer "
if len(h) < len(p) || !strings.EqualFold(h[:len(p)], p) {
return ""
}
return strings.TrimSpace(h[len(p):])
}
func decodeHex(s string) ([]byte, error) {
s = strings.TrimSpace(s)
s = strings.ReplaceAll(s, " ", "")
if len(s)%2 == 1 {
return nil, errors.New("odd hex")
}
return hex.DecodeString(s)
}
type apiError struct {
status int
code string
msg string
}
func (e *apiError) Error() string { return e.msg }
func writeErr(w http.ResponseWriter, status int, code, msg string) {
writeJSON(w, status, map[string]string{"error": code, "message": msg})
}
func writeJSON(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
}
type paced struct {
mu sync.Mutex
probes int
bytes int
window time.Time
maxProbe int
maxBytes int
}
func newPaced(maxProbe, maxBytes int) *paced {
return &paced{maxProbe: maxProbe, maxBytes: maxBytes, window: time.Now()}
}
func (p *paced) wait(ctx context.Context, packet int) error {
if packet < 1 {
packet = 1
}
for {
p.mu.Lock()
now := time.Now()
if now.Sub(p.window) >= time.Second {
p.window = now
p.probes = 0
p.bytes = 0
}
if p.probes < p.maxProbe && p.bytes+packet <= p.maxBytes {
p.probes++
p.bytes += packet
p.mu.Unlock()
return nil
}
wait := time.Second - now.Sub(p.window)
p.mu.Unlock()
if wait < 10*time.Millisecond {
wait = 10 * time.Millisecond
}
timer := time.NewTimer(wait)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
}
+587
View File
@@ -0,0 +1,587 @@
package main
import (
"bufio"
"context"
"encoding/binary"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestSafetyBlocksPrivateAndMetadata(t *testing.T) {
ctx := context.Background()
cases := []string{"127.0.0.1", "10.1.2.3", "192.168.1.1", "169.254.169.254", "169.254.1.1", "::1", "metadata.google.internal", "localhost"}
for _, host := range cases {
if _, err := targetOK(ctx, nil, host, false, nil); !errors.Is(err, errForbiddenTarget) {
t.Fatalf("%s: got %v", host, err)
}
}
if _, err := targetOK(ctx, nil, "169.254.169.254", true, nil); !errors.Is(err, errForbiddenTarget) {
t.Fatalf("metadata must stay blocked with allow-private: %v", err)
}
if _, err := targetOK(ctx, nil, "127.0.0.1", true, nil); err != nil {
t.Fatal(err)
}
_, n, _ := net.ParseCIDR("10.1.2.0/24")
ip, err := targetOK(ctx, nil, "10.1.2.9", false, []*net.IPNet{n})
if err != nil || !ip.Equal(net.ParseIP("10.1.2.9")) {
t.Fatalf("allow net: %v %v", ip, err)
}
_, err = targetOK(ctx, nil, "10.9.9.9", false, []*net.IPNet{n})
if !errors.Is(err, errForbiddenTarget) {
t.Fatalf("outside allow net: %v", err)
}
if _, err := targetOK(ctx, nil, "1.1.1.1", false, nil); err != nil {
t.Fatal(err)
}
rebinding := stubResolver{[]net.IP{net.ParseIP("1.1.1.1"), net.ParseIP("10.0.0.1")}}
if _, err := targetOK(ctx, rebinding, "example.com", false, nil); !errors.Is(err, errForbiddenTarget) {
t.Fatalf("rebinding: %v", err)
}
}
type stubResolver struct{ ips []net.IP }
func (s stubResolver) LookupIPAddr(context.Context, string) ([]net.IPAddr, error) {
out := make([]net.IPAddr, len(s.ips))
for i, ip := range s.ips {
out[i] = net.IPAddr{IP: ip}
}
return out, nil
}
func TestPublicAndPrivateAuth(t *testing.T) {
public := httptest.NewServer(newNode("", true, nil, testLimits()).Handler())
defer public.Close()
res, err := http.Post(public.URL+"/v1/jobs", "application/json", strings.NewReader(`{"target":"127.0.0.1","port":1,"profile":"tcp-connect","durationSec":1,"intervalMs":200,"timeoutMs":200}`))
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != http.StatusCreated {
t.Fatalf("public status %d", res.StatusCode)
}
info, err := http.Get(public.URL + "/v1/info")
if err != nil {
t.Fatal(err)
}
defer info.Body.Close()
var body map[string]any
if err := json.NewDecoder(info.Body).Decode(&body); err != nil {
t.Fatal(err)
}
if body["visibility"] != "public" || body["authRequired"] != false {
t.Fatalf("info %+v", body)
}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
var accepted atomic.Int32
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
accepted.Add(1)
c.Close()
}
}()
port := ln.Addr().(*net.TCPAddr).Port
private := httptest.NewServer(newNode("secret-token", true, nil, testLimits()).Handler())
defer private.Close()
payload := `{"target":"127.0.0.1","port":` + itoa(port) + `,"profile":"tcp-connect","durationSec":2,"intervalMs":200,"timeoutMs":300}`
post := func(token string) *http.Response {
t.Helper()
req, err := http.NewRequest(http.MethodPost, private.URL+"/v1/jobs", strings.NewReader(payload))
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)
}
res.Body.Close()
return res
}
if post("").StatusCode != http.StatusUnauthorized {
t.Fatal("missing token was accepted")
}
if post("wrong").StatusCode != http.StatusUnauthorized {
t.Fatal("wrong token was accepted")
}
time.Sleep(200 * time.Millisecond)
if accepted.Load() != 0 {
t.Fatalf("auth failure dialed the target %d times", accepted.Load())
}
if post("secret-token").StatusCode != http.StatusCreated {
t.Fatal("good token was rejected")
}
}
func TestNodeNQAndTCPAndUDP(t *testing.T) {
tcpLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
udpConn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
echo := &Server{}
go echo.ServeTCP(tcpLn)
go echo.ServeUDP(udpConn)
defer echo.Close()
node := newNode("", true, nil, testLimits())
srv := httptest.NewServer(node.Handler())
defer srv.Close()
tcpPort := tcpLn.Addr().(*net.TCPAddr).Port
udpPort := udpConn.LocalAddr().(*net.UDPAddr).Port
tcpJob := createJob(t, srv.URL, "", map[string]any{
"target": "127.0.0.1", "port": tcpPort, "profile": "nq-tcp",
"intervalMs": 200, "timeoutMs": 800, "durationSec": 3, "packetSize": 80,
})
sample := readOneSample(t, srv.URL, "", tcpJob)
if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 {
t.Fatalf("nq tcp %+v", sample)
}
if sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 {
t.Fatalf("loss %+v", sample.Summary)
}
udpJob := createJob(t, srv.URL, "", map[string]any{
"target": "127.0.0.1", "port": udpPort, "profile": "nq-udp",
"intervalMs": 200, "timeoutMs": 800, "durationSec": 3, "packetSize": 80,
})
sample = readOneSample(t, srv.URL, "", udpJob)
if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 {
t.Fatalf("nq udp %+v", sample)
}
okJob := createJob(t, srv.URL, "", map[string]any{
"target": "127.0.0.1", "port": tcpPort, "profile": "tcp-connect",
"intervalMs": 200, "timeoutMs": 800, "durationSec": 2,
})
sample = readOneSample(t, srv.URL, "", okJob)
if sample.Status != statusOK || sample.Kind != kindConnect {
t.Fatalf("tcp connect %+v", sample)
}
refused := createJob(t, srv.URL, "", map[string]any{
"target": "127.0.0.1", "port": 1, "profile": "tcp-connect",
"intervalMs": 200, "timeoutMs": 400, "durationSec": 2,
})
sample = readOneSample(t, srv.URL, "", refused)
if sample.Status != statusRefused || sample.Summary.FailurePct == nil || *sample.Summary.FailurePct != 100 {
t.Fatalf("refused %+v", sample)
}
if sample.Summary.ProbeLossPct != nil {
t.Fatalf("tcp connect must not report probe loss %+v", sample.Summary)
}
}
func TestGenericUDPUnknownAndEcho(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()
go func() {
buf := make([]byte, 64)
for {
_, _, err := blackhole.ReadFromUDP(buf)
if err != nil {
return
}
}
}()
node := httptest.NewServer(newNode("", true, nil, testLimits()).Handler())
defer node.Close()
id := createJob(t, node.URL, "", map[string]any{
"target": "127.0.0.1", "port": blackhole.LocalAddr().(*net.UDPAddr).Port,
"profile": "udp-generic", "intervalMs": 200, "timeoutMs": 250, "durationSec": 2, "packetSize": 16,
})
sample := readOneSample(t, node.URL, "", id)
if sample.Status != statusUnknown || sample.Summary.ProbeLossPct != nil {
t.Fatalf("unknown %+v", sample)
}
if sample.Summary.UnknownPct == nil || *sample.Summary.UnknownPct != 100 {
t.Fatalf("unknown pct %+v", sample.Summary)
}
echo, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
defer echo.Close()
go func() {
buf := make([]byte, 256)
for {
n, addr, err := echo.ReadFromUDP(buf)
if err != nil {
return
}
_, _ = echo.WriteToUDP(append([]byte(nil), buf[:n]...), addr)
}
}()
id = createJob(t, node.URL, "", map[string]any{
"target": "127.0.0.1", "port": echo.LocalAddr().(*net.UDPAddr).Port,
"profile": "custom-udp", "intervalMs": 200, "timeoutMs": 800, "durationSec": 2,
"payloadHex": "0102", "expectHex": "0102",
})
sample = readOneSample(t, node.URL, "", id)
if sample.Status != statusOK || sample.RttMs == nil {
t.Fatalf("custom echo %+v", sample)
}
id = createJob(t, node.URL, "", map[string]any{
"target": "127.0.0.1", "port": echo.LocalAddr().(*net.UDPAddr).Port,
"profile": "custom-udp", "intervalMs": 200, "timeoutMs": 400, "durationSec": 2,
"payloadHex": "0102", "expectHex": "ffff",
})
sample = readOneSample(t, node.URL, "", id)
if sample.Status != statusProtocol {
t.Fatalf("mismatch %+v", sample)
}
}
func TestMinecraftJavaAndBedrockFixtures(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
go serveFakeJava(ln)
udp, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
defer udp.Close()
go serveFakeBedrock(udp, true)
node := httptest.NewServer(newNode("", true, nil, testLimits()).Handler())
defer node.Close()
id := createJob(t, node.URL, "", map[string]any{
"target": "127.0.0.1", "port": ln.Addr().(*net.TCPAddr).Port,
"profile": "minecraft-java", "intervalMs": 200, "timeoutMs": 1000, "durationSec": 3,
})
sample := readOneSample(t, node.URL, "", id)
if sample.Status != statusOK || sample.Detail["motd"] != "Hello" || sample.Detail["version"] != "1.21.1" || sample.Detail["players"] != "3/20" {
t.Fatalf("java %+v", sample)
}
if sample.RttMs == nil || *sample.RttMs < 0 || sample.Summary.FailurePct == nil || *sample.Summary.FailurePct != 0 {
t.Fatalf("java rtt %+v", sample)
}
id = createJob(t, node.URL, "", map[string]any{
"target": "127.0.0.1", "port": udp.LocalAddr().(*net.UDPAddr).Port,
"profile": "minecraft-bedrock", "intervalMs": 200, "timeoutMs": 1000, "durationSec": 3,
})
sample = readOneSample(t, node.URL, "", id)
if sample.Status != statusOK || sample.Detail["motd"] != "Bed" || sample.RttMs == nil {
t.Fatalf("bedrock %+v", sample)
}
bad, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
defer bad.Close()
go serveFakeBedrock(bad, false)
id = createJob(t, node.URL, "", map[string]any{
"target": "127.0.0.1", "port": bad.LocalAddr().(*net.UDPAddr).Port,
"profile": "minecraft-bedrock", "intervalMs": 200, "timeoutMs": 400, "durationSec": 2,
})
sample = readOneSample(t, node.URL, "", id)
if sample.Status != statusProtocol {
t.Fatalf("bad magic %+v", sample)
}
}
func TestDNSAndDeleteAndLimits(t *testing.T) {
dns, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
defer dns.Close()
go func() {
buf := make([]byte, 512)
for {
n, addr, err := dns.ReadFromUDP(buf)
if err != nil || n < 2 {
return
}
reply := []byte{buf[0], buf[1], 0x81, 0x80, 0, 1, 0, 0, 0, 0, 0, 0}
_, _ = dns.WriteToUDP(reply, addr)
}
}()
limits := testLimits()
limits.MaxJobs = 1
node := newNode("", true, nil, limits)
srv := httptest.NewServer(node.Handler())
defer srv.Close()
id := createJob(t, srv.URL, "", map[string]any{
"target": "127.0.0.1", "port": dns.LocalAddr().(*net.UDPAddr).Port,
"profile": "dns", "dnsName": "example.com", "intervalMs": 200, "timeoutMs": 800, "durationSec": 5,
})
res, err := http.Post(srv.URL+"/v1/jobs", "application/json", strings.NewReader(`{"target":"127.0.0.1","port":9,"profile":"tcp-connect","durationSec":5,"intervalMs":200,"timeoutMs":200}`))
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != http.StatusTooManyRequests {
t.Fatalf("limit status %d", res.StatusCode)
}
del, err := http.NewRequest(http.MethodDelete, srv.URL+"/v1/jobs/"+id, nil)
if err != nil {
t.Fatal(err)
}
res, err = http.DefaultClient.Do(del)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != http.StatusNoContent {
t.Fatalf("delete %d", res.StatusCode)
}
deadline := time.Now().Add(2 * time.Second)
for node.jobCount() != 0 && time.Now().Before(deadline) {
time.Sleep(20 * time.Millisecond)
}
if node.jobCount() != 0 {
t.Fatalf("job still running: %d", node.jobCount())
}
again := createJob(t, srv.URL, "", map[string]any{
"target": "127.0.0.1", "port": dns.LocalAddr().(*net.UDPAddr).Port,
"profile": "dns", "dnsName": "example.com", "intervalMs": 200, "timeoutMs": 800, "durationSec": 3,
})
sample := readOneSample(t, srv.URL, "", again)
if sample.Status != statusOK || sample.RttMs == nil {
t.Fatalf("dns %+v", sample)
}
}
func TestBookIgnoresPendingAndNQConnectFailure(t *testing.T) {
b := &sampleBook{profile: "nq-tcp"}
s := b.summary()
if s.ProbeLossPct != nil || s.Completed != 0 {
t.Fatalf("empty book %+v", s)
}
b.add(Outcome{Status: statusRefused, Kind: kindConnect, Reconnect: true})
s = b.summary()
if s.ProbeLossPct != nil || s.Reconnects != 1 {
t.Fatalf("connect failure counted as loss %+v", s)
}
b.add(Outcome{Status: statusTimeout, Kind: kindProbe})
b.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: time.Millisecond})
s = b.summary()
if s.ProbeLossPct == nil || *s.ProbeLossPct != 50 {
t.Fatalf("probe loss %+v", s)
}
u := &sampleBook{profile: "udp-generic"}
u.add(Outcome{Status: statusUnknown, Kind: kindQuery})
if u.summary().ProbeLossPct != nil || u.summary().UnknownPct == nil {
t.Fatalf("unknown %+v", u.summary())
}
}
func TestLateUDPReplyIgnored(t *testing.T) {
echo, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
defer echo.Close()
go func() {
buf := make([]byte, 2048)
for {
n, addr, err := echo.ReadFromUDP(buf)
if err != nil {
return
}
pkt, err := ParsePacket(append([]byte(nil), buf[:n]...))
if err != nil || pkt.Type != typeRequest {
continue
}
pkt.Type = typeReply
pkt.ServerUnixNano = uint64(time.Now().UnixNano())
raw, err := pkt.Marshal()
if err != nil {
continue
}
seq := pkt.Sequence
dest := &net.UDPAddr{IP: append(net.IP(nil), addr.IP...), Port: addr.Port}
go func(seq uint32, raw []byte, dest *net.UDPAddr) {
if seq == 1 {
time.Sleep(400 * time.Millisecond)
}
_, _ = echo.WriteToUDP(raw, dest)
}(seq, raw, dest)
}
}()
p := &nqUDP{spec: jobSpec{
IP: net.IPv4(127, 0, 0, 1), Port: echo.LocalAddr().(*net.UDPAddr).Port,
Timeout: 150 * time.Millisecond, PacketSize: 80,
}}
defer p.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
first := p.Probe(ctx)
if first.Status != statusTimeout {
t.Fatalf("first %+v", first)
}
second := p.Probe(ctx)
if second.Status != statusOK {
t.Fatalf("second %+v", second)
}
}
func testLimits() Limits {
l := defaultLimits()
l.MaxJobs = 4
l.MinInterval = 200 * time.Millisecond
l.MaxDuration = 10 * time.Second
return l
}
func createJob(t *testing.T, base, token string, body map[string]any) string {
t.Helper()
raw, _ := json.Marshal(body)
req, err := http.NewRequest(http.MethodPost, base+"/v1/jobs", strings.NewReader(string(raw)))
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)
}
defer res.Body.Close()
if res.StatusCode != http.StatusCreated {
b, _ := io.ReadAll(res.Body)
t.Fatalf("create %d %s", res.StatusCode, b)
}
var out struct {
JobID string `json:"jobId"`
}
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
t.Fatal(err)
}
if out.JobID == "" {
t.Fatal("empty job id")
}
return out.JobID
}
func readOneSample(t *testing.T, base, token, id string) sampleMsg {
t.Helper()
req, err := http.NewRequest(http.MethodGet, base+"/v1/jobs/"+id+"/stream", nil)
if err != nil {
t.Fatal(err)
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
req = req.WithContext(ctx)
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
b, _ := io.ReadAll(res.Body)
t.Fatalf("stream %d %s", res.StatusCode, b)
}
sc := bufio.NewScanner(res.Body)
for sc.Scan() {
line := sc.Text()
if !strings.HasPrefix(line, "data: ") {
continue
}
var msg sampleMsg
if err := json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &msg); err != nil {
t.Fatal(err)
}
if msg.Status == "" || msg.Status == "pending" {
continue
}
return msg
}
t.Fatal(sc.Err())
return sampleMsg{}
}
func serveFakeJava(ln net.Listener) {
for {
c, err := ln.Accept()
if err != nil {
return
}
go func(conn net.Conn) {
defer conn.Close()
r := bufio.NewReader(conn)
if _, err := readMC(r); err != nil {
return
}
if _, err := readMC(r); err != nil {
return
}
status := []byte(`{"version":{"name":"1.21.1","protocol":767},"players":{"online":3,"max":20},"description":{"text":"Hello"}}`)
payload := appendMCString([]byte{0x00}, string(status))
if err := writeMC(conn, payload); err != nil {
return
}
ping, err := readMC(r)
if err != nil {
return
}
_ = writeMC(conn, ping)
}(c)
}
}
func serveFakeBedrock(conn *net.UDPConn, good bool) {
buf := make([]byte, 1500)
for {
n, addr, err := conn.ReadFromUDP(buf)
if err != nil || n < 33 {
return
}
ts := binary.BigEndian.Uint64(buf[1:9])
motd := "MCPE;Bed;844;1.21.50;1;10;0;world;Survival;1;19132;0;"
body := make([]byte, 1+8+8+16+2+len(motd))
body[0] = 0x1c
binary.BigEndian.PutUint64(body[1:9], ts)
binary.BigEndian.PutUint64(body[9:17], 99)
copy(body[17:33], rakMagic)
if !good {
body[17] = 0x11
}
binary.BigEndian.PutUint16(body[33:35], uint16(len(motd)))
copy(body[35:], motd)
_, _ = conn.WriteToUDP(body, addr)
}
}
func itoa(n int) string { return strconv.Itoa(n) }
+721
View File
@@ -0,0 +1,721 @@
package main
import (
"bufio"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"syscall"
"time"
)
type prober interface {
Probe(ctx context.Context) Outcome
Close() error
}
func newProber(spec jobSpec) (prober, error) {
switch spec.Profile {
case "nq-tcp":
return &nqTCP{spec: spec}, nil
case "nq-udp":
return &nqUDP{spec: spec}, nil
case "tcp-connect":
return &tcpConnect{spec: spec}, nil
case "udp-generic":
return &udpQuery{spec: spec, generic: true}, nil
case "custom-udp":
return &udpQuery{spec: spec}, nil
case "dns":
return &dnsQuery{spec: spec}, nil
case "minecraft-java":
return &mcJava{spec: spec}, nil
case "minecraft-bedrock":
return &mcBedrock{spec: spec}, nil
default:
return nil, fmt.Errorf("unknown profile %q", spec.Profile)
}
}
func dialTCP(ctx context.Context, ip net.IP, port int) (net.Conn, error) {
network := "tcp4"
if ip.To4() == nil {
network = "tcp6"
}
var d net.Dialer
return d.DialContext(ctx, network, net.JoinHostPort(ip.String(), strconv.Itoa(port)))
}
func dialUDP(ip net.IP, port int) (*net.UDPConn, error) {
network := "udp4"
if ip.To4() == nil {
network = "udp6"
}
raddr, err := net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), strconv.Itoa(port)))
if err != nil {
return nil, err
}
var laddr *net.UDPAddr
if ip.To4() != nil {
laddr = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
} else {
laddr = &net.UDPAddr{IP: net.IPv6zero, Port: 0}
}
return net.DialUDP(network, laddr, raddr)
}
func classifyDial(err error) Outcome {
if err == nil {
return Outcome{Status: statusOK, Kind: kindConnect}
}
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
return Outcome{Status: statusTimeout, Kind: kindConnect, Note: "连接超时"}
}
var dnsErr *net.DNSError
if errors.As(err, &dnsErr) {
return Outcome{Status: statusDNS, Kind: kindConnect, Note: "域名无法解析"}
}
if errors.Is(err, syscall.ECONNREFUSED) {
return Outcome{Status: statusRefused, Kind: kindConnect, Note: "连接被拒绝"}
}
var ne net.Error
if errors.As(err, &ne) && ne.Timeout() {
return Outcome{Status: statusTimeout, Kind: kindConnect, Note: "连接超时"}
}
return Outcome{Status: statusError, Kind: kindConnect, Note: "连接失败"}
}
func nqPacket(seq uint32, token [tokenLen]byte, size int) ([]byte, error) {
if size < headerSize {
size = headerSize
}
if size > 1400 {
size = 1400
}
p := Packet{
Version: protocolVer,
Type: typeRequest,
Sequence: seq,
ClientSendUnixNano: uint64(time.Now().UnixNano()),
Token: token,
Payload: make([]byte, size-headerSize),
}
return p.Marshal()
}
type nqTCP struct {
spec jobSpec
conn net.Conn
reader *bufio.Reader
seq uint32
}
func (p *nqTCP) Close() error {
if p.conn != nil {
err := p.conn.Close()
p.conn = nil
p.reader = nil
return err
}
return nil
}
func (p *nqTCP) dial(ctx context.Context) error {
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
if err != nil {
return err
}
if tc, ok := conn.(*net.TCPConn); ok {
_ = tc.SetNoDelay(true)
}
p.conn = conn
p.reader = bufio.NewReaderSize(conn, headerSize+maxPayloadSize)
return nil
}
func (p *nqTCP) Probe(ctx context.Context) Outcome {
if p.conn == nil {
if err := p.dial(ctx); err != nil {
out := classifyDial(err)
out.Reconnect = true
if out.Note == "" {
out.Note = "TCP 反射连接失败,将重试"
}
return out
}
}
p.seq++
raw, err := nqPacket(p.seq, p.spec.Echo, p.spec.PacketSize)
if err != nil {
return Outcome{Status: statusError, Kind: kindProbe, Note: "无法构造探测包"}
}
_ = p.conn.SetWriteDeadline(time.Now().Add(p.spec.Timeout))
if _, err := p.conn.Write(raw); err != nil {
_ = p.Close()
return Outcome{Status: statusError, Kind: kindConnect, Reconnect: true, Note: "发送失败,连接将重连"}
}
start := time.Now()
deadline := start.Add(p.spec.Timeout)
for {
if ctx.Err() != nil {
return Outcome{Status: statusTimeout, Kind: kindConnect, Note: "已停止"}
}
_ = p.conn.SetReadDeadline(deadline)
pkt, err := readFrame(p.reader)
if err != nil {
_ = p.Close()
if ne, ok := err.(net.Error); ok && ne.Timeout() || errors.Is(err, context.DeadlineExceeded) {
return Outcome{
Status: statusTimeout,
Kind: kindProbe,
Note: "已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包",
}
}
return Outcome{Status: statusError, Kind: kindConnect, Reconnect: true, Note: "连接中断,将重连"}
}
if pkt.Type != typeReply || pkt.Sequence != p.seq {
continue
}
return Outcome{
Status: statusOK,
Kind: kindProbe,
HasRtt: true,
Rtt: time.Since(start),
Note: "收到回显",
}
}
}
type nqUDP struct {
spec jobSpec
conn *net.UDPConn
seq uint32
}
func (p *nqUDP) Close() error {
if p.conn != nil {
err := p.conn.Close()
p.conn = nil
return err
}
return nil
}
func (p *nqUDP) ensure() error {
if p.conn != nil {
return nil
}
c, err := dialUDP(p.spec.IP, p.spec.Port)
if err != nil {
return err
}
p.conn = c
return nil
}
func (p *nqUDP) Probe(ctx context.Context) Outcome {
if err := p.ensure(); err != nil {
return classifyDial(err)
}
p.seq++
raw, err := nqPacket(p.seq, p.spec.Echo, p.spec.PacketSize)
if err != nil {
return Outcome{Status: statusError, Kind: kindProbe, Note: "无法构造探测包"}
}
start := time.Now()
deadline := start.Add(p.spec.Timeout)
_ = p.conn.SetWriteDeadline(deadline)
if _, err := p.conn.Write(raw); err != nil {
return classifyDial(err)
}
buf := make([]byte, 2048)
sawInvalid := false
for {
if ctx.Err() != nil {
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "已停止"}
}
_ = p.conn.SetReadDeadline(deadline)
n, err := p.conn.Read(buf)
if err != nil {
if errors.Is(err, syscall.ECONNREFUSED) {
return Outcome{Status: statusRefused, Kind: kindQuery, Note: "目标端口不可达"}
}
if sawInvalid {
return Outcome{Status: statusProtocol, Kind: kindProbe, Note: "收到的 UDP 包不是有效回显"}
}
return Outcome{
Status: statusTimeout,
Kind: kindProbe,
Note: "未收到回显。这是探测没有应答,不是网卡上的物理丢包计数",
}
}
pkt, err := ParsePacket(buf[:n])
if err != nil || pkt.Type != typeReply {
sawInvalid = true
continue
}
if pkt.Sequence != p.seq {
continue
}
return Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: time.Since(start), Note: "收到回显"}
}
}
type tcpConnect struct{ spec jobSpec }
func (p *tcpConnect) Close() error { return nil }
func (p *tcpConnect) Probe(ctx context.Context) Outcome {
start := time.Now()
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
if err != nil {
return classifyDial(err)
}
_ = conn.Close()
return Outcome{Status: statusOK, Kind: kindConnect, HasRtt: true, Rtt: time.Since(start), Note: "TCP 已连通"}
}
type udpQuery struct {
spec jobSpec
generic bool
conn *net.UDPConn
}
func (p *udpQuery) Close() error {
if p.conn != nil {
err := p.conn.Close()
p.conn = nil
return err
}
return nil
}
func (p *udpQuery) Probe(ctx context.Context) Outcome {
if p.conn == nil {
c, err := dialUDP(p.spec.IP, p.spec.Port)
if err != nil {
return classifyDial(err)
}
p.conn = c
}
payload := p.spec.Payload
if p.generic {
n := p.spec.PacketSize
if n < 1 {
n = 16
}
if n > 1400 {
n = 1400
}
payload = make([]byte, n)
}
start := time.Now()
deadline := start.Add(p.spec.Timeout)
_ = p.conn.SetWriteDeadline(deadline)
if _, err := p.conn.Write(payload); err != nil {
return classifyDial(err)
}
buf := make([]byte, 2048)
_ = p.conn.SetReadDeadline(deadline)
n, err := p.conn.Read(buf)
if err != nil {
if errors.Is(err, syscall.ECONNREFUSED) {
return Outcome{Status: statusRefused, Kind: kindQuery, Note: "目标端口不可达"}
}
if ctx.Err() != nil {
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "已停止"}
}
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "没有收到 UDP 应答,不能据此断定物理丢包"}
}
got := buf[:n]
if len(p.spec.Expect) > 0 {
if len(got) < len(p.spec.Expect) || string(got[:len(p.spec.Expect)]) != string(p.spec.Expect) {
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "收到了数据,但和预期的响应不一致"}
}
}
return Outcome{Status: statusOK, Kind: kindQuery, HasRtt: true, Rtt: time.Since(start), Note: "收到 UDP 响应"}
}
type dnsQuery struct {
spec jobSpec
conn *net.UDPConn
id uint16
}
func (p *dnsQuery) Close() error {
if p.conn != nil {
err := p.conn.Close()
p.conn = nil
return err
}
return nil
}
func (p *dnsQuery) Probe(ctx context.Context) Outcome {
if p.conn == nil {
c, err := dialUDP(p.spec.IP, p.spec.Port)
if err != nil {
return classifyDial(err)
}
p.conn = c
}
p.id++
if p.id == 0 {
p.id = 1
}
name := p.spec.DNSName
if name == "" {
name = "example.com"
}
query, err := dnsQueryMessage(p.id, name)
if err != nil {
return Outcome{Status: statusError, Kind: kindQuery, Note: "无法构造 DNS 查询"}
}
start := time.Now()
deadline := start.Add(p.spec.Timeout)
_ = p.conn.SetWriteDeadline(deadline)
if _, err := p.conn.Write(query); err != nil {
return classifyDial(err)
}
buf := make([]byte, 1500)
for {
if ctx.Err() != nil {
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "已停止"}
}
_ = p.conn.SetReadDeadline(deadline)
n, err := p.conn.Read(buf)
if err != nil {
if errors.Is(err, syscall.ECONNREFUSED) {
return Outcome{Status: statusRefused, Kind: kindQuery, Note: "DNS 端口不可达"}
}
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "没有收到 DNS 应答,不能据此断定物理丢包"}
}
if n < 12 {
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "DNS 应答太短"}
}
id := binary.BigEndian.Uint16(buf[:2])
if id != p.id {
continue
}
if buf[2]&0x80 == 0 {
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "收到的包不是 DNS 应答"}
}
return Outcome{Status: statusOK, Kind: kindQuery, HasRtt: true, Rtt: time.Since(start), Note: "收到 DNS 应答"}
}
}
func dnsQueryMessage(id uint16, name string) ([]byte, error) {
var q []byte
for _, label := range strings.Split(name, ".") {
if label == "" {
continue
}
if len(label) > 63 {
return nil, errors.New("label too long")
}
q = append(q, byte(len(label)))
q = append(q, label...)
}
q = append(q, 0, 0, 1, 0, 1)
msg := make([]byte, 12+len(q))
binary.BigEndian.PutUint16(msg[0:2], id)
binary.BigEndian.PutUint16(msg[2:4], 0x0100)
binary.BigEndian.PutUint16(msg[4:6], 1)
copy(msg[12:], q)
return msg, nil
}
var rakMagic = []byte{0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE, 0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78}
type mcBedrock struct {
spec jobSpec
conn *net.UDPConn
guid uint64
}
func (p *mcBedrock) Close() error {
if p.conn != nil {
err := p.conn.Close()
p.conn = nil
return err
}
return nil
}
func (p *mcBedrock) Probe(ctx context.Context) Outcome {
if p.conn == nil {
c, err := dialUDP(p.spec.IP, p.spec.Port)
if err != nil {
return classifyDial(err)
}
p.conn = c
p.guid = uint64(time.Now().UnixNano())
}
ts := uint64(time.Now().UnixNano())
pkt := make([]byte, 1+8+16+8)
pkt[0] = 0x01
binary.BigEndian.PutUint64(pkt[1:9], ts)
copy(pkt[9:25], rakMagic)
binary.BigEndian.PutUint64(pkt[25:33], p.guid)
start := time.Now()
deadline := start.Add(p.spec.Timeout)
_ = p.conn.SetWriteDeadline(deadline)
if _, err := p.conn.Write(pkt); err != nil {
return classifyDial(err)
}
buf := make([]byte, 1500)
sawInvalid := false
for {
if ctx.Err() != nil {
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "已停止"}
}
_ = p.conn.SetReadDeadline(deadline)
n, err := p.conn.Read(buf)
if err != nil {
if sawInvalid {
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "收到的包不是有效的 RakNet Pong"}
}
if errors.Is(err, syscall.ECONNREFUSED) {
return Outcome{Status: statusRefused, Kind: kindQuery, Note: "目标端口不可达"}
}
return Outcome{Status: statusUnknown, Kind: kindQuery, Note: "未收到 RakNet 应答,不能据此断定物理丢包"}
}
detail, ok := parseRakPong(buf[:n], ts)
if !ok {
sawInvalid = true
continue
}
return Outcome{Status: statusOK, Kind: kindQuery, HasRtt: true, Rtt: time.Since(start), Note: "收到 Bedrock 应答", Detail: detail}
}
}
func parseRakPong(b []byte, ts uint64) (map[string]string, bool) {
if len(b) < 1+8+8+16+2 || b[0] != 0x1c {
return nil, false
}
if binary.BigEndian.Uint64(b[1:9]) != ts {
return nil, false
}
if string(b[17:33]) != string(rakMagic) {
return nil, false
}
strlen := int(binary.BigEndian.Uint16(b[33:35]))
if 35+strlen > len(b) {
return nil, false
}
text := string(b[35 : 35+strlen])
parts := strings.Split(text, ";")
detail := map[string]string{}
if len(parts) > 1 {
detail["motd"] = parts[1]
}
if len(parts) > 3 {
detail["version"] = parts[3]
}
if len(parts) > 5 {
detail["players"] = parts[4] + "/" + parts[5]
}
return detail, true
}
type mcJava struct{ spec jobSpec }
func (p *mcJava) Close() error { return nil }
func (p *mcJava) Probe(ctx context.Context) Outcome {
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
if err != nil {
return classifyDial(err)
}
defer conn.Close()
deadline, ok := ctx.Deadline()
if !ok {
deadline = time.Now().Add(p.spec.Timeout)
}
_ = conn.SetDeadline(deadline)
r := bufio.NewReader(conn)
host := p.spec.Host
if err := writeMC(conn, mcHandshake(host, p.spec.Port)); err != nil {
return Outcome{Status: statusError, Kind: kindConnect, Note: "无法发送 Minecraft 握手"}
}
if err := writeMC(conn, []byte{0x00}); err != nil {
return Outcome{Status: statusError, Kind: kindConnect, Note: "无法发送状态请求"}
}
payload, err := readMC(r)
if err != nil || len(payload) < 2 || payload[0] != 0x00 {
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "Minecraft 状态响应无效"}
}
jsonText, _, err := readMCString(payload[1:])
if err != nil {
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "Minecraft 状态内容无法解析"}
}
detail := minecraftStatusDetail(jsonText)
nonce := time.Now().UnixNano()
ping := []byte{0x01}
var num [8]byte
binary.BigEndian.PutUint64(num[:], uint64(nonce))
ping = append(ping, num[:]...)
start := time.Now()
if err := writeMC(conn, ping); err != nil {
return Outcome{Status: statusError, Kind: kindQuery, Note: "无法发送 Minecraft ping", Detail: detail}
}
pong, err := readMC(r)
if err != nil || len(pong) != 9 || pong[0] != 0x01 {
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "没有收到有效的 Minecraft pong", Detail: detail}
}
if int64(binary.BigEndian.Uint64(pong[1:])) != nonce {
return Outcome{Status: statusProtocol, Kind: kindQuery, Note: "Minecraft pong 的时间戳不匹配", Detail: detail}
}
return Outcome{
Status: statusOK,
Kind: kindQuery,
HasRtt: true,
Rtt: time.Since(start),
Note: "收到 Minecraft 状态和 ping 应答",
Detail: detail,
}
}
func mcHandshake(host string, port int) []byte {
var p []byte
p = append(p, 0x00)
p = appendVarInt(p, 767)
p = appendMCString(p, host)
var pb [2]byte
binary.BigEndian.PutUint16(pb[:], uint16(port))
p = append(p, pb[:]...)
p = appendVarInt(p, 1)
return p
}
func minecraftStatusDetail(raw string) map[string]string {
var body map[string]any
if err := json.Unmarshal([]byte(raw), &body); err != nil {
return map[string]string{}
}
out := map[string]string{}
if v, ok := body["version"].(map[string]any); ok {
if name, ok := v["name"].(string); ok {
out["version"] = name
}
}
if p, ok := body["players"].(map[string]any); ok {
online, _ := asInt(p["online"])
max, _ := asInt(p["max"])
out["players"] = fmt.Sprintf("%d/%d", online, max)
}
if desc, ok := body["description"]; ok {
if text := motdText(desc); text != "" {
out["motd"] = text
}
}
return out
}
func asInt(v any) (int, bool) {
switch n := v.(type) {
case float64:
return int(n), true
case int:
return n, true
default:
return 0, false
}
}
func motdText(v any) string {
switch t := v.(type) {
case string:
return t
case map[string]any:
var b strings.Builder
if s, ok := t["text"].(string); ok {
b.WriteString(s)
}
if extra, ok := t["extra"].([]any); ok {
for _, e := range extra {
b.WriteString(motdText(e))
}
}
return b.String()
default:
return ""
}
}
func appendVarInt(dst []byte, v int) []byte {
u := uint32(v)
for {
if u&^0x7f == 0 {
return append(dst, byte(u))
}
dst = append(dst, byte(u)|0x80)
u >>= 7
}
}
func readVarInt(r *bufio.Reader) (int, error) {
var n uint32
for i := 0; i < 5; i++ {
b, err := r.ReadByte()
if err != nil {
return 0, err
}
n |= uint32(b&0x7f) << (7 * i)
if b&0x80 == 0 {
return int(n), nil
}
}
return 0, errors.New("varint too long")
}
func appendMCString(dst []byte, s string) []byte {
dst = appendVarInt(dst, len(s))
return append(dst, s...)
}
func readMCString(b []byte) (string, []byte, error) {
n, rest, err := readVarIntBytes(b)
if err != nil || n < 0 || n > len(rest) {
return "", nil, errors.New("bad string")
}
return string(rest[:n]), rest[n:], nil
}
func readVarIntBytes(b []byte) (int, []byte, error) {
var n uint32
for i := 0; i < 5 && i < len(b); i++ {
by := b[i]
n |= uint32(by&0x7f) << (7 * i)
if by&0x80 == 0 {
return int(n), b[i+1:], nil
}
}
return 0, nil, errors.New("varint")
}
func writeMC(w io.Writer, payload []byte) error {
frame := appendVarInt(nil, len(payload))
frame = append(frame, payload...)
_, err := w.Write(frame)
return err
}
func readMC(r *bufio.Reader) ([]byte, error) {
n, err := readVarInt(r)
if err != nil {
return nil, err
}
if n < 1 || n > 1<<20 {
return nil, errors.New("bad packet length")
}
buf := make([]byte, n)
_, err = io.ReadFull(r, buf)
return buf, err
}
+145
View File
@@ -0,0 +1,145 @@
// Package main implements the NetQuality reflector.
//
// Wire format (version 1), little-endian. The same layout is used for one
// UDP datagram and for one TCP frame. TCP frames are concatenated on the
// stream and split using PayloadLen; there is no extra length prefix.
//
// Offset Size Field
// 0 4 Magic "NQ01"
// 4 1 Version (1)
// 5 1 Type (1 request, 2 reply)
// 6 1 Flags (reserved, send 0)
// 7 1 Reserved (0)
// 8 4 Sequence uint32
// 12 8 ClientSendUnixNano uint64
// 20 8 ServerUnixNano uint64 (0 on request)
// 28 32 Token (UTF-8, zero padded; zeros if unused)
// 60 2 PayloadLen uint16
// 62 N Payload (opaque, echoed unchanged)
package main
import (
"encoding/binary"
"errors"
"fmt"
)
const (
magic = "NQ01"
protocolVer = 1
headerSize = 62
tokenOffset = 28
tokenLen = 32
payloadLenOff = 60
maxPayloadSize = 2048
typeRequest byte = 1
typeReply byte = 2
)
var (
errShortPacket = errors.New("packet shorter than header")
errBadMagic = errors.New("bad magic")
errBadVersion = errors.New("unsupported version")
errBadType = errors.New("unsupported type")
errBadPayloadLen = errors.New("payload length out of range")
errTrailingBytes = errors.New("trailing bytes after payload")
errBadToken = errors.New("token mismatch")
)
// Packet is a decoded probe frame.
type Packet struct {
Version byte
Type byte
Flags byte
Sequence uint32
ClientSendUnixNano uint64
ServerUnixNano uint64
Token [tokenLen]byte
Payload []byte
}
func (p Packet) Marshal() ([]byte, error) {
if len(p.Payload) > maxPayloadSize {
return nil, errBadPayloadLen
}
buf := make([]byte, headerSize+len(p.Payload))
copy(buf[0:4], magic)
buf[4] = p.Version
buf[5] = p.Type
buf[6] = p.Flags
buf[7] = 0
binary.LittleEndian.PutUint32(buf[8:12], p.Sequence)
binary.LittleEndian.PutUint64(buf[12:20], p.ClientSendUnixNano)
binary.LittleEndian.PutUint64(buf[20:28], p.ServerUnixNano)
copy(buf[tokenOffset:tokenOffset+tokenLen], p.Token[:])
binary.LittleEndian.PutUint16(buf[payloadLenOff:payloadLenOff+2], uint16(len(p.Payload)))
copy(buf[headerSize:], p.Payload)
return buf, nil
}
// ParsePacket decodes a single frame. n is the number of bytes consumed,
// which equals the full frame size. Extra bytes are rejected so a UDP
// datagram must contain exactly one frame.
func ParsePacket(b []byte) (Packet, error) {
if len(b) < headerSize {
return Packet{}, errShortPacket
}
if string(b[0:4]) != magic {
return Packet{}, errBadMagic
}
if b[4] != protocolVer {
return Packet{}, errBadVersion
}
typ := b[5]
if typ != typeRequest && typ != typeReply {
return Packet{}, errBadType
}
payloadLen := int(binary.LittleEndian.Uint16(b[payloadLenOff : payloadLenOff+2]))
if payloadLen > maxPayloadSize {
return Packet{}, errBadPayloadLen
}
total := headerSize + payloadLen
if len(b) < total {
return Packet{}, fmt.Errorf("%w: need %d bytes, have %d", errShortPacket, total, len(b))
}
if len(b) != total {
return Packet{}, errTrailingBytes
}
var p Packet
p.Version = b[4]
p.Type = typ
p.Flags = b[6]
p.Sequence = binary.LittleEndian.Uint32(b[8:12])
p.ClientSendUnixNano = binary.LittleEndian.Uint64(b[12:20])
p.ServerUnixNano = binary.LittleEndian.Uint64(b[20:28])
copy(p.Token[:], b[tokenOffset:tokenOffset+tokenLen])
if payloadLen > 0 {
p.Payload = append([]byte(nil), b[headerSize:total]...)
} else {
p.Payload = []byte{}
}
return p, nil
}
// tokenBytes normalizes a configured shared token into the 32-byte field.
// Empty means "no token required".
func tokenBytes(s string) ([tokenLen]byte, error) {
var out [tokenLen]byte
if s == "" {
return out, nil
}
b := []byte(s)
if len(b) > tokenLen {
return out, fmt.Errorf("token longer than %d bytes", tokenLen)
}
copy(out[:], b)
return out, nil
}
func tokenMatches(got [tokenLen]byte, want [tokenLen]byte, required bool) bool {
if !required {
return true
}
return got == want
}
+212
View File
@@ -0,0 +1,212 @@
package main
import (
"bytes"
"encoding/binary"
"net"
"testing"
"time"
)
func TestGoldenRequest(t *testing.T) {
var p Packet
p.Version = protocolVer
p.Type = typeRequest
p.Sequence = 1
p.ClientSendUnixNano = 1000
p.Payload = []byte{0x01, 0x02, 0x03, 0x04}
got, err := p.Marshal()
if err != nil {
t.Fatal(err)
}
want := goldenRequest()
if !bytes.Equal(got, want) {
t.Fatalf("golden mismatch\n got %x\nwant %x", got, want)
}
back, err := ParsePacket(got)
if err != nil {
t.Fatal(err)
}
if back.Sequence != 1 || back.ClientSendUnixNano != 1000 || back.Type != typeRequest {
t.Fatalf("round trip fields: %+v", back)
}
if !bytes.Equal(back.Payload, p.Payload) {
t.Fatalf("payload %x", back.Payload)
}
}
func TestRejects(t *testing.T) {
good := goldenRequest()
if _, err := ParsePacket(good[:10]); err == nil {
t.Fatal("expected short packet error")
}
badMagic := append([]byte(nil), good...)
badMagic[0] = 'X'
if _, err := ParsePacket(badMagic); err != errBadMagic {
t.Fatalf("magic: %v", err)
}
badVer := append([]byte(nil), good...)
badVer[4] = 9
if _, err := ParsePacket(badVer); err != errBadVersion {
t.Fatalf("version: %v", err)
}
trailing := append(append([]byte(nil), good...), 0xFF)
if _, err := ParsePacket(trailing); err != errTrailingBytes {
t.Fatalf("trailing: %v", err)
}
}
func TestTokenRequired(t *testing.T) {
tok, err := tokenBytes("secret")
if err != nil {
t.Fatal(err)
}
s := &Server{Token: tok, Required: true}
var p Packet
p.Version = protocolVer
p.Type = typeRequest
p.Sequence = 7
p.ClientSendUnixNano = 42
p.Payload = []byte("hi")
if _, ok := s.HandlePacket(p, time.Unix(0, 99)); ok {
t.Fatal("expected token rejection")
}
p.Token = tok
reply, ok := s.HandlePacket(p, time.Unix(0, 99))
if !ok {
t.Fatal("expected accept")
}
back, err := ParsePacket(reply)
if err != nil {
t.Fatal(err)
}
if back.Type != typeReply || back.Sequence != 7 || back.ClientSendUnixNano != 42 || back.ServerUnixNano != 99 {
t.Fatalf("reply %+v", back)
}
if string(back.Payload) != "hi" || back.Token != tok {
t.Fatalf("echo mismatch")
}
}
func TestTokenTooLong(t *testing.T) {
if _, err := tokenBytes("0123456789abcdef0123456789abcdefX"); err == nil {
t.Fatal("expected error")
}
}
func TestUDPAndTCPEcho(t *testing.T) {
s := &Server{}
udpAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
udpConn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
t.Fatal(err)
}
defer udpConn.Close()
go s.ServeUDP(udpConn)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
go s.ServeTCP(ln)
payload := bytes.Repeat([]byte{0xAB}, 16)
req := Packet{
Version: protocolVer,
Type: typeRequest,
Sequence: 3,
ClientSendUnixNano: uint64(time.Now().UnixNano()),
Payload: payload,
}
raw, err := req.Marshal()
if err != nil {
t.Fatal(err)
}
clientUDP, err := net.DialUDP("udp", nil, udpConn.LocalAddr().(*net.UDPAddr))
if err != nil {
t.Fatal(err)
}
defer clientUDP.Close()
if _, err := clientUDP.Write(raw); err != nil {
t.Fatal(err)
}
_ = clientUDP.SetReadDeadline(time.Now().Add(2 * time.Second))
buf := make([]byte, 2048)
n, err := clientUDP.Read(buf)
if err != nil {
t.Fatal(err)
}
assertReply(t, buf[:n], req)
tcpClient, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatal(err)
}
defer tcpClient.Close()
req.Sequence = 4
raw, _ = req.Marshal()
// Two frames back-to-back to prove TCP framing.
if _, err := tcpClient.Write(append(append([]byte{}, raw...), raw...)); err != nil {
t.Fatal(err)
}
_ = tcpClient.SetReadDeadline(time.Now().Add(2 * time.Second))
got := make([]byte, len(raw)*2)
if _, err := ioReadFull(tcpClient, got); err != nil {
t.Fatal(err)
}
assertReply(t, got[:len(raw)], req)
assertReply(t, got[len(raw):], req)
}
func assertReply(t *testing.T, raw []byte, req Packet) {
t.Helper()
p, err := ParsePacket(raw)
if err != nil {
t.Fatal(err)
}
if p.Type != typeReply {
t.Fatalf("type %d", p.Type)
}
if p.Sequence != req.Sequence || p.ClientSendUnixNano != req.ClientSendUnixNano {
t.Fatalf("identity not preserved: %+v", p)
}
if !bytes.Equal(p.Payload, req.Payload) {
t.Fatalf("payload changed")
}
if p.ServerUnixNano == 0 {
t.Fatal("server timestamp not set")
}
}
func ioReadFull(c net.Conn, buf []byte) (int, error) {
n := 0
for n < len(buf) {
r, err := c.Read(buf[n:])
n += r
if err != nil {
return n, err
}
}
return n, nil
}
func goldenRequest() []byte {
buf := make([]byte, headerSize+4)
copy(buf[0:4], "NQ01")
buf[4] = 1
buf[5] = 1
binary.LittleEndian.PutUint32(buf[8:12], 1)
binary.LittleEndian.PutUint64(buf[12:20], 1000)
binary.LittleEndian.PutUint16(buf[payloadLenOff:payloadLenOff+2], 4)
copy(buf[headerSize:], []byte{1, 2, 3, 4})
return buf
}
+97
View File
@@ -0,0 +1,97 @@
package main
import (
"context"
"errors"
"fmt"
"net"
"strings"
"time"
)
var errForbiddenTarget = errors.New("forbidden target")
// metadataNames are never probed, even when the operator allows LAN targets.
var metadataNames = map[string]struct{}{
"localhost": {},
"metadata": {},
"metadata.google.internal": {},
"metadata.google.com": {},
}
var metadataIP = net.ParseIP("169.254.169.254")
// targetOK decides whether a remote node may dial this address.
// Loopback, private, link-local and cloud metadata are rejected unless
// allowPrivate is set. Metadata addresses stay blocked either way.
// 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.
func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) (net.IP, error) {
host = strings.TrimSpace(host)
host = strings.Trim(host, "[]")
if host == "" {
return nil, errors.New("empty host")
}
if _, banned := metadataNames[strings.ToLower(host)]; banned {
return nil, fmt.Errorf("%w: metadata or localhost name", errForbiddenTarget)
}
if ip := net.ParseIP(host); ip != nil {
if !ipAllowed(ip, allowPrivate, extra) {
return nil, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String())
}
return ip, nil
}
if resolver == nil {
resolver = net.DefaultResolver
}
lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
addrs, err := resolver.LookupIPAddr(lookupCtx, host)
if err != nil {
return nil, err
}
if len(addrs) == 0 {
return nil, &net.DNSError{Err: "no addresses", Name: host, IsNotFound: true}
}
var allowed []net.IP
for _, addr := range addrs {
if ipAllowed(addr.IP, allowPrivate, extra) {
allowed = append(allowed, addr.IP)
}
}
if len(allowed) == 0 {
return nil, fmt.Errorf("%w: %s resolved only to blocked addresses", errForbiddenTarget, host)
}
if len(allowed) != len(addrs) {
return nil, fmt.Errorf("%w: %s resolved to a mix of public and blocked addresses", errForbiddenTarget, host)
}
return allowed[0], nil
}
func ipAllowed(ip net.IP, allowPrivate bool, extra []*net.IPNet) bool {
if ip == nil {
return false
}
if ip.Equal(metadataIP) || ip.Equal(net.ParseIP("fd00:ec2::254")) {
return false
}
for _, n := range extra {
if n.Contains(ip) {
return true
}
}
if ip.IsMulticast() || ip.IsUnspecified() || ip.IsLinkLocalMulticast() {
return false
}
if allowPrivate {
return true
}
if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() {
return false
}
return true
}
type resolver interface {
LookupIPAddr(context.Context, string) ([]net.IPAddr, error)
}