172 lines
5.3 KiB
Dart
172 lines
5.3 KiB
Dart
import 'dart:async';
|
||
import 'dart:convert';
|
||
import 'dart:io';
|
||
|
||
import 'package:crypto/crypto.dart';
|
||
import 'package:path/path.dart' as p;
|
||
|
||
typedef UsbRun = Future<String> Function(String exe, List<String> args);
|
||
|
||
class UsbDriver {
|
||
static const filename = 'USBip-0.9.8.1-x64.exe';
|
||
static const hash =
|
||
'38cad6d4432b52d5bb9409d9ad03b72fdffc4ada4cd3a48fbeca1a2752a8518a';
|
||
static String defaultUsbip() => p.join(
|
||
Platform.environment['ProgramFiles'] ?? r'C:Program Files',
|
||
'USBip',
|
||
'usbip.exe',
|
||
);
|
||
static Future<bool> installed(UsbRun run) async {
|
||
if (!Platform.isWindows) {
|
||
return false;
|
||
}
|
||
try {
|
||
await run('sc.exe', ['query', 'usbip2_ude']);
|
||
return true;
|
||
} on ProcessException {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
static String installer(String? root) {
|
||
final adjacent = p.join(
|
||
p.dirname(Platform.resolvedExecutable),
|
||
'drivers',
|
||
filename,
|
||
);
|
||
if (File(adjacent).existsSync()) {
|
||
return adjacent;
|
||
}
|
||
return root == null ? adjacent : p.join(root, 'work', filename);
|
||
}
|
||
|
||
static Future<bool> validHash(File file) async =>
|
||
(await sha256.bind(file.openRead()).first).toString() == hash;
|
||
|
||
/// Only invoked after the user selects Install in the missing-driver dialog.
|
||
static Future<int> install(String file) async {
|
||
if (!Platform.isWindows) {
|
||
throw UnsupportedError('USB 模拟目前仅支持 Windows');
|
||
}
|
||
if (!await File(file).exists() || !await validHash(File(file))) {
|
||
throw StateError('USBip 安装包缺失或 SHA-256 校验失败,请重新获取完整 Windows 安装包');
|
||
}
|
||
const script = r"""
|
||
$ErrorActionPreference='Stop'
|
||
$f=$env:ADS_USB_INSTALLER
|
||
$s=Get-AuthenticodeSignature -LiteralPath $f
|
||
if ($s.Status -ne 'Valid' -or $s.SignerCertificate.Thumbprint -ne '9AC56B6C76141395D74FFF6652818376E80B9C95') { throw 'USBip signature verification failed' }
|
||
$p=Start-Process -FilePath $f -ArgumentList '/NORESTART' -Verb RunAs -PassThru -Wait
|
||
exit $p.ExitCode
|
||
""";
|
||
final result = await Process.run(
|
||
'powershell.exe',
|
||
['-NoProfile', '-NonInteractive', '-Command', script],
|
||
environment: Map.of(Platform.environment)
|
||
..removeWhere((key, value) => key.startsWith('ADS_'))
|
||
..['ADS_USB_INSTALLER'] = p.absolute(file),
|
||
includeParentEnvironment: false,
|
||
);
|
||
if (result.exitCode != 0 && result.exitCode != 3010) {
|
||
throw StateError(
|
||
'USBip 安装未完成(可能已取消 UAC),退出码 ${result.exitCode}:${result.stderr}',
|
||
);
|
||
}
|
||
return result.exitCode;
|
||
}
|
||
}
|
||
|
||
class WindowsUsbSession {
|
||
final String serial;
|
||
final int port;
|
||
Process? bridge;
|
||
bool exited = false;
|
||
WindowsUsbSession(String device, this.port) : serial = serialFor(device);
|
||
static String serialFor(String device) =>
|
||
'ADS-${device.length <= 116 ? device : sha256.convert(utf8.encode(device)).toString().substring(0, 24).toUpperCase()}';
|
||
|
||
Future<void> start({
|
||
required String leaseFile,
|
||
required String upstream,
|
||
required String executable,
|
||
required String usbip,
|
||
required Map<String, String> environment,
|
||
required UsbRun run,
|
||
required void Function(Process, String) watch,
|
||
required bool Function() cancelled,
|
||
Duration leaseTimeout = const Duration(seconds: 40),
|
||
}) async {
|
||
final deadline = DateTime.now().add(leaseTimeout);
|
||
while (true) {
|
||
if (cancelled()) {
|
||
throw StateError('USB 连接已取消或客户端已退出');
|
||
}
|
||
final file = File(leaseFile);
|
||
try {
|
||
if (await file.exists() &&
|
||
(await file.readAsString()).trim() == 'true') {
|
||
break;
|
||
}
|
||
} on FileSystemException {
|
||
/* publisher is replacing its readiness file */
|
||
}
|
||
if (DateTime.now().isAfter(deadline)) {
|
||
throw StateError('等待 USB 设备租约超时');
|
||
}
|
||
await Future<void>.delayed(const Duration(milliseconds: 150));
|
||
}
|
||
bridge = await Process.start(
|
||
executable,
|
||
[
|
||
'--listen',
|
||
'127.0.0.1:$port',
|
||
'--upstream',
|
||
upstream,
|
||
'--serial',
|
||
serial,
|
||
],
|
||
environment: environment,
|
||
includeParentEnvironment: false,
|
||
);
|
||
watch(bridge!, serial);
|
||
unawaited(bridge!.exitCode.then((_) => exited = true));
|
||
final readyDeadline = DateTime.now().add(const Duration(seconds: 5));
|
||
while (true) {
|
||
if (exited || cancelled()) {
|
||
throw StateError('虚拟 USB 设备进程已退出');
|
||
}
|
||
try {
|
||
final probe = await Socket.connect(
|
||
InternetAddress.loopbackIPv4,
|
||
port,
|
||
timeout: const Duration(milliseconds: 250),
|
||
);
|
||
probe.destroy();
|
||
break;
|
||
} on SocketException {
|
||
if (DateTime.now().isAfter(readyDeadline)) {
|
||
rethrow;
|
||
}
|
||
await Future<void>.delayed(const Duration(milliseconds: 100));
|
||
}
|
||
}
|
||
final output = await run(usbip, [
|
||
'--tcp-port',
|
||
'$port',
|
||
'attach',
|
||
'--remote',
|
||
'127.0.0.1',
|
||
'--bus-id',
|
||
'1-1',
|
||
'--terse',
|
||
'--once',
|
||
]);
|
||
final imported = int.tryParse(output.trim());
|
||
if (imported == null || imported < 1 || imported > 127) {
|
||
throw StateError('无法确认 USBip 挂载成功:$output');
|
||
}
|
||
// --once has no persistent retry. Closing only our bridge removes only our
|
||
// device; do not detach by a hub number that might have been reused.
|
||
}
|
||
}
|