fix: working HTTP and SOCKS5 proxies; save only working servers
- SOCKS5 had been fed to HttpClient.findProxy, which supports only HTTP
proxies ("Invalid proxy configuration"), and socks5h was treated as an
HTTP proxy ("Invalid request method"). HTTP/HTTPS proxies stay on
findProxy; socks5/socks5h tunnel through socks5_proxy, which resolves
names at the proxy; user:pass in the proxy URL is passed along.
- Saving moved to the successful path: a failed attempt stays in the form
with a short reason, and the server list keeps no duplicates.
- package net.blumia.openchamber.flutter (namespace, applicationId,
MainActivity, iOS bundle id), version 0.3.1 (code 301).
- show the proxy in the instance and server lists; clearer connect errors.
- tool/proxy_probe.dart checks direct, socks5, socks5h and HTTP proxies
(requests and SSE) against a live server.
This commit is contained in:
1 parent
782ac2bd4d
commit
55dac37baf
12 files changed
+227
-46
No files matched your search
+86
-13
@@ -6,6 +6,8 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:socks5_proxy/socks_client.dart';
|
||||
|
||||
import 'models.dart';
|
||||
|
||||
class ApiError implements Exception {
|
||||
@@ -16,6 +18,48 @@ class ApiError implements Exception {
|
||||
String toString() => message.isEmpty ? 'HTTP $status' : message;
|
||||
}
|
||||
|
||||
/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one.
|
||||
class _ProxyConfig {
|
||||
final String scheme; // http | https | socks5 | socks5h
|
||||
final String host;
|
||||
final int port;
|
||||
final String? username;
|
||||
final String? password;
|
||||
_ProxyConfig(this.scheme, this.host, this.port, [this.username, this.password]);
|
||||
|
||||
bool get socks => scheme.startsWith('socks');
|
||||
}
|
||||
|
||||
_ProxyConfig? _parseProxy(String? raw) {
|
||||
final s = raw?.trim() ?? '';
|
||||
if (s.isEmpty) return null;
|
||||
var normalized = s;
|
||||
if (!normalized.contains('://')) normalized = 'http://$normalized';
|
||||
final uri = Uri.tryParse(normalized);
|
||||
if (uri == null || uri.host.isEmpty) {
|
||||
throw ArgumentError('代理地址无效:$raw');
|
||||
}
|
||||
final scheme = uri.scheme.toLowerCase();
|
||||
final socks = scheme == 'socks' || scheme == 'socks5' || scheme == 'socks5h';
|
||||
final http = scheme == 'http' || scheme == 'https';
|
||||
if (!socks && !http) {
|
||||
throw ArgumentError('不支持的代理协议:$scheme(支持 http、https、socks5、socks5h)');
|
||||
}
|
||||
String? user;
|
||||
String? pass;
|
||||
if (uri.userInfo.isNotEmpty) {
|
||||
final i = uri.userInfo.indexOf(':');
|
||||
if (i >= 0) {
|
||||
user = Uri.decodeComponent(uri.userInfo.substring(0, i));
|
||||
pass = Uri.decodeComponent(uri.userInfo.substring(i + 1));
|
||||
} else {
|
||||
user = Uri.decodeComponent(uri.userInfo);
|
||||
}
|
||||
}
|
||||
final port = uri.hasPort ? uri.port : (socks ? 1080 : 8080);
|
||||
return _ProxyConfig(scheme, uri.host, port, user, pass);
|
||||
}
|
||||
|
||||
class Client {
|
||||
final Uri base;
|
||||
final String? proxy; // http://host:port or socks5://host:port
|
||||
@@ -23,6 +67,8 @@ class Client {
|
||||
final String? fingerprint;
|
||||
String? token;
|
||||
late HttpClient _http;
|
||||
_ProxyConfig? _proxyConfig;
|
||||
InternetAddress? _proxyAddress;
|
||||
|
||||
Client(
|
||||
this.base, {
|
||||
@@ -32,23 +78,50 @@ class Client {
|
||||
}) {
|
||||
_http = HttpClient();
|
||||
_http.connectionTimeout = const Duration(seconds: 20);
|
||||
if (proxy != null && proxy!.isNotEmpty) {
|
||||
_http.findProxy = (uri) {
|
||||
final u = Uri.parse(proxy!);
|
||||
final scheme = u.scheme.toLowerCase();
|
||||
if (scheme == 'socks5' || scheme == 'socks') {
|
||||
return 'SOCKS ${u.host}:${u.port}';
|
||||
_proxyConfig = _parseProxy(proxy);
|
||||
if (_proxyConfig != null && _proxyConfig!.socks) {
|
||||
// Dart's HttpClient has no SOCKS support in findProxy; the socks5_proxy
|
||||
// package tunnels the socket and hands a Socket back to the client.
|
||||
_http.connectionFactory = (uri, _, __) async {
|
||||
final address = await _resolveProxyAddress();
|
||||
final settings = ProxySettings(address, _proxyConfig!.port,
|
||||
username: _proxyConfig!.username, password: _proxyConfig!.password);
|
||||
final tunnel = SocksTCPClient.connect(
|
||||
[settings],
|
||||
// A unix-type address carries the host name, so the proxy resolves
|
||||
// it (socks5h semantics) instead of resolving it here.
|
||||
InternetAddress(uri.host, type: InternetAddressType.unix),
|
||||
uri.port,
|
||||
);
|
||||
if (uri.scheme == 'https') {
|
||||
final secure = tunnel.then(
|
||||
(s) => s.secure(uri.host, onBadCertificate: _badCertificate));
|
||||
return ConnectionTask.fromSocket(secure, () {});
|
||||
}
|
||||
return 'PROXY ${u.host}:${u.port}';
|
||||
return ConnectionTask.fromSocket(tunnel, () {});
|
||||
};
|
||||
} else if (_proxyConfig != null) {
|
||||
_http.findProxy = (_) => 'PROXY ${_proxyConfig!.host}:${_proxyConfig!.port}';
|
||||
}
|
||||
if (insecure || (fingerprint != null && fingerprint!.isNotEmpty)) {
|
||||
_http.badCertificateCallback = (cert, host, port) {
|
||||
if (insecure) return true;
|
||||
final der = _sha256(cert.der);
|
||||
return der == fingerprint!.replaceAll(':', '');
|
||||
};
|
||||
_http.badCertificateCallback = (cert, host, port) => _badCertificate(cert);
|
||||
}
|
||||
|
||||
Future<InternetAddress> _resolveProxyAddress() async {
|
||||
if (_proxyAddress != null) return _proxyAddress!;
|
||||
final addresses = await InternetAddress.lookup(_proxyConfig!.host);
|
||||
if (addresses.isEmpty) {
|
||||
throw const SocketException('无法解析代理主机');
|
||||
}
|
||||
return _proxyAddress = addresses.first;
|
||||
}
|
||||
|
||||
/// True for a certificate the app was told to accept: the user trusts any
|
||||
/// (insecure), or its SHA-256 matches the pinned fingerprint.
|
||||
bool _badCertificate(X509Certificate cert) {
|
||||
if (insecure) return true;
|
||||
final pinned = fingerprint?.replaceAll(':', '').toLowerCase();
|
||||
if (pinned == null || pinned.isEmpty) return false;
|
||||
return _sha256(cert.der) == pinned;
|
||||
}
|
||||
|
||||
String get baseUrl => base.toString();
|
||||
|
||||
@@ -92,7 +92,17 @@ class _ServersScreenState extends State<ServersScreen> {
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
child: ListTile(
|
||||
title: Text(c.label, style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
subtitle: Text(c.url, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
subtitle: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(c.url, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
if (c.proxy.isNotEmpty)
|
||||
Text('经由 ${c.proxy}',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 12, color: theme.hintColor)),
|
||||
],
|
||||
),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
@@ -146,6 +156,8 @@ class _ServersScreenState extends State<ServersScreen> {
|
||||
}
|
||||
|
||||
void _startEdit(Connection? c) {
|
||||
widget.app.error = null;
|
||||
widget.app.clearLastError();
|
||||
setState(() {
|
||||
_editing = true;
|
||||
_editNew = c == null;
|
||||
@@ -166,7 +178,11 @@ class _ServersScreenState extends State<ServersScreen> {
|
||||
appBar: AppBar(
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () => setState(() => _editing = false),
|
||||
onPressed: () {
|
||||
widget.app.error = null;
|
||||
widget.app.clearLastError();
|
||||
setState(() => _editing = false);
|
||||
},
|
||||
),
|
||||
title: Text(_editNew ? '添加服务器' : '连接 ${_edit!.label}'),
|
||||
),
|
||||
@@ -257,19 +273,8 @@ class _ServersScreenState extends State<ServersScreen> {
|
||||
insecure: _insecure,
|
||||
fingerprint: _fingerprint,
|
||||
);
|
||||
if (_editNew) {
|
||||
await widget.app.saveConnection(c);
|
||||
} else {
|
||||
final list = [...widget.app.connections];
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if (list[i].id == c.id) {
|
||||
list[i] = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
widget.app.connections = list;
|
||||
await widget.app.storage.saveConnections(list);
|
||||
}
|
||||
// Only a connection that works is saved (AppState saves it on success),
|
||||
// so failed attempts do not pile up in the server list.
|
||||
await widget.app.connect(c, password: _password);
|
||||
if (mounted) {
|
||||
if (widget.app.client != null) {
|
||||
|
||||
@@ -304,7 +304,7 @@ class _SessionsScreenState extends State<SessionsScreen> {
|
||||
for (final c in app.connections) ...[
|
||||
ListTile(
|
||||
title: Text(c.label),
|
||||
subtitle: Text(c.url),
|
||||
subtitle: Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'),
|
||||
trailing: app.conn?.id == c.id
|
||||
? Text('已连接', style: TextStyle(color: Theme.of(context).colorScheme.primary))
|
||||
: null,
|
||||
|
||||
+25
-2
@@ -3,6 +3,7 @@
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
@@ -109,15 +110,37 @@ class AppState extends ChangeNotifier {
|
||||
_connected(cl, c);
|
||||
} catch (e) {
|
||||
busy = false;
|
||||
error = e.toString();
|
||||
error = friendlyConnectError(e);
|
||||
if (!silent) {
|
||||
// Surface in the form: the UI reads error itself.
|
||||
_lastError = e.toString();
|
||||
_lastError = error;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// A short, actionable message for a failed connect.
|
||||
String friendlyConnectError(Object e) {
|
||||
if (e is ApiError) return e.message;
|
||||
if (e is ArgumentError) return e.message?.toString() ?? e.toString();
|
||||
if (e is TimeoutException) return '连接超时:检查服务器与代理地址';
|
||||
final s = e.toString();
|
||||
if (e is SocketException) {
|
||||
if (s.contains('Connection refused')) {
|
||||
return '连接被拒绝:服务器或代理未启动,或端口不对';
|
||||
}
|
||||
if (s.contains('Failed host lookup') || s.contains('nodename nor servname')) {
|
||||
return '无法解析地址:检查服务器或代理主机名';
|
||||
}
|
||||
if (s.contains('Network is unreachable')) return '网络不可达';
|
||||
if (s.contains('Connection closed') || s.contains('reset by peer')) {
|
||||
return '连接被断开:检查代理是否可用';
|
||||
}
|
||||
return '网络错误:$s';
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
String? _lastError;
|
||||
String? get lastError => _lastError;
|
||||
void clearLastError() => _lastError = null;
|
||||
|
||||
Reference in new issue
Block a user