This commit is contained in:
2509_92447106 committed 2026-11-07 18:46:11 +08:00
1 parent 5760fb77b0
commit 6e23391339
22 files changed
+306 -100

No files matched your search

@@ -83,6 +83,7 @@ public sealed class DirectoryRemote : IModelRemote
}
var url = package.Url;
if (string.IsNullOrWhiteSpace(url)) return null;
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
if (Path.IsPathRooted(url) && File.Exists(url))
@@ -64,6 +64,8 @@ public sealed class L : INotifyPropertyChanged
Language = code;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Language)));
// 顺带清理已回收的弱引用,避免 _watchers 只增不减
_watchers.RemoveAll(w => !w.TryGetTarget(out _));
foreach (var w in _watchers)
if (w.TryGetTarget(out var ls)) ls.Refresh();
LanguageChanged?.Invoke();
@@ -162,6 +162,10 @@ public sealed class LoadedModel : IDisposable
{
if (_disposed) return;
_disposed = true;
// 顺序:先释放视图(停计时器/Dispose 位图),再释放运行时,最后卸载程序集。
// 否则视图里的事件订阅会继续持有 ALC 内的类型,collectible 上下文无法回收。
try { (View as IDisposable)?.Dispose(); }
catch (Exception ex) { Console.Error.WriteLine($"释放模型视图失败: {ex.Message}"); }
try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
}
@@ -31,7 +31,12 @@ public static class ModelInstaller
{
ct.ThrowIfCancellationRequested();
var relative = Path.GetRelativePath(model.Directory, file);
var dest = Path.Combine(staging, relative);
// 路径穿越防护:相对路径必须完整落在 staging 目录内
var dest = Path.GetFullPath(Path.Combine(staging, relative));
var stagingFull = Path.GetFullPath(staging)
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"非法的模型文件路径: {relative}");
var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
@@ -46,17 +51,29 @@ public static class ModelInstaller
progress?.Report((done, total <= 0 ? done : total));
}
if (Directory.Exists(target))
// 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空
var backup = target + ".old";
if (Directory.Exists(backup)) Directory.Delete(backup, true);
var hasBackup = false;
try
{
var backup = target + ".old";
if (Directory.Exists(backup)) Directory.Delete(backup, true);
Directory.Move(target, backup);
if (Directory.Exists(target))
{
Directory.Move(target, backup);
hasBackup = true;
}
Directory.Move(staging, target);
try { Directory.Delete(backup, true); } catch { }
}
else
catch
{
Directory.Move(staging, target);
// 新目录尚未就位时把旧目录还原;staging 由外层 catch 清理
if (hasBackup && !Directory.Exists(target) && Directory.Exists(backup))
Directory.Move(backup, target);
throw;
}
if (hasBackup)
{
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
}
progress?.Report((total, total));
@@ -173,7 +173,7 @@ public sealed class ModelSourceClient
var extractDir = Path.Combine(tmpRoot, "extract");
Directory.CreateDirectory(extractDir);
ZipFile.ExtractToDirectory(zipPath, extractDir, true);
ZipSafety.ExtractToDirectory(zipPath, extractDir);
var root = FindModelRoot(extractDir) ?? extractDir;
foreach (var entry in Directory.GetFileSystemEntries(root))
@@ -195,6 +195,8 @@ public sealed class UpdateService
private static bool IsPayload(string id, string relative)
{
var rel = relative.Replace('\\', '/');
// 拒绝任何形式的父目录穿越与绝对路径
if (rel.StartsWith('/') || rel.Contains("..", StringComparison.Ordinal)) return false;
return rel.Equals(id + ".json", StringComparison.OrdinalIgnoreCase) ||
rel.StartsWith(id + ".model/", StringComparison.OrdinalIgnoreCase);
}
@@ -223,7 +225,14 @@ public sealed class UpdateService
{
ct.ThrowIfCancellationRequested();
var bytes = await _remote.DownloadAsync(entry, ct);
var dest = Path.Combine(staging, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar));
// 路径穿越防护:规范化后必须仍落在 staging 目录内,
// 防止远端清单里的 "../" 或绝对路径写进安装目录之外。
var dest = Path.GetFullPath(Path.Combine(staging,
entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)));
var stagingFull = Path.GetFullPath(staging)
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"非法的模型文件路径: {entry.RelativePath}");
var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
await File.WriteAllBytesAsync(dest, bytes, ct);
@@ -307,7 +316,7 @@ public sealed class UpdateService
await File.WriteAllBytesAsync(zip, bytes, ct);
try
{
ZipFile.ExtractToDirectory(zip, payload, true);
ZipSafety.ExtractToDirectory(zip, payload);
}
finally
{
@@ -0,0 +1,36 @@
using System;
using System.IO;
using System.IO.Compression;
namespace EarthModelStudio.Services;
/// <summary>
/// 安全解压:拒绝 zip slip(条目名含 ../、绝对路径、盘符),
/// 并在解压前逐条校验目标路径完整落在目标目录内。
/// </summary>
public static class ZipSafety
{
public static void ExtractToDirectory(string zipPath, string destination)
{
var destFull = Path.GetFullPath(destination)
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
using (var archive = ZipFile.OpenRead(zipPath))
{
foreach (var entry in archive.Entries)
{
var name = entry.FullName.Replace('\\', '/');
if (name.StartsWith('/') || name.Contains("..", StringComparison.Ordinal) ||
(name.Length >= 2 && name[1] == ':'))
throw new InvalidOperationException($"压缩包含非法路径条目: {entry.FullName}");
var target = Path.GetFullPath(Path.Combine(destFull, name));
if (!target.StartsWith(destFull, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}");
}
}
// 校验通过后交给框架解压(保留 overwrite 语义)
ZipFile.ExtractToDirectory(zipPath, destination, true);
}
}
@@ -19,6 +19,9 @@ public partial class DownloadViewModel : ObservableObject
private readonly AppServices _services;
private readonly MainViewModel _main;
private bool _initialized;
// 每次切源取消上一次加载,并用 generation 序号丢弃过期结果,避免并发写 Models 集合
private CancellationTokenSource? _loadCts;
private int _loadGeneration;
public ObservableCollection<SourceItemViewModel> Sources { get; } = new();
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
@@ -157,12 +160,22 @@ public partial class DownloadViewModel : ObservableObject
private async Task LoadAsync(SourceItemViewModel source, bool force)
{
if (!source.Model.Enabled) return;
// 取消上一次尚未完成的加载,避免快速切换源时并发 Clear/写入同一集合
_loadCts?.Cancel();
_loadCts?.Dispose();
_loadCts = new CancellationTokenSource();
var ct = _loadCts.Token;
var generation = ++_loadGeneration;
IsBusy = true;
StatusMessage = L.I["dl.syncing"];
try
{
var index = await _services.Sources.FetchAsync(source.Model, force, null, CancellationToken.None);
if (SelectedSource != source) return;
var index = await _services.Sources.FetchAsync(source.Model, force, null, ct);
// 只有「仍是当前选中源 + 仍是最新一次加载」才可以写 UI 集合
if (ct.IsCancellationRequested || generation != _loadGeneration || SelectedSource != source)
return;
if (index.Error != null)
{
@@ -189,13 +202,18 @@ public partial class DownloadViewModel : ObservableObject
? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}"
: L.I.F("dl.ready", Models.Count);
}
catch (OperationCanceledException)
{
// 被更新的加载取代或页面关闭:忽略,不覆盖新结果
}
catch (Exception ex)
{
StatusMessage = ex.Message;
if (!ct.IsCancellationRequested) StatusMessage = ex.Message;
}
finally
{
IsBusy = false;
// 只有最后一次加载才复位 Busy,避免旧任务把新任务的忙碌状态清掉
if (generation == _loadGeneration) IsBusy = false;
}
}
@@ -20,6 +20,7 @@ public partial class MainWindow : Window
private readonly List<PlayerWindow> _players = new();
private MainViewModel? _viewModel;
private ContentControl? _pageHost;
private bool _isClosing;
public MainWindow()
{
@@ -74,9 +75,19 @@ public partial class MainWindow : Window
}, DispatcherPriority.Render);
}
private async void OpenPlayerWindow(ModelPackage package)
// 事件处理器必须是 void,因此包一层可观察异常的入口:
// fire-and-forget 的 Task 也要观察异常,绝不外泄到 Avalonia 事件循环导致进程崩溃。
private void OpenPlayerWindow(ModelPackage package) => _ = OpenPlayerWindowSafeAsync(package);
private async Task OpenPlayerWindowSafeAsync(ModelPackage package)
{
if (_viewModel == null) return;
try { await OpenPlayerWindowAsync(package); }
catch (Exception ex) { Console.Error.WriteLine($"打开模型窗口失败: {ex}"); }
}
private async Task OpenPlayerWindowAsync(ModelPackage package)
{
if (_viewModel == null || _isClosing) return;
// 启动进度窗:模型加载、地表纹理生成、界面构建的真实进度
var loading = new LoadingWindow(package.LocalizedName);
@@ -88,9 +99,18 @@ public partial class MainWindow : Window
PlayerWindow? window = null;
LoadedModel? loaded = null;
Exception? error = null;
// 关键修复:requestClose 过去捕获的是「尚未赋值的 window」,加载期恒为 null,
// 模型在 Prepare/CreateView 里调用 context.RequestClose() 会静默失效。
// 改为关闭当前存在的窗口(加载期=进度窗,加载完成=模型窗),统一走 UI 线程。
void RequestClose() => Dispatcher.UIThread.Post(() =>
{
(window ?? (Window?)loading)?.Close();
});
try
{
loaded = await _viewModel.Models.LoadAsync(package, () => window?.Close(),
loaded = await _viewModel.Models.LoadAsync(package, RequestClose,
(value, message) => loading.Report(value, message));
}
catch (Exception ex)
@@ -100,6 +120,13 @@ public partial class MainWindow : Window
loading.Close();
// 加载期间用户关掉了主窗口:不要再弹出幽灵模型窗口,直接释放已加载模型
if (_isClosing)
{
loaded?.Dispose();
return;
}
if (loaded == null || error != null)
{
var message = error?.Message ?? L.I["player.errorHint"];
@@ -119,11 +146,14 @@ public partial class MainWindow : Window
private void OnClosed(object? sender, EventArgs e)
{
_isClosing = true;
if (_viewModel != null)
{
_viewModel.PlayerRequested -= OpenPlayerWindow;
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
}
// 先取快照再关闭:PlayerWindow.Closed 回调会 _players.Remove,
// 直接遍历原集合会在 foreach 期间修改底层导致异常。
foreach (var window in _players.ToList()) window.Close();
_players.Clear();
}