Merge pull request #5: HTTP 探测改为填写网址,缺本机引擎时立刻失败

HTTP 探测改为填写网址,缺本机引擎时立刻失败
This commit is contained in:
yanjiu0721 authored and GitHub committed 2026-11-27 07:11:45 +08:00
commit b8cc446454
20 files changed
+778 -102

No files matched your search

+2 -2
View File
@@ -60,14 +60,14 @@ flutter run -d linux
1. 「探测来源」选「本机」或「远程节点」。 1. 「探测来源」选「本机」或「远程节点」。
2. 远程时点「管理节点」。名称自定。地址写成 `https://你的域名:8443` 这种控制地址,不要把口令写进地址。公开节点的口令留空;私有节点把节点口令填在这一栏。它和目标回显口令不是同一个。 2. 远程时点「管理节点」。名称自定。地址写成 `https://你的域名:8443` 这种控制地址,不要把口令写进地址。公开节点的口令留空;私有节点把节点口令填在这一栏。它和目标回显口令不是同一个。
3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。 3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。HTTP 不单独填端口:写成 `https://www.cause-by-siky.top:2025/` 这样的完整网址,或只写主机名。只写主机名或 IP 时按 `http://主机/`,端口是 80。HTTP 超时默认 5000 毫秒。
4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。 4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。
本机的 UDP 探测会记下这次解析出的每个地址。结果上的「实际地址」是真正发包或连通的地址,并注明 IPv4 或 IPv6。域名解析出来的地址单独标成「解析到」,不会被说成已经在用。还没有哪个地址应答时,一次失败就换下一个,这次失败不计入正式丢包,界面会说明回退;已经有应答之后,超时算正式结果,要连续三次没有应答才换。全部地址都失败时显示失败,不会显示 0% 成功。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。 本机的 UDP 探测会记下这次解析出的每个地址。结果上的「实际地址」是真正发包或连通的地址,并注明 IPv4 或 IPv6。域名解析出来的地址单独标成「解析到」,不会被说成已经在用。还没有哪个地址应答时,一次失败就换下一个,这次失败不计入正式丢包,界面会说明回退;已经有应答之后,超时算正式结果,要连续三次没有应答才换。全部地址都失败时显示失败,不会显示 0% 成功。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。
远程节点从 1.1.2 起会在每条结果里带上实际地址。更早的节点没有这个字段时,界面写明「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。1.1.1 的节点仍会把选址失败算进统计。 远程节点从 1.1.2 起会在每条结果里带上实际地址。更早的节点没有这个字段时,界面写明「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。1.1.1 的节点仍会把选址失败算进统计。
端口框写着当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。 端口框写着当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。HTTP 模式不显示这个端口框。
已有远程节点可以改名称、控制地址和口令。节点编号和当前选择不变。口令留空表示不改,界面不显示已经保存的口令。 已有远程节点可以改名称、控制地址和口令。节点编号和当前选择不变。口令留空表示不改,界面不显示已经保存的口令。
+1 -1
View File
@@ -7,4 +7,4 @@ flutter pub get
flutter run -d linux flutter run -d linux
``` ```
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。合作反射 UDP 默认 `19091`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。当前版本是 1.1.3。本机 HTTP 探测需要旁边有 `netquality-reflector`,或设置 `NQ_PROBE_HELPER`。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。 默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。合作反射 UDP 默认 `19091`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。当前版本是 1.1.3。HTTP 的目标是完整网址,或只写主机名(按 http、端口 80),不再单独填端口,超时默认 5000 毫秒。本机 HTTP 探测需要旁边有 `netquality-reflector`,或设置 `NQ_PROBE_HELPER`;找不到或启动不了时会立刻说明,并建议改用远程节点。Android 安装包不包含这个程序。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。
+103
View File
@@ -0,0 +1,103 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
/// An HTTP probe target. The separate port field is not used.
class HttpTarget {
const HttpTarget({
required this.url,
required this.host,
required this.port,
required this.scheme,
});
/// Canonical absolute URL. Default ports are omitted.
final String url;
/// Hostname or IP, without brackets.
final String host;
final int port;
final String scheme;
}
HttpTarget? parseHttpTarget(String raw) => readHttpTarget(raw).target;
String? httpTargetError(String raw) => readHttpTarget(raw).error;
({HttpTarget? target, String? error}) readHttpTarget(String raw) {
final text = raw.trim();
if (text.isEmpty) {
return (target: null, error: '请填写目标地址');
}
if (text.contains('://')) {
final uri = Uri.tryParse(text);
if (uri == null) {
return (target: null, error: _portOrUrlError(text));
}
if ((uri.scheme != 'http' && uri.scheme != 'https') || uri.host.isEmpty) {
return (target: null, error: 'HTTP 目标需要是主机名或 http/https 网址');
}
return _fromUri(uri);
}
final cut = _splitCut(text);
final hostport = cut < 0 ? text : text.substring(0, cut);
final rest = cut < 0 ? '' : text.substring(cut);
if (hostport.isEmpty) {
return (target: null, error: 'HTTP 目标需要是主机名或 http/https 网址');
}
var bracketed = hostport;
if (':'.allMatches(hostport).length >= 2 && !hostport.startsWith('[')) {
bracketed = '[$hostport]';
}
final uri = Uri.tryParse('http://$bracketed$rest');
if (uri == null || uri.host.isEmpty || uri.scheme != 'http') {
return (target: null, error: _portOrUrlError(text));
}
return _fromUri(uri);
}
({HttpTarget? target, String? error}) _fromUri(Uri uri) {
final port = uri.hasPort ? uri.port : (uri.scheme == 'https' ? 443 : 80);
if (port < 1 || port > 65535) {
return (target: null, error: '端口需要在 1 到 65535 之间');
}
final built = Uri(
scheme: uri.scheme,
host: uri.host,
port: port,
path: uri.path.isEmpty ? '/' : uri.path,
query: uri.hasQuery ? uri.query : null,
fragment: uri.hasFragment ? uri.fragment : null,
);
return (
target: HttpTarget(
url: built.toString(),
host: uri.host,
port: port,
scheme: uri.scheme,
),
error: null,
);
}
int _splitCut(String text) {
final slash = text.indexOf('/');
final query = text.indexOf('?');
if (slash < 0) {
return query;
}
if (query < 0) {
return slash;
}
return slash < query ? slash : query;
}
String _portOrUrlError(String text) {
final match = RegExp(r':(\d+)(?=[/?#]|$)').firstMatch(text);
if (match != null) {
final port = int.tryParse(match.group(1)!);
if (port == null || port < 1 || port > 65535) {
return '端口需要在 1 到 65535 之间';
}
}
return 'HTTP 目标需要是主机名或 http/https 网址';
}
+17 -8
View File
@@ -23,20 +23,29 @@ String portHint(ProbeProfile profile) {
return '合作反射 TCP 默认 19090'; return '合作反射 TCP 默认 19090';
case 'nq-udp': case 'nq-udp':
return '合作反射 UDP 默认 19091'; return '合作反射 UDP 默认 19091';
case 'http':
return 'HTTP 默认 443(https)或 80(http)';
default: default:
return '${profile.label} 默认 ${profile.port}'; return '${profile.label} 默认 ${profile.port}';
} }
} }
/// Default port for an HTTP target. A full http:// URL uses 80. Anything else uses 443. const nonHttpTimeoutMs = 1000;
int httpDefaultPort(String target) { const httpTimeoutMs = 5000;
final text = target.trim().toLowerCase();
if (text.startsWith('http://')) { int timeoutDefaultFor(String profileId) =>
return 80; profileId == 'http' ? httpTimeoutMs : nonHttpTimeoutMs;
/// An empty timeout, or one that is still the previous profile's default,
/// follows the newly selected profile. A value the user typed stays.
String timeoutAfterProfileChange({
required String current,
required int previousDefault,
required int nextDefault,
}) {
final trimmed = current.trim();
if (trimmed.isEmpty || int.tryParse(trimmed) == previousDefault) {
return '$nextDefault';
} }
return 443; return current;
} }
const portHelperText = const portHelperText =
+1 -2
View File
@@ -68,8 +68,7 @@ class ProbeProfile {
id: 'http', id: 'http',
label: 'HTTP', label: 'HTTP',
port: 443, port: 443,
blurb: blurb: '按 HTTP 请求测量。目标填完整网址;只填主机名或 IP 时按 http,端口 80。默认优先 HTTP/2,服务器不支持时降到 HTTP/1.1。强制的版本不支持就失败,不会偷偷降级。4xx 和 5xx 会显示状态码,不算丢包。',
'按 HTTP 请求测量。默认优先 HTTP/2,服务器不支持时降到 HTTP/1.1。强制的版本不支持就失败,不会偷偷降级。4xx 和 5xx 会显示状态码,不算丢包。',
rateLabel: '失败率', rateLabel: '失败率',
); );
static const customUdp = ProbeProfile( static const customUdp = ProbeProfile(
+26 -12
View File
@@ -1,6 +1,7 @@
import 'dart:convert'; import 'dart:convert';
import '../protocol/probe_packet.dart'; import '../protocol/probe_packet.dart';
import 'http_target.dart';
import 'ip_family.dart'; import 'ip_family.dart';
import 'probe_profile.dart'; import 'probe_profile.dart';
@@ -66,7 +67,9 @@ class RemoteNode {
baseUrl: confidential baseUrl: confidential
? '' ? ''
: (json['baseUrl'] is String ? json['baseUrl'] as String : ''), : (json['baseUrl'] is String ? json['baseUrl'] as String : ''),
visibility: json['visibility'] is String ? json['visibility'] as String : '', visibility: json['visibility'] is String
? json['visibility'] as String
: '',
fromCenter: json['fromCenter'] == true, fromCenter: json['fromCenter'] == true,
confidential: confidential, confidential: confidential,
centerLinkId: json['centerLinkId'] is String centerLinkId: json['centerLinkId'] is String
@@ -88,11 +91,7 @@ class CenterLink {
final String url; final String url;
final String account; final String account;
Map<String, Object?> toJson() => { Map<String, Object?> toJson() => {'id': id, 'url': url, 'account': account};
'id': id,
'url': url,
'account': account,
};
factory CenterLink.fromJson(Map<String, dynamic> json) { factory CenterLink.fromJson(Map<String, dynamic> json) {
return CenterLink( return CenterLink(
@@ -185,6 +184,10 @@ class SessionConfig {
ProbeProfile get profile => ProbeProfile.byId(profileId); ProbeProfile get profile => ProbeProfile.byId(profileId);
/// Parsed HTTP target. Null for other profiles, or when the text is invalid.
HttpTarget? get httpTarget =>
profileId == 'http' ? parseHttpTarget(host) : null;
RemoteNode? get node { RemoteNode? get node {
for (final item in nodes) { for (final item in nodes) {
if (item.id == nodeId) { if (item.id == nodeId) {
@@ -195,7 +198,15 @@ class SessionConfig {
} }
String? validate() { String? validate() {
final family = familyRefusal(host, v4: allowIPv4, v6: allowIPv6); final http = profileId == 'http' ? readHttpTarget(host) : null;
if (http != null && http.error != null) {
return http.error;
}
final family = familyRefusal(
http?.target?.host ?? host,
v4: allowIPv4,
v6: allowIPv6,
);
if (family != null) { if (family != null) {
return family; return family;
} }
@@ -209,7 +220,7 @@ class SessionConfig {
return resolveFamily.replaceFirst('目标', '指定解析'); return resolveFamily.replaceFirst('目标', '指定解析');
} }
} }
if (host.trim().isEmpty) { if (profileId != 'http' && host.trim().isEmpty) {
return '请填写目标地址'; return '请填写目标地址';
} }
if (profileId == 'http') { if (profileId == 'http') {
@@ -224,8 +235,7 @@ class SessionConfig {
if (!versions.contains(httpVersion)) { if (!versions.contains(httpVersion)) {
return 'HTTP 版本需要是自动、1.1、2 或 3'; return 'HTTP 版本需要是自动、1.1、2 或 3';
} }
} } else if (port < 1 || port > 65535) {
if (port < 1 || port > 65535) {
return '端口需要在 1 到 65535 之间'; return '端口需要在 1 到 65535 之间';
} }
final minInterval = remote ? 200 : 100; final minInterval = remote ? 200 : 100;
@@ -333,11 +343,15 @@ class SessionConfig {
dnsName: json['dnsName'] is String dnsName: json['dnsName'] is String
? json['dnsName'] as String ? json['dnsName'] as String
: defaults.dnsName, : defaults.dnsName,
payloadHex: json['payloadHex'] is String ? json['payloadHex'] as String : '', payloadHex: json['payloadHex'] is String
? json['payloadHex'] as String
: '',
expectHex: json['expectHex'] is String ? json['expectHex'] as String : '', expectHex: json['expectHex'] is String ? json['expectHex'] as String : '',
allowIPv4: json['allowIPv4'] is bool ? json['allowIPv4'] as bool : true, allowIPv4: json['allowIPv4'] is bool ? json['allowIPv4'] as bool : true,
allowIPv6: json['allowIPv6'] is bool ? json['allowIPv6'] as bool : true, allowIPv6: json['allowIPv6'] is bool ? json['allowIPv6'] as bool : true,
autoUpdate: json['autoUpdate'] is bool ? json['autoUpdate'] as bool : true, autoUpdate: json['autoUpdate'] is bool
? json['autoUpdate'] as bool
: true,
httpVersion: json['httpVersion'] is String httpVersion: json['httpVersion'] is String
? json['httpVersion'] as String ? json['httpVersion'] as String
: 'auto', : 'auto',
+7 -3
View File
@@ -34,11 +34,14 @@ class TargetEntry {
} }
String get label { String get label {
if (profileId == 'http') {
final where = httpUrl.trim().isNotEmpty ? httpUrl.trim() : host.trim(); final where = httpUrl.trim().isNotEmpty ? httpUrl.trim() : host.trim();
final methodText = profileId == 'http' && method.trim().isNotEmpty final methodText = method.trim().isNotEmpty
? ' ${method.trim().toUpperCase()}' ? ' ${method.trim().toUpperCase()}'
: ''; : '';
return '$where:$port · $profileId$methodText'; return '$where · HTTP$methodText';
}
return '${host.trim()}:$port · $profileId';
} }
Map<String, Object?> toJson() => { Map<String, Object?> toJson() => {
@@ -94,7 +97,8 @@ class TargetHistory {
TargetHistory clear() => empty; TargetHistory clear() => empty;
String encode() => jsonEncode(entries.map((entry) => entry.toJson()).toList()); String encode() =>
jsonEncode(entries.map((entry) => entry.toJson()).toList());
factory TargetHistory.decode(String raw) { factory TargetHistory.decode(String raw) {
if (raw.trim().isEmpty) { if (raw.trim().isEmpty) {
+52 -3
View File
@@ -7,9 +7,32 @@ import 'dart:io';
import '../metrics/sample_book.dart'; import '../metrics/sample_book.dart';
const helperMissingNote = const helperMissingNote =
'本机 HTTP 探测使用和节点相同的 Go 引擎。请把 netquality-reflector 放在程序旁边,或设置环境变量 NQ_PROBE_HELPER。远程节点不受影响。'; '本机 HTTP 探测需要 Go 程序 netquality-reflector,现在没有找到,所以探测没有开始。请把探测来源改成「远程节点」。桌面端也可以把 netquality-reflector 放在程序旁边,或设置环境变量 NQ_PROBE_HELPER。';
const helperStartFailedNote =
'本机 HTTP 探测找到了 netquality-reflector,但没有启动成功,所以探测没有开始。请把探测来源改成「远程节点」。桌面端也可以检查这个程序能否运行,或改用环境变量 NQ_PROBE_HELPER。';
/// Thrown before any sample is recorded when the local HTTP engine cannot run.
class LocalHttpHelperException implements Exception {
const LocalHttpHelperException(this.message);
final String message;
}
bool isLocalHttpHelperFailure(Outcome outcome) {
return outcome.status == Outcome.error &&
(outcome.note == helperMissingNote ||
outcome.note == helperStartFailedNote);
}
/// Tests set this to skip the search next to the executable.
String? Function()? locateProbeHelperOverride;
String? locateProbeHelper() { String? locateProbeHelper() {
final override = locateProbeHelperOverride;
if (override != null) {
return override();
}
final env = Platform.environment['NQ_PROBE_HELPER']; final env = Platform.environment['NQ_PROBE_HELPER'];
if (env != null && env.isNotEmpty && File(env).existsSync()) { if (env != null && env.isNotEmpty && File(env).existsSync()) {
return env; return env;
@@ -27,6 +50,23 @@ String? locateProbeHelper() {
return null; return null;
} }
/// Null when the local Go helper can be started. Otherwise a Chinese reason
/// that already tells the user to switch the source to a remote node.
Future<String?> localHttpBlockedReason({String? binary}) async {
final path = binary ?? locateProbeHelper();
if (path == null || path.isEmpty || !File(path).existsSync()) {
return helperMissingNote;
}
try {
final process = await Process.start(path, const ['-mode', 'helper']);
process.kill();
process.exitCode.ignore();
return null;
} catch (_) {
return helperStartFailedNote;
}
}
Outcome outcomeFromHelper(String line) { Outcome outcomeFromHelper(String line) {
try { try {
final decoded = jsonDecode(line); final decoded = jsonDecode(line);
@@ -107,14 +147,23 @@ class HttpHelperSession {
return null; return null;
} }
final path = binary ?? locateProbeHelper(); final path = binary ?? locateProbeHelper();
if (path == null) { if (path == null || path.isEmpty || !File(path).existsSync()) {
return const Outcome( return const Outcome(
status: Outcome.error, status: Outcome.error,
kind: Outcome.query, kind: Outcome.query,
note: helperMissingNote, note: helperMissingNote,
); );
} }
final process = await Process.start(path, const ['-mode', 'helper']); final Process process;
try {
process = await Process.start(path, const ['-mode', 'helper']);
} catch (_) {
return const Outcome(
status: Outcome.error,
kind: Outcome.query,
note: helperStartFailedNote,
);
}
_process = process; _process = process;
process.stdout process.stdout
.transform(utf8.decoder) .transform(utf8.decoder)
+42 -6
View File
@@ -11,6 +11,7 @@ import '../models/probe_profile.dart';
import '../models/session_config.dart'; import '../models/session_config.dart';
import '../ui/address_text.dart'; import '../ui/address_text.dart';
import 'endpoint_picker.dart'; import 'endpoint_picker.dart';
import 'http_helper.dart';
import 'probe_loop.dart'; import 'probe_loop.dart';
import 'remote_client.dart'; import 'remote_client.dart';
@@ -226,6 +227,13 @@ class ProbeController extends ChangeNotifier {
notifyListeners(); notifyListeners();
return; return;
} }
if (!config.remote && config.profileId == 'http') {
final helperProblem = await localHttpBlockedReason();
if (helperProblem != null) {
_rejectSetup(helperProblem);
return;
}
}
await stop(); await stop();
_nodeToken = nodeToken; _nodeToken = nodeToken;
_remoteMode = config.remote; _remoteMode = config.remote;
@@ -237,6 +245,9 @@ class ProbeController extends ChangeNotifier {
..start(); ..start();
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机'; final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
final profile = ProbeProfile.byId(config.profileId); final profile = ProbeProfile.byId(config.profileId);
final httpTarget = config.httpTarget;
final target = httpTarget?.url ?? config.host.trim();
final port = httpTarget?.port ?? config.port;
view = ProbeView( view = ProbeView(
running: true, running: true,
phase: '探测中', phase: '探测中',
@@ -250,7 +261,7 @@ class ProbeController extends ChangeNotifier {
sessionId: session, sessionId: session,
profileId: config.profileId, profileId: config.profileId,
elapsed: Duration.zero, elapsed: Duration.zero,
targetHost: '${config.host.trim()}:${config.port}', targetHost: httpTarget?.url ?? '$target:$port',
profileLabel: profile.label, profileLabel: profile.label,
startedAt: _startedAt, startedAt: _startedAt,
); );
@@ -270,7 +281,9 @@ class ProbeController extends ChangeNotifier {
baseUrl = link.url; baseUrl = link.url;
token = nodeToken; token = nodeToken;
} }
if (config.profileId == 'http' || !config.allowIPv4 || !config.allowIPv6) { if (config.profileId == 'http' ||
!config.allowIPv4 ||
!config.allowIPv6) {
if (!selected.confidential) { if (!selected.confidential) {
final info = await fetchNodeInfo(baseUrl); final info = await fetchNodeInfo(baseUrl);
final upgrade = remoteUpgradeMessage( final upgrade = remoteUpgradeMessage(
@@ -290,8 +303,8 @@ class ProbeController extends ChangeNotifier {
baseUrl: baseUrl, baseUrl: baseUrl,
nodeToken: token, nodeToken: token,
body: ProbeBody( body: ProbeBody(
target: config.host.trim(), target: target,
port: config.port, port: port,
profile: config.profileId, profile: config.profileId,
intervalMs: config.intervalMs, intervalMs: config.intervalMs,
timeoutMs: config.timeoutMs, timeoutMs: config.timeoutMs,
@@ -347,8 +360,8 @@ class ProbeController extends ChangeNotifier {
_local = loop; _local = loop;
await loop.run( await loop.run(
request: ProbeRequest( request: ProbeRequest(
host: config.host.trim(), host: target,
port: config.port, port: port,
profileId: config.profileId, profileId: config.profileId,
interval: Duration(milliseconds: config.intervalMs), interval: Duration(milliseconds: config.intervalMs),
timeout: Duration(milliseconds: config.timeoutMs), timeout: Duration(milliseconds: config.timeoutMs),
@@ -373,6 +386,8 @@ class ProbeController extends ChangeNotifier {
); );
} }
_finish(generation, '已停止'); _finish(generation, '已停止');
} on LocalHttpHelperException catch (error) {
_rejectSetup(error.message, generation: generation);
} on RemoteException catch (error) { } on RemoteException catch (error) {
_finish(generation, '出错', banner: error.message); _finish(generation, '出错', banner: error.message);
} on Object { } on Object {
@@ -416,6 +431,27 @@ class ProbeController extends ChangeNotifier {
} }
} }
void _rejectSetup(String message, {int? generation}) {
if (generation != null && generation != _token) {
return;
}
_clock.stop();
_tick?.cancel();
view = view.copyWith(
running: false,
phase: '无法开始',
banner: message,
note: '',
detail: const {},
summary: ProbeSummary.empty,
samples: const [],
elapsed: Duration.zero,
clearReport: true,
clearTrying: true,
);
notifyListeners();
}
void _finish(int generation, String phase, {String? banner}) { void _finish(int generation, String phase, {String? banner}) {
if (generation != _token || !view.running) { if (generation != _token || !view.running) {
return; return;
+5
View File
@@ -119,6 +119,11 @@ class ProbeLoop {
if (!countsAfterStop(outcome, cancelled: cancelled())) { if (!countsAfterStop(outcome, cancelled: cancelled())) {
break; break;
} }
if (request.profileId == 'http' &&
outcome != null &&
isLocalHttpHelperFailure(outcome)) {
throw LocalHttpHelperException(outcome.note);
}
var commit = <Outcome>[outcome!]; var commit = <Outcome>[outcome!];
if (_usesDatagram(request.profileId) && _picker != null) { if (_usesDatagram(request.profileId) && _picker != null) {
_ledger ??= SelectionLedger(_picker!.candidates.length); _ledger ??= SelectionLedger(_picker!.candidates.length);
+103 -52
View File
@@ -67,12 +67,13 @@ class _HomePageState extends State<HomePage> {
var _ready = false; var _ready = false;
var _idSeq = 0; var _idSeq = 0;
var _formEpoch = 0; var _formEpoch = 0;
String? _portBeforeHttp;
String? _profileBeforeHttp;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_controller.addListener(_rebuild); _controller.addListener(_rebuild);
_host.addListener(_onHostChanged);
_load(); _load();
} }
@@ -123,20 +124,6 @@ class _HomePageState extends State<HomePage> {
} }
} }
void _onHostChanged() {
if (_profileId != 'http') {
return;
}
final current = int.tryParse(_port.text.trim());
if (_port.text.trim().isNotEmpty && current != 80 && current != 443) {
return;
}
final next = '${httpDefaultPort(_host.text)}';
if (_port.text != next) {
_port.text = next;
}
}
void _rebuild() { void _rebuild() {
if (mounted) { if (mounted) {
setState(() {}); setState(() {});
@@ -148,7 +135,6 @@ class _HomePageState extends State<HomePage> {
unawaited(_controller.stop()); unawaited(_controller.stop());
unawaited(_persist()); unawaited(_persist());
_controller.removeListener(_rebuild); _controller.removeListener(_rebuild);
_host.removeListener(_onHostChanged);
_controller.dispose(); _controller.dispose();
for (final field in [ for (final field in [
_host, _host,
@@ -212,12 +198,13 @@ class _HomePageState extends State<HomePage> {
await _persist(); await _persist();
final config = _config(); final config = _config();
if (config.validate() == null) { if (config.validate() == null) {
final httpTarget = config.httpTarget;
_history = _history.add( _history = _history.add(
TargetEntry( TargetEntry(
host: config.host, host: httpTarget?.url ?? config.host,
port: config.port, port: httpTarget?.port ?? config.port,
profileId: config.profileId, profileId: config.profileId,
httpUrl: config.profileId == 'http' ? config.host : '', httpUrl: httpTarget?.url ?? '',
method: config.profileId == 'http' ? config.httpMethod : '', method: config.profileId == 'http' ? config.httpMethod : '',
savedAtMs: DateTime.now().millisecondsSinceEpoch, savedAtMs: DateTime.now().millisecondsSinceEpoch,
), ),
@@ -241,23 +228,42 @@ class _HomePageState extends State<HomePage> {
} }
void _changeProfile(String? id) { void _changeProfile(String? id) {
if (id == null) { if (id == null || id == _profileId) {
return; return;
} }
final previous = ProbeProfile.byId(_profileId); final previous = ProbeProfile.byId(_profileId);
final next = ProbeProfile.byId(id); final next = ProbeProfile.byId(id);
setState(() {
_timeout.text = timeoutAfterProfileChange(
current: _timeout.text,
previousDefault: timeoutDefaultFor(_profileId),
nextDefault: timeoutDefaultFor(id),
);
if (id == 'http') {
_portBeforeHttp = _port.text;
_profileBeforeHttp = _profileId;
} else if (_profileId == 'http' &&
_portBeforeHttp != null &&
_profileBeforeHttp != null) {
_port.text = portAfterProfileChange(
current: _portBeforeHttp!,
previousDefault: ProbeProfile.byId(_profileBeforeHttp!).port,
nextDefault: next.port,
);
_portBeforeHttp = null;
_profileBeforeHttp = null;
} else {
final currentPort = int.tryParse(_port.text.trim()); final currentPort = int.tryParse(_port.text.trim());
var previousDefault = previous.port; var previousDefault = previous.port;
if (_profileId == 'http' && (currentPort == 80 || currentPort == 443)) { if (_profileId == 'http' && (currentPort == 80 || currentPort == 443)) {
previousDefault = currentPort!; previousDefault = currentPort!;
} }
final nextDefault = id == 'http' ? httpDefaultPort(_host.text) : next.port;
setState(() {
_port.text = portAfterProfileChange( _port.text = portAfterProfileChange(
current: _port.text, current: _port.text,
previousDefault: previousDefault, previousDefault: previousDefault,
nextDefault: nextDefault, nextDefault: next.port,
); );
}
_profileId = id; _profileId = id;
}); });
} }
@@ -312,22 +318,18 @@ class _HomePageState extends State<HomePage> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
if (profile.id == 'http')
_hostRow(
view.running,
'https://example.com:2025/ 或 example.com',
helper:
'只填主机名或 IP 时按 http:// 和端口 80。完整网址使用其中的协议、端口和路径。',
fieldKey: const Key('target-field'),
)
else
_pair( _pair(
wide, wide,
Row( _hostRow(view.running, '域名、IP,或 http(s) 地址'),
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: _field(_host, '目标地址', '域名、IP,或 http(s) 地址'),
),
IconButton(
key: const Key('target-history'),
tooltip: '最近目标',
onPressed: view.running ? null : _showHistory,
icon: const Icon(Icons.history),
),
],
),
_field( _field(
_port, _port,
'端口', '端口',
@@ -373,7 +375,15 @@ class _HomePageState extends State<HomePage> {
'间隔(毫秒)', '间隔(毫秒)',
_remote ? '至少 200' : '至少 100', _remote ? '至少 200' : '至少 100',
), ),
_field(_timeout, '超时(毫秒)', '100–15000'), _field(
_timeout,
'超时(毫秒)',
'100–15000',
fieldKey: const Key('timeout-field'),
helper: profile.id == 'http'
? 'HTTP 默认 5000 毫秒'
: null,
),
), ),
if (profile.needsPacketSize) ...[ if (profile.needsPacketSize) ...[
const SizedBox(height: 12), const SizedBox(height: 12),
@@ -575,11 +585,7 @@ class _HomePageState extends State<HomePage> {
: (value) => setState(() => _httpVersion = value ?? 'auto'), : (value) => setState(() => _httpVersion = value ?? 'auto'),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
_field( _field(_httpResolve, '指定解析', '可选。Host 和 SNI 仍用上面的地址,连接改走这里的 IP 或主机名'),
_httpResolve,
'指定解析',
'可选。Host 和 SNI 仍用上面的地址,连接改走这里的 IP 或主机名',
),
const SizedBox(height: 12), const SizedBox(height: 12),
DropdownButtonFormField<String>( DropdownButtonFormField<String>(
key: ValueKey('http-method-$_httpMethod-$_formEpoch'), key: ValueKey('http-method-$_httpMethod-$_formEpoch'),
@@ -739,15 +745,48 @@ class _HomePageState extends State<HomePage> {
void _applyHistory(TargetEntry entry) { void _applyHistory(TargetEntry entry) {
setState(() { setState(() {
_formEpoch += 1; _formEpoch += 1;
_portBeforeHttp = null;
_profileBeforeHttp = null;
_profileId = entry.profileId; _profileId = entry.profileId;
_host.text = entry.httpUrl.isNotEmpty ? entry.httpUrl : entry.host; _host.text = entry.profileId == 'http' && entry.httpUrl.isNotEmpty
? entry.httpUrl
: entry.host;
_port.text = '${entry.port}'; _port.text = '${entry.port}';
if (entry.profileId == 'http' && entry.method.isNotEmpty) { if (entry.profileId == 'http' && entry.method.isNotEmpty) {
_httpMethod = entry.method; _httpMethod = entry.method;
} }
if (entry.profileId == 'http') {
final current = int.tryParse(_timeout.text.trim());
if (current == null || current == timeoutDefaultFor('nq-tcp')) {
_timeout.text = '${timeoutDefaultFor('http')}';
}
}
}); });
} }
Widget _hostRow(bool running, String hint, {String? helper, Key? fieldKey}) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: _field(
_host,
'目标地址',
hint,
helper: helper,
fieldKey: fieldKey,
),
),
IconButton(
key: const Key('target-history'),
tooltip: '最近目标',
onPressed: running ? null : _showHistory,
icon: const Icon(Icons.history),
),
],
);
}
String _newId() { String _newId() {
_idSeq += 1; _idSeq += 1;
return '${DateTime.now().microsecondsSinceEpoch}-$_idSeq'; return '${DateTime.now().microsecondsSinceEpoch}-$_idSeq';
@@ -760,13 +799,18 @@ class _HomePageState extends State<HomePage> {
} }
var link = added.link; var link = added.link;
for (final existing in _centers) { for (final existing in _centers) {
if (existing.url == added.link.url && existing.account == added.link.account) { if (existing.url == added.link.url &&
existing.account == added.link.account) {
link = existing; link = existing;
break; break;
} }
} }
await _vault.write(centerTokenKey(link.id), added.token); await _vault.write(centerTokenKey(link.id), added.token);
await _applyCatalog(link, added.catalog, '已添加 ${added.catalog.servers.length} 台服务器'); await _applyCatalog(
link,
added.catalog,
'已添加 ${added.catalog.servers.length} 台服务器',
);
} }
Future<void> _refreshCenter(CenterLink link) async { Future<void> _refreshCenter(CenterLink link) async {
@@ -789,7 +833,10 @@ class _HomePageState extends State<HomePage> {
} }
await _vault.delete(centerTokenKey(link.id)); await _vault.delete(centerTokenKey(link.id));
setState(() { setState(() {
_centers = [for (final item in _centers) if (item.id != link.id) item]; _centers = [
for (final item in _centers)
if (item.id != link.id) item,
];
_nodes = [ _nodes = [
for (final node in _nodes) for (final node in _nodes)
if (node.centerLinkId != link.id) node, if (node.centerLinkId != link.id) node,
@@ -802,7 +849,11 @@ class _HomePageState extends State<HomePage> {
await _persist(); await _persist();
} }
Future<void> _applyCatalog(CenterLink link, Catalog catalog, String hint) async { Future<void> _applyCatalog(
CenterLink link,
Catalog catalog,
String hint,
) async {
final before = { final before = {
for (final node in _nodes) for (final node in _nodes)
if (node.centerLinkId == link.id) node.id, if (node.centerLinkId == link.id) node.id,
@@ -843,7 +894,9 @@ class _HomePageState extends State<HomePage> {
for (final node in _nodes) for (final node in _nodes)
if (node.centerLinkId == link.id) node, if (node.centerLinkId == link.id) node,
]; ];
final title = link.account.isEmpty ? link.url : '${link.account} · ${link.url}'; final title = link.account.isEmpty
? link.url
: '${link.account} · ${link.url}';
return ExpansionTile( return ExpansionTile(
tilePadding: EdgeInsets.zero, tilePadding: EdgeInsets.zero,
title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis), title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis),
@@ -1164,9 +1217,7 @@ class _NodeDialogState extends State<_NodeDialog> {
'${node.name} · ${visibilityLabel(node.visibility)}', '${node.name} · ${visibilityLabel(node.visibility)}',
), ),
subtitle: Text( subtitle: Text(
node.confidential node.confidential ? '地址由中心代为连接,本机不保存。' : node.baseUrl,
? '地址由中心代为连接,本机不保存。'
: node.baseUrl,
maxLines: 2, maxLines: 2,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
+1 -1
View File
@@ -63,7 +63,7 @@ class MetricGuidePage extends StatelessWidget {
), ),
_Section( _Section(
title: 'HTTP', title: 'HTTP',
body: 'HTTP 探测记下 DNS、连接、TLS、首字节和总时间,以及状态码、最终地址和实际用到的 HTTP 版本(1.1、2 或 3)。曲线上的延迟是总时间。已经收到的响应算成功,4xx 和 5xx 只显示状态码,不叫丢包,也不算进失败率。连不上或强制的版本不被支持,才算失败。\n\n默认先试 HTTP/2,不行再降到 1.1。选了「仅 HTTP/1.1」「仅 HTTP/2」或「仅 HTTP/3」时,服务器不支持就失败,不会悄悄换一种。指定解析只改连接走的地址,Host 和 SNI 仍用目标网址,用来看 CDN。它不是把 1.1.1.1 当成 DNS 服务器。\n\nHTTP/3 的连接和 TLS 是同一次 QUIC 握手,这两项时间相同。本机探测和节点用的是同一个 Go 引擎。桌面端需要把 netquality-reflector 放在程序旁边,或设置 NQ_PROBE_HELPER。Android 上如果系统不允许从应用目录启动这个程序,本机 HTTP 会说明缺引擎;远程节点不受影响。', body: 'HTTP 探测记下 DNS、连接、TLS、首字节和总时间,以及状态码、最终地址和实际用到的 HTTP 版本(1.1、2 或 3)。曲线上的延迟是总时间。已经收到的响应算成功,4xx 和 5xx 只显示状态码,不叫丢包,也不算进失败率。连不上或强制的版本不被支持,才算失败。\n\n默认先试 HTTP/2,不行再降到 1.1。选了「仅 HTTP/1.1」「仅 HTTP/2」或「仅 HTTP/3」时,服务器不支持就失败,不会悄悄换一种。指定解析只改连接走的地址,Host 和 SNI 仍用目标网址,用来看 CDN。它不是把 1.1.1.1 当成 DNS 服务器。\n\nHTTP/3 的连接和 TLS 是同一次 QUIC 握手,这两项时间相同。目标填完整网址,例如 https://example.com:2025/path,也可以只填主机名。只填主机名或 IP 时按 http://主机/,端口是 80,不会改成 https 或 443。网址里写了端口、路径或查询,就按网址本身探测,HTTP 模式不再单独填端口。超时默认 5000 毫秒。\n\n本机探测和节点用的是同一个 Go 引擎。桌面端需要把 netquality-reflector 放在程序旁边,或设置 NQ_PROBE_HELPER。找不到或启动不了时,探测不会开始,也不会记成一次全部失败;界面会说明原因,并建议把探测来源改成远程节点。Android 安装包不带这个程序,本机 HTTP 会直接这样提示。远程节点不受影响。',
), ),
_Section( _Section(
title: '停止以后', title: '停止以后',
+1 -1
View File
@@ -1,6 +1,6 @@
# 网络质量探测 · Linux 桌面客户端 # 网络质量探测 · Linux 桌面客户端
这是 1.1.3 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。HTTP 探测还需要同一目录里的 `netquality-reflector`。 这是 1.1.3 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。HTTP 探测还需要同一目录里的 `netquality-reflector`。找不到或启动不了时,程序会立刻提示改用远程节点,不会把这次记成全部失败。
## 先安装系统库 ## 先安装系统库
+214
View File
@@ -0,0 +1,214 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/models/http_target.dart';
import 'package:netquality/models/port_field.dart';
import 'package:netquality/models/session_config.dart';
import 'package:netquality/probe/http_helper.dart';
import 'package:netquality/probe/probe_controller.dart';
void main() {
test(
'bare hosts become http on port 80 and full URLs keep their own parts',
() {
final bare = parseHttpTarget('rxsend.cn');
expect(bare, isNotNull);
expect(bare!.url, 'http://rxsend.cn/');
expect(bare.port, 80);
expect(bare.scheme, 'http');
final path = parseHttpTarget('example.com/path?q=1');
expect(path!.url, 'http://example.com/path?q=1');
expect(path.port, 80);
final explicit = parseHttpTarget('example.com:8080/a');
expect(explicit!.url, 'http://example.com:8080/a');
expect(explicit.port, 8080);
expect(explicit.scheme, 'http');
final full = parseHttpTarget('https://www.cause-by-siky.top:2025/');
expect(full!.url, 'https://www.cause-by-siky.top:2025/');
expect(full.port, 2025);
expect(full.scheme, 'https');
expect(full.host, 'www.cause-by-siky.top');
final httpsDefault = parseHttpTarget('https://example.com/path');
expect(httpsDefault!.url, 'https://example.com/path');
expect(httpsDefault.port, 443);
final httpDefault = parseHttpTarget('http://example.com/path');
expect(httpDefault!.url, 'http://example.com/path');
expect(httpDefault.port, 80);
final v6 = parseHttpTarget('[2001:db8::1]');
expect(v6!.url, 'http://[2001:db8::1]/');
expect(v6.port, 80);
expect(v6.host, '2001:db8::1');
final v6Port = parseHttpTarget('[2001:db8::1]:8080/a');
expect(v6Port!.url, 'http://[2001:db8::1]:8080/a');
expect(v6Port.port, 8080);
final bareV6 = parseHttpTarget('2001:db8::1');
expect(bareV6!.url, 'http://[2001:db8::1]/');
expect(bareV6.port, 80);
},
);
test('invalid HTTP targets explain the problem in Chinese', () {
expect(httpTargetError(''), '请填写目标地址');
expect(httpTargetError(' '), '请填写目标地址');
expect(httpTargetError('ftp://example.com'), contains('http/https'));
expect(httpTargetError('https://example.com:99999/'), contains('端口'));
expect(httpTargetError('example.com:70000'), contains('端口'));
expect(parseHttpTarget('ftp://example.com'), isNull);
});
test('HTTP validation ignores the separate port and other profiles still require one', () {
final url = _config(
host: 'https://www.cause-by-siky.top:2025/path',
port: 0,
);
expect(url.validate(), isNull);
expect(url.httpTarget!.port, 2025);
expect(url.httpTarget!.url, 'https://www.cause-by-siky.top:2025/path');
final bare = _config(host: 'rxsend.cn', port: 19090);
expect(bare.validate(), isNull);
expect(bare.httpTarget!.url, 'http://rxsend.cn/');
expect(bare.httpTarget!.port, 80);
final bad = _config(host: 'ftp://example.com', port: 443);
expect(bad.validate(), contains('http/https'));
final family = _config(
host: 'https://203.0.113.9/path',
port: 0,
allow4: false,
);
expect(family.validate(), contains('IPv4'));
final tcp = _config(host: '203.0.113.8', port: 0, profileId: 'tcp-connect');
expect(tcp.validate(), contains('端口'));
expect(tcp.httpTarget, isNull);
});
test('HTTP timeout default is 5 seconds and a typed timeout stays', () {
expect(timeoutDefaultFor('http'), 5000);
expect(timeoutDefaultFor('nq-tcp'), 1000);
expect(
timeoutAfterProfileChange(
current: '1000',
previousDefault: 1000,
nextDefault: 5000,
),
'5000',
);
expect(
timeoutAfterProfileChange(
current: '2000',
previousDefault: 1000,
nextDefault: 5000,
),
'2000',
);
expect(
timeoutAfterProfileChange(
current: '5000',
previousDefault: 5000,
nextDefault: 1000,
),
'1000',
);
expect(
timeoutAfterProfileChange(
current: '',
previousDefault: 1000,
nextDefault: 5000,
),
'5000',
);
});
test(
'starting local HTTP without a helper does not open a loss run',
() async {
locateProbeHelperOverride = () => null;
addTearDown(() => locateProbeHelperOverride = null);
final controller = ProbeController();
addTearDown(controller.dispose);
await controller.start(
_config(host: 'rxsend.cn', port: 443),
nodeToken: '',
echoToken: '',
);
expect(controller.view.running, isFalse);
expect(controller.view.phase, '无法开始');
expect(controller.view.banner, helperMissingNote);
expect(controller.view.banner, contains('远程节点'));
expect(controller.view.samples, isEmpty);
expect(controller.view.summary.completed, 0);
expect(controller.view.report, isNull);
final started = DateTime.now();
await controller.start(
_config(host: 'https://www.cause-by-siky.top:2025/', port: 9),
nodeToken: '',
echoToken: '',
);
expect(DateTime.now().difference(started).inSeconds, lessThan(2));
expect(controller.view.running, isFalse);
expect(controller.view.report, isNull);
expect(controller.view.summary.completed, 0);
},
);
test(
'a missing local helper fails immediately and names the remote source',
() async {
final message = await localHttpBlockedReason(
binary: '/no/such/netquality-reflector',
);
expect(message, helperMissingNote);
expect(message, contains('远程节点'));
expect(message, contains('没有开始'));
},
);
test('a helper that cannot be executed fails immediately', () async {
final dir = Directory.systemTemp.createTempSync('nq-helper');
addTearDown(() => dir.deleteSync(recursive: true));
final file = File('${dir.path}/netquality-reflector')
..writeAsStringSync('not a binary');
final message = await localHttpBlockedReason(binary: file.path);
expect(message, helperStartFailedNote);
expect(message, contains('远程节点'));
});
}
SessionConfig _config({
required String host,
required int port,
String profileId = 'http',
bool allow4 = true,
}) {
return SessionConfig(
remote: false,
nodeId: '',
nodes: const [],
host: host,
port: port,
profileId: profileId,
intervalMs: 300,
timeoutMs: 5000,
durationSec: 60,
packetSize: 128,
dnsName: 'example.com',
payloadHex: '',
expectHex: '',
allowIPv4: allow4,
);
}
+32
View File
@@ -6,6 +6,7 @@ import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/metrics/sample_book.dart'; import 'package:netquality/metrics/sample_book.dart';
import 'package:netquality/probe/game_codec.dart'; import 'package:netquality/probe/game_codec.dart';
import 'package:netquality/probe/http_helper.dart';
import 'package:netquality/probe/probe_loop.dart'; import 'package:netquality/probe/probe_loop.dart';
import 'package:netquality/probe/remote_client.dart'; import 'package:netquality/probe/remote_client.dart';
@@ -389,6 +390,37 @@ void main() {
expect(samples.single.detail['httpVersion'], '1.1'); expect(samples.single.detail['httpVersion'], '1.1');
expect(samples.single.summary.failurePct, 0); expect(samples.single.summary.failurePct, 0);
}); });
test('a missing local http helper records no loss sample', () async {
final samples = <ProbeSample>[];
final loop = ProbeLoop(helperPath: '/no/such/netquality-reflector');
await expectLater(
loop.run(
request: const ProbeRequest(
host: 'http://127.0.0.1/health',
port: 80,
profileId: 'http',
interval: Duration(milliseconds: 200),
timeout: Duration(seconds: 1),
packetSize: 64,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
onSample: samples.add,
cancelled: () => false,
),
throwsA(
isA<LocalHttpHelperException>().having(
(error) => error.message,
'message',
contains('远程节点'),
),
),
);
expect(samples, isEmpty);
});
} }
Future<List<ProbeSample>> _collect( Future<List<ProbeSample>> _collect(
+37
View File
@@ -81,6 +81,43 @@ void main() {
}, },
); );
testWidgets('HTTP mode uses a URL, a 5 second timeout, and no port field', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(1280, 1800);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const NetQualityApp());
await tester.pumpAndSettle();
await tester.ensureVisible(find.byKey(const Key('profile')));
await tester.tap(find.byKey(const Key('profile')));
await tester.pumpAndSettle();
await tester.tap(find.text('HTTP').last);
await tester.pumpAndSettle();
expect(find.byKey(const Key('port-field')), findsNothing);
expect(find.text('HTTP 默认 5000 毫秒'), findsOneWidget);
expect(find.text('5000'), findsWidgets);
expect(
find.text('只填主机名或 IP 时按 http:// 和端口 80。完整网址使用其中的协议、端口和路径。'),
findsOneWidget,
);
expect(find.byKey(const Key('target-field')), findsOneWidget);
await tester.enterText(find.byKey(const Key('timeout-field')), '2000');
await tester.tap(find.byKey(const Key('profile')));
await tester.pumpAndSettle();
await tester.tap(find.text('合作反射 UDP').last);
await tester.pumpAndSettle();
expect(find.byKey(const Key('port-field')), findsOneWidget);
expect(find.text('19091'), findsWidgets);
expect(find.text('2000'), findsOneWidget);
expect(find.text('HTTP 默认 5000 毫秒'), findsNothing);
});
testWidgets('editing a node keeps its id and does not reveal the token', ( testWidgets('editing a node keeps its id and does not reveal the token', (
tester, tester,
) async { ) async {
+2 -2
View File
@@ -85,9 +85,9 @@
| `referer` / `userAgent` / `cookies` | 可选,各最长 4KB | | `referer` / `userAgent` / `cookies` | 可选,各最长 4KB |
| `maxRedirects` | 0 到 20,不写时是 5。301/302/303 改为 GET 并丢掉正文;307/308 保持方法和正文。最终状态码是最后一跳的 | | `maxRedirects` | 0 到 20,不写时是 5。301/302/303 改为 GET 并丢掉正文;307/308 保持方法和正文。最终状态码是最后一跳的 |
目标可以是主机名,也可以是完整的 `http://` 或 `https://` URL。没写端口时,https 用 443,http 用 80。 目标可以是主机名,也可以是完整的 `http://` 或 `https://` URL(可带端口、路径和查询)。没有写协议时按 `http`。没有写端口时,http 用 80,https 用 443。URL 里已经写了端口就用那个端口。请求里的 `port` 可以省略或写 0;如果 URL 自己没有端口,而 `port` 仍是 1 到 65535,就用这个 `port`,以便旧客户端继续工作。非 HTTP 类型仍然必须带 1 到 65535 的端口。
本机探测不在 Dart 里另写一套 HTTP。桌面和 Android 都把请求交给同一个 Go 程序的 `-mode helper`,一行 JSON 进、一行结果出。环境变量 `NQ_PROBE_HELPER` 可以指向这个程序;不设置时,客户端在自己的可执行文件旁边找 `netquality-reflector`。 本机探测不在 Dart 里另写一套 HTTP。桌面和 Android 都把请求交给同一个 Go 程序的 `-mode helper`,一行 JSON 进、一行结果出。环境变量 `NQ_PROBE_HELPER` 可以指向这个程序;不设置时,客户端在自己的可执行文件旁边找 `netquality-reflector`。找不到或启动不了时,本机 HTTP 立刻失败并说明原因,建议改用远程节点,不会记成一次全部失败的探测。Android 安装包不包含这个程序。
## 中心 ## 中心
+17 -7
View File
@@ -460,10 +460,7 @@ func buildHTTPURL(target string, port int) (*url.URL, error) {
} }
raw := target raw := target
if !strings.Contains(raw, "://") { if !strings.Contains(raw, "://") {
scheme := "https" // A bare host or IP is HTTP on port 80 unless the text itself has a port.
if port == 80 {
scheme = "http"
}
hostpart := raw hostpart := raw
path := "" path := ""
if i := strings.Index(raw, "/"); i >= 0 { if i := strings.Index(raw, "/"); i >= 0 {
@@ -472,17 +469,30 @@ func buildHTTPURL(target string, port int) (*url.URL, error) {
if strings.Count(hostpart, ":") >= 2 && !strings.HasPrefix(hostpart, "[") { if strings.Count(hostpart, ":") >= 2 && !strings.HasPrefix(hostpart, "[") {
hostpart = "[" + hostpart + "]" hostpart = "[" + hostpart + "]"
} }
raw = scheme + "://" + hostpart + path raw = "http://" + hostpart + path
} }
u, err := url.Parse(raw) u, err := url.Parse(raw)
if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") { if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") {
return nil, errors.New("HTTP 目标需要是主机名或 http/https 网址") return nil, errors.New("HTTP 目标需要是主机名或 http/https 网址")
} }
if u.Port() == "" { if u.Port() == "" {
if port < 1 || port > 65535 { use := port
if use == 0 {
if u.Scheme == "https" {
use = 443
} else {
use = 80
}
}
if use < 1 || use > 65535 {
return nil, errors.New("端口需要在 1 到 65535 之间")
}
u.Host = net.JoinHostPort(u.Hostname(), strconv.Itoa(use))
} else {
parsed, err := strconv.Atoi(u.Port())
if err != nil || parsed < 1 || parsed > 65535 {
return nil, errors.New("端口需要在 1 到 65535 之间") return nil, errors.New("端口需要在 1 到 65535 之间")
} }
u.Host = net.JoinHostPort(u.Hostname(), strconv.Itoa(port))
} }
if u.Path == "" { if u.Path == "" {
u.Path = "/" u.Path = "/"
+106
View File
@@ -332,6 +332,112 @@ func TestHelperSpeaksHTTPEngine(t *testing.T) {
} }
} }
func TestBuildHTTPURLDefaults(t *testing.T) {
cases := []struct {
target string
wire int
scheme string
host string
port string
path string
query string
}{
{"example.com", 0, "http", "example.com", "80", "/", ""},
{"example.com", 80, "http", "example.com", "80", "/", ""},
{"example.com", 443, "http", "example.com", "443", "/", ""},
{"rxsend.cn", 0, "http", "rxsend.cn", "80", "/", ""},
{"https://www.cause-by-siky.top:2025/", 80, "https", "www.cause-by-siky.top", "2025", "/", ""},
{"https://www.cause-by-siky.top:2025/a?q=1", 9, "https", "www.cause-by-siky.top", "2025", "/a", "q=1"},
{"http://example.com/path", 0, "http", "example.com", "80", "/path", ""},
{"https://example.com/path", 0, "https", "example.com", "443", "/path", ""},
{"example.com:8080/a", 443, "http", "example.com", "8080", "/a", ""},
{"example.com/path?q=1", 0, "http", "example.com", "80", "/path", "q=1"},
{"[2001:db8::1]", 0, "http", "2001:db8::1", "80", "/", ""},
{"[2001:db8::1]:8080/a", 80, "http", "2001:db8::1", "8080", "/a", ""},
{"2001:db8::1", 0, "http", "2001:db8::1", "80", "/", ""},
}
for _, tc := range cases {
u, err := buildHTTPURL(tc.target, tc.wire)
if err != nil {
t.Fatalf("%s port %d: %v", tc.target, tc.wire, err)
}
if u.Scheme != tc.scheme || u.Hostname() != tc.host || u.Port() != tc.port || u.Path != tc.path || u.RawQuery != tc.query {
t.Fatalf("%s port %d -> %s", tc.target, tc.wire, u.String())
}
}
if _, err := buildHTTPURL("", 80); err == nil || !strings.Contains(err.Error(), "目标地址") {
t.Fatal(err)
}
if _, err := buildHTTPURL("ftp://example.com", 80); err == nil || !strings.Contains(err.Error(), "http/https") {
t.Fatal(err)
}
if _, err := buildHTTPURL("https://example.com:99999/", 80); err == nil || !strings.Contains(err.Error(), "端口") {
t.Fatal(err)
}
if _, err := buildHTTPURL("example.com", 70000); err == nil || !strings.Contains(err.Error(), "端口") {
t.Fatal(err)
}
}
func TestHTTPExplicitURLPortIgnoresField(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/health" {
http.NotFound(w, r)
return
}
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
out := probeHTTP(context.Background(), HTTPInput{
Target: srv.URL + "/health", Port: 1, Version: "1.1",
Allow4: true, Allow6: true, Timeout: 3 * time.Second,
})
if out.Status != statusOK || out.Detail["statusCode"] != "204" {
t.Fatalf("url port should win: %s %s %+v", out.Status, out.Note, out.Detail)
}
omitted := probeHTTP(context.Background(), HTTPInput{
Target: srv.URL + "/health", Port: 0, Version: "1.1",
Allow4: true, Allow6: true, Timeout: 3 * time.Second,
})
if omitted.Status != statusOK || omitted.Detail["statusCode"] != "204" {
t.Fatalf("omitted port: %s %s %+v", omitted.Status, omitted.Note, omitted.Detail)
}
}
func TestHTTPJobAcceptsURLWithoutPortField(t *testing.T) {
page := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusAccepted)
}))
defer page.Close()
node := newNode("", true, nil, testLimits())
ts := httptest.NewServer(node.Handler())
defer ts.Close()
created := postJSON(t, ts.URL+"/v1/jobs", `{"target":"`+page.URL+`/","port":0,"profile":"http","intervalMs":200,"timeoutMs":1500,"durationSec":2,"http":{"version":"1.1","method":"GET"}}`)
defer created.Body.Close()
if created.StatusCode != http.StatusCreated {
raw, _ := io.ReadAll(created.Body)
t.Fatalf("http without port field %d %s", created.StatusCode, raw)
}
var job map[string]any
if err := json.NewDecoder(created.Body).Decode(&job); err != nil {
t.Fatal(err)
}
id, _ := job["jobId"].(string)
sample := readSampleURL(t, ts.URL+"/v1/jobs/"+id+"/stream")
if sample["status"] != statusOK {
t.Fatalf("sample %+v", sample)
}
detail, _ := sample["detail"].(map[string]any)
if detail["statusCode"] != "202" {
t.Fatalf("detail %+v", detail)
}
tcp := postJSON(t, ts.URL+"/v1/jobs", `{"target":"127.0.0.1","port":0,"profile":"tcp-connect","intervalMs":200,"timeoutMs":300,"durationSec":1}`)
defer tcp.Body.Close()
if tcp.StatusCode != http.StatusBadRequest {
t.Fatalf("tcp still requires a port, got %d", tcp.StatusCode)
}
}
func tlsInput(target string, port int, version string, pool *x509.CertPool) HTTPInput { func tlsInput(target string, port int, version string, pool *x509.CertPool) HTTPInput {
return HTTPInput{ return HTTPInput{
Target: target, Port: port, Version: version, Resolve: "127.0.0.1", Target: target, Port: port, Version: version, Resolve: "127.0.0.1",
+9 -2
View File
@@ -11,6 +11,7 @@ import (
"io" "io"
"net" "net"
"net/http" "net/http"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -224,7 +225,7 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
} }
allow4 := flagOrDefault(req.AllowIPv4, true) allow4 := flagOrDefault(req.AllowIPv4, true)
allow6 := flagOrDefault(req.AllowIPv6, true) allow6 := flagOrDefault(req.AllowIPv6, true)
if req.Port < 1 || req.Port > 65535 { if req.Profile != "http" && (req.Port < 1 || req.Port > 65535) {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_port", "端口需要在 1 到 65535 之间"} return jobSpec{}, &apiError{http.StatusBadRequest, "bad_port", "端口需要在 1 到 65535 之间"}
} }
interval := time.Duration(req.IntervalMs) * time.Millisecond interval := time.Duration(req.IntervalMs) * time.Millisecond
@@ -279,11 +280,17 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
} }
applyHTTPOptions(&httpIn, req.HTTP) applyHTTPOptions(&httpIn, req.HTTP)
lookupHost := req.Target lookupHost := req.Target
resolvedPort := req.Port
if req.Profile == "http" { if req.Profile == "http" {
page, err := buildHTTPURL(req.Target, req.Port) page, err := buildHTTPURL(req.Target, req.Port)
if err != nil { if err != nil {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", err.Error()} return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", err.Error()}
} }
if p, convErr := strconv.Atoi(page.Port()); convErr == nil {
resolvedPort = p
httpIn.Port = p
}
httpIn.Target = page.String()
if _, err := normalizeHTTPVersion(httpIn.Version); err != nil { if _, err := normalizeHTTPVersion(httpIn.Version); err != nil {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", err.Error()} return jobSpec{}, &apiError{http.StatusBadRequest, "bad_profile", err.Error()}
} }
@@ -315,7 +322,7 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_family", "地址族不被允许"} return jobSpec{}, &apiError{http.StatusBadRequest, "bad_family", "地址族不被允许"}
} }
return jobSpec{ return jobSpec{
Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ips[0], Host: req.Target, Port: resolvedPort, Profile: req.Profile, IP: ips[0],
state: &dialState{picker: newEndpointPicker(ips)}, state: &dialState{picker: newEndpointPicker(ips)},
Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size, Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size,
Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect, Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect,