From f6ffbde518f6b57cad5293ec64d458f8ce349ecd Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 23:06:30 +0000 Subject: [PATCH] Import netquality 1.1.1 Initial import of the 1.1.1 source tree. Corresponds to Origin commit f9d97e368818acfe7dd44fa9fe5088b9629d0dff. Co-authored-by: yanjiu0721 --- .gitignore | 3 + README.md | 100 ++- client/.gitignore | 48 + client/.metadata | 36 + client/README.md | 10 + client/analysis_options.yaml | 35 + client/android/.gitignore | 14 + client/android/app/build.gradle.kts | 49 + .../android/app/src/debug/AndroidManifest.xml | 7 + .../android/app/src/main/AndroidManifest.xml | 46 + .../dev/netquality/netquality/MainActivity.kt | 5 + .../res/drawable-v21/launch_background.xml | 12 + .../main/res/drawable/launch_background.xml | 12 + .../src/main/res/mipmap-hdpi/ic_launcher.png | Bin 0 -> 544 bytes .../src/main/res/mipmap-mdpi/ic_launcher.png | Bin 0 -> 442 bytes .../src/main/res/mipmap-xhdpi/ic_launcher.png | Bin 0 -> 721 bytes .../main/res/mipmap-xxhdpi/ic_launcher.png | Bin 0 -> 1031 bytes .../main/res/mipmap-xxxhdpi/ic_launcher.png | Bin 0 -> 1443 bytes .../app/src/main/res/values-night/styles.xml | 18 + .../app/src/main/res/values/styles.xml | 18 + .../app/src/profile/AndroidManifest.xml | 7 + client/android/build.gradle.kts | 24 + client/android/gradle.properties | 6 + .../gradle/wrapper/gradle-wrapper.properties | 5 + client/android/settings.gradle.kts | 26 + client/assets/fonts/NOTICE.txt | 7 + client/assets/fonts/wqy-subset.ttf | Bin 0 -> 130032 bytes client/lib/main.dart | 50 ++ client/lib/metrics/sample_book.dart | 331 +++++++ client/lib/models/probe_profile.dart | 103 +++ client/lib/models/session_config.dart | 291 ++++++ client/lib/probe/endpoint_picker.dart | 76 ++ client/lib/probe/game_codec.dart | 243 +++++ client/lib/probe/probe_controller.dart | 288 ++++++ client/lib/probe/probe_loop.dart | 841 ++++++++++++++++++ client/lib/probe/remote_client.dart | 281 ++++++ client/lib/protocol/probe_packet.dart | 165 ++++ client/lib/storage/app_store.dart | 59 ++ client/lib/storage/token_vault.dart | 103 +++ client/lib/ui/format.dart | 76 ++ client/lib/ui/home_page.dart | 631 +++++++++++++ client/lib/ui/quality_charts.dart | 284 ++++++ client/linux/.gitignore | 1 + client/linux/CMakeLists.txt | 128 +++ client/linux/flutter/CMakeLists.txt | 88 ++ .../flutter/generated_plugin_registrant.cc | 11 + .../flutter/generated_plugin_registrant.h | 15 + client/linux/flutter/generated_plugins.cmake | 24 + client/linux/runner/CMakeLists.txt | 26 + client/linux/runner/main.cc | 6 + client/linux/runner/my_application.cc | 148 +++ client/linux/runner/my_application.h | 21 + client/pubspec.lock | 490 ++++++++++ client/pubspec.yaml | 97 ++ client/test/endpoint_picker_test.dart | 50 ++ client/test/probe_loop_test.dart | 498 +++++++++++ client/test/probe_packet_test.dart | 75 ++ client/test/sample_book_test.dart | 96 ++ client/test/widget_test.dart | 50 ++ client/windows/.gitignore | 17 + client/windows/CMakeLists.txt | 108 +++ client/windows/flutter/CMakeLists.txt | 109 +++ .../flutter/generated_plugin_registrant.cc | 11 + .../flutter/generated_plugin_registrant.h | 15 + .../windows/flutter/generated_plugins.cmake | 24 + client/windows/runner/CMakeLists.txt | 40 + client/windows/runner/Runner.rc | 121 +++ client/windows/runner/flutter_window.cpp | 71 ++ client/windows/runner/flutter_window.h | 33 + client/windows/runner/main.cpp | 43 + client/windows/runner/resource.h | 16 + client/windows/runner/resources/app_icon.ico | Bin 0 -> 33772 bytes client/windows/runner/runner.exe.manifest | 14 + client/windows/runner/utils.cpp | 69 ++ client/windows/runner/utils.h | 19 + client/windows/runner/win32_window.cpp | 288 ++++++ client/windows/runner/win32_window.h | 102 +++ docs/PROTOCOL.md | 86 ++ docs/server-linux.md | 207 +++++ server/.gitignore | 1 + server/Makefile | 10 + server/deploy/netquality-node.service | 23 + server/deploy/netquality-reflector.service | 20 + server/echo.go | 205 +++++ server/go.mod | 3 + server/main.go | 250 ++++++ server/metrics.go | 202 +++++ server/node.go | 568 ++++++++++++ server/node_test.go | 587 ++++++++++++ server/probes.go | 721 +++++++++++++++ server/protocol.go | 145 +++ server/protocol_test.go | 212 +++++ server/safety.go | 97 ++ 93 files changed, 10570 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 client/.gitignore create mode 100644 client/.metadata create mode 100644 client/README.md create mode 100644 client/analysis_options.yaml create mode 100644 client/android/.gitignore create mode 100644 client/android/app/build.gradle.kts create mode 100644 client/android/app/src/debug/AndroidManifest.xml create mode 100644 client/android/app/src/main/AndroidManifest.xml create mode 100644 client/android/app/src/main/kotlin/dev/netquality/netquality/MainActivity.kt create mode 100644 client/android/app/src/main/res/drawable-v21/launch_background.xml create mode 100644 client/android/app/src/main/res/drawable/launch_background.xml create mode 100644 client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png create mode 100644 client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png create mode 100644 client/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png create mode 100644 client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png create mode 100644 client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png create mode 100644 client/android/app/src/main/res/values-night/styles.xml create mode 100644 client/android/app/src/main/res/values/styles.xml create mode 100644 client/android/app/src/profile/AndroidManifest.xml create mode 100644 client/android/build.gradle.kts create mode 100644 client/android/gradle.properties create mode 100644 client/android/gradle/wrapper/gradle-wrapper.properties create mode 100644 client/android/settings.gradle.kts create mode 100644 client/assets/fonts/NOTICE.txt create mode 100644 client/assets/fonts/wqy-subset.ttf create mode 100644 client/lib/main.dart create mode 100644 client/lib/metrics/sample_book.dart create mode 100644 client/lib/models/probe_profile.dart create mode 100644 client/lib/models/session_config.dart create mode 100644 client/lib/probe/endpoint_picker.dart create mode 100644 client/lib/probe/game_codec.dart create mode 100644 client/lib/probe/probe_controller.dart create mode 100644 client/lib/probe/probe_loop.dart create mode 100644 client/lib/probe/remote_client.dart create mode 100644 client/lib/protocol/probe_packet.dart create mode 100644 client/lib/storage/app_store.dart create mode 100644 client/lib/storage/token_vault.dart create mode 100644 client/lib/ui/format.dart create mode 100644 client/lib/ui/home_page.dart create mode 100644 client/lib/ui/quality_charts.dart create mode 100644 client/linux/.gitignore create mode 100644 client/linux/CMakeLists.txt create mode 100644 client/linux/flutter/CMakeLists.txt create mode 100644 client/linux/flutter/generated_plugin_registrant.cc create mode 100644 client/linux/flutter/generated_plugin_registrant.h create mode 100644 client/linux/flutter/generated_plugins.cmake create mode 100644 client/linux/runner/CMakeLists.txt create mode 100644 client/linux/runner/main.cc create mode 100644 client/linux/runner/my_application.cc create mode 100644 client/linux/runner/my_application.h create mode 100644 client/pubspec.lock create mode 100644 client/pubspec.yaml create mode 100644 client/test/endpoint_picker_test.dart create mode 100644 client/test/probe_loop_test.dart create mode 100644 client/test/probe_packet_test.dart create mode 100644 client/test/sample_book_test.dart create mode 100644 client/test/widget_test.dart create mode 100644 client/windows/.gitignore create mode 100644 client/windows/CMakeLists.txt create mode 100644 client/windows/flutter/CMakeLists.txt create mode 100644 client/windows/flutter/generated_plugin_registrant.cc create mode 100644 client/windows/flutter/generated_plugin_registrant.h create mode 100644 client/windows/flutter/generated_plugins.cmake create mode 100644 client/windows/runner/CMakeLists.txt create mode 100644 client/windows/runner/Runner.rc create mode 100644 client/windows/runner/flutter_window.cpp create mode 100644 client/windows/runner/flutter_window.h create mode 100644 client/windows/runner/main.cpp create mode 100644 client/windows/runner/resource.h create mode 100644 client/windows/runner/resources/app_icon.ico create mode 100644 client/windows/runner/runner.exe.manifest create mode 100644 client/windows/runner/utils.cpp create mode 100644 client/windows/runner/utils.h create mode 100644 client/windows/runner/win32_window.cpp create mode 100644 client/windows/runner/win32_window.h create mode 100644 docs/PROTOCOL.md create mode 100644 docs/server-linux.md create mode 100644 server/.gitignore create mode 100644 server/Makefile create mode 100644 server/deploy/netquality-node.service create mode 100644 server/deploy/netquality-reflector.service create mode 100644 server/echo.go create mode 100644 server/go.mod create mode 100644 server/main.go create mode 100644 server/metrics.go create mode 100644 server/node.go create mode 100644 server/node_test.go create mode 100644 server/probes.go create mode 100644 server/protocol.go create mode 100644 server/protocol_test.go create mode 100644 server/safety.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1b573d7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.DS_Store +*.exe +server/netquality-reflector diff --git a/README.md b/README.md index 62135f7..d533a8c 100644 --- a/README.md +++ b/README.md @@ -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`。 diff --git a/client/.gitignore b/client/.gitignore new file mode 100644 index 0000000..79f7eca --- /dev/null +++ b/client/.gitignore @@ -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/ diff --git a/client/.metadata b/client/.metadata new file mode 100644 index 0000000..2cf45df --- /dev/null +++ b/client/.metadata @@ -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' diff --git a/client/README.md b/client/README.md new file mode 100644 index 0000000..7a35c11 --- /dev/null +++ b/client/README.md @@ -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` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。 diff --git a/client/analysis_options.yaml b/client/analysis_options.yaml new file mode 100644 index 0000000..149de80 --- /dev/null +++ b/client/analysis_options.yaml @@ -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 diff --git a/client/android/.gitignore b/client/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/client/android/.gitignore @@ -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 diff --git a/client/android/app/build.gradle.kts b/client/android/app/build.gradle.kts new file mode 100644 index 0000000..f25514e --- /dev/null +++ b/client/android/app/build.gradle.kts @@ -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 = "../.." +} diff --git a/client/android/app/src/debug/AndroidManifest.xml b/client/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/client/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/client/android/app/src/main/AndroidManifest.xml b/client/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..5e386f6 --- /dev/null +++ b/client/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/client/android/app/src/main/kotlin/dev/netquality/netquality/MainActivity.kt b/client/android/app/src/main/kotlin/dev/netquality/netquality/MainActivity.kt new file mode 100644 index 0000000..4d5bd05 --- /dev/null +++ b/client/android/app/src/main/kotlin/dev/netquality/netquality/MainActivity.kt @@ -0,0 +1,5 @@ +package dev.netquality.netquality + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/client/android/app/src/main/res/drawable-v21/launch_background.xml b/client/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/client/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/client/android/app/src/main/res/drawable/launch_background.xml b/client/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/client/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..db77bb4b7b0906d62b1847e87f15cdcacf6a4f29 GIT binary patch literal 544 zcmeAS@N?(olHy`uVBq!ia0vp^9w5xY3?!3`olAj~WQl7;NpOBzNqJ&XDuZK6ep0G} zXKrG8YEWuoN@d~6R2!h8bpbvhu0Wd6uZuB!w&u2PAxD2eNXD>P5D~Wn-+_Wa#27Xc zC?Zj|6r#X(-D3u$NCt}(Ms06KgJ4FxJVv{GM)!I~&n8Bnc94O7-Hd)cjDZswgC;Qs zO=b+9!WcT8F?0rF7!Uys2bs@gozCP?z~o%U|N3vA*22NaGQG zlg@K`O_XuxvZ&Ks^m&R!`&1=spLvfx7oGDKDwpwW`#iqdw@AL`7MR}m`rwr|mZgU`8P7SBkL78fFf!WnuYWm$5Z0 zNXhDbCv&49sM544K|?c)WrFfiZvCi9h0O)B3Pgg&ebxsLQ05GG~ AQ2+n{ literal 0 HcmV?d00001 diff --git a/client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..17987b79bb8a35cc66c3c1fd44f5a5526c1b78be GIT binary patch literal 442 zcmeAS@N?(olHy`uVBq!ia0vp^1|ZDA3?vioaBc-sk|nMYCBgY=CFO}lsSJ)O`AMk? zp1FzXsX?iUDV2pMQ*D5Xx&nMcT!A!W`0S9QKQy;}1Cl^CgaH=;G9cpY;r$Q>i*pfB zP2drbID<_#qf;rPZx^FqH)F_D#*k@@q03KywUtLX8Ua?`H+NMzkczFPK3lFz@i_kW%1NOn0|D2I9n9wzH8m|-tHjsw|9>@K=iMBhxvkv6m8Y-l zytQ?X=U+MF$@3 zt`~i=@j|6y)RWMK--}M|=T`o&^Ni>IoWKHEbBXz7?A@mgWoL>!*SXo`SZH-*HSdS+ yn*9;$7;m`l>wYBC5bq;=U}IMqLzqbYCidGC!)_gkIk_C@Uy!y&wkt5C($~2D>~)O*cj@FGjOCM)M>_ixfudOh)?xMu#Fs z#}Y=@YDTwOM)x{K_j*Q;dPdJ?Mz0n|pLRx{4n|)f>SXlmV)XB04CrSJn#dS5nK2lM zrZ9#~WelCp7&e13Y$jvaEXHskn$2V!!DN-nWS__6T*l;H&Fopn?A6HZ-6WRLFP=R` zqG+CE#d4|IbyAI+rJJ`&x9*T`+a=p|0O(+s{UBcyZdkhj=yS1>AirP+0R;mf2uMgM zC}@~JfByORAh4SyRgi&!(cja>F(l*O+nd+@4m$|6K6KDn_&uvCpV23&>G9HJp{xgg zoq1^2_p9@|WEo z*X_Uko@K)qYYv~>43eQGMdbiGbo>E~Q& zrYBH{QP^@Sti!`2)uG{irBBq@y*$B zi#&(U-*=fp74j)RyIw49+0MRPMRU)+a2r*PJ$L5roHt2$UjExCTZSbq%V!HeS7J$N zdG@vOZB4v_lF7Plrx+hxo7(fCV&}fHq)$ literal 0 HcmV?d00001 diff --git a/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..d5f1c8d34e7a88e3f88bea192c3a370d44689c3c GIT binary patch literal 1031 zcmeAS@N?(olHy`uVBq!ia0vp^6F``Q8Ax83A=Cw=BuiW)N`mv#O3D+9QW+dm@{>{( zJaZG%Q-e|yQz{EjrrIztFa`(sgt!6~Yi|1%a`XoT0ojZ}lNrNjb9xjc(B0U1_% zz5^97Xt*%oq$rQy4?0GKNfJ44uvxI)gC`h-NZ|&0-7(qS@?b!5r36oQ}zyZrNO3 zMO=Or+<~>+A&uN&E!^Sl+>xE!QC-|oJv`ApDhqC^EWD|@=#J`=d#Xzxs4ah}w&Jnc z$|q_opQ^2TrnVZ0o~wh<3t%W&flvYGe#$xqda2bR_R zvPYgMcHgjZ5nSA^lJr%;<&0do;O^tDDh~=pIxA#coaCY>&N%M2^tq^U%3DB@ynvKo}b?yu-bFc-u0JHzced$sg7S3zqI(2 z#Km{dPr7I=pQ5>FuK#)QwK?Y`E`B?nP+}U)I#c1+FM*1kNvWG|a(TpksZQ3B@sD~b zpQ2)*V*TdwjFOtHvV|;OsiDqHi=6%)o4b!)x$)%9pGTsE z-JL={-Ffv+T87W(Xpooq<`r*VzWQcgBN$$`u}f>-ZQI1BB8ykN*=e4rIsJx9>z}*o zo~|9I;xof literal 0 HcmV?d00001 diff --git a/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/client/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..4d6372eebdb28e45604e46eeda8dd24651419bc0 GIT binary patch literal 1443 zcmb`G{WsKk6vsdJTdFg%tJav9_E4vzrOaqkWF|A724Nly!y+?N9`YV6wZ}5(X(D_N(?!*n3`|_r0Hc?=PQw&*vnU?QTFY zB_MsH|!j$PP;I}?dppoE_gA(4uc!jV&0!l7_;&p2^pxNo>PEcNJv za5_RT$o2Mf!<+r?&EbHH6nMoTsDOa;mN(wv8RNsHpG)`^ymG-S5By8=l9iVXzN_eG%Xg2@Xeq76tTZ*dGh~Lo9vl;Zfs+W#BydUw zCkZ$o1LqWQO$FC9aKlLl*7x9^0q%0}$OMlp@Kk_jHXOjofdePND+j!A{q!8~Jn+s3 z?~~w@4?egS02}8NuulUA=L~QQfm;MzCGd)XhiftT;+zFO&JVyp2mBww?;QByS_1w! zrQlx%{^cMj0|Bo1FjwY@Q8?Hx0cIPF*@-ZRFpPc#bBw{5@tD(5%sClzIfl8WU~V#u zm5Q;_F!wa$BSpqhN>W@2De?TKWR*!ujY;Yylk_X5#~V!L*Gw~;$%4Q8~Mad z@`-kG?yb$a9cHIApZDVZ^U6Xkp<*4rU82O7%}0jjHlK{id@?-wpN*fCHXyXh(bLt* zPc}H-x0e4E&nQ>y%B-(EL=9}RyC%MyX=upHuFhAk&MLbsF0LP-q`XnH78@fT+pKPW zu72MW`|?8ht^tz$iC}ZwLp4tB;Q49K!QCF3@!iB1qOI=?w z7In!}F~ij(18UYUjnbmC!qKhPo%24?8U1x{7o(+?^Zu0Hx81|FuS?bJ0jgBhEMzf< zCgUq7r2OCB(`XkKcN-TL>u5y#dD6D!)5W?`O5)V^>jb)P)GBdy%t$uUMpf$SNV31$ zb||OojAbvMP?T@$h_ZiFLFVHDmbyMhJF|-_)HX3%m=CDI+ID$0^C>kzxprBW)hw(v zr!Gmda);ICoQyhV_oP5+C%?jcG8v+D@9f?Dk*!BxY}dazmrT@64UrP3hlslANK)bq z$67n83eh}OeW&SV@HG95P|bjfqJ7gw$e+`Hxo!4cx`jdK1bJ>YDSpGKLPZ^1cv$ek zIB?0S<#tX?SJCLWdMd{-ME?$hc7A$zBOdIJ)4!KcAwb=VMov)nK;9z>x~rfT1>dS+ zZ6#`2v@`jgbqq)P22H)Tx2CpmM^o1$B+xT6`(v%5xJ(?j#>Q$+rx_R|7TzDZe{J6q zG1*EcU%tE?!kO%^M;3aM6JN*LAKUVb^xz8-Pxo#jR5(-KBeLJvA@-gxNHx0M-ZJLl z;#JwQoh~9V?`UVo#}{6ka@II>++D@%KqGpMdlQ}?9E*wFcf5(#XQnP$Dk5~%iX^>f z%$y;?M0BLp{O3a(-4A?ewryHrrD%cx#Q^%KY1H zNre$ve+vceSLZcNY4U(RBX&)oZn*Py()h)XkE?PL$!bNb{N5FVI2Y%LKEm%yvpyTP z(1P?z~7YxD~Rf<(a@_y` literal 0 HcmV?d00001 diff --git a/client/android/app/src/main/res/values-night/styles.xml b/client/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/client/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/client/android/app/src/main/res/values/styles.xml b/client/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/client/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/client/android/app/src/profile/AndroidManifest.xml b/client/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/client/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/client/android/build.gradle.kts b/client/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/client/android/build.gradle.kts @@ -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("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/client/android/gradle.properties b/client/android/gradle.properties new file mode 100644 index 0000000..e96108c --- /dev/null +++ b/client/android/gradle.properties @@ -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 diff --git a/client/android/gradle/wrapper/gradle-wrapper.properties b/client/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a20f2c4 --- /dev/null +++ b/client/android/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/client/android/settings.gradle.kts b/client/android/settings.gradle.kts new file mode 100644 index 0000000..b28021a --- /dev/null +++ b/client/android/settings.gradle.kts @@ -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") diff --git a/client/assets/fonts/NOTICE.txt b/client/assets/fonts/NOTICE.txt new file mode 100644 index 0000000..5195896 --- /dev/null +++ b/client/assets/fonts/NOTICE.txt @@ -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 diff --git a/client/assets/fonts/wqy-subset.ttf b/client/assets/fonts/wqy-subset.ttf new file mode 100644 index 0000000000000000000000000000000000000000..d30e282cda460298378de7373485e3a45a3f8ee0 GIT binary patch literal 130032 zcma&O31A!LnKwS~JDQPvNh6=K9ov%SLynV3v0_`!q1+uTygxe+wuEP zI8JCX3yyqm zKgW4HV>cX#ed7PPYB=&8T#vqYGp<+hl&ygy(^x;(aWk&hQ@#1?9QmV(ou8vL485d< zEXQLN9C6uQgLu#|ADYQTXEe@48$ey?<{Z)CBrm$-R9zhou#_qEcx zS}S$8FQO!LtN)!sZTq6;CU1LfZM(Orc~N^U`LfAz{>83-m(Awt@9OMtm!$T7EQ`CF ze~Nz7ki^Ul%5IZlHkakgCd#O{?0DI!GM-a7Ug9VC0&n6)O3gf^@cX@f;vG3RGEzO{ zJ-66LcsK9DgKX$I*+Uoh+|VPO(F#;z4|WYd9BK;JXy)3uFUnz_Z)$SXx3-u~Vnc)2 z$PtrCc;4Y~)wRvDn96Evt8LZ_Q_b_`A&E#*Wo22YoRrTa!75VqY^B9i*~UrF+8gWa z!}cxqckFznz0xi;)QIH*=k*W!tA~cX-VwXs4;A$pKSuicAS{#FJ0ksO!%&~Sx?#xf z_p+D%(rdq$t-@7@Rn!=depihP4?k}_>Ii=2|7Dms^q+3Kf4lzkZK=(=PFhy!za_of z?%zf_x2Lufapu2?Th@Qh->zp*>)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HCIx03Q z6lIFaf-kcb;|)fYL>0m(q&%@vF;O8yS(IS7q=a+-VkIVz&*GIRZkAf}<8}^%`<1Xz zLz9}aBq{;;i-FCJUn6K>Fo6p`EL9LL&0ZW;rus4%B~daS7Ds^?B`9v@!_u2z26?!l z5k3jvF@%>vGa*Hp5>^PejF*`q_%RF#_;tfKS_uh3B7TH1s3rQ#a0VeM&K;+)Sb@u8 zv8PNmxrQR%#~&^m7K6Jrlew<9Yw?*clRTp-7StIPeegjKnABKk7Jg;CZrB+Y5jY$d%Rvnq zvuQ3C$~aI!z7=p}(6A>j*#W?p+j-wM0V`;T!3hbUAzBL4GJ_GY>ZLMTgHt2r zqR&ubFc}*0GAZz~!t<87c<#!ufqJn?;h_Y4`J+lGlRd*xOsk}FU~)rFA(2tUaLX(% zse(_X7>)D-^AQ^i^{|Hwb%t8Jbz&^S8-T?J4P~&9M)`$5Vl^sqD2a+STx6+$F9x_n zkfsuj*wHMW62@XPynut)CdkeWR~DlQ4@;GWR6HkG3Kp6mMoX7q2Jx0i7YR!r1WX00 zSjFN<4T?7Kn#zdqkl4t60XIv*i(E0pf`dZ%Ar}?ON(gdHi4{VwmBG&s3Ya{Lkv@x7 zAq+Oq&r+2{MN5^68?sV3X7EF_CaM@T_+e)n#r*tY4Puwzv|km{%8G9xC@+C@gMh{O zV0^M)mWI(#Y-q%d*$jV-DlLY$L}Czwq#k~;&_SeNd7(TB2xr=-Pza4e-63TGwp$9o zPtgP=jK$7UIFO@^IDuD*m|TBi8I_=(!SI2KECnKq&*%&p8kO`i+&;X1MP`MNUNNX) zl4G*>pVR3FbR%g*IE%#~_(2(y zPDl*H#^EA_Rst5o!R%Z+U=tO$l0qqA3S}B3rYTA|T6H0+%+QEX)d&7=_QiVjVbYLQ kJF5{G1;B 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 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 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 detail; + final ProbeSummary summary; + + factory ProbeSample.fromJson(Map json) { + final summary = json['summary'] is Map + ? ProbeSummary.fromJson(Map.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 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 _detail(Object? value) { + if (value is! Map) { + return const {}; + } + final out = {}; + value.forEach((key, item) { + if (key is String && item is String) { + out[key] = item; + } + }); + return out; +} diff --git a/client/lib/models/probe_profile.dart b/client/lib/models/probe_profile.dart new file mode 100644 index 0000000..fc1bf69 --- /dev/null +++ b/client/lib/models/probe_profile.dart @@ -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 = [ + 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; diff --git a/client/lib/models/session_config.dart b/client/lib/models/session_config.dart new file mode 100644 index 0000000..50700da --- /dev/null +++ b/client/lib/models/session_config.dart @@ -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 toJson() => { + 'id': id, + 'name': name, + 'baseUrl': baseUrl, + 'visibility': visibility, + }; + + factory RemoteNode.fromJson(Map 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 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 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 json) { + final rawNodes = json['nodes']; + final nodes = []; + if (rawNodes is List) { + for (final item in rawNodes) { + if (item is Map) { + nodes.add(RemoteNode.fromJson(Map.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.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, + ); +} diff --git a/client/lib/probe/endpoint_picker.dart b/client/lib/probe/endpoint_picker.dart new file mode 100644 index 0000000..d821746 --- /dev/null +++ b/client/lib/probe/endpoint_picker.dart @@ -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 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> 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 = {}; + final unique = []; + for (final address in found) { + if (seen.add('${address.type.name} ${address.address}')) { + unique.add(address); + } + } + return unique; +} diff --git a/client/lib/probe/game_codec.dart b/client/lib/probe/game_codec.dart new file mode 100644 index 0000000..a9b5a1b --- /dev/null +++ b/client/lib/probe/game_codec.dart @@ -0,0 +1,243 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +const rakMagic = [ + 0x00, + 0xff, + 0xff, + 0x00, + 0xfe, + 0xfe, + 0xfe, + 0xfe, + 0xfd, + 0xfd, + 0xfd, + 0xfd, + 0x12, + 0x34, + 0x56, + 0x78, +]; + +Uint8List encodeVarInt(int value) { + final out = []; + 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 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 minecraftStatusDetail(String raw) { + final decoded = jsonDecode(raw); + if (decoded is! Map) { + return const {}; + } + final out = {}; + 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? 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 = {}; + 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; +} diff --git a/client/lib/probe/probe_controller.dart b/client/lib/probe/probe_controller.dart new file mode 100644 index 0000000..f970b16 --- /dev/null +++ b/client/lib/probe/probe_controller.dart @@ -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 detail; + final ProbeSummary summary; + final List 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? detail, + ProbeSummary? summary, + List? 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 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 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 '出错'; + } +} diff --git a/client/lib/probe/probe_loop.dart b/client/lib/probe/probe_loop.dart new file mode 100644 index 0000000..1a72e67 --- /dev/null +++ b/client/lib/probe/probe_loop.dart @@ -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> 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 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.delayed(rest); + } + } + } finally { + await close(); + } + } + + Future 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 _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 _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 _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 _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 _dropTcp() async { + final tcp = _tcp; + _tcp = null; + if (tcp != null) { + await tcp.close(); + } + } + + Future _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 _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 _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 _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? 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 _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 _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 _frames = []; + late final StreamSubscription _sub; + Completer? _pending; + bool _failed = false; + var _cursor = 0; + + void _signal() { + final pending = _pending; + _pending = null; + if (pending != null && !pending.isCompleted) { + pending.complete(); + } + } + + Future 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(); + _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 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 _queue = []; + late final StreamSubscription _sub; + Completer? _pending; + var _cursor = 0; + + void send(List bytes, int port) { + socket.send(bytes, peer, port); + } + + void _signal() { + final pending = _pending; + _pending = null; + if (pending != null && !pending.isCompleted) { + pending.complete(); + } + } + + Future 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(); + _pending = waiter; + if (_cursor < _queue.length) { + _signal(); + } + try { + await waiter.future.timeout(left); + } on TimeoutException { + if (identical(_pending, waiter)) { + _pending = null; + } + return null; + } + } + } + + Future 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 _sub; + Completer? _pending; + + void _signal() { + final pending = _pending; + _pending = null; + if (pending != null && !pending.isCompleted) { + pending.complete(); + } + } + + Future 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(); + _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 close() => _sub.cancel(); +} diff --git a/client/lib/probe/remote_client.dart b/client/lib/probe/remote_client.dart new file mode 100644 index 0000000..562fe17 --- /dev/null +++ b/client/lib/probe/remote_client.dart @@ -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 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 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 _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 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 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 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.from(json)); + if (sample.status.isEmpty || sample.status == 'pending') { + return null; + } + return sample; + } on FormatException { + return null; + } +} diff --git a/client/lib/protocol/probe_packet.dart b/client/lib/protocol/probe_packet.dart new file mode 100644 index 0000000..84bcda9 --- /dev/null +++ b/client/lib/protocol/probe_packet.dart @@ -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 add(List chunk) { + _buf.add(chunk); + final bytes = _buf.toBytes(); + var offset = 0; + final frames = []; + 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(); + } +} diff --git a/client/lib/storage/app_store.dart b/client/lib/storage/app_store.dart new file mode 100644 index 0000000..c34e5ba --- /dev/null +++ b/client/lib/storage/app_store.dart @@ -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.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 save(SessionConfig config) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_key, jsonEncode(config.toJson())); + } +} + +Future 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(); + } +} diff --git a/client/lib/storage/token_vault.dart b/client/lib/storage/token_vault.dart new file mode 100644 index 0000000..daa5a5c --- /dev/null +++ b/client/lib/storage/token_vault.dart @@ -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 read(String key); + Future write(String key, String value); + Future delete(String key); +} + +class MemoryTokenVault implements TokenVault { + final Map _values = {}; + + @override + Future delete(String key) async { + _values.remove(key); + } + + @override + Future read(String key) async => _values[key]; + + @override + Future 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 _values = {}; + bool _loaded = false; + + Future 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 delete(String key) async { + await load(); + _values.remove(key); + await _flush(); + } + + @override + Future read(String key) async { + await load(); + return _values[key]; + } + + @override + Future write(String key, String value) async { + await load(); + if (value.isEmpty) { + _values.remove(key); + } else { + _values[key] = value; + } + await _flush(); + } + + Future _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'; diff --git a/client/lib/ui/format.dart b/client/lib/ui/format.dart new file mode 100644 index 0000000..c4cd3f5 --- /dev/null +++ b/client/lib/ui/format.dart @@ -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 = [ + '完成 ${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(' · '); +} diff --git a/client/lib/ui/home_page.dart b/client/lib/ui/home_page.dart new file mode 100644 index 0000000..6e3a537 --- /dev/null +++ b/client/lib/ui/home_page.dart @@ -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 createState() => _HomePageState(); +} + +class _HomePageState extends State { + 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 = []; + var _ready = false; + + @override + void initState() { + super.initState(); + _controller.addListener(_rebuild); + _load(); + } + + Future _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 _persist() async { + await _store.save(_config()); + await _vault.write(echoTokenKey, _echo.text); + } + + Future _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( + 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().followedBy(const [null]).firstWhere( + (node) => node?.id == _nodeId, + orElse: () => null, + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SegmentedButton( + 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( + 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 _manageNodes() async { + await showDialog( + 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 nodes; + final TokenVault vault; + final void Function(List nodes, String? selected) onChanged; + + @override + State<_NodeDialog> createState() => _NodeDialogState(); +} + +class _NodeDialogState extends State<_NodeDialog> { + late List _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 _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 _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 _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))), + ); +} diff --git a/client/lib/ui/quality_charts.dart b/client/lib/ui/quality_charts.dart new file mode 100644 index 0000000..7b255c3 --- /dev/null +++ b/client/lib/ui/quality_charts.dart @@ -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 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 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 _spots() { + final spots = []; + 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 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); +} diff --git a/client/linux/.gitignore b/client/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/client/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/client/linux/CMakeLists.txt b/client/linux/CMakeLists.txt new file mode 100644 index 0000000..4d67193 --- /dev/null +++ b/client/linux/CMakeLists.txt @@ -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 "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>: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() diff --git a/client/linux/flutter/CMakeLists.txt b/client/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/client/linux/flutter/CMakeLists.txt @@ -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} +) diff --git a/client/linux/flutter/generated_plugin_registrant.cc b/client/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/client/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/client/linux/flutter/generated_plugin_registrant.h b/client/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/client/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/client/linux/flutter/generated_plugins.cmake b/client/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..be1ee3e --- /dev/null +++ b/client/linux/flutter/generated_plugins.cmake @@ -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 $) + 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) diff --git a/client/linux/runner/CMakeLists.txt b/client/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/client/linux/runner/CMakeLists.txt @@ -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}") diff --git a/client/linux/runner/main.cc b/client/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/client/linux/runner/main.cc @@ -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); +} diff --git a/client/linux/runner/my_application.cc b/client/linux/runner/my_application.cc new file mode 100644 index 0000000..0824cc7 --- /dev/null +++ b/client/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#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)); +} diff --git a/client/linux/runner/my_application.h b/client/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/client/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +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_ diff --git a/client/pubspec.lock b/client/pubspec.lock new file mode 100644 index 0000000..db01969 --- /dev/null +++ b/client/pubspec.lock @@ -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" diff --git a/client/pubspec.yaml b/client/pubspec.yaml new file mode 100644 index 0000000..9906526 --- /dev/null +++ b/client/pubspec.yaml @@ -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 diff --git a/client/test/endpoint_picker_test.dart b/client/test/endpoint_picker_test.dart new file mode 100644 index 0000000..88992a5 --- /dev/null +++ b/client/test/endpoint_picker_test.dart @@ -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); + }); +} diff --git a/client/test/probe_loop_test.dart b/client/test/probe_loop_test.dart new file mode 100644 index 0000000..fb94d51 --- /dev/null +++ b/client/test/probe_loop_test.dart @@ -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 = []; + final remote = RemoteProbe(); + final done = Completer(); + 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 = []; + 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> _collect( + ProbeRequest request, { + required int count, + ProbeLoop? loop, +}) async { + final probe = loop ?? ProbeLoop(); + final samples = []; + 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(); + 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 _waitListen(Process process) async { + final ready = Completer(); + 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 _freeTcp() async { + final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final port = server.port; + await server.close(); + return port; +} + +Future _freeUdp() async { + final socket = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0); + final port = socket.port; + socket.close(); + return port; +} + +Future<({int port, Future 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? _pending; + + Future 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(); + _pending = waiter; + if (takeMcPacket(_buf.toBytes()) != null) { + waiter.complete(); + } + try { + await waiter.future.timeout(left); + } on TimeoutException { + return null; + } + } + } +} diff --git a/client/test/probe_packet_test.dart b/client/test/probe_packet_test.dart new file mode 100644 index 0000000..2681596 --- /dev/null +++ b/client/test/probe_packet_test.dart @@ -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())); + }); + + 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()), + ); + final extra = Uint8List(packet.length + 1)..setRange(0, packet.length, packet); + expect(() => ProbePacket.decode(extra), throwsA(isA())); + }); +} diff --git a/client/test/sample_book_test.dart b/client/test/sample_book_test.dart new file mode 100644 index 0000000..0b4ee7d --- /dev/null +++ b/client/test/sample_book_test.dart @@ -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 json) { + return json.keys.contains('nodeToken') || json.values.contains('node-control-secret'); +} diff --git a/client/test/widget_test.dart b/client/test/widget_test.dart new file mode 100644 index 0000000..0dfe315 --- /dev/null +++ b/client/test/widget_test.dart @@ -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); + }); +} diff --git a/client/windows/.gitignore b/client/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/client/windows/.gitignore @@ -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/ diff --git a/client/windows/CMakeLists.txt b/client/windows/CMakeLists.txt new file mode 100644 index 0000000..575c723 --- /dev/null +++ b/client/windows/CMakeLists.txt @@ -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 "$<$:_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 "$") +# 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) diff --git a/client/windows/flutter/CMakeLists.txt b/client/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/client/windows/flutter/CMakeLists.txt @@ -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} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/client/windows/flutter/generated_plugin_registrant.cc b/client/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/client/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/client/windows/flutter/generated_plugin_registrant.h b/client/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/client/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/client/windows/flutter/generated_plugins.cmake b/client/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..3ad69c6 --- /dev/null +++ b/client/windows/flutter/generated_plugins.cmake @@ -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 $) + 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) diff --git a/client/windows/runner/CMakeLists.txt b/client/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/client/windows/runner/CMakeLists.txt @@ -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) diff --git a/client/windows/runner/Runner.rc b/client/windows/runner/Runner.rc new file mode 100644 index 0000000..608775c --- /dev/null +++ b/client/windows/runner/Runner.rc @@ -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 diff --git a/client/windows/runner/flutter_window.cpp b/client/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/client/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#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( + 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 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); +} diff --git a/client/windows/runner/flutter_window.h b/client/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/client/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#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_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/client/windows/runner/main.cpp b/client/windows/runner/main.cpp new file mode 100644 index 0000000..6460f0c --- /dev/null +++ b/client/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#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 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; +} diff --git a/client/windows/runner/resource.h b/client/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/client/windows/runner/resource.h @@ -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 diff --git a/client/windows/runner/resources/app_icon.ico b/client/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c04e20caf6370ebb9253ad831cc31de4a9c965f6 GIT binary patch literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^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Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK literal 0 HcmV?d00001 diff --git a/client/windows/runner/runner.exe.manifest b/client/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/client/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/client/windows/runner/utils.cpp b/client/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/client/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +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 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::vector 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(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(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; +} diff --git a/client/windows/runner/utils.h b/client/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/client/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// 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, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/client/windows/runner/win32_window.cpp b/client/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/client/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#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(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( + 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(origin.x), + static_cast(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(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(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(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( + 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)); + } +} diff --git a/client/windows/runner/win32_window.h b/client/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/client/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// 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_ diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md new file mode 100644 index 0000000..96f92e7 --- /dev/null +++ b/docs/PROTOCOL.md @@ -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 的单元测试都锁了这组字节。实现另一套客户端时,先对上这组字节再谈连上服务器。 diff --git a/docs/server-linux.md b/docs/server-linux.md new file mode 100644 index 0000000..0f50f08 --- /dev/null +++ b/docs/server-linux.md @@ -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,不代表宽带或移动网络的质量。 diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..0821839 --- /dev/null +++ b/server/.gitignore @@ -0,0 +1 @@ +/netquality-reflector diff --git a/server/Makefile b/server/Makefile new file mode 100644 index 0000000..12c4b32 --- /dev/null +++ b/server/Makefile @@ -0,0 +1,10 @@ +.PHONY: build run test + +build: + go build -o netquality-reflector . + +run: build + ./netquality-reflector + +test: + go test ./... diff --git a/server/deploy/netquality-node.service b/server/deploy/netquality-node.service new file mode 100644 index 0000000..03a8f29 --- /dev/null +++ b/server/deploy/netquality-node.service @@ -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 diff --git a/server/deploy/netquality-reflector.service b/server/deploy/netquality-reflector.service new file mode 100644 index 0000000..0581a9e --- /dev/null +++ b/server/deploy/netquality-reflector.service @@ -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 diff --git a/server/echo.go b/server/echo.go new file mode 100644 index 0000000..30420a8 --- /dev/null +++ b/server/echo.go @@ -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() + } +} diff --git a/server/go.mod b/server/go.mod new file mode 100644 index 0000000..1227ccf --- /dev/null +++ b/server/go.mod @@ -0,0 +1,3 @@ +module netquality/server + +go 1.22 diff --git a/server/main.go b/server/main.go new file mode 100644 index 0000000..260daca --- /dev/null +++ b/server/main.go @@ -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 + } +} diff --git a/server/metrics.go b/server/metrics.go new file mode 100644 index 0000000..4d9e77b --- /dev/null +++ b/server/metrics.go @@ -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"` +} diff --git a/server/node.go b/server/node.go new file mode 100644 index 0000000..b6a40c8 --- /dev/null +++ b/server/node.go @@ -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: + } + } +} diff --git a/server/node_test.go b/server/node_test.go new file mode 100644 index 0000000..434fe2c --- /dev/null +++ b/server/node_test.go @@ -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) } diff --git a/server/probes.go b/server/probes.go new file mode 100644 index 0000000..565d4de --- /dev/null +++ b/server/probes.go @@ -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 +} diff --git a/server/protocol.go b/server/protocol.go new file mode 100644 index 0000000..f188490 --- /dev/null +++ b/server/protocol.go @@ -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 +} diff --git a/server/protocol_test.go b/server/protocol_test.go new file mode 100644 index 0000000..c010774 --- /dev/null +++ b/server/protocol_test.go @@ -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 +} diff --git a/server/safety.go b/server/safety.go new file mode 100644 index 0000000..ced841b --- /dev/null +++ b/server/safety.go @@ -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) +}