This commit is contained in:
LZX committed 2026-09-13 16:41:19 +08:00
1 parent 87e03ce0d8
commit e932c60dbd
47 files changed
+4417 -923

No files matched your search

+190 -49
View File
@@ -1,6 +1,8 @@
import 'dart:ffi';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
/// 安装进度回调
@@ -8,6 +10,15 @@ import 'package:path/path.dart' as p;
/// [message] 当前阶段说明
typedef InstallProgressCallback = void Function(double progress, String message);
/// 取消安装异常
class DistroInstallCancelledException implements Exception {
final String message;
DistroInstallCancelledException([this.message = '用户已取消系统导入']);
@override
String toString() => message;
}
/// Linux 发行版 Rootfs 安装与解压服务
class DistroInstaller {
/// 解压并安装 tar.gz 格式的 Rootfs 到目标目录
@@ -15,67 +26,112 @@ class DistroInstaller {
/// [tarGzBytes] .tar.gz 压缩包字节流
/// [targetDir] 目标解压目录 (即容器的 rootfs 路径)
/// [onProgress] 进度回调
/// [isCancelled] 外部取消检查函数
static Future<void> installFromBytes({
required Uint8List tarGzBytes,
required Directory targetDir,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
onProgress?.call(0.05, '正在校验与解析系统镜像...');
if (!targetDir.existsSync()) {
targetDir.createSync(recursive: true);
}
// 1. 在后台解压 Gzip 与 Tar(避免 UI 线程卡顿)
onProgress?.call(0.15, '正在解压内核与文件系统结构...');
final archive = await compute(_decodeTarGz, tarGzBytes);
try {
// 1. 在后台解压 Gzip 与 Tar(避免 UI 线程卡顿)
onProgress?.call(0.15, '正在解压内核与文件系统结构...');
final archive = await compute(_decodeTarGz, tarGzBytes);
// 2. 写入文件与目录
final total = archive.length;
int processed = 0;
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
for (final file in archive) {
processed++;
final filename = file.name;
// 避免路径穿越漏洞 (Directory Traversal)
if (filename.contains('..')) continue;
// 2. 写入文件与目录
//
// 权限位必须逐条按 tar 头恢复:dart:io 没有 chmod,而解压本身不会保留
// 可执行位,所以恢复方式是按 mode 分组批量调用 chmod(避免逐文件 fork)。
// 之前这里用 `chmod -R 755` 一把梭,会把 /etc 下的配置文件也变成可执行。
final total = archive.length;
int processed = 0;
final Map<int, List<String>> byMode = <int, List<String>>{};
final outPath = p.join(targetDir.path, filename);
if (file.isFile) {
final parentDir = Directory(p.dirname(outPath));
if (!parentDir.existsSync()) {
parentDir.createSync(recursive: true);
for (final file in archive) {
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
// 处理符号链接与常规文件
if (file.isSymbolicLink) {
try {
final link = Link(outPath);
if (link.existsSync()) link.deleteSync();
link.createSync(file.nameOfLinkedFile);
} catch (_) {
// Windows 或受限环境降级为写入目标路径文本或忽略
processed++;
final filename = file.name;
// 避免路径穿越漏洞 (Directory Traversal)
if (filename.contains('..')) continue;
final outPath = p.join(targetDir.path, filename);
if (file.isFile) {
final parentDir = Directory(p.dirname(outPath));
if (!parentDir.existsSync()) {
parentDir.createSync(recursive: true);
}
// 处理符号链接与常规文件
if (file.isSymbolicLink) {
try {
final link = Link(outPath);
if (link.existsSync()) link.deleteSync();
link.createSync(file.nameOfLinkedFile);
} catch (_) {
// Windows 或受限环境降级为写入目标路径文本或忽略
}
} else {
final content = file.content as List<int>;
File(outPath).writeAsBytesSync(content, flush: false);
}
} else {
final content = file.content as List<int>;
File(outPath).writeAsBytesSync(content, flush: false);
Directory(outPath).createSync(recursive: true);
}
// 记录 tar 头里的权限位(仅低 12 位有效位)。
// 符号链接必须跳过:chmod 会跟随链接,把目标文件的权限改坏
// (tar 里 symlink 条目的 mode 固定为 0777)。
final mode = file.mode & 0xFFF;
if (mode != 0 && !file.isSymbolicLink) {
byMode.putIfAbsent(mode, () => <String>[]).add(outPath);
}
if (processed % 50 == 0 || processed == total) {
final percent = 0.20 + (processed / total) * 0.70; // 20% ~ 90%
onProgress?.call(percent, '正在释放系统文件 ($processed/$total)...');
}
} else {
Directory(outPath).createSync(recursive: true);
}
if (processed % 100 == 0 || processed == total) {
final percent = 0.20 + (processed / total) * 0.70; // 20% ~ 90%
onProgress?.call(percent, '正在释放系统文件 ($processed/$total)...');
if (!Platform.isWindows) {
await _restoreModes(byMode);
}
if (isCancelled?.call() == true) {
throw DistroInstallCancelledException();
}
// 3. 执行系统配置与网络补丁
onProgress?.call(0.92, '正在配置网络 DNS 与系统环境...');
await postInstallConfigure(targetDir);
onProgress?.call(1.0, '系统初始化就绪!');
} catch (e) {
// 若中途失败或取消,清理不完整的根目录
try {
if (targetDir.existsSync()) {
targetDir.deleteSync(recursive: true);
}
} catch (_) {}
rethrow;
}
// 3. 执行系统配置与网络补丁
onProgress?.call(0.92, '正在配置网络 DNS 与系统环境...');
await postInstallConfigure(targetDir);
onProgress?.call(1.0, '系统初始化就绪!');
}
/// 后台 Isolate 解压 tar.gz
@@ -84,10 +140,37 @@ class DistroInstaller {
return TarDecoder().decodeBytes(tarData);
}
/// 按 tar 头恢复权限位(dart:io 无 chmod,按 mode 分组批量调用,避免逐文件 fork)
static Future<void> _restoreModes(Map<int, List<String>> byMode) async {
for (final entry in byMode.entries) {
final octal = entry.key.toRadixString(8).padLeft(4, '0');
final paths = entry.value;
// 单次 chmod 的参数长度有限,分批执行
const batch = 100;
for (var i = 0; i < paths.length; i += batch) {
final end = (i + batch < paths.length) ? i + batch : paths.length;
final slice = paths.sublist(i, end);
try {
await Process.run('chmod', [octal, ...slice]);
} catch (e) {
debugPrint('[DistroInstaller] 恢复权限失败 ($octal): $e');
}
}
}
}
/// 容器可用的 DNS 解析器(按"可达优先"排序:国内公共 DNS 在前)
static const String guestResolvConf = '# Generated by CodeEditor\n'
'nameserver 223.5.5.5\n'
'nameserver 119.29.29.29\n'
'nameserver 114.114.114.114\n';
/// 自动化环境补丁与配置
/// 1. 注入 DNS (resolv.conf) 防止容器内 apk/apt 无法联网
/// 2. 注入 hosts
/// 3. 创建挂载点 /workspace 和 /tmp
///
/// 只做"发行版自身不会做、但容器化必需"的事:DNS、hosts、镜像源、
/// 挂载点目录、shim 部署。**不再改写 guest 的 /etc/profile** —— 那会破坏
/// 非 Alpine 发行版自带的登录环境(Alpine 原版 profile 与本项目此前写入的
/// 模板逐行相同,所以删掉它对 Alpine 没有任何影响)。
static Future<void> postInstallConfigure(Directory rootfsDir) async {
final etcDir = Directory(p.join(rootfsDir.path, 'etc'));
if (!etcDir.existsSync()) {
@@ -97,12 +180,7 @@ class DistroInstaller {
// 1. 配置 DNS 解析器
final resolvFile = File(p.join(etcDir.path, 'resolv.conf'));
try {
resolvFile.writeAsStringSync(
'# Generated by CodeEditor DistroManager\n'
'nameserver 1.1.1.1\n'
'nameserver 8.8.8.8\n'
'nameserver 114.114.114.114\n',
);
resolvFile.writeAsStringSync(guestResolvConf);
} catch (e) {
debugPrint('[DistroInstaller] 写入 resolv.conf 失败: $e');
}
@@ -118,16 +196,79 @@ class DistroInstaller {
debugPrint('[DistroInstaller] 写入 hosts 失败: $e');
}
// 3. 确保 /workspace 挂载点目录存在
// 3. 配置 Alpine apk 软件源镜像(使用阿里云高速稳定镜像)
final apkDir = Directory(p.join(etcDir.path, 'apk'));
if (apkDir.existsSync()) {
final repoFile = File(p.join(apkDir.path, 'repositories'));
try {
repoFile.writeAsStringSync(
'https://mirrors.aliyun.com/alpine/v3.20/main\n'
'https://mirrors.aliyun.com/alpine/v3.20/community\n',
);
} catch (e) {
debugPrint('[DistroInstaller] 写入 repositories 失败: $e');
}
}
// 4. 确保 /workspace 挂载点目录存在
final workspaceDir = Directory(p.join(rootfsDir.path, 'workspace'));
if (!workspaceDir.existsSync()) {
workspaceDir.createSync(recursive: true);
}
// 4. 确保 /tmp 目录存在
// 5. 确保 /tmp 目录存在
final tmpDir = Directory(p.join(rootfsDir.path, 'tmp'));
if (!tmpDir.existsSync()) {
tmpDir.createSync(recursive: true);
}
// 6. 部署容器修复 Shim(libfix_seccomp.so)
await ensureSeccompShim(rootfsDir);
}
/// 部署容器修复 Shim(libfix_seccomp.so)
///
/// 它只做两件在 Android app 进程里必需的事:
/// 1. `utimensat()`(两个架构):Android 不允许应用数据区创建硬链接,PRoot
/// 的 `--link2symlink` 用 symlink + 隐藏记账文件模拟硬链接,导致 apk
/// 保 mtime 时跟随解析失败(`Failed to preserve modification time`)。
/// 2. `poll/select/pipe/dup2`(仅 x86_64):Android 的 app seccomp 策略把这些
/// 传统 syscall 返回 ENOSYS,而 musl 在有这些调用的架构上优先用它们。
static Future<void> ensureSeccompShim(Directory rootfsDir) async {
final libDir = Directory(p.join(rootfsDir.path, 'lib'));
if (!libDir.existsSync()) {
libDir.createSync(recursive: true);
}
final targetShim = File(p.join(libDir.path, 'libfix_seccomp.so'));
String? archFolder;
if (Platform.isAndroid || Platform.isLinux) {
final currentAbi = Abi.current();
if (currentAbi == Abi.androidX64 || currentAbi == Abi.linuxX64) {
archFolder = 'x86_64';
} else if (currentAbi == Abi.androidArm64 || currentAbi == Abi.linuxArm64) {
archFolder = 'arm64-v8a';
}
}
if (archFolder == null) return;
try {
final assetPath = 'assets/shims/$archFolder/libfix_seccomp.so';
final byteData = await rootBundle.load(assetPath);
final bytes = byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes);
// 如果目标文件已存在且大小一致,则跳过写入
if (targetShim.existsSync() && targetShim.lengthSync() == bytes.length) {
return;
}
await targetShim.writeAsBytes(bytes, flush: true);
if (!Platform.isWindows) {
await Process.run('chmod', ['755', targetShim.path]);
}
debugPrint('[DistroInstaller] 成功部署 SECCOMP Shim: ${targetShim.path}');
} catch (e) {
debugPrint('[DistroInstaller] 部署 SECCOMP Shim 失败: $e');
}
}
}
+317 -96
View File
@@ -35,40 +35,16 @@ class ProotLaunchConfig {
}
}
/// Linux 发行版管理器服务(单例模式,易扩展)
/// Linux 发行版与多系统实例管理器服务(单例模式,易扩展)
class DistroManager {
static final DistroManager _instance = DistroManager._internal();
factory DistroManager() => _instance;
DistroManager._internal() {
// 注册内置默认发行版
for (final d in DistroInfo.defaults) {
_distros[d.id] = d;
}
}
DistroManager._internal();
/// 自定义覆盖根目录(主要用于测试)
@visibleForTesting
Directory? customBaseDir;
/// 发行版注册表 `Map<id, DistroInfo>`
final Map<String, DistroInfo> _distros = {};
/// 获取所有已注册的发行版
List<DistroInfo> listDistros() => _distros.values.toList();
/// 获取指定发行版元数据
DistroInfo? getDistro(String id) => _distros[id];
/// 动态注册新的发行版(支持未来插件化或用户自定义导入)
void registerDistro(DistroInfo distro) {
_distros[distro.id] = distro;
}
/// 注销指定发行版
void unregisterDistro(String id) {
_distros.remove(id);
}
/// 获取发行版存储基础目录: `<app_dir>/distros`
Future<Directory> getBaseDistrosDir() async {
if (customBaseDir != null) {
@@ -82,115 +58,212 @@ class DistroManager {
return distrosDir;
}
/// 获取指定发行版的 Rootfs 解压目录: `<app_dir>/distros/<distroId>/rootfs`
Future<Directory> getDistroRootDir(String distroId) async {
/// 获取指定系统实例的 Rootfs 解压目录: `<app_dir>/distros/<systemName>/rootfs`
Future<Directory> getSystemRootDir(String systemName) async {
final baseDir = await getBaseDistrosDir();
return Directory(p.join(baseDir.path, distroId, 'rootfs'));
return Directory(p.join(baseDir.path, systemName, 'rootfs'));
}
/// 检测指定发行版是否已安装就绪
Future<bool> isInstalled(String distroId) async {
// host 为宿主系统,无需安装
if (distroId == 'host') return true;
/// 获取当前已创建并解压成功的系统实例列表(文件夹名称即系统名称)
Future<List<String>> listInstalledSystems() async {
final baseDir = await getBaseDistrosDir();
if (!baseDir.existsSync()) return [];
final rootDir = await getDistroRootDir(distroId);
final List<String> systems = [];
final entities = baseDir.listSync(followLinks: false);
for (final entity in entities) {
if (entity is Directory) {
final name = p.basename(entity.path);
// 若子目录存在 rootfs/ 且包含基础目录结构,则视为有效系统实例
final rootDir = Directory(p.join(entity.path, 'rootfs'));
if (rootDir.existsSync()) {
systems.add(name);
}
}
}
// 按名称字母排序
systems.sort((a, b) => a.compareTo(b));
return systems;
}
/// 是否存在任何已安装的系统
Future<bool> hasAnySystem() async {
final systems = await listInstalledSystems();
return systems.isNotEmpty;
}
/// 检测指定系统实例是否已安装就绪
Future<bool> isSystemInstalled(String systemName) async {
if (systemName == 'host') return true;
final rootDir = await getSystemRootDir(systemName);
if (!rootDir.existsSync()) return false;
// 检查关键目录和常用 shell 是否存在
final hasEtc = Directory(p.join(rootDir.path, 'etc')).existsSync();
final hasBin = Directory(p.join(rootDir.path, 'bin')).existsSync();
return hasEtc && hasBin;
}
/// 安装发行版(优先从内置 asset 离线安装,支持进度回调)
Future<void> installDistro(
String distroId, {
InstallProgressCallback? onProgress,
}) async {
final distro = getDistro(distroId);
if (distro == null) {
throw ArgumentError('未知的发行版 ID: $distroId');
/// 校验系统名称是否合法且未被占用
Future<void> validateSystemName(String systemName) async {
final trimmed = systemName.trim();
if (trimmed.isEmpty) {
throw ArgumentError('系统名称不能为空');
}
// 限制字符集:字母、数字、下划线、短横线、中文字符
final validRegex = RegExp(r'^[\w\u4e00-\u9fa5\-_]+$');
if (!validRegex.hasMatch(trimmed)) {
throw ArgumentError('系统名称只能包含字母、数字、中文、下划线或短横线');
}
if (distroId == 'host') {
onProgress?.call(1.0, '本地 Shell 无需安装');
return;
final systems = await listInstalledSystems();
if (systems.any((s) => s.toLowerCase() == trimmed.toLowerCase())) {
throw ArgumentError('已存在同名系统 "$trimmed",请使用其他名称');
}
final targetDir = await getDistroRootDir(distroId);
// 优先从内置 Asset 安装
if (distro.assetPath != null) {
onProgress?.call(0.02, '正在读取内置系统资源包...');
final byteData = await rootBundle.load(distro.assetPath!);
final bytes = byteData.buffer.asUint8List();
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
targetDir: targetDir,
onProgress: onProgress,
);
return;
}
// 远程下载模式扩展点
if (distro.downloadUrl != null) {
throw UnsupportedError('远程下载安装功能后续支持,请先使用内置版本');
}
throw StateError('该发行版既无内置 asset 也无下载链接: $distroId');
}
/// 从用户本地指定的 .tar.gz 文件安装自定义系统
Future<void> installFromCustomTarGz(
String distroId,
File tarGzFile, {
/// 从应用内置资源导入 Alpine Linux 系统实例
///
/// [systemName] 系统名称(默认为 'alpine',同一个 rootfs 包可创建多个系统)
Future<void> importBuiltinAlpine({
required String systemName,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
final targetDir = await getDistroRootDir(distroId);
final bytes = await tarGzFile.readAsBytes();
await validateSystemName(systemName);
final assetPath = DistroInfo.builtinAlpineAssetPath;
onProgress?.call(0.02, '正在读取应用内置系统资源包...');
final byteData = await rootBundle.load(assetPath);
final bytes = byteData.buffer.asUint8List();
final targetDir = await getSystemRootDir(systemName);
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
/// 卸载并清除指定发行版的 rootfs 目录
Future<void> uninstallDistro(String distroId) async {
if (distroId == 'host') return;
/// 从用户本地指定的 .tar.gz 压缩包导入外部系统实例
Future<void> importFromCustomTarGz({
required String systemName,
required File tarGzFile,
InstallProgressCallback? onProgress,
bool Function()? isCancelled,
}) async {
await validateSystemName(systemName);
if (!tarGzFile.existsSync()) {
throw ArgumentError('所选压缩包文件不存在: ${tarGzFile.path}');
}
onProgress?.call(0.02, '正在读取外部系统压缩包...');
final bytes = await tarGzFile.readAsBytes();
final targetDir = await getSystemRootDir(systemName);
await DistroInstaller.installFromBytes(
tarGzBytes: bytes,
targetDir: targetDir,
onProgress: onProgress,
isCancelled: isCancelled,
);
}
/// 高危操作:彻底删除指定系统实例及其所有存储数据
Future<void> deleteSystem(String systemName) async {
if (systemName == 'host') return;
final baseDir = await getBaseDistrosDir();
final distroDir = Directory(p.join(baseDir.path, distroId));
if (distroDir.existsSync()) {
distroDir.deleteSync(recursive: true);
final systemDir = Directory(p.join(baseDir.path, systemName));
if (!systemDir.existsSync()) return;
for (int attempt = 0; attempt < 3; attempt++) {
try {
if (!systemDir.existsSync()) break;
await systemDir.delete(recursive: true);
break;
} catch (e) {
if (Platform.isLinux || Platform.isAndroid) {
try {
await Process.run('chmod', ['-R', '777', systemDir.path]);
} catch (_) {}
}
await Future<void>.delayed(const Duration(milliseconds: 60));
if (attempt == 2) {
try {
if (systemDir.existsSync()) {
systemDir.deleteSync(recursive: true);
}
} catch (_) {}
}
}
}
}
static const MethodChannel _nativeChannel = MethodChannel('com.example.code_editor/native');
String? _cachedProotPath;
String? _cachedNativeDir;
/// 获取 App 原生动态库目录路径(用于定位 libproot.so 与 libtalloc.so)
Future<String?> getNativeLibraryDir() async {
if (_cachedNativeDir != null) return _cachedNativeDir;
if (Platform.isAndroid) {
try {
final dir = await _nativeChannel.invokeMethod<String>('getNativeLibraryDir');
if (dir != null && dir.isNotEmpty) {
_cachedNativeDir = dir;
return dir;
}
} catch (e) {
debugPrint('获取原生动态库目录失败: $e');
}
}
return null;
}
/// 获取 proot 可执行程序的物理路径(优先检测 nativeLibraryDir/libproot.so)
Future<String> getProotExecutablePath() async {
if (_cachedProotPath != null && File(_cachedProotPath!).existsSync()) {
return _cachedProotPath!;
}
final nativeDir = await getNativeLibraryDir();
if (nativeDir != null) {
final soPath = p.join(nativeDir, 'libproot.so');
if (File(soPath).existsSync()) {
_cachedProotPath = soPath;
return soPath;
}
}
return 'proot';
}
/// 构建 PRoot 容器启动命令与环境参数
///
/// [distroId] 发行版标识符
/// [systemName] 当前选择的系统名称
/// [workspacePath] 挂载的代码工程路径(挂载到容器内部的 /workspace)
/// [prootPath] proot 二进制路径(默认可传入 'proot' 或设备内部特定路径)
/// [customCommand] 自定义初始执行命令(默认进入交互式 login shell)
/// [prootPath] proot 二进制路径
/// [customCommand] 自定义执行命令
Future<ProotLaunchConfig> buildLaunchConfig({
required String distroId,
required String systemName,
String? workspacePath,
String prootPath = 'proot',
String? customCommand,
}) async {
final distro = getDistro(distroId) ?? DistroInfo.alpine;
// 1. 本地 Shell 特殊处理:无需 PRoot
if (distroId == 'host') {
// 1. 本地 Shell 特殊处理
if (systemName == 'host') {
final initialDir = (workspacePath != null && Directory(workspacePath).existsSync())
? workspacePath
: Directory.current.path;
final args = customCommand != null ? ['-c', customCommand] : <String>[];
return ProotLaunchConfig(
executable: distro.defaultShell,
executable: '/system/bin/sh',
arguments: args,
environment: {
'TERM': 'xterm-256color',
@@ -200,17 +273,53 @@ class DistroManager {
}
// 2. Linux 容器 (PRoot 隔离环境)
final rootDir = await getDistroRootDir(distroId);
final targetShell = distro.defaultShell;
final rootDir = await getSystemRootDir(systemName);
final nativeDir = await getNativeLibraryDir();
final effectiveProot = (prootPath == 'proot') ? await getProotExecutablePath() : prootPath;
const targetShell = '/bin/sh';
// 确保容器内 DNS 配置存在(对标 proot-distro,保证网络连通与 apk/curl 正常解析)
await _ensureGuestDns(rootDir);
// 确保独立的 /dev/shm 目录存在(对标 proot-distro shm.py,解决 POSIX 共享内存缺失)
final shmDir = await _ensureShmDir(systemName);
// 确保独立的 .l2s 硬链接目录存在(对标 proot-distro --link2symlink 规范)
final l2sDir = await _ensureL2sDir(systemName);
// 确保独立的 sysdata 桩目录存在(对标 proot-distro sysdata.py,提供 SELinux 与 Proc 补充数据)
final sysdataDir = await _ensureSysdataDir(systemName);
String tmpPath = '/tmp';
try {
tmpPath = (await getTemporaryDirectory()).path;
} catch (_) {
tmpPath = '/tmp';
}
final args = <String>[
'--kill-on-exit',
'--link2symlink',
'-0', // 模拟 root 权限 (uid 0)
'-k', '5.4.0-proot', // 伪装内核版本(解决 musl libc 调用 clone3/ppoll 时的 Function not implemented)
'-L', // 修复 lstat 符号链接大小属性
'-r', rootDir.path, // 根文件系统路径
'-b', '/dev', // 挂载标准设备节点
'-b', '/dev', // 挂载标准设备节点(宿主已有 /dev/stdin, stdout, stderr 等软链接)
'-b', '/dev/urandom:/dev/random', // 补充随机数设备节点
if (shmDir != null) ...['-b', '${shmDir.path}:/dev/shm'], // 挂载独立 POSIX 共享内存
'-b', '/proc', // 挂载进程信息
'-b', '/sys', // 挂载系统信息
if (sysdataDir != null) ...[
'-b', '${p.join(sysdataDir.path, 'sys_empty')}:/sys/fs/selinux',
'-b', '${p.join(sysdataDir.path, 'sysctl_entry_cap_last_cap')}:/proc/sys/kernel/cap_last_cap',
'-b', '${p.join(sysdataDir.path, 'sysctl_inotify_max_user_watches')}:/proc/sys/fs/inotify/max_user_watches',
],
];
if (Directory(tmpPath).existsSync()) {
args.addAll(['-b', '$tmpPath:/tmp']);
}
// 挂载工作区
String containerWorkDir = '/root';
if (workspacePath != null && Directory(workspacePath).existsSync()) {
@@ -221,6 +330,26 @@ class DistroManager {
// 设置容器内工作目录
args.addAll(['-w', containerWorkDir]);
// 用 /usr/bin/env -i 彻底隔离宿主(Android app 进程)继承的环境变量,
// 只注入标准纯净的容器环境变量;若修复 Shim 已部署则注入 LD_PRELOAD。
// Shim 的两项职责见 DistroInstaller.ensureSeccompShim 的注释。
await DistroInstaller.ensureSeccompShim(rootDir);
final shimFile = File(p.join(rootDir.path, 'lib', 'libfix_seccomp.so'));
final hasShim = shimFile.existsSync();
final guestEnvArgs = <String>[
'/usr/bin/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',
if (hasShim) 'LD_PRELOAD=/lib/libfix_seccomp.so',
];
args.addAll(guestEnvArgs);
// 登录 Shell 或自定义命令
if (customCommand != null && customCommand.isNotEmpty) {
args.addAll([targetShell, '-c', customCommand]);
@@ -234,14 +363,106 @@ class DistroManager {
'TERM': 'xterm-256color',
'LANG': 'C.UTF-8',
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
'TMPDIR': '/tmp',
'TMPDIR': tmpPath,
'PROOT_TMP_DIR': tmpPath,
if (l2sDir != null) 'PROOT_L2S_DIR': l2sDir.path,
if (nativeDir != null) 'LD_LIBRARY_PATH': nativeDir,
};
// Process.start 的宿主工作目录必须在 Android 宿主真实存在
final hostWorkDir = rootDir.path;
return ProotLaunchConfig(
executable: prootPath,
executable: effectiveProot,
arguments: args,
environment: env,
workingDirectory: containerWorkDir,
workingDirectory: hostWorkDir,
);
}
/// 确保容器内具备标准 DNS 解析文件 `/etc/resolv.conf`(对标 proot-distro)
Future<void> _ensureGuestDns(Directory rootDir) async {
try {
final etcDir = Directory(p.join(rootDir.path, 'etc'));
if (!etcDir.existsSync()) {
etcDir.createSync(recursive: true);
}
final resolvConf = File(p.join(etcDir.path, 'resolv.conf'));
if (!resolvConf.existsSync() || (await resolvConf.length()) == 0) {
// "可达优先"排序:国内公共 DNS 在前(8.8.8.8/1.1.1.1 在国内常被丢包,
// 排在首位会让 musl/glibc 解析器先等一次超时)。与 DistroInstaller
// 的 guestResolvConf 保持一致。
await resolvConf.writeAsString(
DistroInstaller.guestResolvConf,
flush: true,
);
}
} catch (e) {
debugPrint('配置容器 DNS 失败 (非阻塞): $e');
}
}
/// 确保容器实例拥有独立的 POSIX 共享内存目录(对标 proot-distro shm.py)
Future<Directory?> _ensureShmDir(String systemName) async {
try {
final baseDir = await getBaseDistrosDir();
final shmDir = Directory(p.join(baseDir.path, systemName, 'shm'));
if (!shmDir.existsSync()) {
shmDir.createSync(recursive: true);
}
return shmDir;
} catch (e) {
debugPrint('创建容器 shm 目录失败 (非阻塞): $e');
return null;
}
}
/// 确保容器实例拥有独立的 .l2s 硬链接跟踪目录(对标 proot-distro login/__init__.py)
Future<Directory?> _ensureL2sDir(String systemName) async {
try {
final baseDir = await getBaseDistrosDir();
final l2sDir = Directory(p.join(baseDir.path, systemName, '.l2s'));
if (!l2sDir.existsSync()) {
l2sDir.createSync(recursive: true);
}
return l2sDir;
} catch (e) {
debugPrint('创建容器 .l2s 目录失败 (非阻塞): $e');
return null;
}
}
/// 确保容器实例拥有独立的 sysdata 桩目录与 SELinux 覆盖节点(对标 proot-distro sysdata.py)
Future<Directory?> _ensureSysdataDir(String systemName) async {
try {
final baseDir = await getBaseDistrosDir();
final sysdataDir = Directory(p.join(baseDir.path, systemName, 'sysdata'));
if (!sysdataDir.existsSync()) {
sysdataDir.createSync(recursive: true);
}
// 1. 空目录用于覆盖 /sys/fs/selinux(禁用 selinux 检测)
final emptyDir = Directory(p.join(sysdataDir.path, 'sys_empty'));
if (!emptyDir.existsSync()) {
emptyDir.createSync(recursive: true);
}
// 2. /proc/sys/kernel/cap_last_cap 桩
final capFile = File(p.join(sysdataDir.path, 'sysctl_entry_cap_last_cap'));
if (!capFile.existsSync()) {
capFile.writeAsStringSync('40\n');
}
// 3. /proc/sys/fs/inotify/max_user_watches 桩
final inotifyFile = File(p.join(sysdataDir.path, 'sysctl_inotify_max_user_watches'));
if (!inotifyFile.existsSync()) {
inotifyFile.writeAsStringSync('4096\n');
}
return sysdataDir;
} catch (e) {
debugPrint('创建容器 sysdata 目录失败 (非阻塞): $e');
return null;
}
}
}