This commit is contained in:
LZX committed 2026-09-17 19:20:24 +08:00
1 parent a59ebed397
commit 6fd164fa6f
12 files changed
+1179 -7

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
/// Chroot 环境准备、挂载管理与生命周期服务
class ChrootMountManager {
static final ChrootMountManager instance = ChrootMountManager._();
ChrootMountManager._();
/// 测试桩:用于单测模拟挂载准备是否成功
@visibleForTesting
bool? mockPrepareSuccess;
/// 准备并挂载 Chroot 运行环境
///
/// 执行步骤:
/// 1. 预先执行懒卸载清理旧挂载,保证环境纯净;
/// 2. 挂载 /data suid;
/// 3. 安全挂载 /dev, /dev/pts, /dev/shm, /proc, /sys;
/// 4. 挂载手机外部存储 /sdcard 与工程工作区目录 /workspace;
/// 5. 确保 /etc/resolv.conf 存在有效 DNS;
/// 6. 执行最小化探针测试,若失败返回 false。
Future<bool> prepareChrootEnvironment({
required Directory rootDir,
String? workspacePath,
Duration timeout = const Duration(seconds: 8),
}) async {
if (mockPrepareSuccess != null) {
return mockPrepareSuccess!;
}
if (!kIsWeb && !Platform.isAndroid) {
// 非 Android 平台测试环境降级
return false;
}
final rootfs = rootDir.path;
final workspace = workspacePath ?? '';
final script = StringBuffer();
// 1. 懒卸载陈旧挂载
script.writeln('umount -l "$rootfs/workspace" 2>/dev/null');
script.writeln('umount -l "$rootfs/sdcard" 2>/dev/null');
script.writeln('umount -l "$rootfs/dev/pts" 2>/dev/null');
script.writeln('umount -l "$rootfs/dev/shm" 2>/dev/null');
script.writeln('umount -l "$rootfs/dev" 2>/dev/null');
script.writeln('umount -l "$rootfs/proc" 2>/dev/null');
script.writeln('umount -l "$rootfs/sys" 2>/dev/null');
// 2. 基础目录与权限
script.writeln('mount -o remount,suid /data 2>/dev/null');
script.writeln('mkdir -p "$rootfs/dev" "$rootfs/proc" "$rootfs/sys" "$rootfs/etc" "$rootfs/root" "$rootfs/sdcard" "$rootfs/workspace" 2>/dev/null');
// 3. 核心虚拟文件系统挂载
script.writeln('mount --bind /dev "$rootfs/dev" 2>/dev/null');
script.writeln('mkdir -p "$rootfs/dev/pts" "$rootfs/dev/shm" 2>/dev/null');
script.writeln('mount -t devpts devpts -o gid=5,mode=620 "$rootfs/dev/pts" 2>/dev/null');
script.writeln('mount -t tmpfs tmpfs -o mode=1777 "$rootfs/dev/shm" 2>/dev/null');
script.writeln('mount -t proc proc "$rootfs/proc" 2>/dev/null');
script.writeln('mount --bind /sys "$rootfs/sys" 2>/dev/null');
// 4. 存储与工作区
script.writeln('if [ -d /sdcard ]; then mount --bind /sdcard "$rootfs/sdcard" 2>/dev/null; fi');
if (workspace.isNotEmpty) {
script.writeln('if [ -d "$workspace" ]; then mount --bind "$workspace" "$rootfs/workspace" 2>/dev/null; fi');
}
// 5. DNS 配置
script.writeln('if [ ! -s "$rootfs/etc/resolv.conf" ]; then');
script.writeln(' echo "nameserver 223.5.5.5" > "$rootfs/etc/resolv.conf" 2>/dev/null');
script.writeln(' echo "nameserver 119.29.29.29" >> "$rootfs/etc/resolv.conf" 2>/dev/null');
script.writeln(' echo "nameserver 1.1.1.1" >> "$rootfs/etc/resolv.conf" 2>/dev/null');
script.writeln(' echo "nameserver 8.8.8.8" >> "$rootfs/etc/resolv.conf" 2>/dev/null');
script.writeln('fi');
// 6. 验证环境是否能通过 chroot 执行最小探针
script.writeln('CHROOT_BIN="\$(command -v chroot 2>/dev/null || echo "/system/bin/chroot")"');
script.writeln('"\$CHROOT_BIN" "$rootfs" /bin/sh -c "exit 0"');
try {
final result = await Process.run(
'su',
['-c', script.toString()],
).timeout(timeout);
if (result.exitCode == 0) {
return true;
} else {
debugPrint('[ChrootMountManager] 挂载或探针校验失败 (exitCode ${result.exitCode}): ${result.stderr}');
return false;
}
} catch (e) {
debugPrint('[ChrootMountManager] 准备 Chroot 异常: $e');
return false;
}
}
/// 安全释放清理挂载点
Future<void> cleanupMounts(Directory rootDir) async {
if (!kIsWeb && !Platform.isAndroid) return;
final rootfs = rootDir.path;
final script = '''
umount -l "$rootfs/workspace" 2>/dev/null
umount -l "$rootfs/sdcard" 2>/dev/null
umount -l "$rootfs/dev/pts" 2>/dev/null
umount -l "$rootfs/dev/shm" 2>/dev/null
umount -l "$rootfs/dev" 2>/dev/null
umount -l "$rootfs/proc" 2>/dev/null
umount -l "$rootfs/sys" 2>/dev/null
''';
try {
await Process.run('su', ['-c', script]).timeout(const Duration(seconds: 4));
} catch (_) {}
}
/// 探测并解析容器内首选 Shell(优先 zsh,其次 bash,兜底 sh)
String resolveTargetShell(Directory rootDir) {
if (File(p.join(rootDir.path, 'bin', 'zsh')).existsSync() ||
File(p.join(rootDir.path, 'usr', 'bin', 'zsh')).existsSync()) {
return '/bin/zsh';
}
if (File(p.join(rootDir.path, 'bin', 'bash')).existsSync() ||
File(p.join(rootDir.path, 'usr', 'bin', 'bash')).existsSync()) {
return '/bin/bash';
}
return '/bin/sh';
}
}
+212 -5
View File
@@ -1,12 +1,18 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../l10n/app_localizations.dart';
import '../models/distro_manifest.dart';
import '../providers/settings_provider.dart';
import 'chroot_mount_manager.dart';
import 'distro_installer.dart';
import 'root_service.dart';
/// 容器启动配置数据
class ProotLaunchConfig {
@@ -46,6 +52,12 @@ enum DistroFamily {
unknown,
}
/// 当前生效的底层容器运行类型
enum ContainerRuntimeType {
proot,
chroot,
}
/// 后台静默命令的取消令牌:把子进程句柄暴露给上层(如任务探测会话),
/// 支持"切换工程 / 关闭弹窗 / 用户取消"时立即终止容器内的长时间探测。
class HeadlessCancelToken {
@@ -99,6 +111,97 @@ class DistroManager {
@visibleForTesting
String? customSdcardPath;
/// 当前生效的容器运行环境(PRoot 或 Chroot)
ContainerRuntimeType _activeRuntimeType = ContainerRuntimeType.proot;
ContainerRuntimeType get activeRuntimeType => _activeRuntimeType;
@visibleForTesting
set activeRuntimeType(ContainerRuntimeType val) => _activeRuntimeType = val;
/// 根据设置执行容器运行时检测机制:
/// - 自动 (auto):用户有 root 权限时尝试申请(永远只会申请一次);
/// 被授予 root 权限则尝试挂载 chroot,挂载失败转 proot;没有被授予直接转 proot。
/// - proot 显式:直接转 proot。
/// - chroot 显式:如果用户设备有 root 但是软件尚未被授予 root 权限,弹出 dialog 尝试申请;
/// 被授予则尝试挂载 chroot,失败转 proot;未被授予直接转 proot。
///
/// 检测完毕后,通过普通 Toast 告知用户当前生效的环境是 PRoot 还是 Chroot。
Future<ContainerRuntimeType> detectAndApplyRuntime({
BuildContext? context,
required SettingsProvider settings,
bool showToast = true,
}) async {
final mode = settings.containerRuntimeMode;
final rootDir = await getSystemRootDir(DistroRepository.defaultSystemName);
ContainerRuntimeType effective = ContainerRuntimeType.proot;
switch (mode) {
case ContainerRuntimeMode.proot:
effective = ContainerRuntimeType.proot;
break;
case ContainerRuntimeMode.auto:
bool hasRoot = false;
if (RootService.instance.isDeviceRootCapable()) {
if (!settings.hasPromptedRootRequest) {
hasRoot = await RootService.instance.requestRootPermissionOnce(settings);
} else {
hasRoot = await RootService.instance.isRootAvailablePassive();
}
}
if (hasRoot && rootDir.existsSync()) {
final chrootReady = await ChrootMountManager.instance.prepareChrootEnvironment(
rootDir: rootDir,
);
effective = chrootReady ? ContainerRuntimeType.chroot : ContainerRuntimeType.proot;
} else {
effective = ContainerRuntimeType.proot;
}
break;
case ContainerRuntimeMode.chroot:
bool hasRoot = false;
if (RootService.instance.isDeviceRootCapable()) {
hasRoot = await RootService.instance.isRootAvailablePassive();
if (!hasRoot) {
hasRoot = await RootService.instance.promptRequestRootExplicit();
}
}
if (hasRoot && rootDir.existsSync()) {
final chrootReady = await ChrootMountManager.instance.prepareChrootEnvironment(
rootDir: rootDir,
);
effective = chrootReady ? ContainerRuntimeType.chroot : ContainerRuntimeType.proot;
} else {
effective = ContainerRuntimeType.proot;
}
break;
}
_activeRuntimeType = effective;
if (showToast && context != null && context.mounted) {
final l10n = AppLocalizations.of(context);
if (l10n != null) {
final modeName = effective == ContainerRuntimeType.chroot ? 'Chroot' : 'PRoot';
final message = l10n.containerRuntimeToast(modeName);
try {
ScaffoldMessenger.of(context).removeCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
duration: const Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
),
);
} catch (_) {}
}
}
return effective;
}
/// 获取发行版存储基础目录: `<app_dir>/distros`
Future<Directory> getBaseDistrosDir() async {
if (customBaseDir != null) {
@@ -341,6 +444,7 @@ class DistroManager {
String prootPath = 'proot',
String? customCommand,
Directory? customRootDir,
SettingsProvider? settingsProvider,
}) async {
// 1. 本地 Shell 特殊处理
if (systemName == 'host') {
@@ -360,13 +464,116 @@ class DistroManager {
);
}
// 2. Linux 容器 (PRoot 隔离环境)
// 2. Linux 容器 (动态判定 Chroot 还是 PRoot)
final rootDir = customRootDir ?? await getSystemRootDir(systemName);
// 前置守卫:rootfs 必须先真实存在。否则下方一系列 ensure*(DNS/CA 证书/shm/l2s/sysdata)
// 会 recursive 地创建出一套空壳目录,把"并不存在的系统"伪造成系统选择器里的已安装项。
if (!rootDir.existsSync()) {
throw StateError('目标系统未安装,拒绝构建启动配置: $systemName(rootfs 不存在: ${rootDir.path})');
}
ContainerRuntimeMode runtimeMode = settingsProvider?.containerRuntimeMode ?? ContainerRuntimeMode.auto;
if (settingsProvider == null) {
try {
final prefs = await SharedPreferences.getInstance();
final saved = prefs.getString('container_runtime_mode');
if (saved != null) {
runtimeMode = ContainerRuntimeMode.values.firstWhere(
(e) => e.name == saved,
orElse: () => ContainerRuntimeMode.auto,
);
}
} catch (_) {}
}
bool shouldTryChroot = false;
if (runtimeMode == ContainerRuntimeMode.chroot) {
shouldTryChroot = true;
} else if (runtimeMode == ContainerRuntimeMode.auto) {
shouldTryChroot = await RootService.instance.isRootAvailablePassive();
}
if (shouldTryChroot) {
final chrootReady = await ChrootMountManager.instance.prepareChrootEnvironment(
rootDir: rootDir,
workspacePath: workspacePath,
);
if (chrootReady) {
_activeRuntimeType = ContainerRuntimeType.chroot;
return _buildChrootLaunchConfig(
rootDir: rootDir,
workspacePath: workspacePath,
customCommand: customCommand,
);
} else {
_activeRuntimeType = ContainerRuntimeType.proot;
debugPrint('[DistroManager] Chroot 环境准备失败,自动优雅降级回 PRoot 模式');
}
}
_activeRuntimeType = ContainerRuntimeType.proot;
return _buildProotLaunchConfig(
systemName: systemName,
rootDir: rootDir,
workspacePath: workspacePath,
prootPath: prootPath,
customCommand: customCommand,
);
}
/// 构建原生的 Chroot 满血启动配置
ProotLaunchConfig _buildChrootLaunchConfig({
required Directory rootDir,
String? workspacePath,
String? customCommand,
}) {
final targetShell = ChrootMountManager.instance.resolveTargetShell(rootDir);
final targetDir = (workspacePath != null && Directory(workspacePath).existsSync())
? '/workspace'
: '/root';
String suPath = 'su';
for (final p in ['/system/bin/su', '/system/xbin/su', '/sbin/su', '/su/bin/su']) {
try {
if (File(p).existsSync()) {
suPath = p;
break;
}
} catch (_) {}
}
const envPrefix = 'LD_PRELOAD= exec env -i HOME=/root USER=root TERM=xterm-256color LANG=C.UTF-8 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin';
const chrootBin = '/system/bin/chroot';
String shellCmd;
if (customCommand != null && customCommand.isNotEmpty) {
final escapedCmd = customCommand.replaceAll("'", "'\\''");
shellCmd = '$chrootBin "${rootDir.path}" $targetShell -c \'cd $targetDir && $escapedCmd\'';
} else {
shellCmd = '$chrootBin "${rootDir.path}" $targetShell -l';
}
final fullCommand = '$envPrefix $shellCmd';
return ProotLaunchConfig(
executable: suPath,
arguments: ['-c', fullCommand],
environment: {
'TERM': 'xterm-256color',
'SHELL': '/system/bin/sh',
},
workingDirectory: rootDir.path,
);
}
/// 构建 PRoot 容器隔离运行配置
Future<ProotLaunchConfig> _buildProotLaunchConfig({
required String systemName,
required Directory rootDir,
String? workspacePath,
String prootPath = 'proot',
String? customCommand,
}) async {
final nativeDir = await getNativeLibraryDir();
final effectiveProot = (prootPath == 'proot') ? await getProotExecutablePath() : prootPath;
final targetShell = _resolveTargetShell(rootDir);
@@ -390,13 +597,13 @@ class DistroManager {
await DistroInstaller.ensureAptPolicyAndDiversions(rootDir);
// 确保独立的 /dev/shm 目录存在(对标 proot-distro shm.py,解决 POSIX 共享内存缺失)
final shmDir = await _ensureShmDir(systemName, customBaseDir: customRootDir?.parent);
final shmDir = await _ensureShmDir(systemName, customBaseDir: rootDir.parent);
// 确保独立的 .l2s 硬链接目录存在(对标 proot-distro --link2symlink 规范,位于 rootfs/.l2s)
final l2sDir = await _ensureL2sDir(systemName, rootDir, customBaseDir: customRootDir?.parent);
final l2sDir = await _ensureL2sDir(systemName, rootDir, customBaseDir: rootDir.parent);
// 确保独立的 sysdata 桩目录存在(对标 proot-distro sysdata.py,提供 SELinux 与 Proc 补充数据)
final sysdataDir = await _ensureSysdataDir(systemName, customBaseDir: customRootDir?.parent);
final sysdataDir = await _ensureSysdataDir(systemName, customBaseDir: rootDir.parent);
String tmpPath = '/tmp';
try {
+108
View File
@@ -0,0 +1,108 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import '../providers/settings_provider.dart';
/// 设备 Root 权限探测与授权管理服务
class RootService {
static final RootService instance = RootService._();
RootService._();
/// 测试桩:用于单测中模拟设备是否具备 Root 能力
@visibleForTesting
bool? mockRootCapable;
/// 测试桩:用于单测中模拟 Root 授权状态
@visibleForTesting
bool? mockRootGranted;
/// 常见 Linux/Android su 二进制搜索路径
static const List<String> _commonSuPaths = [
'/system/bin/su',
'/system/xbin/su',
'/sbin/su',
'/system/xbin/daemonsu',
'/su/bin/su',
'/system/sd/xbin/su',
'/data/local/xbin/su',
'/data/local/bin/su',
];
/// 静态检测当前设备是否具备 Root 能力(文件系统存在 su 二进制)
///
/// 该方法纯粹检查静态文件路径,绝不调用任何命令,因此绝对不会触发 Magisk / KernelSU / APatch 授权弹窗。
bool isDeviceRootCapable() {
if (mockRootCapable != null) {
return mockRootCapable!;
}
if (!kIsWeb && Platform.isAndroid) {
for (final path in _commonSuPaths) {
try {
if (File(path).existsSync()) {
return true;
}
} catch (_) {}
}
}
return false;
}
/// 全局入口单次防打扰 Root 授权申请
///
/// 规则:
/// 1. 如果设备本身没有 Root 能力,完全不申请权限;
/// 2. 如果具备 Root 能力,仅在首次启动时主动执行一次 `su` 触发系统授权弹窗;
/// 3. 记录标记 `hasPromptedRootRequest = true`,无论用户同意还是拒绝,之后永不再主动弹出。
Future<bool> requestRootPermissionOnce(SettingsProvider settings) async {
if (settings.hasPromptedRootRequest) {
return false;
}
if (!isDeviceRootCapable()) {
await settings.setHasPromptedRootRequest(true);
return false;
}
// 标记为已主动申请过,防止后续反复打扰
await settings.setHasPromptedRootRequest(true);
// 触发单次授权探测
return await isRootAvailablePassive();
}
/// 被动检测当前是否已获得真实 Root 权限 (uid=0)
///
/// 仅在用户主动触发 Chroot 操作、或 Auto 模式下准备启动容器时被动调用。
Future<bool> isRootAvailablePassive({Duration timeout = const Duration(seconds: 4)}) async {
if (mockRootGranted != null) {
return mockRootGranted!;
}
if (!isDeviceRootCapable()) {
return false;
}
try {
final result = await Process.run(
'su',
['-c', 'id -u'],
).timeout(timeout);
if (result.exitCode == 0) {
final out = result.stdout.toString().trim();
return out == '0';
}
} catch (e) {
debugPrint('[RootService] 被动 Root 检查失败: $e');
}
return false;
}
/// 显式尝试申请 Root 权限(执行一次 `su` 唤起系统的授权 dialog)
Future<bool> promptRequestRootExplicit({Duration timeout = const Duration(seconds: 8)}) async {
return await isRootAvailablePassive(timeout: timeout);
}
}