2
This commit is contained in:
1 parent
cce34e7960
commit
b49e096355
56 files changed
+8343
-296
No files matched your search
@@ -0,0 +1,448 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import '../models/distro_manifest.dart';
|
||||
import 'distro_image_resolver.dart';
|
||||
|
||||
/// 系统包下载状态枚举
|
||||
enum DistroDownloadState {
|
||||
notStarted,
|
||||
downloading,
|
||||
completed,
|
||||
cancelled,
|
||||
failed,
|
||||
}
|
||||
|
||||
/// 单个系统的下载状态快照
|
||||
class DistroDownloadProgress {
|
||||
final String distroId;
|
||||
final DistroDownloadState state;
|
||||
final double progress; // 0.0 ~ 1.0
|
||||
final int receivedBytes;
|
||||
final int totalBytes;
|
||||
final String? errorMessage;
|
||||
final File? targetFile;
|
||||
|
||||
const DistroDownloadProgress({
|
||||
required this.distroId,
|
||||
required this.state,
|
||||
this.progress = 0.0,
|
||||
this.receivedBytes = 0,
|
||||
this.totalBytes = -1,
|
||||
this.errorMessage,
|
||||
this.targetFile,
|
||||
});
|
||||
|
||||
DistroDownloadProgress copyWith({
|
||||
DistroDownloadState? state,
|
||||
double? progress,
|
||||
int? receivedBytes,
|
||||
int? totalBytes,
|
||||
String? errorMessage,
|
||||
File? targetFile,
|
||||
}) {
|
||||
return DistroDownloadProgress(
|
||||
distroId: distroId,
|
||||
state: state ?? this.state,
|
||||
progress: progress ?? this.progress,
|
||||
receivedBytes: receivedBytes ?? this.receivedBytes,
|
||||
totalBytes: totalBytes ?? this.totalBytes,
|
||||
errorMessage: errorMessage ?? this.errorMessage,
|
||||
targetFile: targetFile ?? this.targetFile,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载被取消异常
|
||||
class DistroDownloadCancelledException implements Exception {
|
||||
final String message;
|
||||
const DistroDownloadCancelledException([this.message = 'Download cancelled']);
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// 全局异步系统镜像下载管理器(单例模式)
|
||||
class DistroDownloadManager extends ChangeNotifier {
|
||||
static final DistroDownloadManager _instance = DistroDownloadManager._internal();
|
||||
factory DistroDownloadManager() => _instance;
|
||||
DistroDownloadManager._internal();
|
||||
|
||||
final Map<String, DistroDownloadProgress> _progressMap = {};
|
||||
final Map<String, HttpClientRequest> _activeRequests = {};
|
||||
final Map<String, HttpClient> _activeClients = {};
|
||||
final Map<String, StreamSubscription<List<int>>> _activeSubscriptions = {};
|
||||
final Map<String, IOSink> _activeSinks = {};
|
||||
final Map<String, Completer<void>> _activeCompleters = {};
|
||||
final Set<String> _cancelledDistroIds = {};
|
||||
|
||||
@visibleForTesting
|
||||
Directory? customPackagesDir;
|
||||
|
||||
/// 获取系统安装包持久化存储目录: `<app_dir>/distro_packages`
|
||||
Future<Directory> getPackagesDir() async {
|
||||
if (customPackagesDir != null) return customPackagesDir!;
|
||||
final appDir = await getApplicationSupportDirectory();
|
||||
final dir = Directory(p.join(appDir.path, 'distro_packages'));
|
||||
if (!dir.existsSync()) {
|
||||
dir.createSync(recursive: true);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
/// 获取指定系统的安装包文件对象
|
||||
Future<File> getPackageFile(String distroId, [String? downloadUrl]) async {
|
||||
final dir = await getPackagesDir();
|
||||
final ext = (downloadUrl?.endsWith('.tar.gz') ?? false) ? '.tar.gz' : '.tar.xz';
|
||||
final targetFile = File(p.join(dir.path, '${distroId}_rootfs$ext'));
|
||||
if (targetFile.existsSync()) return targetFile;
|
||||
final altExt = ext == '.tar.xz' ? '.tar.gz' : '.tar.xz';
|
||||
final altFile = File(p.join(dir.path, '${distroId}_rootfs$altExt'));
|
||||
if (altFile.existsSync()) return altFile;
|
||||
return targetFile;
|
||||
}
|
||||
|
||||
/// 检测指定系统的离线安装包是否已下载完备
|
||||
Future<bool> isPackageDownloaded(String distroId, [String? downloadUrl]) async {
|
||||
final dir = await getPackagesDir();
|
||||
final xzFile = File(p.join(dir.path, '${distroId}_rootfs.tar.xz'));
|
||||
final gzFile = File(p.join(dir.path, '${distroId}_rootfs.tar.gz'));
|
||||
return (xzFile.existsSync() && xzFile.lengthSync() > 0) ||
|
||||
(gzFile.existsSync() && gzFile.lengthSync() > 0);
|
||||
}
|
||||
|
||||
/// 物理删除已下载的系统安装包
|
||||
Future<void> deletePackage(String distroId, [String? downloadUrl]) async {
|
||||
if (isDownloading(distroId)) {
|
||||
await cancelDownload(distroId);
|
||||
}
|
||||
final dir = await getPackagesDir();
|
||||
final files = [
|
||||
File(p.join(dir.path, '${distroId}_rootfs.tar.xz')),
|
||||
File(p.join(dir.path, '${distroId}_rootfs.tar.gz')),
|
||||
];
|
||||
for (final f in files) {
|
||||
if (f.existsSync()) {
|
||||
try {
|
||||
f.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
_progressMap.remove(distroId);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 获取所有正在跟踪的下载任务快照
|
||||
Map<String, DistroDownloadProgress> get allProgress => Map.unmodifiable(_progressMap);
|
||||
|
||||
/// 查询指定系统的下载状态
|
||||
DistroDownloadProgress? getProgress(String distroId) => _progressMap[distroId];
|
||||
|
||||
/// 是否正在下载
|
||||
bool isDownloading(String distroId) {
|
||||
final status = _progressMap[distroId];
|
||||
return status != null && status.state == DistroDownloadState.downloading;
|
||||
}
|
||||
|
||||
/// 启动异步流式下载
|
||||
Future<File?> startDownload({
|
||||
required String distroId,
|
||||
required String downloadUrl,
|
||||
DistroMirror? mirror,
|
||||
DistroManifestItem? manifestItem,
|
||||
}) async {
|
||||
if (isDownloading(distroId)) return null;
|
||||
|
||||
// 资源检测:若本地已存在完整的离线镜像包,拒绝重复下载并直接返回已有文件
|
||||
if (await isPackageDownloaded(distroId, downloadUrl)) {
|
||||
final existingFile = await getPackageFile(distroId, downloadUrl);
|
||||
_progressMap[distroId] = DistroDownloadProgress(
|
||||
distroId: distroId,
|
||||
state: DistroDownloadState.completed,
|
||||
progress: 1.0,
|
||||
receivedBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
|
||||
totalBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
|
||||
targetFile: existingFile,
|
||||
);
|
||||
notifyListeners();
|
||||
return existingFile;
|
||||
}
|
||||
|
||||
// 清除历史取消标记
|
||||
_cancelledDistroIds.remove(distroId);
|
||||
|
||||
// 状态更新为 downloading
|
||||
_progressMap[distroId] = DistroDownloadProgress(
|
||||
distroId: distroId,
|
||||
state: DistroDownloadState.downloading,
|
||||
progress: 0.0,
|
||||
);
|
||||
notifyListeners();
|
||||
|
||||
String actualDownloadUrl = downloadUrl;
|
||||
if (manifestItem != null && manifestItem.lxcSpec != null) {
|
||||
try {
|
||||
final activeMirror = mirror ?? DistroRepository.defaultMirror;
|
||||
actualDownloadUrl = await DistroImageResolver().resolveDownloadUrl(
|
||||
item: manifestItem,
|
||||
arch: DistroManifestItem.currentArch,
|
||||
mirror: activeMirror,
|
||||
);
|
||||
} catch (e) {
|
||||
if (_cancelledDistroIds.contains(distroId)) {
|
||||
_cleanupCancelledState(distroId);
|
||||
return null;
|
||||
}
|
||||
_progressMap[distroId] = DistroDownloadProgress(
|
||||
distroId: distroId,
|
||||
state: DistroDownloadState.failed,
|
||||
errorMessage: e.toString(),
|
||||
);
|
||||
notifyListeners();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (_cancelledDistroIds.contains(distroId)) {
|
||||
_cleanupCancelledState(distroId);
|
||||
return null;
|
||||
}
|
||||
|
||||
// 二次资源检测:解析目标 URL 后再次检测文件是否完备
|
||||
if (await isPackageDownloaded(distroId, actualDownloadUrl)) {
|
||||
final existingFile = await getPackageFile(distroId, actualDownloadUrl);
|
||||
_progressMap[distroId] = DistroDownloadProgress(
|
||||
distroId: distroId,
|
||||
state: DistroDownloadState.completed,
|
||||
progress: 1.0,
|
||||
receivedBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
|
||||
totalBytes: existingFile.existsSync() ? existingFile.lengthSync() : 0,
|
||||
targetFile: existingFile,
|
||||
);
|
||||
notifyListeners();
|
||||
return existingFile;
|
||||
}
|
||||
|
||||
final targetFile = await getPackageFile(distroId, actualDownloadUrl);
|
||||
final partFilePath = '${targetFile.path}.part';
|
||||
final partFile = File(partFilePath);
|
||||
|
||||
HttpClient? client;
|
||||
IOSink? sink;
|
||||
StreamSubscription<List<int>>? subscription;
|
||||
final completer = Completer<void>();
|
||||
_activeCompleters[distroId] = completer;
|
||||
|
||||
try {
|
||||
if (partFile.existsSync()) {
|
||||
try {
|
||||
partFile.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
if (_cancelledDistroIds.contains(distroId)) {
|
||||
throw const DistroDownloadCancelledException();
|
||||
}
|
||||
|
||||
client = HttpClient()
|
||||
..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
|
||||
_activeClients[distroId] = client;
|
||||
|
||||
final uri = Uri.parse(actualDownloadUrl);
|
||||
final request = await client.getUrl(uri);
|
||||
_activeRequests[distroId] = request;
|
||||
|
||||
if (_cancelledDistroIds.contains(distroId)) {
|
||||
throw const DistroDownloadCancelledException();
|
||||
}
|
||||
|
||||
final response = await request.close();
|
||||
if (_cancelledDistroIds.contains(distroId)) {
|
||||
throw const DistroDownloadCancelledException();
|
||||
}
|
||||
|
||||
if (response.statusCode != HttpStatus.ok) {
|
||||
throw HttpException('HTTP Error: ${response.statusCode} ${response.reasonPhrase}');
|
||||
}
|
||||
|
||||
final total = response.contentLength;
|
||||
int received = 0;
|
||||
sink = partFile.openWrite();
|
||||
_activeSinks[distroId] = sink;
|
||||
|
||||
subscription = response.listen(
|
||||
(chunk) {
|
||||
if (_cancelledDistroIds.contains(distroId)) {
|
||||
subscription?.cancel();
|
||||
return;
|
||||
}
|
||||
sink?.add(chunk);
|
||||
received += chunk.length;
|
||||
final prog = total > 0 ? (received / total).clamp(0.0, 1.0) : 0.0;
|
||||
|
||||
_progressMap[distroId] = DistroDownloadProgress(
|
||||
distroId: distroId,
|
||||
state: DistroDownloadState.downloading,
|
||||
progress: prog,
|
||||
receivedBytes: received,
|
||||
totalBytes: total,
|
||||
);
|
||||
notifyListeners();
|
||||
},
|
||||
onDone: () async {
|
||||
if (_cancelledDistroIds.contains(distroId)) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(const DistroDownloadCancelledException());
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await sink?.flush();
|
||||
await sink?.close();
|
||||
sink = null;
|
||||
} catch (_) {}
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete();
|
||||
}
|
||||
},
|
||||
onError: (e) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(e);
|
||||
}
|
||||
},
|
||||
cancelOnError: true,
|
||||
);
|
||||
_activeSubscriptions[distroId] = subscription;
|
||||
|
||||
await completer.future;
|
||||
|
||||
if (_cancelledDistroIds.contains(distroId)) {
|
||||
throw const DistroDownloadCancelledException();
|
||||
}
|
||||
|
||||
// 下载完成,原子重命名 .part -> targetFile
|
||||
if (targetFile.existsSync()) {
|
||||
targetFile.deleteSync();
|
||||
}
|
||||
partFile.renameSync(targetFile.path);
|
||||
|
||||
_progressMap[distroId] = DistroDownloadProgress(
|
||||
distroId: distroId,
|
||||
state: DistroDownloadState.completed,
|
||||
progress: 1.0,
|
||||
receivedBytes: received,
|
||||
totalBytes: total,
|
||||
targetFile: targetFile,
|
||||
);
|
||||
notifyListeners();
|
||||
return targetFile;
|
||||
} catch (e) {
|
||||
final isCancelled = _cancelledDistroIds.contains(distroId) ||
|
||||
e is DistroDownloadCancelledException;
|
||||
|
||||
// 无论如何先关闭写入流,确保文件句柄释放
|
||||
try {
|
||||
await sink?.close();
|
||||
} catch (_) {}
|
||||
|
||||
// 清理临时文件
|
||||
if (partFile.existsSync()) {
|
||||
try {
|
||||
partFile.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
if (isCancelled) {
|
||||
_cleanupCancelledState(distroId);
|
||||
} else {
|
||||
_progressMap[distroId] = DistroDownloadProgress(
|
||||
distroId: distroId,
|
||||
state: DistroDownloadState.failed,
|
||||
errorMessage: e.toString(),
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
_activeRequests.remove(distroId);
|
||||
_activeSubscriptions.remove(distroId);
|
||||
_activeSinks.remove(distroId);
|
||||
_activeCompleters.remove(distroId);
|
||||
final c = _activeClients.remove(distroId);
|
||||
try {
|
||||
c?.close(force: true);
|
||||
} catch (_) {}
|
||||
_cancelledDistroIds.remove(distroId);
|
||||
}
|
||||
}
|
||||
|
||||
/// 取消下载并清理已下载的临时缓存资源
|
||||
Future<void> cancelDownload(String distroId) async {
|
||||
_cancelledDistroIds.add(distroId);
|
||||
|
||||
// 1. 中断活跃 Completer
|
||||
final completer = _activeCompleters.remove(distroId);
|
||||
if (completer != null && !completer.isCompleted) {
|
||||
completer.completeError(const DistroDownloadCancelledException());
|
||||
}
|
||||
|
||||
// 2. 中断 Request 并强力关闭 HttpClient(立即熔断底层 TCP Socket,避免 sub.cancel() 陷入 socket 耗尽等待)
|
||||
final request = _activeRequests.remove(distroId);
|
||||
if (request != null) {
|
||||
try {
|
||||
request.abort();
|
||||
} catch (_) {}
|
||||
}
|
||||
final client = _activeClients.remove(distroId);
|
||||
if (client != null) {
|
||||
try {
|
||||
client.close(force: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// 3. 取消活跃 Stream 订阅以停止接收数据包(不阻塞等待 drain)
|
||||
final sub = _activeSubscriptions.remove(distroId);
|
||||
if (sub != null) {
|
||||
try {
|
||||
unawaited(sub.cancel());
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// 4. 关闭文件写入流以释放文件句柄(Windows 平台必须关闭方可删除)
|
||||
final sink = _activeSinks.remove(distroId);
|
||||
if (sink != null) {
|
||||
try {
|
||||
await sink.close();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// 5. 立即清除临时 .part 文件
|
||||
try {
|
||||
final dir = await getPackagesDir();
|
||||
final partFiles = [
|
||||
File(p.join(dir.path, '${distroId}_rootfs.tar.gz.part')),
|
||||
File(p.join(dir.path, '${distroId}_rootfs.tar.xz.part')),
|
||||
];
|
||||
for (final f in partFiles) {
|
||||
if (f.existsSync()) {
|
||||
f.deleteSync();
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
// 6. 重置状态并通知刷新
|
||||
_cleanupCancelledState(distroId);
|
||||
}
|
||||
|
||||
void _cleanupCancelledState(String distroId) {
|
||||
_progressMap.remove(distroId);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 重置已完成或失败的状态
|
||||
void resetState(String distroId) {
|
||||
_progressMap.remove(distroId);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../models/distro_manifest.dart';
|
||||
|
||||
/// LXC 镜像源索引行条目
|
||||
class DistroIndexEntry {
|
||||
final String distribution;
|
||||
final String release;
|
||||
final String arch;
|
||||
final String variant;
|
||||
final String buildDate;
|
||||
final String path;
|
||||
|
||||
const DistroIndexEntry({
|
||||
required this.distribution,
|
||||
required this.release,
|
||||
required this.arch,
|
||||
required this.variant,
|
||||
required this.buildDate,
|
||||
required this.path,
|
||||
});
|
||||
|
||||
factory DistroIndexEntry.fromLine(String line) {
|
||||
final parts = line.trim().split(';');
|
||||
if (parts.length < 6) {
|
||||
throw FormatException('Invalid index line: $line');
|
||||
}
|
||||
return DistroIndexEntry(
|
||||
distribution: parts[0],
|
||||
release: parts[1],
|
||||
arch: parts[2],
|
||||
variant: parts[3],
|
||||
buildDate: parts[4],
|
||||
path: parts[5],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 发行版镜像真实下载链接解析器(遵循 LinuxContainers 标准 index-system 规范)
|
||||
class DistroImageResolver {
|
||||
static final DistroImageResolver _instance = DistroImageResolver._internal();
|
||||
factory DistroImageResolver() => _instance;
|
||||
DistroImageResolver._internal();
|
||||
|
||||
/// 缓存的解析结果 (key: "mirrorId:distroId:arch", value: url)
|
||||
final Map<String, String> _resolvedUrlCache = {};
|
||||
|
||||
/// 缓存的 index-system 纯文本内容 (key: mirrorId, value: (cachedTime, content))
|
||||
final Map<String, (DateTime, String)> _indexContentCache = {};
|
||||
|
||||
/// 索引缓存有效期 (1 小时)
|
||||
static const Duration cacheTtl = Duration(hours: 1);
|
||||
|
||||
@visibleForTesting
|
||||
String? customIndexContent;
|
||||
|
||||
/// 清空指定系统或所有缓存
|
||||
void invalidateCache({String? distroId}) {
|
||||
if (distroId != null) {
|
||||
_resolvedUrlCache.removeWhere((key, _) => key.contains(':$distroId:'));
|
||||
} else {
|
||||
_resolvedUrlCache.clear();
|
||||
_indexContentCache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// 将系统架构枚举映射为 LXC 索引架构命名(arm64 -> arm64, x86_64 -> amd64)
|
||||
static String toLxcArch(DistroArch arch) {
|
||||
switch (arch) {
|
||||
case DistroArch.arm64:
|
||||
return 'arm64';
|
||||
case DistroArch.x86_64:
|
||||
return 'amd64';
|
||||
}
|
||||
}
|
||||
|
||||
/// 动态解析指定发行版在指定镜像源上的最新真实下载 URL
|
||||
Future<String> resolveDownloadUrl({
|
||||
required DistroManifestItem item,
|
||||
required DistroArch arch,
|
||||
required DistroMirror mirror,
|
||||
bool forceRefresh = false,
|
||||
}) async {
|
||||
// 内置系统直接返回静态资源路径
|
||||
if (item.isBuiltin) {
|
||||
return item.packages[arch] ?? '';
|
||||
}
|
||||
|
||||
final spec = item.lxcSpec;
|
||||
if (spec == null) {
|
||||
return item.packages[arch] ?? '';
|
||||
}
|
||||
|
||||
final cacheKey = '${mirror.id}:${item.id}:${arch.name}';
|
||||
if (!forceRefresh && _resolvedUrlCache.containsKey(cacheKey)) {
|
||||
return _resolvedUrlCache[cacheKey]!;
|
||||
}
|
||||
|
||||
// 1. 获取对应镜像源的 meta/1.0/index-system 索引
|
||||
final indexContent = await _fetchIndexContent(mirror, forceRefresh: forceRefresh);
|
||||
|
||||
// 2. 解析为条目列表
|
||||
final entries = parseIndex(indexContent);
|
||||
final targetArch = toLxcArch(arch);
|
||||
|
||||
// 3. 匹配符合发行版、版本、变体及 CPU 架构的条目
|
||||
final matching = entries.where((e) =>
|
||||
e.distribution.toLowerCase() == spec.distribution.toLowerCase() &&
|
||||
e.release.toLowerCase() == spec.release.toLowerCase() &&
|
||||
e.arch.toLowerCase() == targetArch.toLowerCase() &&
|
||||
e.variant.toLowerCase() == spec.variant.toLowerCase(),
|
||||
).toList();
|
||||
|
||||
if (matching.isEmpty) {
|
||||
throw HttpException(
|
||||
'Image not found in mirror ${mirror.name}: ${spec.distribution}/${spec.release}/$targetArch',
|
||||
);
|
||||
}
|
||||
|
||||
// 4. 按 buildDate 降序排序,取最新一次构建
|
||||
matching.sort((a, b) => b.buildDate.compareTo(a.buildDate));
|
||||
final latestEntry = matching.first;
|
||||
|
||||
// 5. 组合目标真实 URL
|
||||
final base = mirror.baseUrl.replaceAll(RegExp(r'/+$'), '');
|
||||
final relPath = latestEntry.path.replaceAll(RegExp(r'^/+'), '');
|
||||
final fullUrl = '$base/$relPath' 'rootfs.tar.xz';
|
||||
|
||||
_resolvedUrlCache[cacheKey] = fullUrl;
|
||||
return fullUrl;
|
||||
}
|
||||
|
||||
/// 解析 index-system 纯文本内容为条目列表
|
||||
static List<DistroIndexEntry> parseIndex(String content) {
|
||||
final lines = content.split('\n');
|
||||
final List<DistroIndexEntry> list = [];
|
||||
for (final line in lines) {
|
||||
final trimmed = line.trim();
|
||||
if (trimmed.isEmpty || trimmed.startsWith('#')) continue;
|
||||
try {
|
||||
list.add(DistroIndexEntry.fromLine(trimmed));
|
||||
} catch (_) {}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// 从网络拉取镜像源的 meta/1.0/index-system
|
||||
Future<String> _fetchIndexContent(DistroMirror mirror, {bool forceRefresh = false}) async {
|
||||
if (customIndexContent != null) {
|
||||
return customIndexContent!;
|
||||
}
|
||||
|
||||
final now = DateTime.now();
|
||||
if (!forceRefresh && _indexContentCache.containsKey(mirror.id)) {
|
||||
final (cachedAt, text) = _indexContentCache[mirror.id]!;
|
||||
if (now.difference(cachedAt) < cacheTtl) {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
HttpClient? client;
|
||||
try {
|
||||
client = HttpClient()
|
||||
..connectionTimeout = const Duration(seconds: 15)
|
||||
..badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
|
||||
|
||||
final indexUrl = '${mirror.baseUrl.replaceAll(RegExp(r'/+$'), '')}/meta/1.0/index-system';
|
||||
final request = await client.getUrl(Uri.parse(indexUrl));
|
||||
final response = await request.close().timeout(const Duration(seconds: 20));
|
||||
|
||||
if (response.statusCode != HttpStatus.ok) {
|
||||
throw HttpException('Failed to fetch mirror index from ${mirror.name}: HTTP ${response.statusCode}');
|
||||
}
|
||||
|
||||
final body = await response.transform(utf8.decoder).join();
|
||||
_indexContentCache[mirror.id] = (now, body);
|
||||
return body;
|
||||
} finally {
|
||||
client?.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:ffi';
|
||||
import 'dart:io';
|
||||
import 'package:archive/archive.dart';
|
||||
import 'dart:isolate';
|
||||
import 'package:archive/archive_io.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'low_memory_xz_decoder.dart';
|
||||
|
||||
final RegExp _paxRecordRegexp = RegExp(r"(\d+) (\w+)=(.*)");
|
||||
|
||||
/// 安装进度回调
|
||||
/// [progress] 0.0 ~ 1.0
|
||||
@@ -19,16 +25,99 @@ class DistroInstallCancelledException implements Exception {
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
class _ExtractIsolateParams {
|
||||
final String archivePath;
|
||||
final String targetDirPath;
|
||||
final SendPort sendPort;
|
||||
|
||||
const _ExtractIsolateParams({
|
||||
required this.archivePath,
|
||||
required this.targetDirPath,
|
||||
required this.sendPort,
|
||||
});
|
||||
}
|
||||
|
||||
/// 流式 TAR 块头部结构解析器
|
||||
class _TarHeader {
|
||||
final String filename;
|
||||
final int mode;
|
||||
final int fileSize;
|
||||
final String typeFlag;
|
||||
final String? nameOfLinkedFile;
|
||||
|
||||
_TarHeader({
|
||||
required this.filename,
|
||||
required this.mode,
|
||||
required this.fileSize,
|
||||
required this.typeFlag,
|
||||
this.nameOfLinkedFile,
|
||||
});
|
||||
|
||||
static _TarHeader? read(InputStreamBase input) {
|
||||
if (input.isEOS) return null;
|
||||
final header = input.readBytes(512);
|
||||
if (header.length < 512) return null;
|
||||
final bytes = header.toUint8List();
|
||||
|
||||
var allZero = true;
|
||||
for (var i = 0; i < 512; i++) {
|
||||
if (bytes[i] != 0) {
|
||||
allZero = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (allZero) return null;
|
||||
|
||||
String parseString(int offset, int length) {
|
||||
var end = offset;
|
||||
final max = offset + length;
|
||||
while (end < max && bytes[end] != 0) {
|
||||
end++;
|
||||
}
|
||||
return utf8.decode(bytes.sublist(offset, end), allowMalformed: true);
|
||||
}
|
||||
|
||||
int parseInt(int offset, int length) {
|
||||
final s = parseString(offset, length).trim();
|
||||
if (s.isEmpty) return 0;
|
||||
return int.tryParse(s, radix: 8) ?? 0;
|
||||
}
|
||||
|
||||
var filename = parseString(0, 100);
|
||||
final mode = parseInt(100, 8);
|
||||
final fileSize = parseInt(124, 12);
|
||||
final typeFlag = parseString(156, 1);
|
||||
String? nameOfLinkedFile = parseString(157, 100);
|
||||
if (nameOfLinkedFile.isEmpty) nameOfLinkedFile = null;
|
||||
|
||||
final ustarIndicator = parseString(257, 6);
|
||||
if (ustarIndicator == 'ustar') {
|
||||
final filenamePrefix = parseString(345, 155);
|
||||
if (filenamePrefix.isNotEmpty) {
|
||||
filename = '$filenamePrefix/$filename';
|
||||
}
|
||||
}
|
||||
|
||||
return _TarHeader(
|
||||
filename: filename,
|
||||
mode: mode,
|
||||
fileSize: fileSize,
|
||||
typeFlag: typeFlag,
|
||||
nameOfLinkedFile: nameOfLinkedFile,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Linux 发行版 Rootfs 安装与解压服务
|
||||
class DistroInstaller {
|
||||
/// 解压并安装 tar.gz 格式的 Rootfs 到目标目录
|
||||
/// 从本地文件流式解压并安装 Rootfs(低内存、防卡顿、支持 XZ/GZip/Tar)
|
||||
///
|
||||
/// [tarGzBytes] .tar.gz 压缩包字节流
|
||||
/// [archiveFile] 压缩包文件 (.tar.xz 或 .tar.gz)
|
||||
/// [targetDir] 目标解压目录 (即容器的 rootfs 路径)
|
||||
/// [onProgress] 进度回调
|
||||
/// [isCancelled] 外部取消检查函数
|
||||
static Future<void> installFromBytes({
|
||||
required Uint8List tarGzBytes,
|
||||
static Future<void> installFromFile({
|
||||
required File archiveFile,
|
||||
required Directory targetDir,
|
||||
InstallProgressCallback? onProgress,
|
||||
bool Function()? isCancelled,
|
||||
@@ -37,88 +126,30 @@ class DistroInstaller {
|
||||
throw DistroInstallCancelledException();
|
||||
}
|
||||
|
||||
onProgress?.call(0.05, '正在校验与解析系统镜像...');
|
||||
if (!archiveFile.existsSync()) {
|
||||
throw ArgumentError('压缩包文件不存在: ${archiveFile.path}');
|
||||
}
|
||||
|
||||
onProgress?.call(0.05, '正在校验与准备解压目录...');
|
||||
|
||||
if (!targetDir.existsSync()) {
|
||||
targetDir.createSync(recursive: true);
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. 在后台解压 Gzip 与 Tar(避免 UI 线程卡顿)
|
||||
onProgress?.call(0.15, '正在解压内核与文件系统结构...');
|
||||
final archive = await compute(_decodeTarGz, tarGzBytes);
|
||||
// 全平台统一使用低内存流式 Isolate 解压引擎(稳定、确定性进度、低内存、零外部依赖)
|
||||
await _extractWithDartStreamIsolate(
|
||||
archiveFile: archiveFile,
|
||||
targetDir: targetDir,
|
||||
onProgress: onProgress,
|
||||
isCancelled: isCancelled,
|
||||
);
|
||||
|
||||
if (isCancelled?.call() == true) {
|
||||
throw DistroInstallCancelledException();
|
||||
}
|
||||
|
||||
// 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>>{};
|
||||
|
||||
for (final file in archive) {
|
||||
if (isCancelled?.call() == true) {
|
||||
throw DistroInstallCancelledException();
|
||||
}
|
||||
|
||||
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 {
|
||||
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)...');
|
||||
}
|
||||
}
|
||||
|
||||
if (!Platform.isWindows) {
|
||||
await _restoreModes(byMode);
|
||||
}
|
||||
|
||||
if (isCancelled?.call() == true) {
|
||||
throw DistroInstallCancelledException();
|
||||
}
|
||||
|
||||
// 3. 执行系统配置与网络补丁
|
||||
// 阶段 3:执行系统配置与网络补丁
|
||||
onProgress?.call(0.92, '正在配置网络 DNS 与系统环境...');
|
||||
await postInstallConfigure(targetDir);
|
||||
|
||||
@@ -134,12 +165,334 @@ class DistroInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
/// 后台 Isolate 解压 tar.gz
|
||||
static Archive _decodeTarGz(Uint8List bytes) {
|
||||
final tarData = GZipDecoder().decodeBytes(bytes);
|
||||
return TarDecoder().decodeBytes(tarData);
|
||||
/// 解压并安装内存字节流格式的 Rootfs 到目标目录(兼容已有内置 asset 资源包接口)
|
||||
static Future<void> installFromBytes({
|
||||
required Uint8List tarGzBytes,
|
||||
required Directory targetDir,
|
||||
InstallProgressCallback? onProgress,
|
||||
bool Function()? isCancelled,
|
||||
}) async {
|
||||
final tempDir = Directory.systemTemp.createTempSync('distro_temp_');
|
||||
try {
|
||||
final tempFile = File(p.join(tempDir.path, 'archive.bin'));
|
||||
await tempFile.writeAsBytes(tarGzBytes, flush: true);
|
||||
await installFromFile(
|
||||
archiveFile: tempFile,
|
||||
targetDir: targetDir,
|
||||
onProgress: onProgress,
|
||||
isCancelled: isCancelled,
|
||||
);
|
||||
} finally {
|
||||
if (tempDir.existsSync()) {
|
||||
try {
|
||||
tempDir.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 在独立后台 Isolate 中执行流式解压与逐文件直接落盘(避免生成几十万对象引发 OOM)
|
||||
static Future<void> _extractWithDartStreamIsolate({
|
||||
required File archiveFile,
|
||||
required Directory targetDir,
|
||||
InstallProgressCallback? onProgress,
|
||||
bool Function()? isCancelled,
|
||||
}) async {
|
||||
final receivePort = ReceivePort();
|
||||
final exitPort = ReceivePort();
|
||||
final completer = Completer<Map<int, List<String>>>();
|
||||
Isolate? isolate;
|
||||
Timer? cancelTimer;
|
||||
|
||||
try {
|
||||
isolate = await Isolate.spawn<_ExtractIsolateParams>(
|
||||
_extractIsolateEntry,
|
||||
_ExtractIsolateParams(
|
||||
archivePath: archiveFile.path,
|
||||
targetDirPath: targetDir.path,
|
||||
sendPort: receivePort.sendPort,
|
||||
),
|
||||
);
|
||||
|
||||
isolate.addOnExitListener(exitPort.sendPort);
|
||||
exitPort.listen((_) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(Exception('解压引擎意外退出'));
|
||||
}
|
||||
});
|
||||
|
||||
cancelTimer = Timer.periodic(const Duration(milliseconds: 100), (_) {
|
||||
if (isCancelled?.call() == true) {
|
||||
isolate?.kill(priority: Isolate.immediate);
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(DistroInstallCancelledException());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
receivePort.listen((message) {
|
||||
if (message is List) {
|
||||
final type = message[0] as int;
|
||||
if (type == 0) {
|
||||
final prog = message[1] as double;
|
||||
final msg = message[2] as String;
|
||||
onProgress?.call(prog, msg);
|
||||
} else if (type == 1) {
|
||||
final byMode = (message[1] as Map).cast<int, List<String>>();
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(byMode);
|
||||
}
|
||||
} else if (type == 3) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(Exception(message[1].toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
final byMode = await completer.future;
|
||||
|
||||
if (!Platform.isWindows) {
|
||||
await _restoreModes(byMode);
|
||||
}
|
||||
} finally {
|
||||
cancelTimer?.cancel();
|
||||
receivePort.close();
|
||||
exitPort.close();
|
||||
isolate?.kill(priority: Isolate.immediate);
|
||||
}
|
||||
}
|
||||
|
||||
/// Isolate 入口:低内存流式解压与逐文件直接落盘
|
||||
static Future<void> _extractIsolateEntry(_ExtractIsolateParams params) async {
|
||||
File? tempTarFile;
|
||||
try {
|
||||
params.sendPort.send([0, 0.10, '正在读取并解析系统压缩包...']);
|
||||
final archiveFile = File(params.archivePath);
|
||||
if (!archiveFile.existsSync()) {
|
||||
params.sendPort.send([3, '压缩包文件不存在: ${params.archivePath}']);
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. 检查头部魔数判断文件格式
|
||||
final raf = archiveFile.openSync(mode: FileMode.read);
|
||||
final magic = raf.readSync(6);
|
||||
raf.closeSync();
|
||||
|
||||
final isXz = magic.length >= 6 &&
|
||||
magic[0] == 0xFD &&
|
||||
magic[1] == 0x37 &&
|
||||
magic[2] == 0x7A &&
|
||||
magic[3] == 0x58 &&
|
||||
magic[4] == 0x5A &&
|
||||
magic[5] == 0x00;
|
||||
|
||||
final isGz = magic.length >= 2 && magic[0] == 0x1F && magic[1] == 0x8B;
|
||||
|
||||
final targetDir = Directory(params.targetDirPath);
|
||||
final tempDir = targetDir.parent.existsSync()
|
||||
? targetDir.parent
|
||||
: Directory.systemTemp;
|
||||
|
||||
File tarToExtract;
|
||||
if (isXz) {
|
||||
params.sendPort.send([0, 0.12, '正在流式解压内核与文件系统结构 (XZ)...']);
|
||||
tempTarFile = File(p.join(
|
||||
tempDir.path,
|
||||
'temp_distro_extract_${DateTime.now().microsecondsSinceEpoch}.tar',
|
||||
));
|
||||
if (tempTarFile.existsSync()) {
|
||||
try {
|
||||
tempTarFile.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
final tarSink = tempTarFile.openWrite();
|
||||
final inputStream = InputFileStream(archiveFile.path);
|
||||
final archiveSize = archiveFile.lengthSync();
|
||||
|
||||
try {
|
||||
final decoder = LowMemoryXZDecoder();
|
||||
decoder.decodeToSink(
|
||||
inputStream,
|
||||
tarSink,
|
||||
onProgress: (decompressed, compPos) {
|
||||
final frac = archiveSize > 0
|
||||
? (compPos / archiveSize).clamp(0.0, 1.0)
|
||||
: 0.0;
|
||||
final prog = 0.12 + frac * 0.38; // 0.12 ~ 0.50
|
||||
final mb = (decompressed / (1024 * 1024)).toStringAsFixed(1);
|
||||
params.sendPort.send([0, prog, '正在解压系统文件 ($mb MB)...']);
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
await tarSink.flush();
|
||||
await tarSink.close();
|
||||
await inputStream.close();
|
||||
}
|
||||
tarToExtract = tempTarFile;
|
||||
} else if (isGz) {
|
||||
params.sendPort.send([0, 0.12, '正在流式解压内核与文件系统结构 (GZip)...']);
|
||||
tempTarFile = File(p.join(
|
||||
tempDir.path,
|
||||
'temp_distro_extract_${DateTime.now().microsecondsSinceEpoch}.tar',
|
||||
));
|
||||
if (tempTarFile.existsSync()) {
|
||||
try {
|
||||
tempTarFile.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
final tarSink = tempTarFile.openWrite();
|
||||
try {
|
||||
await archiveFile.openRead().transform(gzip.decoder).pipe(tarSink);
|
||||
} finally {
|
||||
await tarSink.close();
|
||||
}
|
||||
tarToExtract = tempTarFile;
|
||||
} else {
|
||||
tarToExtract = archiveFile;
|
||||
}
|
||||
|
||||
// 2. 流式释放 TAR 文件到目标根目录
|
||||
params.sendPort.send([0, 0.50, '正在释放系统文件...']);
|
||||
final byMode = await _streamExtractTarFile(
|
||||
tarFile: tarToExtract,
|
||||
targetDirPath: params.targetDirPath,
|
||||
sendPort: params.sendPort,
|
||||
progressStart: 0.50,
|
||||
progressEnd: 0.90,
|
||||
);
|
||||
|
||||
params.sendPort.send([1, byMode]);
|
||||
} catch (e) {
|
||||
params.sendPort.send([3, e.toString()]);
|
||||
} finally {
|
||||
if (tempTarFile != null && tempTarFile.existsSync()) {
|
||||
try {
|
||||
tempTarFile.deleteSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 流式逐条解析 TAR 文件并直接落盘
|
||||
static Future<Map<int, List<String>>> _streamExtractTarFile({
|
||||
required File tarFile,
|
||||
required String targetDirPath,
|
||||
required SendPort sendPort,
|
||||
required double progressStart,
|
||||
required double progressEnd,
|
||||
}) async {
|
||||
final input = InputFileStream(tarFile.path);
|
||||
final byMode = <int, List<String>>{};
|
||||
final totalLen = tarFile.lengthSync();
|
||||
String? nextName;
|
||||
String? nextLinkName;
|
||||
int processed = 0;
|
||||
|
||||
try {
|
||||
while (!input.isEOS) {
|
||||
final th = _TarHeader.read(input);
|
||||
if (th == null) break;
|
||||
|
||||
if (th.filename == '././@LongLink') {
|
||||
final contentBytes = input.readBytes(th.fileSize).toUint8List();
|
||||
final remainder = th.fileSize % 512;
|
||||
if (remainder != 0) input.skip(512 - remainder);
|
||||
final text = utf8.decode(contentBytes, allowMalformed: true).split('\x00').first;
|
||||
if (th.typeFlag == 'K') {
|
||||
nextLinkName = text;
|
||||
} else {
|
||||
nextName = text;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (th.typeFlag == 'g' || th.typeFlag == 'x') {
|
||||
// PAX Header
|
||||
try {
|
||||
final paxBytes = input.readBytes(th.fileSize).toUint8List();
|
||||
final remainder = th.fileSize % 512;
|
||||
if (remainder != 0) input.skip(512 - remainder);
|
||||
final headerContent = utf8.decode(paxBytes, allowMalformed: true);
|
||||
for (final line in headerContent.split('\n')) {
|
||||
final match = _paxRecordRegexp.firstMatch(line);
|
||||
if (match != null) {
|
||||
final k = match.group(2);
|
||||
final v = match.group(3);
|
||||
if (k == 'path' && v != null) nextName = v;
|
||||
if (k == 'linkpath' && v != null) nextLinkName = v;
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
continue;
|
||||
}
|
||||
|
||||
final filename = nextName ?? th.filename;
|
||||
nextName = null;
|
||||
final linkName = nextLinkName ?? th.nameOfLinkedFile;
|
||||
nextLinkName = null;
|
||||
|
||||
if (filename.contains('..')) {
|
||||
if (th.fileSize > 0) {
|
||||
input.skip(th.fileSize);
|
||||
final remainder = th.fileSize % 512;
|
||||
if (remainder != 0) input.skip(512 - remainder);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
final outPath = p.join(targetDirPath, filename);
|
||||
|
||||
if (th.typeFlag == '5' || th.filename.endsWith('/')) {
|
||||
final d = Directory(outPath);
|
||||
if (!d.existsSync()) d.createSync(recursive: true);
|
||||
} else if ((th.typeFlag == '2' || th.typeFlag == '1') && linkName != null) {
|
||||
try {
|
||||
final parent = Directory(p.dirname(outPath));
|
||||
if (!parent.existsSync()) parent.createSync(recursive: true);
|
||||
final link = Link(outPath);
|
||||
if (link.existsSync()) link.deleteSync();
|
||||
link.createSync(linkName);
|
||||
} catch (_) {}
|
||||
} else {
|
||||
final parent = Directory(p.dirname(outPath));
|
||||
if (!parent.existsSync()) parent.createSync(recursive: true);
|
||||
|
||||
final f = File(outPath);
|
||||
final sink = f.openWrite();
|
||||
var remaining = th.fileSize;
|
||||
while (remaining > 0) {
|
||||
final chunk = remaining < 65536 ? remaining : 65536;
|
||||
sink.add(input.readBytes(chunk).toUint8List());
|
||||
remaining -= chunk;
|
||||
}
|
||||
await sink.flush();
|
||||
await sink.close();
|
||||
|
||||
final remainder = th.fileSize % 512;
|
||||
if (remainder != 0) input.skip(512 - remainder);
|
||||
}
|
||||
|
||||
final mode = th.mode & 0xFFF;
|
||||
if (mode != 0 && th.typeFlag != '2') {
|
||||
byMode.putIfAbsent(mode, () => <String>[]).add(outPath);
|
||||
}
|
||||
|
||||
processed++;
|
||||
if (processed % 150 == 0) {
|
||||
final fraction = totalLen > 0 ? (input.position / totalLen).clamp(0.0, 1.0) : 0.0;
|
||||
final prog = progressStart + fraction * (progressEnd - progressStart);
|
||||
sendPort.send([0, prog, '正在释放系统文件 ($processed)...']);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await input.close();
|
||||
}
|
||||
|
||||
return byMode;
|
||||
}
|
||||
|
||||
|
||||
/// 按 tar 头恢复权限位(dart:io 无 chmod,按 mode 分组批量调用,避免逐文件 fork)
|
||||
static Future<void> _restoreModes(Map<int, List<String>> byMode) async {
|
||||
for (final entry in byMode.entries) {
|
||||
@@ -197,34 +550,171 @@ class DistroInstaller {
|
||||
debugPrint('[DistroInstaller] 写入 hosts 失败: $e');
|
||||
}
|
||||
|
||||
// 3. 配置 Alpine apk 软件源镜像(使用阿里云高速稳定镜像)
|
||||
// 3. 配置软件源镜像(按发行版自动适配,国内高速镜像)
|
||||
final apkDir = Directory(p.join(etcDir.path, 'apk'));
|
||||
if (apkDir.existsSync()) {
|
||||
// 3.1 Alpine apk 软件源镜像(使用阿里云高速镜像,自适应主版本号)
|
||||
var alpineVer = 'v3.20';
|
||||
final alpineRel = File(p.join(etcDir.path, 'alpine-release'));
|
||||
if (alpineRel.existsSync()) {
|
||||
try {
|
||||
final relStr = alpineRel.readAsStringSync().trim();
|
||||
final match = RegExp(r'^(\d+\.\d+)').firstMatch(relStr);
|
||||
if (match != null) {
|
||||
alpineVer = 'v${match.group(1)}';
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
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',
|
||||
'https://mirrors.aliyun.com/alpine/$alpineVer/main\n'
|
||||
'https://mirrors.aliyun.com/alpine/$alpineVer/community\n',
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[DistroInstaller] 写入 repositories 失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 确保 /workspace 挂载点目录存在
|
||||
// 4. 自动部署根证书(解决最小化 Linux 发行版缺少 ca-certificates 导致 https 证书验证失败)
|
||||
await ensureCaCertificates(rootfsDir);
|
||||
|
||||
final aptDir = Directory(p.join(etcDir.path, 'apt'));
|
||||
if (aptDir.existsSync()) {
|
||||
final sourcesD = Directory(p.join(aptDir.path, 'sources.list.d'));
|
||||
final ubuntuSources = File(p.join(sourcesD.path, 'ubuntu.sources'));
|
||||
final isUbuntu = ubuntuSources.existsSync() ||
|
||||
(File(p.join(etcDir.path, 'os-release')).existsSync() &&
|
||||
File(p.join(etcDir.path, 'os-release')).readAsStringSync().toLowerCase().contains('ubuntu'));
|
||||
|
||||
if (isUbuntu) {
|
||||
// 3.2 Ubuntu deb822 源配置(清华大学高速镜像)
|
||||
if (!sourcesD.existsSync()) sourcesD.createSync(recursive: true);
|
||||
try {
|
||||
final isArm = (Abi.current() == Abi.androidArm64 || Abi.current() == Abi.linuxArm64);
|
||||
final mirrorUri = isArm
|
||||
? 'https://mirrors.tuna.tsinghua.edu.cn/ubuntu-ports/'
|
||||
: 'https://mirrors.tuna.tsinghua.edu.cn/ubuntu/';
|
||||
ubuntuSources.writeAsStringSync(
|
||||
'Types: deb\n'
|
||||
'URIs: $mirrorUri\n'
|
||||
'Suites: noble noble-updates noble-backports noble-security\n'
|
||||
'Components: main universe restricted multiverse\n'
|
||||
'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n',
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[DistroInstaller] 写入 ubuntu.sources 失败: $e');
|
||||
}
|
||||
} else {
|
||||
// 3.3 Debian 源配置(清华大学高速镜像)
|
||||
final debianSources = File(p.join(sourcesD.path, 'debian.sources'));
|
||||
final sourcesList = File(p.join(aptDir.path, 'sources.list'));
|
||||
try {
|
||||
sourcesList.writeAsStringSync(
|
||||
'deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware\n'
|
||||
'deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware\n'
|
||||
'deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware\n'
|
||||
'deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware\n',
|
||||
);
|
||||
if (debianSources.existsSync()) {
|
||||
debianSources.writeAsStringSync(
|
||||
'Types: deb\n'
|
||||
'URIs: https://mirrors.tuna.tsinghua.edu.cn/debian/\n'
|
||||
'Suites: bookworm bookworm-updates bookworm-backports\n'
|
||||
'Components: main contrib non-free non-free-firmware\n'
|
||||
'Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg\n'
|
||||
'\n'
|
||||
'Types: deb\n'
|
||||
'URIs: https://mirrors.tuna.tsinghua.edu.cn/debian-security\n'
|
||||
'Suites: bookworm-security\n'
|
||||
'Components: main contrib non-free non-free-firmware\n'
|
||||
'Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg\n',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('[DistroInstaller] 写入 debian sources 失败: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3.4 Arch Linux pacman 源配置(清华大学高速镜像)
|
||||
final pacmanDir = Directory(p.join(etcDir.path, 'pacman.d'));
|
||||
if (pacmanDir.existsSync()) {
|
||||
final mirrorlist = File(p.join(pacmanDir.path, 'mirrorlist'));
|
||||
try {
|
||||
mirrorlist.writeAsStringSync(
|
||||
'Server = https://mirrors.tuna.tsinghua.edu.cn/archlinux/\$repo/os/\$arch\n'
|
||||
'Server = https://mirrors.aliyun.com/archlinux/\$repo/os/\$arch\n',
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[DistroInstaller] 写入 Arch mirrorlist 失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// 3.5 Fedora yum/dnf 源配置(清华大学高速镜像)
|
||||
final yumDir = Directory(p.join(etcDir.path, 'yum.repos.d'));
|
||||
if (yumDir.existsSync()) {
|
||||
final fedoraRepo = File(p.join(yumDir.path, 'fedora.repo'));
|
||||
if (fedoraRepo.existsSync()) {
|
||||
try {
|
||||
var content = fedoraRepo.readAsStringSync();
|
||||
content = content.replaceAll('metalink=', '#metalink=');
|
||||
content = content.replaceAll(
|
||||
'#baseurl=http://download.example/pub/fedora/linux/',
|
||||
'baseurl=https://mirrors.tuna.tsinghua.edu.cn/fedora/',
|
||||
);
|
||||
fedoraRepo.writeAsStringSync(content);
|
||||
} catch (e) {
|
||||
debugPrint('[DistroInstaller] 写入 Fedora repo 失败: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 确保 /workspace 挂载点目录存在
|
||||
final workspaceDir = Directory(p.join(rootfsDir.path, 'workspace'));
|
||||
if (!workspaceDir.existsSync()) {
|
||||
workspaceDir.createSync(recursive: true);
|
||||
}
|
||||
|
||||
// 5. 确保 /tmp 目录存在
|
||||
// 6. 确保 /tmp 目录存在
|
||||
final tmpDir = Directory(p.join(rootfsDir.path, 'tmp'));
|
||||
if (!tmpDir.existsSync()) {
|
||||
tmpDir.createSync(recursive: true);
|
||||
}
|
||||
|
||||
// 6. 部署容器修复 Shim(libfix_seccomp.so)
|
||||
// 7. 部署容器修复 Shim(libfix_seccomp.so)
|
||||
await ensureSeccompShim(rootfsDir);
|
||||
|
||||
// 8. 自动配置 Java 运行时动态链接路径
|
||||
await ensureJavaConfiguration(rootfsDir);
|
||||
}
|
||||
|
||||
/// 自动部署标准 SSL CA 证书链(让 APT / Curl / Git 默认支持 HTTPS)
|
||||
static Future<void> ensureCaCertificates(Directory rootfsDir) async {
|
||||
try {
|
||||
final certsDir = Directory(p.join(rootfsDir.path, 'etc', 'ssl', 'certs'));
|
||||
if (!certsDir.existsSync()) {
|
||||
certsDir.createSync(recursive: true);
|
||||
}
|
||||
final targetCert = File(p.join(certsDir.path, 'ca-certificates.crt'));
|
||||
if (!targetCert.existsSync() || targetCert.lengthSync() == 0) {
|
||||
final byteData = await rootBundle.load('assets/certs/ca-certificates.crt');
|
||||
final bytes = byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes);
|
||||
await targetCert.writeAsBytes(bytes, flush: true);
|
||||
|
||||
// 建立标准符号链接以兼容 OpenSSL/GnuTLS 默认寻找路径
|
||||
final etcSslDir = Directory(p.join(rootfsDir.path, 'etc', 'ssl'));
|
||||
final certPem = Link(p.join(etcSslDir.path, 'cert.pem'));
|
||||
if (!certPem.existsSync()) {
|
||||
try {
|
||||
certPem.createSync('certs/ca-certificates.crt');
|
||||
} catch (_) {}
|
||||
}
|
||||
debugPrint('[DistroInstaller] 成功注入根证书链: ${targetCert.path}');
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('[DistroInstaller] 注入根证书链异常 (非阻塞): $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// 部署容器修复 Shim(libfix_seccomp.so)
|
||||
@@ -237,8 +727,10 @@ class DistroInstaller {
|
||||
/// 传统 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);
|
||||
if (!libDir.existsSync() && !FileSystemEntity.isLinkSync(libDir.path)) {
|
||||
try {
|
||||
libDir.createSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
final targetShim = File(p.join(libDir.path, 'libfix_seccomp.so'));
|
||||
|
||||
@@ -272,4 +764,44 @@ class DistroInstaller {
|
||||
debugPrint('[DistroInstaller] 部署 SECCOMP Shim 失败: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// 自动探测并适配 OpenJDK 运行环境(解决 Debian/Ubuntu 等发行版下 /usr/bin/java
|
||||
/// 符号链接调用时找不到 libjli.so / libjvm.so 的问题)
|
||||
static Future<void> ensureJavaConfiguration(Directory rootfsDir) async {
|
||||
try {
|
||||
final jvmDir = Directory(p.join(rootfsDir.path, 'usr', 'lib', 'jvm'));
|
||||
if (!jvmDir.existsSync()) return;
|
||||
|
||||
final javaConfLines = <String>[];
|
||||
final jvmEntries = jvmDir.listSync();
|
||||
for (final entry in jvmEntries) {
|
||||
if (entry is Directory) {
|
||||
final guestJvmBase = '/usr/lib/jvm/${p.basename(entry.path)}';
|
||||
final libDir = Directory(p.join(entry.path, 'lib'));
|
||||
if (libDir.existsSync()) {
|
||||
javaConfLines.add('$guestJvmBase/lib');
|
||||
final serverDir = Directory(p.join(libDir.path, 'server'));
|
||||
if (serverDir.existsSync()) {
|
||||
javaConfLines.add('$guestJvmBase/lib/server');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (javaConfLines.isNotEmpty) {
|
||||
final ldConfD = Directory(p.join(rootfsDir.path, 'etc', 'ld.so.conf.d'));
|
||||
if (!ldConfD.existsSync()) {
|
||||
ldConfD.createSync(recursive: true);
|
||||
}
|
||||
final javaConfFile = File(p.join(ldConfD.path, 'java.conf'));
|
||||
final newContent = '${javaConfLines.join('\n')}\n';
|
||||
if (!javaConfFile.existsSync() || javaConfFile.readAsStringSync() != newContent) {
|
||||
javaConfFile.writeAsStringSync(newContent);
|
||||
debugPrint('[DistroInstaller] 自动配置 /etc/ld.so.conf.d/java.conf');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('[DistroInstaller] 配置 Java ld.so 失败 (非阻塞): $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import 'package:flutter/services.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import '../models/distro_info.dart';
|
||||
import '../models/distro_manifest.dart';
|
||||
import 'distro_installer.dart';
|
||||
|
||||
/// 容器启动配置数据
|
||||
@@ -35,6 +35,16 @@ class ProotLaunchConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linux 发行版家族分类(用于包管理器与工具链自动适配)
|
||||
enum DistroFamily {
|
||||
alpine,
|
||||
ubuntu,
|
||||
debian,
|
||||
arch,
|
||||
fedora,
|
||||
unknown,
|
||||
}
|
||||
|
||||
/// Linux 发行版与多系统实例管理器服务(单例模式,易扩展)
|
||||
class DistroManager {
|
||||
static final DistroManager _instance = DistroManager._internal();
|
||||
@@ -104,6 +114,55 @@ class DistroManager {
|
||||
return hasEtc && hasBin;
|
||||
}
|
||||
|
||||
/// 自动探测指定已安装系统所属的发行版家族(Alpine / Ubuntu / Debian / Arch / Fedora / Unknown)
|
||||
Future<DistroFamily> detectDistroFamily(String systemName) async {
|
||||
if (systemName == 'host') return DistroFamily.unknown;
|
||||
|
||||
final rootDir = await getSystemRootDir(systemName);
|
||||
if (!rootDir.existsSync()) return DistroFamily.unknown;
|
||||
|
||||
final etcDir = Directory(p.join(rootDir.path, 'etc'));
|
||||
if (!etcDir.existsSync()) return DistroFamily.unknown;
|
||||
|
||||
// 1. Alpine Linux (apk / alpine-release)
|
||||
if (Directory(p.join(etcDir.path, 'apk')).existsSync() ||
|
||||
File(p.join(etcDir.path, 'alpine-release')).existsSync() ||
|
||||
File(p.join(rootDir.path, 'sbin', 'apk')).existsSync()) {
|
||||
return DistroFamily.alpine;
|
||||
}
|
||||
|
||||
// 2. Ubuntu 与 Debian (apt / dpkg)
|
||||
final aptDir = Directory(p.join(etcDir.path, 'apt'));
|
||||
if (aptDir.existsSync() || File(p.join(rootDir.path, 'usr', 'bin', 'apt-get')).existsSync()) {
|
||||
final ubuntuSources = File(p.join(aptDir.path, 'sources.list.d', 'ubuntu.sources'));
|
||||
final osRelease = File(p.join(etcDir.path, 'os-release'));
|
||||
var isUbuntu = ubuntuSources.existsSync();
|
||||
if (!isUbuntu && osRelease.existsSync()) {
|
||||
try {
|
||||
isUbuntu = osRelease.readAsStringSync().toLowerCase().contains('ubuntu');
|
||||
} catch (_) {}
|
||||
}
|
||||
return isUbuntu ? DistroFamily.ubuntu : DistroFamily.debian;
|
||||
}
|
||||
|
||||
// 3. Arch Linux (pacman)
|
||||
if (Directory(p.join(etcDir.path, 'pacman.d')).existsSync() ||
|
||||
File(p.join(etcDir.path, 'arch-release')).existsSync() ||
|
||||
File(p.join(rootDir.path, 'usr', 'bin', 'pacman')).existsSync()) {
|
||||
return DistroFamily.arch;
|
||||
}
|
||||
|
||||
// 4. Fedora (dnf / yum / fedora-release)
|
||||
if (Directory(p.join(etcDir.path, 'yum.repos.d')).existsSync() ||
|
||||
File(p.join(etcDir.path, 'fedora-release')).existsSync() ||
|
||||
File(p.join(rootDir.path, 'usr', 'bin', 'dnf')).existsSync()) {
|
||||
return DistroFamily.fedora;
|
||||
}
|
||||
|
||||
// 5. 其他未识别的自定义系统
|
||||
return DistroFamily.unknown;
|
||||
}
|
||||
|
||||
/// 校验系统名称是否合法且未被占用
|
||||
Future<void> validateSystemName(String systemName) async {
|
||||
final trimmed = systemName.trim();
|
||||
@@ -122,18 +181,18 @@ class DistroManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// 从应用内置资源导入 Alpine Linux 系统实例
|
||||
/// 从应用内置资源导入 Ubuntu 24.04 Linux 系统实例
|
||||
///
|
||||
/// [systemName] 系统名称(默认为 'alpine',同一个 rootfs 包可创建多个系统)
|
||||
Future<void> importBuiltinAlpine({
|
||||
/// [systemName] 系统名称(默认为 'ubuntu',同一个 rootfs 包可创建多个系统)
|
||||
Future<void> importBuiltinUbuntu({
|
||||
required String systemName,
|
||||
InstallProgressCallback? onProgress,
|
||||
bool Function()? isCancelled,
|
||||
}) async {
|
||||
await validateSystemName(systemName);
|
||||
|
||||
final assetPath = DistroInfo.builtinAlpineAssetPath;
|
||||
onProgress?.call(0.02, '正在读取应用内置系统资源包...');
|
||||
final assetPath = DistroRepository.builtinUbuntuAssetPath;
|
||||
onProgress?.call(0.02, '正在读取应用内置 Ubuntu 系统资源包...');
|
||||
final byteData = await rootBundle.load(assetPath);
|
||||
final bytes = byteData.buffer.asUint8List();
|
||||
|
||||
@@ -147,7 +206,32 @@ class DistroManager {
|
||||
);
|
||||
}
|
||||
|
||||
/// 从用户本地指定的 .tar.gz 压缩包导入外部系统实例
|
||||
/// 从应用内置资源导入 Alpine Linux 系统实例(保留备用)
|
||||
///
|
||||
/// [systemName] 系统名称(默认为 'alpine',同一个 rootfs 包可创建多个系统)
|
||||
Future<void> importBuiltinAlpine({
|
||||
required String systemName,
|
||||
InstallProgressCallback? onProgress,
|
||||
bool Function()? isCancelled,
|
||||
}) async {
|
||||
await validateSystemName(systemName);
|
||||
|
||||
final assetPath = DistroRepository.builtinAlpineAssetPath;
|
||||
onProgress?.call(0.02, '正在读取应用内置 Alpine 系统资源包...');
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
/// 从用户本地指定的 .tar.gz / .tar.xz 压缩包导入外部系统实例
|
||||
Future<void> importFromCustomTarGz({
|
||||
required String systemName,
|
||||
required File tarGzFile,
|
||||
@@ -160,13 +244,10 @@ class DistroManager {
|
||||
throw ArgumentError('所选压缩包文件不存在: ${tarGzFile.path}');
|
||||
}
|
||||
|
||||
onProgress?.call(0.02, '正在读取外部系统压缩包...');
|
||||
final bytes = await tarGzFile.readAsBytes();
|
||||
|
||||
final targetDir = await getSystemRootDir(systemName);
|
||||
|
||||
await DistroInstaller.installFromBytes(
|
||||
tarGzBytes: bytes,
|
||||
await DistroInstaller.installFromFile(
|
||||
archiveFile: tarGzFile,
|
||||
targetDir: targetDir,
|
||||
onProgress: onProgress,
|
||||
isCancelled: isCancelled,
|
||||
@@ -261,12 +342,13 @@ class DistroManager {
|
||||
? workspacePath
|
||||
: Directory.current.path;
|
||||
|
||||
final args = customCommand != null ? ['-c', customCommand] : <String>[];
|
||||
final args = customCommand != null ? ['-c', customCommand] : <String>['-i'];
|
||||
return ProotLaunchConfig(
|
||||
executable: '/system/bin/sh',
|
||||
arguments: args,
|
||||
environment: {
|
||||
'TERM': 'xterm-256color',
|
||||
'SHELL': '/system/bin/sh',
|
||||
},
|
||||
workingDirectory: initialDir,
|
||||
);
|
||||
@@ -276,11 +358,23 @@ class DistroManager {
|
||||
final rootDir = await getSystemRootDir(systemName);
|
||||
final nativeDir = await getNativeLibraryDir();
|
||||
final effectiveProot = (prootPath == 'proot') ? await getProotExecutablePath() : prootPath;
|
||||
const targetShell = '/bin/sh';
|
||||
final targetShell = _resolveTargetShell(rootDir);
|
||||
|
||||
// 确保容器内 DNS 配置存在(对标 proot-distro,保证网络连通与 apk/curl 正常解析)
|
||||
await _ensureGuestDns(rootDir);
|
||||
|
||||
// 清理此前异常中断留下的陈旧锁文件(如 /etc/group.lock,防止 groupadd/useradd 报错)
|
||||
_cleanStaleLocks(rootDir);
|
||||
|
||||
// 确保 Android 宿主特权/辅助组映射与 .hushlogin 存在(解决 groups: cannot find name for group ID 警告)
|
||||
await _ensureHostGroups(rootDir);
|
||||
|
||||
// 确保容器内具备标准 SSL CA 证书(解决 APT/Git/Curl 访问 HTTPS 时的证书校验失败)
|
||||
await DistroInstaller.ensureCaCertificates(rootDir);
|
||||
|
||||
// 确保 Java 运行时动态链接配置就绪(解决 /usr/bin/java 符号链接找不到 libjli.so)
|
||||
await DistroInstaller.ensureJavaConfiguration(rootDir);
|
||||
|
||||
// 确保独立的 /dev/shm 目录存在(对标 proot-distro shm.py,解决 POSIX 共享内存缺失)
|
||||
final shmDir = await _ensureShmDir(systemName);
|
||||
|
||||
@@ -341,14 +435,42 @@ class DistroManager {
|
||||
final shimFile = File(p.join(rootDir.path, 'lib', 'libfix_seccomp.so'));
|
||||
final hasShim = shimFile.existsSync();
|
||||
|
||||
// 自动检测并注入 JAVA_HOME
|
||||
String? guestJavaHome;
|
||||
final jvmDir = Directory(p.join(rootDir.path, 'usr', 'lib', 'jvm'));
|
||||
if (jvmDir.existsSync()) {
|
||||
try {
|
||||
final defaultJava = Directory(p.join(jvmDir.path, 'default-java'));
|
||||
if (defaultJava.existsSync()) {
|
||||
guestJavaHome = '/usr/lib/jvm/default-java';
|
||||
} else {
|
||||
final entries = jvmDir.listSync().whereType<Directory>().toList();
|
||||
if (entries.isNotEmpty) {
|
||||
entries.sort((a, b) => p.basename(b.path).compareTo(p.basename(a.path)));
|
||||
final selected = entries.firstWhere(
|
||||
(d) => p.basename(d.path).startsWith('java-'),
|
||||
orElse: () => entries.first,
|
||||
);
|
||||
guestJavaHome = '/usr/lib/jvm/${p.basename(selected.path)}';
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
final guestEnvArgs = <String>[
|
||||
'/usr/bin/env',
|
||||
'-i',
|
||||
'HOME=/root',
|
||||
'USER=root',
|
||||
'SHELL=$targetShell',
|
||||
'TERM=xterm-256color',
|
||||
'COLORTERM=truecolor',
|
||||
'LANG=C.UTF-8',
|
||||
'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
|
||||
if (guestJavaHome != null) 'JAVA_HOME=$guestJavaHome',
|
||||
if (guestJavaHome != null)
|
||||
'PATH=$guestJavaHome/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
|
||||
else
|
||||
'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
|
||||
if (hasShim) 'LD_PRELOAD=/lib/libfix_seccomp.so',
|
||||
];
|
||||
|
||||
@@ -358,15 +480,21 @@ class DistroManager {
|
||||
if (customCommand != null && customCommand.isNotEmpty) {
|
||||
args.addAll([targetShell, '-c', customCommand]);
|
||||
} else {
|
||||
args.addAll([targetShell, '-l']);
|
||||
args.addAll([targetShell, '-l', '-i']);
|
||||
}
|
||||
|
||||
final env = <String, String>{
|
||||
'HOME': '/root',
|
||||
'USER': 'root',
|
||||
'SHELL': targetShell,
|
||||
'TERM': 'xterm-256color',
|
||||
'COLORTERM': 'truecolor',
|
||||
'LANG': 'C.UTF-8',
|
||||
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
|
||||
if (guestJavaHome != null) 'JAVA_HOME': guestJavaHome,
|
||||
if (guestJavaHome != null)
|
||||
'PATH': '$guestJavaHome/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
|
||||
else
|
||||
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
|
||||
'TMPDIR': tmpPath,
|
||||
'PROOT_TMP_DIR': tmpPath,
|
||||
if (l2sDir != null) 'PROOT_L2S_DIR': l2sDir.path,
|
||||
@@ -469,4 +597,200 @@ class DistroManager {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 智能选择不同 Linux 发行版最适配的交互式 Shell:
|
||||
/// 1. 优先读取 /etc/passwd 中 root 用户指定的默认登录 Shell(如用户自行切换了 zsh/fish);
|
||||
/// 2. 若配置为 /bin/sh,但在存在 GNU Readline 支持的更好交互 Shell(如 /bin/bash)时优先升级至 bash,
|
||||
/// 彻底解决 Ubuntu/Debian 等发行版 /bin/sh (dash) 缺少行编辑与 Readline 支持的问题;
|
||||
/// 3. 若系统中无 bash(如原版最小化 Alpine),则使用 /bin/ash 或 /bin/sh;
|
||||
/// 4. 支持 /usr/bin/bash、/usr/bin/zsh 等现代 Linux UsrMerge 单一根目录结构。
|
||||
String _resolveTargetShell(Directory rootDir) {
|
||||
String? rootPasswdShell;
|
||||
final passwdFile = File(p.join(rootDir.path, 'etc', 'passwd'));
|
||||
if (passwdFile.existsSync()) {
|
||||
try {
|
||||
final lines = passwdFile.readAsLinesSync();
|
||||
for (final line in lines) {
|
||||
if (line.startsWith('root:')) {
|
||||
final parts = line.split(':');
|
||||
if (parts.length >= 7) {
|
||||
final sh = parts[6].trim();
|
||||
if (sh.isNotEmpty) {
|
||||
rootPasswdShell = sh;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
final hasBash = File(p.join(rootDir.path, 'bin', 'bash')).existsSync() ||
|
||||
File(p.join(rootDir.path, 'usr', 'bin', 'bash')).existsSync();
|
||||
final hasZsh = File(p.join(rootDir.path, 'bin', 'zsh')).existsSync() ||
|
||||
File(p.join(rootDir.path, 'usr', 'bin', 'zsh')).existsSync();
|
||||
final hasAsh = File(p.join(rootDir.path, 'bin', 'ash')).existsSync() ||
|
||||
File(p.join(rootDir.path, 'usr', 'bin', 'ash')).existsSync();
|
||||
|
||||
// 如果 passwd 里配置了非 /bin/sh 的具体 shell(如 /bin/bash, /bin/zsh, /bin/ash, /usr/bin/fish)且物理文件存在,遵从系统配置
|
||||
if (rootPasswdShell != null &&
|
||||
rootPasswdShell != '/bin/sh' &&
|
||||
rootPasswdShell != '/usr/bin/sh') {
|
||||
final shellRel = rootPasswdShell.startsWith('/') ? rootPasswdShell.substring(1) : rootPasswdShell;
|
||||
if (File(p.join(rootDir.path, shellRel)).existsSync()) {
|
||||
return rootPasswdShell;
|
||||
}
|
||||
}
|
||||
|
||||
// 默认回退链:bash (Ubuntu/Debian/Arch/Fedora) -> zsh -> ash (Alpine) -> sh
|
||||
if (hasBash) {
|
||||
return '/bin/bash';
|
||||
} else if (hasZsh) {
|
||||
return '/bin/zsh';
|
||||
} else if (hasAsh) {
|
||||
return '/bin/ash';
|
||||
}
|
||||
return '/bin/sh';
|
||||
}
|
||||
|
||||
/// 保证 Android 宿主分配给当前 App 进程的所有辅助 GID 在容器 /etc/group 中均有注册,
|
||||
/// 并在 /root 下创建 .hushlogin,彻底消除 login 时输出
|
||||
/// "groups: cannot find name for group ID XXX" 等警告。
|
||||
Future<void> _ensureHostGroups(Directory rootDir) async {
|
||||
try {
|
||||
if (!rootDir.existsSync()) return;
|
||||
final etcDir = Directory(p.join(rootDir.path, 'etc'));
|
||||
if (!etcDir.existsSync()) {
|
||||
try {
|
||||
etcDir.createSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
final groupFile = File(p.join(etcDir.path, 'group'));
|
||||
final existingGids = <int>{};
|
||||
String existingContent = '';
|
||||
if (groupFile.existsSync()) {
|
||||
existingContent = groupFile.readAsStringSync();
|
||||
for (final line in existingContent.split('\n')) {
|
||||
final parts = line.split(':');
|
||||
if (parts.length >= 3) {
|
||||
final gid = int.tryParse(parts[2].trim());
|
||||
if (gid != null) existingGids.add(gid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取宿主当前进程拥有的所有 GID
|
||||
final targetGids = <int>{
|
||||
// 常见 Android 特权/网络与存储辅助 GID
|
||||
1015, // sdcard_rw
|
||||
1028, // sdcard_r
|
||||
1077, // ext_data_rw
|
||||
3003, // inet
|
||||
3004, // net_raw
|
||||
3005, // net_admin
|
||||
9997, // everybody
|
||||
};
|
||||
|
||||
// 从 /proc/self/status 动态提取当前真实附加的 Groups
|
||||
final procStatus = File('/proc/self/status');
|
||||
if (procStatus.existsSync()) {
|
||||
try {
|
||||
final lines = procStatus.readAsLinesSync();
|
||||
for (final line in lines) {
|
||||
if (line.startsWith('Groups:')) {
|
||||
final gids = line.substring(7).trim().split(RegExp(r'\s+'));
|
||||
for (final s in gids) {
|
||||
final val = int.tryParse(s);
|
||||
if (val != null) targetGids.add(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
final buffer = StringBuffer();
|
||||
for (final gid in targetGids) {
|
||||
if (!existingGids.contains(gid)) {
|
||||
final groupName = _androidAidGroupName(gid);
|
||||
buffer.writeln('$groupName:x:$gid:');
|
||||
}
|
||||
}
|
||||
|
||||
// 保证常见系统服务所需的用户组存在(如 dbus 所需的 messagebus GID 101)
|
||||
if (!existingGids.contains(101) && !existingContent.contains('messagebus:')) {
|
||||
buffer.writeln('messagebus:x:101:');
|
||||
}
|
||||
|
||||
if (buffer.isNotEmpty) {
|
||||
if (!groupFile.existsSync()) {
|
||||
groupFile.writeAsStringSync(buffer.toString());
|
||||
} else {
|
||||
final separator = existingContent.endsWith('\n') || existingContent.isEmpty ? '' : '\n';
|
||||
groupFile.writeAsStringSync('$separator${buffer.toString()}', mode: FileMode.append);
|
||||
}
|
||||
}
|
||||
|
||||
// 静默模式:创建 /root/.hushlogin 屏蔽 motd / 登录杂乱信息
|
||||
final rootHome = Directory(p.join(rootDir.path, 'root'));
|
||||
if (!rootHome.existsSync()) {
|
||||
try {
|
||||
rootHome.createSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
final hushFile = File(p.join(rootHome.path, '.hushlogin'));
|
||||
if (!hushFile.existsSync()) {
|
||||
try {
|
||||
hushFile.createSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('配置容器辅助用户组失败 (非阻塞): $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// 清理此前异常崩溃或中断留下的陈旧锁文件(防止 groupadd/useradd 等报 /etc/*.lock 锁占用或找不到)
|
||||
void _cleanStaleLocks(Directory rootDir) {
|
||||
try {
|
||||
final etcDir = Directory(p.join(rootDir.path, 'etc'));
|
||||
if (etcDir.existsSync()) {
|
||||
for (final entry in etcDir.listSync(followLinks: false)) {
|
||||
final name = p.basename(entry.path);
|
||||
if (name.endsWith('.lock') ||
|
||||
name.startsWith('group.') ||
|
||||
name.startsWith('passwd.') ||
|
||||
name.startsWith('shadow.') ||
|
||||
name.startsWith('gshadow.')) {
|
||||
try {
|
||||
entry.deleteSync(recursive: true);
|
||||
debugPrint('[DistroManager] 清理陈旧锁文件: ${entry.path}');
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('[DistroManager] 清理陈旧锁文件异常 (非阻塞): $e');
|
||||
}
|
||||
}
|
||||
|
||||
static String _androidAidGroupName(int gid) {
|
||||
switch (gid) {
|
||||
case 1015:
|
||||
return 'aid_sdcard_rw';
|
||||
case 1028:
|
||||
return 'aid_sdcard_r';
|
||||
case 1077:
|
||||
return 'aid_ext_data_rw';
|
||||
case 3003:
|
||||
return 'aid_inet';
|
||||
case 3004:
|
||||
return 'aid_net_raw';
|
||||
case 3005:
|
||||
return 'aid_net_admin';
|
||||
case 9997:
|
||||
return 'aid_everybody';
|
||||
default:
|
||||
return 'aid_$gid';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import 'dart:io';
|
||||
import 'package:archive/archive_io.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
/// 软件内部私有存储项目管理服务 (files/projects)
|
||||
class InternalProjectService {
|
||||
static final InternalProjectService instance = InternalProjectService._();
|
||||
factory InternalProjectService() => instance;
|
||||
InternalProjectService._();
|
||||
|
||||
/// 自定义项目存储根目录(主要用于单元测试与隔离环境)
|
||||
@visibleForTesting
|
||||
Directory? customProjectsDir;
|
||||
|
||||
Directory? _cachedProjectsDir;
|
||||
|
||||
/// 判断指定路径是否为内部存储项目路径 (`files/projects/<projectName>`)
|
||||
bool isInternalProject(String? projectPath) {
|
||||
if (projectPath == null || projectPath.trim().isEmpty) return false;
|
||||
final cleanPath = p.normalize(projectPath.trim());
|
||||
|
||||
if (customProjectsDir != null) {
|
||||
final customParent = p.normalize(customProjectsDir!.path);
|
||||
return p.equals(p.dirname(cleanPath), customParent);
|
||||
}
|
||||
|
||||
if (_cachedProjectsDir != null) {
|
||||
final cachedParent = p.normalize(_cachedProjectsDir!.path);
|
||||
return p.equals(p.dirname(cleanPath), cachedParent);
|
||||
}
|
||||
|
||||
final parentDir = p.normalize(p.dirname(cleanPath));
|
||||
final parts = p.split(parentDir);
|
||||
if (parts.length >= 2 &&
|
||||
parts[parts.length - 2] == 'files' &&
|
||||
parts[parts.length - 1] == 'projects') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// 获取软件内部存储的项目基础目录: `files/projects`
|
||||
Future<Directory> getProjectsDirectory() async {
|
||||
if (customProjectsDir != null) {
|
||||
if (!customProjectsDir!.existsSync()) {
|
||||
customProjectsDir!.createSync(recursive: true);
|
||||
}
|
||||
return customProjectsDir!;
|
||||
}
|
||||
|
||||
if (_cachedProjectsDir != null) {
|
||||
if (!_cachedProjectsDir!.existsSync()) {
|
||||
_cachedProjectsDir!.createSync(recursive: true);
|
||||
}
|
||||
return _cachedProjectsDir!;
|
||||
}
|
||||
|
||||
final appDir = await getApplicationSupportDirectory();
|
||||
// Android 下 getApplicationSupportDirectory 对应 .../files
|
||||
// 若路径已以 files 结尾,则直接拼接 projects;否则拼接 files/projects 保持规范一致
|
||||
final baseDir = p.basename(appDir.path) == 'files'
|
||||
? appDir.path
|
||||
: p.join(appDir.path, 'files');
|
||||
|
||||
final projectsDir = Directory(p.join(baseDir, 'projects'));
|
||||
if (!projectsDir.existsSync()) {
|
||||
projectsDir.createSync(recursive: true);
|
||||
}
|
||||
_cachedProjectsDir = projectsDir;
|
||||
return projectsDir;
|
||||
}
|
||||
|
||||
/// 获取所有已创建的内部项目列表(按文件夹名称升序排列)
|
||||
Future<List<Directory>> listProjects() async {
|
||||
final dir = await getProjectsDirectory();
|
||||
if (!dir.existsSync()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
final entities = dir.listSync(followLinks: false);
|
||||
final projects = entities.whereType<Directory>().toList();
|
||||
projects.sort((a, b) => p
|
||||
.basename(a.path)
|
||||
.toLowerCase()
|
||||
.compareTo(p.basename(b.path).toLowerCase()));
|
||||
return projects;
|
||||
} catch (e) {
|
||||
debugPrint('获取内部项目列表失败: $e');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查指定项目名称是否已存在
|
||||
Future<bool> projectExists(String name) async {
|
||||
final dir = await getProjectsDirectory();
|
||||
final targetDir = Directory(p.join(dir.path, name.trim()));
|
||||
return targetDir.existsSync();
|
||||
}
|
||||
|
||||
/// 在 `files/projects` 下新建一个项目文件夹
|
||||
Future<Directory> createProject(String name) async {
|
||||
final trimmedName = name.trim();
|
||||
if (trimmedName.isEmpty) {
|
||||
throw const FileSystemException('项目名称不能为空');
|
||||
}
|
||||
|
||||
final dir = await getProjectsDirectory();
|
||||
final projectDir = Directory(p.join(dir.path, trimmedName));
|
||||
if (projectDir.existsSync()) {
|
||||
throw FileSystemException('同名项目已存在', projectDir.path);
|
||||
}
|
||||
|
||||
projectDir.createSync(recursive: true);
|
||||
return projectDir;
|
||||
}
|
||||
|
||||
/// 重命名指定的项目文件夹
|
||||
Future<Directory> renameProject(Directory projectDir, String newName) async {
|
||||
final trimmedName = newName.trim();
|
||||
if (trimmedName.isEmpty) {
|
||||
throw const FileSystemException('项目名称不能为空');
|
||||
}
|
||||
|
||||
final parent = projectDir.parent;
|
||||
final newDir = Directory(p.join(parent.path, trimmedName));
|
||||
if (p.normalize(projectDir.path) == p.normalize(newDir.path)) {
|
||||
return projectDir;
|
||||
}
|
||||
|
||||
if (newDir.existsSync()) {
|
||||
throw FileSystemException('同名项目已存在', newDir.path);
|
||||
}
|
||||
|
||||
return projectDir.renameSync(newDir.path);
|
||||
}
|
||||
|
||||
/// 递归删除项目文件夹
|
||||
Future<void> deleteProject(Directory projectDir) async {
|
||||
if (projectDir.existsSync()) {
|
||||
projectDir.deleteSync(recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// 从外部压缩文件解压导入为内部项目 (`files/projects/<projectName>`)
|
||||
Future<Directory> importProjectFromArchive(String archivePath, String projectName) async {
|
||||
final trimmedName = projectName.trim();
|
||||
if (trimmedName.isEmpty) {
|
||||
throw const FileSystemException('项目名称不能为空');
|
||||
}
|
||||
|
||||
final dir = await getProjectsDirectory();
|
||||
final projectDir = Directory(p.join(dir.path, trimmedName));
|
||||
if (projectDir.existsSync()) {
|
||||
throw FileSystemException('同名项目已存在', projectDir.path);
|
||||
}
|
||||
|
||||
final archiveFile = File(archivePath);
|
||||
if (!archiveFile.existsSync()) {
|
||||
throw FileSystemException('压缩包文件不存在', archivePath);
|
||||
}
|
||||
|
||||
projectDir.createSync(recursive: true);
|
||||
try {
|
||||
await extractFileToDisk(archivePath, projectDir.path);
|
||||
return projectDir;
|
||||
} catch (e) {
|
||||
if (projectDir.existsSync()) {
|
||||
try {
|
||||
projectDir.deleteSync(recursive: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,809 @@
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:archive/archive.dart';
|
||||
|
||||
/// 低内存 XZ 流式解压器
|
||||
///
|
||||
/// 解决 package:archive 在解码大于 10MB 的 XZ 压缩包时 LZMA 字典无限增长、
|
||||
/// 频繁触发全量数组复制导致内存爆炸 (OOM) 与卡死的致命缺陷。
|
||||
///
|
||||
/// 本解码器采用固定大小环形滑动窗口(Circular Ring Buffer),内存占用严格恒定在
|
||||
/// 字典大小(如 Debian rootfs 仅需 8MB),并将解压数据分块直接流式写入输出文件 Sink,
|
||||
/// 内存开销从原版的数百 GB 累计分配降至仅 ~10MB。
|
||||
class LowMemoryXZDecoder {
|
||||
final LowMemoryLzmaDecoder decoder = LowMemoryLzmaDecoder();
|
||||
int streamFlags = 0;
|
||||
|
||||
/// 流式解压 XZ 输入流并输出到 [outputSink]
|
||||
void decodeToSink(
|
||||
InputStreamBase input,
|
||||
IOSink outputSink, {
|
||||
void Function(int bytesDecompressed, int compressedPosition)? onProgress,
|
||||
bool Function()? isCancelled,
|
||||
}) {
|
||||
var totalDecompressed = 0;
|
||||
|
||||
while (!input.isEOS) {
|
||||
if (isCancelled?.call() == true) return;
|
||||
|
||||
// 跳过流间或流末尾的 4 字节对齐填充(NULL 字节)
|
||||
while (!input.isEOS && input.peekBytes(1).readByte() == 0) {
|
||||
input.skip(1);
|
||||
}
|
||||
if (input.isEOS) break;
|
||||
|
||||
_readStreamHeader(input);
|
||||
|
||||
while (true) {
|
||||
if (isCancelled?.call() == true) return;
|
||||
|
||||
final blockHeader = input.peekBytes(1).readByte();
|
||||
if (blockHeader == 0) {
|
||||
// 流索引与流尾部
|
||||
final indexSize = _readStreamIndex(input);
|
||||
_readStreamFooter(input, indexSize);
|
||||
break; // 当前流结束
|
||||
}
|
||||
|
||||
final blockLength = (blockHeader + 1) * 4;
|
||||
_readBlock(input, blockLength, outputSink, (bytes) {
|
||||
totalDecompressed += bytes;
|
||||
onProgress?.call(totalDecompressed, input.position);
|
||||
}, isCancelled);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _readStreamHeader(InputStreamBase input) {
|
||||
final magic = input.readBytes(6).toUint8List();
|
||||
if (magic[0] != 253 ||
|
||||
magic[1] != 55 ||
|
||||
magic[2] != 122 ||
|
||||
magic[3] != 88 ||
|
||||
magic[4] != 90 ||
|
||||
magic[5] != 0) {
|
||||
throw ArchiveException('Invalid XZ stream header signature');
|
||||
}
|
||||
final header = input.readBytes(2);
|
||||
if (header.readByte() != 0) {
|
||||
throw ArchiveException('Invalid stream flags');
|
||||
}
|
||||
streamFlags = header.readByte();
|
||||
header.reset();
|
||||
final crc = input.readUint32();
|
||||
if (getCrc32(header.toUint8List()) != crc) {
|
||||
throw ArchiveException('Invalid stream header CRC checksum');
|
||||
}
|
||||
}
|
||||
|
||||
int _readMultibyteInteger(InputStreamBase input) {
|
||||
var val = 0;
|
||||
var shift = 0;
|
||||
while (true) {
|
||||
final b = input.readByte();
|
||||
val |= (b & 0x7f) << shift;
|
||||
if ((b & 0x80) == 0) break;
|
||||
shift += 7;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
int _readPadding(InputStreamBase input) {
|
||||
var count = 0;
|
||||
while (!input.isEOS && (input.position % 4 != 0)) {
|
||||
if (input.readByte() != 0) {
|
||||
throw ArchiveException('Invalid padding byte');
|
||||
}
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
void _readBlock(
|
||||
InputStreamBase input,
|
||||
int headerLength,
|
||||
IOSink sink,
|
||||
void Function(int bytes) onChunk,
|
||||
bool Function()? isCancelled,
|
||||
) {
|
||||
final header = input.readBytes(headerLength - 4);
|
||||
header.skip(1); // 跳过 Header Length 字段
|
||||
final blockFlags = header.readByte();
|
||||
final nFilters = (blockFlags & 0x3) + 1;
|
||||
final hasCompressedLength = (blockFlags & 0x40) != 0;
|
||||
final hasUncompressedLength = (blockFlags & 0x80) != 0;
|
||||
|
||||
if (hasCompressedLength) _readMultibyteInteger(header);
|
||||
if (hasUncompressedLength) _readMultibyteInteger(header);
|
||||
|
||||
final filters = <int>[];
|
||||
var dictionarySize = 0;
|
||||
for (var i = 0; i < nFilters; i++) {
|
||||
final id = _readMultibyteInteger(header);
|
||||
final propLen = _readMultibyteInteger(header);
|
||||
final props = header.readBytes(propLen).toUint8List();
|
||||
if (id == 0x21) {
|
||||
final v = props[0];
|
||||
if (v > 40) throw ArchiveException('Invalid LZMA dictionary size');
|
||||
final mantissa = 2 | (v & 0x1);
|
||||
final exponent = (v >> 1) + 11;
|
||||
dictionarySize = mantissa << exponent;
|
||||
filters.add(id);
|
||||
filters.add(dictionarySize);
|
||||
} else {
|
||||
filters.add(id);
|
||||
filters.add(0);
|
||||
}
|
||||
}
|
||||
_readPadding(header);
|
||||
header.reset();
|
||||
final crc = input.readUint32();
|
||||
if (getCrc32(header.toUint8List()) != crc) {
|
||||
throw ArchiveException('Invalid block CRC checksum');
|
||||
}
|
||||
|
||||
if (filters.length != 2 && filters.first != 0x21) {
|
||||
throw ArchiveException('Unsupported filters: $filters');
|
||||
}
|
||||
|
||||
decoder.ensureDictionarySize(dictionarySize);
|
||||
_readLZMA2(input, sink, onChunk, isCancelled);
|
||||
|
||||
_readPadding(input);
|
||||
|
||||
// 根据 streamFlags 跳过 Check 校验码
|
||||
const checkSizes = [0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64];
|
||||
final checkType = streamFlags & 0xf;
|
||||
if (checkType < checkSizes.length) {
|
||||
final skipBytes = checkSizes[checkType];
|
||||
if (skipBytes > 0) input.skip(skipBytes);
|
||||
}
|
||||
}
|
||||
|
||||
void _readLZMA2(
|
||||
InputStreamBase input,
|
||||
IOSink sink,
|
||||
void Function(int bytes) onChunk,
|
||||
bool Function()? isCancelled,
|
||||
) {
|
||||
while (true) {
|
||||
if (isCancelled?.call() == true) return;
|
||||
|
||||
final control = input.readByte();
|
||||
if (control & 0x80 == 0) {
|
||||
if (control == 0) {
|
||||
// 结束标记
|
||||
decoder.reset(resetDictionary: true);
|
||||
return;
|
||||
} else if (control == 1) {
|
||||
// 非压缩数据(重置字典)
|
||||
decoder.reset(resetDictionary: true);
|
||||
final length = (input.readByte() << 8 | input.readByte()) + 1;
|
||||
final bytes = decoder.decodeUncompressed(input.readBytes(length), length);
|
||||
sink.add(bytes);
|
||||
onChunk(length);
|
||||
} else if (control == 2) {
|
||||
// 非压缩数据(不重置字典)
|
||||
final length = (input.readByte() << 8 | input.readByte()) + 1;
|
||||
final bytes = decoder.decodeUncompressed(input.readBytes(length), length);
|
||||
sink.add(bytes);
|
||||
onChunk(length);
|
||||
} else {
|
||||
throw ArchiveException('Unknown LZMA2 control code $control');
|
||||
}
|
||||
} else {
|
||||
final reset = (control >> 5) & 0x3;
|
||||
final uncompressedLength = ((control & 0x1f) << 16 |
|
||||
input.readByte() << 8 |
|
||||
input.readByte()) +
|
||||
1;
|
||||
final compressedLength = (input.readByte() << 8 | input.readByte()) + 1;
|
||||
int? literalContextBits;
|
||||
int? literalPositionBits;
|
||||
int? positionBits;
|
||||
if (reset >= 2) {
|
||||
var properties = input.readByte();
|
||||
positionBits = properties ~/ 45;
|
||||
properties -= positionBits * 45;
|
||||
literalPositionBits = properties ~/ 9;
|
||||
literalContextBits = properties - literalPositionBits * 9;
|
||||
}
|
||||
if (reset > 0) {
|
||||
decoder.reset(
|
||||
literalContextBits: literalContextBits,
|
||||
literalPositionBits: literalPositionBits,
|
||||
positionBits: positionBits,
|
||||
resetDictionary: reset == 3,
|
||||
);
|
||||
}
|
||||
|
||||
final chunk = decoder.decode(input.readBytes(compressedLength), uncompressedLength);
|
||||
sink.add(chunk);
|
||||
onChunk(uncompressedLength);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int _readStreamIndex(InputStreamBase input) {
|
||||
final startPosition = input.position;
|
||||
input.skip(1); // 跳过 index indicator (0x00)
|
||||
final nRecords = _readMultibyteInteger(input);
|
||||
for (var i = 0; i < nRecords; i++) {
|
||||
_readMultibyteInteger(input); // unpaddedLength
|
||||
_readMultibyteInteger(input); // uncompressedLength
|
||||
}
|
||||
_readPadding(input);
|
||||
|
||||
final indexLength = input.position - startPosition;
|
||||
input.rewind(indexLength);
|
||||
final indexData = input.readBytes(indexLength);
|
||||
|
||||
final crc = input.readUint32();
|
||||
if (getCrc32(indexData.toUint8List()) != crc) {
|
||||
throw ArchiveException('Invalid stream index CRC checksum');
|
||||
}
|
||||
|
||||
return indexLength + 4;
|
||||
}
|
||||
|
||||
void _readStreamFooter(InputStreamBase input, int indexSize) {
|
||||
final crc = input.readUint32();
|
||||
final footer = input.readBytes(6);
|
||||
final backwardSize = (footer.readUint32() + 1) * 4;
|
||||
if (backwardSize != indexSize) {
|
||||
throw ArchiveException('Stream footer has invalid index size');
|
||||
}
|
||||
if (footer.readByte() != 0) {
|
||||
throw ArchiveException('Invalid stream flags');
|
||||
}
|
||||
final footerFlags = footer.readByte();
|
||||
if (footerFlags != streamFlags) {
|
||||
throw ArchiveException("Stream footer flags don't match header flags");
|
||||
}
|
||||
footer.reset();
|
||||
|
||||
if (getCrc32(footer.toUint8List()) != crc) {
|
||||
throw ArchiveException('Invalid stream footer CRC checksum');
|
||||
}
|
||||
|
||||
final magic = input.readBytes(2).toUint8List();
|
||||
if (magic[0] != 89 || magic[1] != 90) { // 'YZ'
|
||||
throw ArchiveException('Invalid XZ stream footer signature');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 采用固定大小环形缓冲区的高性能低内存 LZMA 解码器
|
||||
class LowMemoryLzmaDecoder {
|
||||
final _rc = _LzmaRangeDecoder();
|
||||
|
||||
int _positionBits = 2;
|
||||
int _literalPositionBits = 0;
|
||||
int _literalContextBits = 3;
|
||||
|
||||
final _nonLiteralTables = <_LzmaRangeDecoderTable>[];
|
||||
late final _LzmaRangeDecoderTable _repeatTable;
|
||||
late final _LzmaRangeDecoderTable _repeat0Table;
|
||||
final _longRepeat0Tables = <_LzmaRangeDecoderTable>[];
|
||||
late final _LzmaRangeDecoderTable _repeat1Table;
|
||||
late final _LzmaRangeDecoderTable _repeat2Table;
|
||||
|
||||
final _literalTables = <_LzmaRangeDecoderTable>[];
|
||||
final _matchLiteralTables0 = <_LzmaRangeDecoderTable>[];
|
||||
final _matchLiteralTables1 = <_LzmaRangeDecoderTable>[];
|
||||
|
||||
late final _LzmaLengthDecoder _matchLengthDecoder;
|
||||
late final _LzmaLengthDecoder _repeatLengthDecoder;
|
||||
late final _LzmaDistanceDecoder _distanceDecoder;
|
||||
|
||||
var _distance0 = 0;
|
||||
var _distance1 = 0;
|
||||
var _distance2 = 0;
|
||||
var _distance3 = 0;
|
||||
|
||||
var state = _LzmaState.litLit;
|
||||
|
||||
Uint8List _dict = Uint8List(0);
|
||||
int _dictMask = 0;
|
||||
int _writePos = 0;
|
||||
|
||||
LowMemoryLzmaDecoder() {
|
||||
for (var i = 0; i < _LzmaState.values.length; i++) {
|
||||
_nonLiteralTables.add(_LzmaRangeDecoderTable(_LzmaState.values.length));
|
||||
}
|
||||
_repeatTable = _LzmaRangeDecoderTable(_LzmaState.values.length);
|
||||
_repeat0Table = _LzmaRangeDecoderTable(_LzmaState.values.length);
|
||||
for (var i = 0; i < _LzmaState.values.length; i++) {
|
||||
_longRepeat0Tables.add(_LzmaRangeDecoderTable(_LzmaState.values.length));
|
||||
}
|
||||
_repeat1Table = _LzmaRangeDecoderTable(_LzmaState.values.length);
|
||||
_repeat2Table = _LzmaRangeDecoderTable(_LzmaState.values.length);
|
||||
|
||||
var positionCount = 1 << _positionBits;
|
||||
_matchLengthDecoder = _LzmaLengthDecoder(_rc, positionCount);
|
||||
_repeatLengthDecoder = _LzmaLengthDecoder(_rc, positionCount);
|
||||
_distanceDecoder = _LzmaDistanceDecoder(_rc);
|
||||
|
||||
reset();
|
||||
}
|
||||
|
||||
/// 确保字典大小为大于等于 [dictSize] 的 2 的整数幂,以便通过位掩码快速寻址
|
||||
void ensureDictionarySize(int dictSize) {
|
||||
var capacity = 4096;
|
||||
while (capacity < dictSize) {
|
||||
capacity <<= 1;
|
||||
}
|
||||
if (_dict.length != capacity) {
|
||||
_dict = Uint8List(capacity);
|
||||
_dictMask = capacity - 1;
|
||||
_writePos = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void reset({
|
||||
int? positionBits,
|
||||
int? literalPositionBits,
|
||||
int? literalContextBits,
|
||||
bool resetDictionary = false,
|
||||
}) {
|
||||
_positionBits = positionBits ?? _positionBits;
|
||||
_literalPositionBits = literalPositionBits ?? _literalPositionBits;
|
||||
_literalContextBits = literalContextBits ?? _literalContextBits;
|
||||
|
||||
state = _LzmaState.litLit;
|
||||
_distance0 = 0;
|
||||
_distance1 = 0;
|
||||
_distance2 = 0;
|
||||
_distance3 = 0;
|
||||
|
||||
final maxLiteralStates = 1 << (_literalPositionBits + _literalContextBits);
|
||||
if (_literalTables.length != maxLiteralStates) {
|
||||
for (var i = _literalTables.length; i < maxLiteralStates; i++) {
|
||||
_literalTables.add(_LzmaRangeDecoderTable(256));
|
||||
_matchLiteralTables0.add(_LzmaRangeDecoderTable(256));
|
||||
_matchLiteralTables1.add(_LzmaRangeDecoderTable(256));
|
||||
}
|
||||
}
|
||||
|
||||
for (final table in _nonLiteralTables) {
|
||||
table.reset();
|
||||
}
|
||||
_repeatTable.reset();
|
||||
_repeat0Table.reset();
|
||||
for (final table in _longRepeat0Tables) {
|
||||
table.reset();
|
||||
}
|
||||
_repeat1Table.reset();
|
||||
_repeat2Table.reset();
|
||||
for (final table in _literalTables) {
|
||||
table.reset();
|
||||
}
|
||||
for (final table in _matchLiteralTables0) {
|
||||
table.reset();
|
||||
}
|
||||
for (final table in _matchLiteralTables1) {
|
||||
table.reset();
|
||||
}
|
||||
|
||||
final positionCount = 1 << _positionBits;
|
||||
_matchLengthDecoder.reset(positionCount);
|
||||
_repeatLengthDecoder.reset(positionCount);
|
||||
_distanceDecoder.reset();
|
||||
|
||||
if (resetDictionary) {
|
||||
_writePos = 0;
|
||||
}
|
||||
}
|
||||
|
||||
Uint8List decodeUncompressed(InputStreamBase input, int uncompressedLength) {
|
||||
final inputBytes = input.readBytes(uncompressedLength).toUint8List();
|
||||
for (var i = 0; i < uncompressedLength; i++) {
|
||||
_dict[_writePos & _dictMask] = inputBytes[i];
|
||||
_writePos++;
|
||||
}
|
||||
return inputBytes;
|
||||
}
|
||||
|
||||
Uint8List decode(InputStreamBase input, int uncompressedLength) {
|
||||
_rc.input = input;
|
||||
_rc.initialize();
|
||||
|
||||
final chunkOut = Uint8List(uncompressedLength);
|
||||
var chunkOffset = 0;
|
||||
|
||||
while (chunkOffset < uncompressedLength) {
|
||||
final positionMask = (1 << _positionBits) - 1;
|
||||
final posState = _writePos & positionMask;
|
||||
if (_rc.readBit(_nonLiteralTables[state.index], posState) == 0) {
|
||||
_decodeLiteral(chunkOut, chunkOffset);
|
||||
chunkOffset += 1;
|
||||
} else if (_rc.readBit(_repeatTable, state.index) == 0) {
|
||||
final len = _decodeMatch(posState, chunkOut, chunkOffset);
|
||||
chunkOffset += len;
|
||||
} else {
|
||||
final len = _decodeRepeat(posState, chunkOut, chunkOffset);
|
||||
chunkOffset += len;
|
||||
}
|
||||
}
|
||||
|
||||
return chunkOut;
|
||||
}
|
||||
|
||||
bool _prevPacketIsLiteral() {
|
||||
switch (state) {
|
||||
case _LzmaState.litLit:
|
||||
case _LzmaState.matchLitLit:
|
||||
case _LzmaState.repLitLit:
|
||||
case _LzmaState.shortRepLitLit:
|
||||
case _LzmaState.matchLit:
|
||||
case _LzmaState.repLit:
|
||||
case _LzmaState.shortRepLit:
|
||||
return true;
|
||||
case _LzmaState.litMatch:
|
||||
case _LzmaState.litLongRep:
|
||||
case _LzmaState.litShortRep:
|
||||
case _LzmaState.nonLitMatch:
|
||||
case _LzmaState.nonLitRep:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void _decodeLiteral(Uint8List chunkOut, int chunkOffset) {
|
||||
var prevByte = _writePos > 0 ? _dict[(_writePos - 1) & _dictMask] : 0;
|
||||
final low = prevByte >> (8 - _literalContextBits);
|
||||
final positionMask = (1 << _literalPositionBits) - 1;
|
||||
final high = (_writePos & positionMask) << _literalContextBits;
|
||||
final hash = low + high;
|
||||
final table = _literalTables[hash];
|
||||
|
||||
int value;
|
||||
if (_prevPacketIsLiteral()) {
|
||||
value = _rc.readBittree(table, 8);
|
||||
} else {
|
||||
prevByte = _dict[(_writePos - _distance0 - 1) & _dictMask];
|
||||
|
||||
value = 0;
|
||||
var symbolPrefix = 1;
|
||||
var matched = true;
|
||||
final matchTable0 = _matchLiteralTables0[hash];
|
||||
final matchTable1 = _matchLiteralTables1[hash];
|
||||
for (var i = 0; i < 8; i++) {
|
||||
int b;
|
||||
if (matched) {
|
||||
final matchBit = (prevByte >> 7) & 0x1;
|
||||
prevByte <<= 1;
|
||||
b = _rc.readBit(
|
||||
matchBit == 0 ? matchTable0 : matchTable1, symbolPrefix | value);
|
||||
matched = b == matchBit;
|
||||
} else {
|
||||
b = _rc.readBit(table, symbolPrefix | value);
|
||||
}
|
||||
value = (value << 1) | b;
|
||||
symbolPrefix <<= 1;
|
||||
}
|
||||
}
|
||||
|
||||
_dict[_writePos & _dictMask] = value;
|
||||
chunkOut[chunkOffset] = value;
|
||||
_writePos++;
|
||||
|
||||
switch (state) {
|
||||
case _LzmaState.litLit:
|
||||
case _LzmaState.matchLitLit:
|
||||
case _LzmaState.repLitLit:
|
||||
case _LzmaState.shortRepLitLit:
|
||||
state = _LzmaState.litLit;
|
||||
break;
|
||||
case _LzmaState.matchLit:
|
||||
state = _LzmaState.matchLitLit;
|
||||
break;
|
||||
case _LzmaState.repLit:
|
||||
state = _LzmaState.repLitLit;
|
||||
break;
|
||||
case _LzmaState.shortRepLit:
|
||||
state = _LzmaState.shortRepLitLit;
|
||||
break;
|
||||
case _LzmaState.litMatch:
|
||||
case _LzmaState.nonLitMatch:
|
||||
state = _LzmaState.matchLit;
|
||||
break;
|
||||
case _LzmaState.litLongRep:
|
||||
case _LzmaState.nonLitRep:
|
||||
state = _LzmaState.repLit;
|
||||
break;
|
||||
case _LzmaState.litShortRep:
|
||||
state = _LzmaState.shortRepLit;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int _decodeMatch(int posState, Uint8List chunkOut, int chunkOffset) {
|
||||
final length = _matchLengthDecoder.readLength(posState);
|
||||
final distance = _distanceDecoder.readDistance(length);
|
||||
|
||||
_repeatData(distance, length, chunkOut, chunkOffset);
|
||||
|
||||
_distance3 = _distance2;
|
||||
_distance2 = _distance1;
|
||||
_distance1 = _distance0;
|
||||
_distance0 = distance;
|
||||
|
||||
state =
|
||||
_prevPacketIsLiteral() ? _LzmaState.litMatch : _LzmaState.nonLitMatch;
|
||||
return length;
|
||||
}
|
||||
|
||||
int _decodeRepeat(int posState, Uint8List chunkOut, int chunkOffset) {
|
||||
int distance;
|
||||
if (_rc.readBit(_repeat0Table, state.index) == 0) {
|
||||
if (_rc.readBit(_longRepeat0Tables[state.index], posState) == 0) {
|
||||
_repeatData(_distance0, 1, chunkOut, chunkOffset);
|
||||
state = _prevPacketIsLiteral()
|
||||
? _LzmaState.litShortRep
|
||||
: _LzmaState.nonLitRep;
|
||||
return 1;
|
||||
} else {
|
||||
distance = _distance0;
|
||||
}
|
||||
} else if (_rc.readBit(_repeat1Table, state.index) == 0) {
|
||||
distance = _distance1;
|
||||
_distance1 = _distance0;
|
||||
_distance0 = distance;
|
||||
} else if (_rc.readBit(_repeat2Table, state.index) == 0) {
|
||||
distance = _distance2;
|
||||
_distance2 = _distance1;
|
||||
_distance1 = _distance0;
|
||||
_distance0 = distance;
|
||||
} else {
|
||||
distance = _distance3;
|
||||
_distance3 = _distance2;
|
||||
_distance2 = _distance1;
|
||||
_distance1 = _distance0;
|
||||
_distance0 = distance;
|
||||
}
|
||||
|
||||
var length = _repeatLengthDecoder.readLength(posState);
|
||||
_repeatData(distance, length, chunkOut, chunkOffset);
|
||||
|
||||
state =
|
||||
_prevPacketIsLiteral() ? _LzmaState.litLongRep : _LzmaState.nonLitRep;
|
||||
return length;
|
||||
}
|
||||
|
||||
void _repeatData(int distance, int length, Uint8List chunkOut, int chunkOffset) {
|
||||
var src = _writePos - distance - 1;
|
||||
for (var i = 0; i < length; i++) {
|
||||
if (src < 0 || _writePos < 0) {
|
||||
break;
|
||||
}
|
||||
final b = _dict[src & _dictMask];
|
||||
_dict[_writePos & _dictMask] = b;
|
||||
chunkOut[chunkOffset + i] = b;
|
||||
src++;
|
||||
_writePos++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum _LzmaState {
|
||||
litLit,
|
||||
matchLitLit,
|
||||
repLitLit,
|
||||
shortRepLitLit,
|
||||
matchLit,
|
||||
repLit,
|
||||
shortRepLit,
|
||||
litMatch,
|
||||
litLongRep,
|
||||
litShortRep,
|
||||
nonLitMatch,
|
||||
nonLitRep
|
||||
}
|
||||
|
||||
const _probabilityBitCount = 11;
|
||||
const _probabilityOne = (1 << _probabilityBitCount);
|
||||
const _probabilityHalf = _probabilityOne ~/ 2;
|
||||
|
||||
class _LzmaRangeDecoderTable {
|
||||
final Uint16List table;
|
||||
_LzmaRangeDecoderTable(int length) : table = Uint16List(length) {
|
||||
reset();
|
||||
}
|
||||
void reset() {
|
||||
table.fillRange(0, table.length, _probabilityHalf);
|
||||
}
|
||||
}
|
||||
|
||||
class _LzmaRangeDecoder {
|
||||
late InputStreamBase _input;
|
||||
var range = 0xffffffff;
|
||||
var code = 0;
|
||||
|
||||
set input(InputStreamBase value) {
|
||||
_input = value;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
range = 0xffffffff;
|
||||
code = 0;
|
||||
}
|
||||
|
||||
void initialize() {
|
||||
code = 0;
|
||||
range = 0xffffffff;
|
||||
_input.skip(1);
|
||||
for (var i = 0; i < 4; i++) {
|
||||
code = (code << 8 | _input.readByte());
|
||||
}
|
||||
}
|
||||
|
||||
int readBit(_LzmaRangeDecoderTable table, int index) {
|
||||
_load();
|
||||
final p = table.table[index];
|
||||
final bound = (range >> _probabilityBitCount) * p;
|
||||
const moveBits = 5;
|
||||
if (code < bound) {
|
||||
range = bound;
|
||||
final oneMinusP = _probabilityOne - p;
|
||||
final shifted = oneMinusP >> moveBits;
|
||||
table.table[index] += shifted;
|
||||
return 0;
|
||||
} else {
|
||||
range -= bound;
|
||||
code -= bound;
|
||||
table.table[index] -= p >> moveBits;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
int readBittree(_LzmaRangeDecoderTable table, int count) {
|
||||
var value = 0;
|
||||
var symbolPrefix = 1;
|
||||
for (var i = 0; i < count; i++) {
|
||||
final b = readBit(table, symbolPrefix | value);
|
||||
value = ((value << 1) | b) & 0xffffffff;
|
||||
symbolPrefix = (symbolPrefix << 1) & 0xffffffff;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
int readBittreeReverse(_LzmaRangeDecoderTable table, int count) {
|
||||
var value = 0;
|
||||
var symbolPrefix = 1;
|
||||
for (var i = 0; i < count; i++) {
|
||||
final b = readBit(table, symbolPrefix | value);
|
||||
value = (value | b << i) & 0xffffffff;
|
||||
symbolPrefix = (symbolPrefix << 1) & 0xffffffff;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
int readDirect(int count) {
|
||||
var value = 0;
|
||||
for (var i = 0; i < count; i++) {
|
||||
_load();
|
||||
range >>= 1;
|
||||
code -= range;
|
||||
value <<= 1;
|
||||
if (code & 0x80000000 != 0) {
|
||||
code += range;
|
||||
} else {
|
||||
value++;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
void _load() {
|
||||
const topValue = 1 << 24;
|
||||
if (range < topValue) {
|
||||
range <<= 8;
|
||||
code = (code << 8) | _input.readByte();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _LzmaLengthDecoder {
|
||||
final _LzmaRangeDecoder _input;
|
||||
late final _LzmaRangeDecoderTable formTable;
|
||||
late final List<_LzmaRangeDecoderTable> shortTables;
|
||||
late final List<_LzmaRangeDecoderTable> mediumTables;
|
||||
late final _LzmaRangeDecoderTable longTable;
|
||||
|
||||
_LzmaLengthDecoder(this._input, int positionCount) {
|
||||
formTable = _LzmaRangeDecoderTable(2);
|
||||
shortTables = <_LzmaRangeDecoderTable>[];
|
||||
mediumTables = <_LzmaRangeDecoderTable>[];
|
||||
longTable = _LzmaRangeDecoderTable(256);
|
||||
reset(positionCount);
|
||||
}
|
||||
|
||||
void reset(int positionCount) {
|
||||
formTable.reset();
|
||||
if (positionCount != shortTables.length) {
|
||||
shortTables.clear();
|
||||
mediumTables.clear();
|
||||
for (var i = 0; i < positionCount; i++) {
|
||||
shortTables.add(_LzmaRangeDecoderTable(8));
|
||||
mediumTables.add(_LzmaRangeDecoderTable(8));
|
||||
}
|
||||
} else {
|
||||
for (var table in shortTables) {
|
||||
table.reset();
|
||||
}
|
||||
for (var table in mediumTables) {
|
||||
table.reset();
|
||||
}
|
||||
}
|
||||
longTable.reset();
|
||||
}
|
||||
|
||||
int readLength(int posState) {
|
||||
if (_input.readBit(formTable, 0) == 0) {
|
||||
return 2 + _input.readBittree(shortTables[posState], 3);
|
||||
} else if (_input.readBit(formTable, 1) == 0) {
|
||||
return 10 + _input.readBittree(mediumTables[posState], 3);
|
||||
} else {
|
||||
return 18 + _input.readBittree(longTable, 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _LzmaDistanceDecoder {
|
||||
final int _slotBitCount = 6;
|
||||
final int _alignBitCount = 4;
|
||||
final _LzmaRangeDecoder _input;
|
||||
late final List<_LzmaRangeDecoderTable> _slotTables;
|
||||
late final List<_LzmaRangeDecoderTable> _shortTables;
|
||||
late final _LzmaRangeDecoderTable _longTable;
|
||||
|
||||
_LzmaDistanceDecoder(this._input) {
|
||||
_slotTables = <_LzmaRangeDecoderTable>[];
|
||||
var slotSize = 1 << _slotBitCount;
|
||||
for (var i = 0; i < 4; i++) {
|
||||
_slotTables.add(_LzmaRangeDecoderTable(slotSize));
|
||||
}
|
||||
_shortTables = <_LzmaRangeDecoderTable>[];
|
||||
for (var slot = 4; slot < 14; slot++) {
|
||||
var bitCount = (slot ~/ 2) - 1;
|
||||
_shortTables.add(_LzmaRangeDecoderTable(1 << bitCount));
|
||||
}
|
||||
var alignSize = 1 << _alignBitCount;
|
||||
_longTable = _LzmaRangeDecoderTable(alignSize);
|
||||
}
|
||||
|
||||
void reset() {
|
||||
for (var table in _slotTables) {
|
||||
table.reset();
|
||||
}
|
||||
for (var table in _shortTables) {
|
||||
table.reset();
|
||||
}
|
||||
_longTable.reset();
|
||||
}
|
||||
|
||||
int readDistance(int length) {
|
||||
var distState = length - 2;
|
||||
if (distState >= _slotTables.length) {
|
||||
distState = _slotTables.length - 1;
|
||||
}
|
||||
final table = _slotTables[distState];
|
||||
final slot = _input.readBittree(table, _slotBitCount);
|
||||
if (slot < 4) return slot;
|
||||
|
||||
final prefix = 0x2 | (slot & 0x1);
|
||||
final bitCount = (slot ~/ 2) - 1;
|
||||
if (slot < 14) {
|
||||
final result = (prefix << bitCount) |
|
||||
_input.readBittreeReverse(_shortTables[slot - 4], bitCount);
|
||||
return result;
|
||||
}
|
||||
|
||||
final directCount = bitCount - _alignBitCount;
|
||||
final directBits = _input.readDirect(directCount);
|
||||
final alignBits = _input.readBittreeReverse(_longTable, _alignBitCount);
|
||||
final r1 = (prefix << bitCount) & 0xffffffff;
|
||||
final r2 = (directBits << _alignBitCount) & 0xffffffff;
|
||||
return r1 | r2 | alignBits;
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ class ProjectTaskDetector {
|
||||
name: 'CMake: Build & Run',
|
||||
command: 'cmake -B build && cmake --build build && ./build/$projectName',
|
||||
source: TaskSource.detected,
|
||||
description: '配置、编译并尝试启动生成的目标程序',
|
||||
description: 'Configure, build, and try launching the target executable',
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
RunTask(
|
||||
@@ -55,7 +55,7 @@ class ProjectTaskDetector {
|
||||
name: 'CMake: Build Only',
|
||||
command: 'cmake -B build && cmake --build build',
|
||||
source: TaskSource.detected,
|
||||
description: '仅执行 cmake 生成与构建',
|
||||
description: 'Only execute cmake generation and build',
|
||||
icon: Icons.build_outlined,
|
||||
),
|
||||
RunTask(
|
||||
@@ -63,7 +63,7 @@ class ProjectTaskDetector {
|
||||
name: 'CMake: Clean',
|
||||
command: 'rm -rf build',
|
||||
source: TaskSource.detected,
|
||||
description: '清理构建缓存目录',
|
||||
description: 'Clean build cache directory',
|
||||
icon: Icons.cleaning_services_outlined,
|
||||
),
|
||||
]);
|
||||
@@ -74,14 +74,14 @@ class ProjectTaskDetector {
|
||||
final gradleFile = File(p.join(projectRoot, 'build.gradle'));
|
||||
final gradleKtsFile = File(p.join(projectRoot, 'build.gradle.kts'));
|
||||
if (gradlewFile.existsSync() || gradleFile.existsSync() || gradleKtsFile.existsSync()) {
|
||||
final exec = gradlewFile.existsSync() ? './gradlew' : 'gradle';
|
||||
final exec = gradlewFile.existsSync() ? 'sh ./gradlew' : 'gradle';
|
||||
buildTasks.addAll([
|
||||
RunTask(
|
||||
id: 'detected_gradle_run',
|
||||
name: 'Gradle: Run',
|
||||
command: '$exec run',
|
||||
source: TaskSource.detected,
|
||||
description: '执行应用程序主入口',
|
||||
description: 'Execute application main entrypoint',
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
RunTask(
|
||||
@@ -89,7 +89,7 @@ class ProjectTaskDetector {
|
||||
name: 'Gradle: Assemble Debug',
|
||||
command: '$exec assembleDebug',
|
||||
source: TaskSource.detected,
|
||||
description: '构建调试输出包',
|
||||
description: 'Build debug output package',
|
||||
icon: Icons.build_outlined,
|
||||
),
|
||||
RunTask(
|
||||
@@ -97,7 +97,7 @@ class ProjectTaskDetector {
|
||||
name: 'Gradle: Build',
|
||||
command: '$exec build',
|
||||
source: TaskSource.detected,
|
||||
description: '执行完整构建与测试',
|
||||
description: 'Execute full build and tests',
|
||||
icon: Icons.done_all_outlined,
|
||||
),
|
||||
]);
|
||||
@@ -112,7 +112,7 @@ class ProjectTaskDetector {
|
||||
name: 'Make: Default',
|
||||
command: 'make',
|
||||
source: TaskSource.detected,
|
||||
description: '执行默认 Makefile 构建目标',
|
||||
description: 'Execute default Makefile build target',
|
||||
icon: Icons.build_circle_outlined,
|
||||
),
|
||||
);
|
||||
@@ -127,7 +127,7 @@ class ProjectTaskDetector {
|
||||
name: 'NPM: Start',
|
||||
command: 'npm start',
|
||||
source: TaskSource.detected,
|
||||
description: '启动 Node 服务或前端开发环境',
|
||||
description: 'Start Node service or frontend development environment',
|
||||
icon: Icons.rocket_launch_outlined,
|
||||
),
|
||||
const RunTask(
|
||||
@@ -135,7 +135,7 @@ class ProjectTaskDetector {
|
||||
name: 'NPM: Test',
|
||||
command: 'npm test',
|
||||
source: TaskSource.detected,
|
||||
description: '执行 npm test 测试套件',
|
||||
description: 'Execute npm test suite',
|
||||
icon: Icons.checklist_outlined,
|
||||
),
|
||||
]);
|
||||
@@ -150,7 +150,7 @@ class ProjectTaskDetector {
|
||||
name: 'Cargo: Run',
|
||||
command: 'cargo run',
|
||||
source: TaskSource.detected,
|
||||
description: '编译并运行 Rust 项目',
|
||||
description: 'Compile and run Rust project',
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
const RunTask(
|
||||
@@ -158,7 +158,7 @@ class ProjectTaskDetector {
|
||||
name: 'Cargo: Build',
|
||||
command: 'cargo build',
|
||||
source: TaskSource.detected,
|
||||
description: '仅编译 Rust 项目',
|
||||
description: 'Compile Rust project only',
|
||||
icon: Icons.build_outlined,
|
||||
),
|
||||
]);
|
||||
@@ -173,7 +173,7 @@ class ProjectTaskDetector {
|
||||
name: 'Dart: Run',
|
||||
command: 'dart run',
|
||||
source: TaskSource.detected,
|
||||
description: '启动 Dart 应用',
|
||||
description: 'Launch Dart application',
|
||||
icon: Icons.play_circle_outline,
|
||||
),
|
||||
);
|
||||
@@ -203,7 +203,7 @@ class ProjectTaskDetector {
|
||||
name: 'Python: $fileName',
|
||||
command: 'python3 "$relPath"',
|
||||
source: TaskSource.detected,
|
||||
description: '运行当前 Python 脚本',
|
||||
description: 'Run current Python script',
|
||||
icon: Icons.code,
|
||||
);
|
||||
case '.c':
|
||||
@@ -212,7 +212,7 @@ class ProjectTaskDetector {
|
||||
name: 'GCC: $fileName',
|
||||
command: 'gcc "$relPath" -o /tmp/a.out && /tmp/a.out',
|
||||
source: TaskSource.detected,
|
||||
description: '编译并执行当前 C 源文件',
|
||||
description: 'Compile and execute current C source file',
|
||||
icon: Icons.terminal,
|
||||
);
|
||||
case '.cpp':
|
||||
@@ -223,7 +223,7 @@ class ProjectTaskDetector {
|
||||
name: 'G++: $fileName',
|
||||
command: 'g++ "$relPath" -o /tmp/a.out && /tmp/a.out',
|
||||
source: TaskSource.detected,
|
||||
description: '编译并执行当前 C++ 源文件',
|
||||
description: 'Compile and execute current C++ source file',
|
||||
icon: Icons.terminal,
|
||||
);
|
||||
case '.sh':
|
||||
@@ -233,7 +233,7 @@ class ProjectTaskDetector {
|
||||
name: 'Shell: $fileName',
|
||||
command: 'sh "$relPath"',
|
||||
source: TaskSource.detected,
|
||||
description: '运行当前 Shell 脚本',
|
||||
description: 'Run current Shell script',
|
||||
icon: Icons.terminal,
|
||||
);
|
||||
case '.dart':
|
||||
@@ -242,7 +242,7 @@ class ProjectTaskDetector {
|
||||
name: 'Dart: $fileName',
|
||||
command: 'dart run "$relPath"',
|
||||
source: TaskSource.detected,
|
||||
description: '运行当前 Dart 文件',
|
||||
description: 'Run current Dart file',
|
||||
icon: Icons.code,
|
||||
);
|
||||
case '.go':
|
||||
@@ -251,7 +251,7 @@ class ProjectTaskDetector {
|
||||
name: 'Go: $fileName',
|
||||
command: 'go run "$relPath"',
|
||||
source: TaskSource.detected,
|
||||
description: '运行当前 Go 源文件',
|
||||
description: 'Run current Go source file',
|
||||
icon: Icons.code,
|
||||
);
|
||||
case '.rs':
|
||||
@@ -260,7 +260,7 @@ class ProjectTaskDetector {
|
||||
name: 'Rust: $fileName',
|
||||
command: 'rustc "$relPath" -o /tmp/a.out && /tmp/a.out',
|
||||
source: TaskSource.detected,
|
||||
description: '编译并执行当前 Rust 源文件',
|
||||
description: 'Compile and execute current Rust source file',
|
||||
icon: Icons.code,
|
||||
);
|
||||
case '.js':
|
||||
@@ -269,7 +269,7 @@ class ProjectTaskDetector {
|
||||
name: 'Node: $fileName',
|
||||
command: 'node "$relPath"',
|
||||
source: TaskSource.detected,
|
||||
description: '运行当前 JS 脚本',
|
||||
description: 'Run current JavaScript script',
|
||||
icon: Icons.javascript,
|
||||
);
|
||||
default:
|
||||
|
||||
@@ -28,22 +28,25 @@ class RunTaskStorageService {
|
||||
}
|
||||
|
||||
final dynamic decoded = jsonDecode(content);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
final lastId = decoded['lastRunTaskId'] as String?;
|
||||
if (decoded is Map) {
|
||||
final lastId = decoded['lastRunTaskId']?.toString();
|
||||
final tasksRaw = decoded['tasks'];
|
||||
List<RunTask> list = [];
|
||||
if (tasksRaw is List) {
|
||||
list = tasksRaw
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map((item) => RunTask.fromJson(item))
|
||||
.toList();
|
||||
for (final item in tasksRaw) {
|
||||
if (item is Map) {
|
||||
list.add(RunTask.fromJson(Map<String, dynamic>.from(item)));
|
||||
}
|
||||
}
|
||||
}
|
||||
return (tasks: list, lastRunTaskId: lastId);
|
||||
} else if (decoded is List) {
|
||||
final list = decoded
|
||||
.whereType<Map<String, dynamic>>()
|
||||
.map((item) => RunTask.fromJson(item))
|
||||
.toList();
|
||||
List<RunTask> list = [];
|
||||
for (final item in decoded) {
|
||||
if (item is Map) {
|
||||
list.add(RunTask.fromJson(Map<String, dynamic>.from(item)));
|
||||
}
|
||||
}
|
||||
return (tasks: list, lastRunTaskId: null);
|
||||
}
|
||||
return (tasks: <RunTask>[], lastRunTaskId: null);
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
import 'dart:io';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'distro_manager.dart';
|
||||
|
||||
/// 单个工具链依赖规格定义
|
||||
class ToolchainRequirement {
|
||||
/// 用于检测是否已安装的可执行文件名(传入 command -v)
|
||||
final String checkBinary;
|
||||
|
||||
/// 用户可见的工具名称/描述
|
||||
final String displayName;
|
||||
|
||||
/// 针对不同发行版家族的自动安装指令
|
||||
final Map<DistroFamily, String> installCommands;
|
||||
|
||||
const ToolchainRequirement({
|
||||
required this.checkBinary,
|
||||
required this.displayName,
|
||||
required this.installCommands,
|
||||
});
|
||||
|
||||
/// 获取指定发行版家族下的安装命令
|
||||
String? getInstallCommand(DistroFamily family) => installCommands[family];
|
||||
}
|
||||
|
||||
/// 预编译软件源与工具链检测/安装适配服务
|
||||
class ToolchainService {
|
||||
/// 已注册的常用编译器与开发工具链元数据
|
||||
static const Map<String, ToolchainRequirement> supportedTools = {
|
||||
'make': ToolchainRequirement(
|
||||
checkBinary: 'make',
|
||||
displayName: 'make 编译构建工具',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache make build-base',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
|
||||
DistroFamily.fedora: 'dnf install -y make gcc gcc-c++',
|
||||
},
|
||||
),
|
||||
'cmake': ToolchainRequirement(
|
||||
checkBinary: 'cmake',
|
||||
displayName: 'cmake 构建套件',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache cmake make build-base',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake build-essential',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm cmake base-devel',
|
||||
DistroFamily.fedora: 'dnf install -y cmake make gcc gcc-c++',
|
||||
},
|
||||
),
|
||||
'gcc': ToolchainRequirement(
|
||||
checkBinary: 'gcc',
|
||||
displayName: 'GCC C 语言编译器',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache gcc musl-dev build-base',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
|
||||
DistroFamily.fedora: 'dnf install -y gcc gcc-c++',
|
||||
},
|
||||
),
|
||||
'g++': ToolchainRequirement(
|
||||
checkBinary: 'g++',
|
||||
displayName: 'G++ C++ 编译器',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache g++ musl-dev build-base',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm base-devel',
|
||||
DistroFamily.fedora: 'dnf install -y gcc-c++',
|
||||
},
|
||||
),
|
||||
'python3': ToolchainRequirement(
|
||||
checkBinary: 'python3',
|
||||
displayName: 'Python 3 运行环境',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache python3 py3-pip',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm python python-pip',
|
||||
DistroFamily.fedora: 'dnf install -y python3 python3-pip',
|
||||
},
|
||||
),
|
||||
'python': ToolchainRequirement(
|
||||
checkBinary: 'python3',
|
||||
displayName: 'Python 3 运行环境',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache python3 py3-pip',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 python3-pip',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm python python-pip',
|
||||
DistroFamily.fedora: 'dnf install -y python3 python3-pip',
|
||||
},
|
||||
),
|
||||
'npm': ToolchainRequirement(
|
||||
checkBinary: 'npm',
|
||||
displayName: 'Node.js 与 NPM 环境',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache nodejs npm',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm nodejs npm',
|
||||
DistroFamily.fedora: 'dnf install -y nodejs npm',
|
||||
},
|
||||
),
|
||||
'node': ToolchainRequirement(
|
||||
checkBinary: 'node',
|
||||
displayName: 'Node.js 运行环境',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache nodejs npm',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs npm',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm nodejs npm',
|
||||
DistroFamily.fedora: 'dnf install -y nodejs npm',
|
||||
},
|
||||
),
|
||||
'cargo': ToolchainRequirement(
|
||||
checkBinary: 'cargo',
|
||||
displayName: 'Rust 与 Cargo 工具链',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache rust cargo',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm rust',
|
||||
DistroFamily.fedora: 'dnf install -y cargo rust',
|
||||
},
|
||||
),
|
||||
'rustc': ToolchainRequirement(
|
||||
checkBinary: 'rustc',
|
||||
displayName: 'Rust 编译器',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache rust cargo',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cargo rustc',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm rust',
|
||||
DistroFamily.fedora: 'dnf install -y cargo rust',
|
||||
},
|
||||
),
|
||||
'go': ToolchainRequirement(
|
||||
checkBinary: 'go',
|
||||
displayName: 'Go 语言环境',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache go',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y golang-go',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm go',
|
||||
DistroFamily.fedora: 'dnf install -y golang',
|
||||
},
|
||||
),
|
||||
'gradle': ToolchainRequirement(
|
||||
checkBinary: 'java',
|
||||
displayName: 'Java / Gradle 运行时',
|
||||
installCommands: {
|
||||
DistroFamily.alpine: 'apk update && apk add --no-cache openjdk17-jre-headless',
|
||||
DistroFamily.ubuntu: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
|
||||
DistroFamily.debian: 'DEBIAN_FRONTEND=noninteractive apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y default-jdk-headless ca-certificates-java && (find /usr/lib/jvm -mindepth 1 -maxdepth 2 -type d \\( -name lib -o -name server \\) > /etc/ld.so.conf.d/java.conf 2>/dev/null; ldconfig 2>/dev/null; update-ca-certificates -f 2>/dev/null || true)',
|
||||
DistroFamily.arch: 'pacman -Sy --noconfirm jdk-openjdk',
|
||||
DistroFamily.fedora: 'dnf install -y java-latest-openjdk-devel',
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
/// 从命令行文本中提取所有潜在调用的工具关键字
|
||||
static List<ToolchainRequirement> detectRequiredTools(String command) {
|
||||
if (command.trim().isEmpty) return const [];
|
||||
|
||||
final List<ToolchainRequirement> detected = [];
|
||||
final seen = <String>{};
|
||||
|
||||
// 按语句分隔符拆解:&&, ||, ;, |, 换行
|
||||
final statements = command.split(RegExp(r'&&|\|\||;|\||\n'));
|
||||
for (var stmt in statements) {
|
||||
stmt = stmt.trim();
|
||||
if (stmt.isEmpty) continue;
|
||||
|
||||
// 提取语句开头的可执行文件名或路径(支持前置 sudo、sh、bash,支持 ./gradlew、/usr/bin/make 等)
|
||||
final match = RegExp(r'^(?:sudo\s+)?(?:(?:sh|bash)\s+)?([a-zA-Z0-9_\.\-\+\/\\]+)').firstMatch(stmt);
|
||||
if (match != null) {
|
||||
var rawBin = match.group(1)!;
|
||||
// 归一化提取二进制文件名
|
||||
var binName = rawBin.split(RegExp(r'[/\\]')).last;
|
||||
if (binName == 'gradlew' || binName == 'gradle') {
|
||||
binName = 'gradle';
|
||||
}
|
||||
|
||||
if (supportedTools.containsKey(binName)) {
|
||||
final req = supportedTools[binName]!;
|
||||
if (!seen.contains(req.checkBinary)) {
|
||||
seen.add(req.checkBinary);
|
||||
detected.add(req);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return detected;
|
||||
}
|
||||
|
||||
/// 检查目标发行版根文件系统中是否已经物理安装了指定工具
|
||||
static bool isToolInstalledInRootfs(Directory rootDir, String checkBinary) {
|
||||
// 候选二进制名称
|
||||
final binariesToCheck = <String>[checkBinary];
|
||||
if (checkBinary == 'python3') binariesToCheck.add('python');
|
||||
if (checkBinary == 'node') binariesToCheck.add('nodejs');
|
||||
if (checkBinary == 'npm') binariesToCheck.add('npm');
|
||||
|
||||
final candidateSubDirs = [
|
||||
['usr', 'bin'],
|
||||
['bin'],
|
||||
['usr', 'local', 'bin'],
|
||||
['sbin'],
|
||||
['usr', 'sbin'],
|
||||
['root', '.cargo', 'bin'],
|
||||
['root', '.local', 'bin'],
|
||||
['root', 'go', 'bin'],
|
||||
['usr', 'lib', 'jvm', 'default-java', 'bin'],
|
||||
];
|
||||
|
||||
for (final bin in binariesToCheck) {
|
||||
for (final subDir in candidateSubDirs) {
|
||||
final fullPath = p.joinAll([rootDir.path, ...subDir, bin]);
|
||||
try {
|
||||
final type = FileSystemEntity.typeSync(fullPath, followLinks: false);
|
||||
if (type != FileSystemEntityType.notFound) {
|
||||
return true;
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
if (checkBinary == 'java') {
|
||||
final jvmDir = Directory(p.join(rootDir.path, 'usr', 'lib', 'jvm'));
|
||||
if (jvmDir.existsSync()) {
|
||||
try {
|
||||
for (final entry in jvmDir.listSync()) {
|
||||
if (entry is Directory) {
|
||||
final javaBin = File(p.join(entry.path, 'bin', 'java'));
|
||||
if (javaBin.existsSync()) return true;
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// 针对不同系统与命令生成自适应的预安装与执行组合脚本
|
||||
///
|
||||
/// - 只有识别出明确发行版家族(Alpine/Ubuntu/Debian/Arch/Fedora)的系统,才会生成前置检测与安装包装;
|
||||
/// - 针对未识别的未知系统([DistroFamily.unknown])或宿主 Shell,直接原样返回指令,不作任何干预;
|
||||
/// - 若传入 [rootDir],将优先在宿主文件系统快速检测工具是否已物理存在,已存在则直接返回原命令;
|
||||
/// - 若命令为多行脚本(包含换行符),将自动转换为 Unix LF 换行并保存至容器 `/root/.ce_task.sh` 执行,
|
||||
/// 彻底避免交互式终端在提示符处逐行错位回显;
|
||||
/// - 若工具缺失,将把工具安装逻辑一并注入引导脚本中,保证执行的平滑与终端的清爽。
|
||||
static String resolveCommand(
|
||||
String rawCommand,
|
||||
DistroFamily family, {
|
||||
Directory? rootDir,
|
||||
}) {
|
||||
if (rawCommand.trim().isEmpty) {
|
||||
return rawCommand;
|
||||
}
|
||||
|
||||
// 1. 规范化统一换行符为 Unix LF,防止 Windows CRLF 导致 /bin/sh: $'\r': command not found
|
||||
final normalizedCommand = rawCommand.replaceAll('\r\n', '\n').replaceAll('\r', '\n').trim();
|
||||
final isMultiLine = normalizedCommand.contains('\n');
|
||||
|
||||
// 2. 识别所需工具链
|
||||
final tools = detectRequiredTools(normalizedCommand);
|
||||
|
||||
// 3. 计算实际物理缺失的工具
|
||||
List<ToolchainRequirement> missingTools = [];
|
||||
if (family != DistroFamily.unknown && tools.isNotEmpty) {
|
||||
if (rootDir != null && rootDir.existsSync()) {
|
||||
missingTools = tools
|
||||
.where((tool) => !isToolInstalledInRootfs(rootDir, tool.checkBinary))
|
||||
.toList();
|
||||
} else {
|
||||
missingTools = tools;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 多行脚本(Multiline Script)模式:封装为 /root/.ce_task.sh 运行
|
||||
if (isMultiLine && rootDir != null && rootDir.existsSync()) {
|
||||
try {
|
||||
final rootHomeDir = Directory(p.join(rootDir.path, 'root'));
|
||||
if (!rootHomeDir.existsSync()) {
|
||||
rootHomeDir.createSync(recursive: true);
|
||||
}
|
||||
final taskFile = File(p.join(rootHomeDir.path, '.ce_task.sh'));
|
||||
final scriptBuffer = StringBuffer();
|
||||
scriptBuffer.writeln('#!/bin/sh');
|
||||
scriptBuffer.writeln('set -e');
|
||||
|
||||
// 若存在缺失的编译工具链依赖,前置注入自动安装
|
||||
for (final tool in missingTools) {
|
||||
final installCmd = tool.getInstallCommand(family);
|
||||
if (installCmd == null || installCmd.isEmpty) continue;
|
||||
scriptBuffer.writeln("printf '\\033[1;33m[CodeEditor] 检测到未安装 %s,正在自动配置编译环境...\\033[0m\\n' '${tool.displayName}'");
|
||||
scriptBuffer.writeln(installCmd);
|
||||
scriptBuffer.writeln("printf '\\033[1;32m[CodeEditor] %s 安装就绪,继续执行任务...\\033[0m\\n' '${tool.displayName}'");
|
||||
}
|
||||
|
||||
// 注入用户编写的多行脚本内容
|
||||
scriptBuffer.writeln(normalizedCommand);
|
||||
|
||||
taskFile.writeAsStringSync(scriptBuffer.toString());
|
||||
return 'sh /root/.ce_task.sh';
|
||||
} catch (_) {
|
||||
// 异常降级
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 单行指令且未知系统:原样返回
|
||||
if (family == DistroFamily.unknown || tools.isEmpty) {
|
||||
return rawCommand;
|
||||
}
|
||||
|
||||
// 6. 单行指令且所有工具已物理就绪:直接返回原命令,零污染无感直达
|
||||
if (rootDir != null && rootDir.existsSync() && missingTools.isEmpty) {
|
||||
return rawCommand;
|
||||
}
|
||||
|
||||
// 7. 单行指令且存在缺失工具:构建轻量 /root/.ce_setup.sh
|
||||
if (rootDir != null && rootDir.existsSync() && missingTools.isNotEmpty) {
|
||||
try {
|
||||
final rootHomeDir = Directory(p.join(rootDir.path, 'root'));
|
||||
if (!rootHomeDir.existsSync()) {
|
||||
rootHomeDir.createSync(recursive: true);
|
||||
}
|
||||
final setupFile = File(p.join(rootHomeDir.path, '.ce_setup.sh'));
|
||||
final scriptBuffer = StringBuffer();
|
||||
scriptBuffer.writeln('#!/bin/sh');
|
||||
scriptBuffer.writeln('set -e');
|
||||
for (final tool in missingTools) {
|
||||
final installCmd = tool.getInstallCommand(family);
|
||||
if (installCmd == null || installCmd.isEmpty) continue;
|
||||
scriptBuffer.writeln("printf '\\033[1;33m[CodeEditor] 检测到未安装 %s,正在自动配置编译环境...\\033[0m\\n' '${tool.displayName}'");
|
||||
scriptBuffer.writeln(installCmd);
|
||||
scriptBuffer.writeln("printf '\\033[1;32m[CodeEditor] %s 安装就绪,继续执行任务...\\033[0m\\n' '${tool.displayName}'");
|
||||
}
|
||||
setupFile.writeAsStringSync(scriptBuffer.toString());
|
||||
return 'sh /root/.ce_setup.sh && ($rawCommand)';
|
||||
} catch (_) {
|
||||
// 异常降级
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 降级方案(未传 rootDir 或写入失败时的内联防护)
|
||||
final checks = <String>[];
|
||||
for (final tool in missingTools) {
|
||||
final installCmd = tool.getInstallCommand(family);
|
||||
if (installCmd == null || installCmd.isEmpty) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final checkScript =
|
||||
'if ! command -v ${tool.checkBinary} >/dev/null 2>&1; then '
|
||||
"printf '\\033[1;33m[CodeEditor] 检测到未安装 %s,正在自动配置编译环境...\\033[0m\\n' '${tool.displayName}'; "
|
||||
'$installCmd; '
|
||||
'if [ \$? -eq 0 ]; then '
|
||||
"printf '\\033[1;32m[CodeEditor] %s 安装就绪,继续执行任务...\\033[0m\\n' '${tool.displayName}'; "
|
||||
'else '
|
||||
"printf '\\033[1;31m[CodeEditor] %s 安装失败,请检查网络或软件源配置。\\033[0m\\n' '${tool.displayName}'; "
|
||||
'exit 1; '
|
||||
'fi; '
|
||||
'fi';
|
||||
checks.add(checkScript);
|
||||
}
|
||||
|
||||
if (checks.isEmpty) {
|
||||
return rawCommand;
|
||||
}
|
||||
|
||||
final preamble = checks.join(' && ');
|
||||
return '$preamble && ($rawCommand)';
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user