diff --git a/MainWindow.axaml.cs b/MainWindow.axaml.cs index 3fa8ba92..51752fc6 100644 --- a/MainWindow.axaml.cs +++ b/MainWindow.axaml.cs @@ -2453,7 +2453,7 @@ namespace N64RecompLauncher { try { - _gameManager.HideGame(game.Name); + _gameManager.HideGame(game); await _gameManager.LoadGamesAsync(); ApplySorting(); } diff --git a/Models/GameInfo.cs b/Models/GameInfo.cs index 2f2d2a84..ea88f6af 100644 --- a/Models/GameInfo.cs +++ b/Models/GameInfo.cs @@ -200,6 +200,9 @@ namespace N64RecompLauncher.Models try { + if (string.IsNullOrEmpty(GameManager.GamesFolder)) + return false; + var gamePath = Path.Combine(GameManager.GamesFolder, FolderName); var selectedExePath = Path.Combine(gamePath, "selected_executable.txt"); return File.Exists(selectedExePath); @@ -1916,7 +1919,7 @@ namespace N64RecompLauncher.Models if (!string.IsNullOrEmpty(tarGzFile)) { - ExtractTarGz(tarGzFile, gamePath); + await ExtractTarGz(tarGzFile, gamePath).ConfigureAwait(false); } else { @@ -1935,7 +1938,7 @@ namespace N64RecompLauncher.Models } else if (assetName.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase)) { - ExtractTarGz(downloadPath, gamePath); + await ExtractTarGz(downloadPath, gamePath).ConfigureAwait(false); } try @@ -1974,18 +1977,18 @@ namespace N64RecompLauncher.Models } } - static void ExtractTarGz(string sourceFilePath, string destinationDirectoryPath) + static async Task ExtractTarGz(string sourceFilePath, string destinationDirectoryPath) { Directory.CreateDirectory(destinationDirectoryPath); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - ExtractTarGzWindows(sourceFilePath, destinationDirectoryPath); + await ExtractTarGzWindows(sourceFilePath, destinationDirectoryPath).ConfigureAwait(false); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { - ExtractTarGzUnix(sourceFilePath, destinationDirectoryPath); + await ExtractTarGzUnix(sourceFilePath, destinationDirectoryPath).ConfigureAwait(false); } else { @@ -1993,7 +1996,7 @@ namespace N64RecompLauncher.Models } } - static async void ExtractTarGzWindows(string sourceFilePath, string destinationDirectoryPath) + static async Task ExtractTarGzWindows(string sourceFilePath, string destinationDirectoryPath) { try { @@ -2011,6 +2014,23 @@ namespace N64RecompLauncher.Models } } + static string GetSafeExtractionPath(string destinationDirectoryPath, string archivePath) + { + var sanitizedArchivePath = archivePath.Replace('/', Path.DirectorySeparatorChar) + .Replace('\\', Path.DirectorySeparatorChar); + var fullDestinationRoot = Path.GetFullPath(destinationDirectoryPath) + .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + var fullDestinationPath = Path.GetFullPath(Path.Combine(fullDestinationRoot, sanitizedArchivePath)); + + if (!fullDestinationPath.StartsWith(fullDestinationRoot + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) && + !fullDestinationPath.Equals(fullDestinationRoot, StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidDataException($"Archive entry escapes the destination directory: {archivePath}"); + } + + return fullDestinationPath; + } + static void ExtractTarFromStream(Stream tarStream, string destinationDirectoryPath) { using var reader = new BinaryReader(tarStream); @@ -2027,7 +2047,7 @@ namespace N64RecompLauncher.Models var fileType = headerBytes[156]; - var destPath = Path.Combine(destinationDirectoryPath, fileName); + var destPath = GetSafeExtractionPath(destinationDirectoryPath, fileName); if (fileType == '5') { @@ -2035,7 +2055,13 @@ namespace N64RecompLauncher.Models } else { - Directory.CreateDirectory(Path.GetDirectoryName(destPath)); + var destinationDirectory = Path.GetDirectoryName(destPath); + if (string.IsNullOrEmpty(destinationDirectory)) + { + throw new InvalidDataException($"Invalid archive entry path: {fileName}"); + } + + Directory.CreateDirectory(destinationDirectory); using var fileStream = File.Create(destPath); int blocksToRead = (int)Math.Ceiling((double)fileSize / 512); @@ -2054,7 +2080,7 @@ namespace N64RecompLauncher.Models } } - static async void ExtractTarGzUnix(string sourceFilePath, string destinationDirectoryPath) + static async Task ExtractTarGzUnix(string sourceFilePath, string destinationDirectoryPath) { try { @@ -2140,6 +2166,16 @@ namespace N64RecompLauncher.Models return relativePath.Count(c => c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar); } + internal static void EnsureExecutableAtRoot(string gamePath) + { + TryEnsureExecutableAtRoot(gamePath); + } + + internal static List GetExecutableCandidates(string gamePath, SearchOption searchOption, out bool needsWine) + { + return FindExecutableCandidates(gamePath, searchOption, out needsWine); + } + static List FindExecutableCandidates(string path, SearchOption searchOption, out bool needsWine) { needsWine = false; diff --git a/Services/CLIHandler.cs b/Services/CLIHandler.cs index e9fbf0c8..f99b60d4 100644 --- a/Services/CLIHandler.cs +++ b/Services/CLIHandler.cs @@ -330,37 +330,25 @@ namespace N64RecompLauncher } var settings = AppSettings.Load(); + var gamesFolder = _gameManager.GamesFolder; + if (string.IsNullOrEmpty(gamesFolder) || string.IsNullOrEmpty(game.FolderName)) + { + return PrintError("Game folder is not configured."); + } // Check if need to select executable - var storedExe = game.LoadSelectedExecutable(_gameManager.GamesFolder); + var storedExe = game.LoadSelectedExecutable(gamesFolder); if (string.IsNullOrEmpty(storedExe)) { // Check if there are multiple executables - var gamePath = Path.Combine(_gameManager.GamesFolder, game.FolderName); - var executables = new List(); + var gamePath = Path.Combine(gamesFolder, game.FolderName); + GameInfo.EnsureExecutableAtRoot(gamePath); - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + var executables = GameInfo.GetExecutableCandidates(gamePath, SearchOption.TopDirectoryOnly, out _); + if (executables.Count == 0) { - executables = Directory.GetFiles(gamePath, "*.exe", SearchOption.TopDirectoryOnly).ToList(); - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) - { - var appBundles = Directory.GetDirectories(gamePath, "*.app", SearchOption.TopDirectoryOnly); - executables.AddRange(appBundles); - } - else // Linux - { - executables.AddRange(Directory.GetFiles(gamePath, "*.x86_64", SearchOption.TopDirectoryOnly)); - executables.AddRange(Directory.GetFiles(gamePath, "*.appimage", SearchOption.TopDirectoryOnly)); - executables.AddRange(Directory.GetFiles(gamePath, "*.arm64", SearchOption.TopDirectoryOnly)); - executables.AddRange(Directory.GetFiles(gamePath, "*.aarch64", SearchOption.TopDirectoryOnly)); - } - - var launchBat = Path.Combine(gamePath, "launch.bat"); - if (File.Exists(launchBat) && !executables.Contains(launchBat)) - { - executables.Add(launchBat); + executables = GameInfo.GetExecutableCandidates(gamePath, SearchOption.AllDirectories, out _); } if (executables.Count > 1) @@ -428,7 +416,7 @@ namespace N64RecompLauncher { await game.PerformActionAsync( _gameManager.HttpClient, - _gameManager.GamesFolder, + gamesFolder, settings.IsPortable, settings); @@ -771,4 +759,4 @@ namespace N64RecompLauncher } } } -} \ No newline at end of file +} diff --git a/Services/GameManager.cs b/Services/GameManager.cs index 59e40073..18d9b338 100644 --- a/Services/GameManager.cs +++ b/Services/GameManager.cs @@ -9,7 +9,7 @@ namespace N64RecompLauncher.Services { public class GameManager : INotifyPropertyChanged, IDisposable { - public AppSettings _settings; + public AppSettings _settings = new(); private readonly HttpClient _httpClient; private bool _disposed = false; private string _gamesFolder; @@ -21,7 +21,7 @@ namespace N64RecompLauncher.Services public string? GamesFolder => _gamesFolder; public string? CacheFolder => _cacheFolder; - private string _CurrentVersionString; + private string _CurrentVersionString = string.Empty; public string CurrentVersionString { get => _CurrentVersionString; @@ -814,24 +814,41 @@ namespace N64RecompLauncher.Services return (standard, experimental, custom); } + private string BuildDefaultGamesJson() + { + var defaultData = GetDefaultGamesData(); + + var data = new + { + standard = defaultData.standard, + experimental = defaultData.experimental, + custom = defaultData.custom + }; + + var options = new JsonSerializerOptions { WriteIndented = true }; + return JsonSerializer.Serialize(data, options); + } + + private void CreateDefaultGamesJson() + { + try + { + string json = BuildDefaultGamesJson(); + File.WriteAllText(_gamesConfigPath, json); + System.Diagnostics.Debug.WriteLine($"Default games.json created at {_gamesConfigPath}"); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Error creating default games.json: {ex.Message}"); + } + } + private async Task CreateDefaultGamesJsonAsync() { try { - var defaultData = GetDefaultGamesData(); - - var data = new - { - standard = defaultData.standard, - experimental = defaultData.experimental, - custom = defaultData.custom - }; - - var options = new JsonSerializerOptions { WriteIndented = true }; - string json = JsonSerializer.Serialize(data, options); - + string json = BuildDefaultGamesJson(); await File.WriteAllTextAsync(_gamesConfigPath, json).ConfigureAwait(false); - System.Diagnostics.Debug.WriteLine($"Default games.json created at {_gamesConfigPath}"); } catch (Exception ex) @@ -884,12 +901,12 @@ namespace N64RecompLauncher.Services public GameInfo? FindGameByName(string name) { - return Games.FirstOrDefault(g => g.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + return Games.FirstOrDefault(g => string.Equals(g.Name, name, StringComparison.OrdinalIgnoreCase)); } public GameInfo? FindGameByFolderName(string folderName) { - return Games.FirstOrDefault(predicate: g => g.FolderName.Equals(folderName, StringComparison.OrdinalIgnoreCase)); + return Games.FirstOrDefault(g => string.Equals(g.FolderName, folderName, StringComparison.OrdinalIgnoreCase)); } public void OnPropertyChanged(string propertyName) @@ -912,7 +929,7 @@ namespace N64RecompLauncher.Services var filteredGames = allGames .Where(game => game != null && (!game.IsExperimental || settings.ShowExperimentalGames)) .Where(game => game != null && (!game.IsCustom || settings.ShowCustomGames)) - .Where(game => game != null && !settings.HiddenGames.Contains(game.Name ?? string.Empty)) + .Where(game => game != null && !IsGameHidden(settings, game)) .ToList(); Games.Clear(); @@ -930,7 +947,7 @@ namespace N64RecompLauncher.Services if (!forceUpdateCheck) { - int cachedCount = Games.Count(g => !GitHubApiCache.NeedsUpdateCheck(g.Repository, + int cachedCount = Games.Count(g => !GitHubApiCache.NeedsUpdateCheck(g.Repository ?? string.Empty, Directory.Exists(Path.Combine(_gamesFolder, g.FolderName ?? "")))); int apiCallCount = Games.Count - cachedCount; System.Diagnostics.Debug.WriteLine($"LoadGamesAsync: {cachedCount} games using cache, {apiCallCount} will check for updates"); @@ -1073,15 +1090,48 @@ namespace N64RecompLauncher.Services return DateTime.MinValue; } - public void HideGame(string gameName) + private static string GetHiddenGameKey(GameInfo game) { - if (string.IsNullOrEmpty(gameName)) + if (!string.IsNullOrWhiteSpace(game.FolderName)) + return $"folder:{game.FolderName}"; + + if (!string.IsNullOrWhiteSpace(game.Repository)) + return $"repo:{game.Repository}"; + + return $"name:{game.Name ?? string.Empty}"; + } + + private static bool IsGameHidden(AppSettings settings, GameInfo game) + { + if (settings?.HiddenGames == null) + return false; + + var hiddenKey = GetHiddenGameKey(game); + return settings.HiddenGames.Contains(hiddenKey) || + (!string.IsNullOrWhiteSpace(game.Name) && settings.HiddenGames.Contains(game.Name)); + } + + private static void AddHiddenGame(AppSettings settings, GameInfo game) + { + if (settings?.HiddenGames == null) + return; + + var hiddenKey = GetHiddenGameKey(game); + if (!settings.HiddenGames.Contains(hiddenKey)) + { + settings.HiddenGames.Add(hiddenKey); + } + } + + public void HideGame(GameInfo game) + { + if (game == null) return; var settings = AppSettings.Load(); - if (!settings.HiddenGames.Contains(gameName)) + if (!IsGameHidden(settings, game)) { - settings.HiddenGames.Add(gameName); + AddHiddenGame(settings, game); AppSettings.Save(settings); FilterGames(settings); } @@ -1108,9 +1158,9 @@ namespace N64RecompLauncher.Services foreach (var game in Games) { - if (game != null && game.Status == GameStatus.NotInstalled && !settings.HiddenGames.Contains(game.Name)) + if (game != null && game.Status == GameStatus.NotInstalled && !IsGameHidden(settings, game)) { - settings.HiddenGames.Add(game.Name); + AddHiddenGame(settings, game); } } AppSettings.Save(settings); @@ -1127,9 +1177,9 @@ namespace N64RecompLauncher.Services foreach (var game in Games) { - if (game != null && game.IsExperimental == true && !settings.HiddenGames.Contains(game.Name)) + if (game != null && game.IsExperimental == true && !IsGameHidden(settings, game)) { - settings.HiddenGames.Add(game.Name); + AddHiddenGame(settings, game); } } AppSettings.Save(settings); @@ -1150,8 +1200,7 @@ namespace N64RecompLauncher.Services { if (!File.Exists(_gamesConfigPath)) { - // Create default games.json if it doesn't exist - _ = CreateDefaultGamesJsonAsync(); + CreateDefaultGamesJson(); } string json = File.ReadAllText(_gamesConfigPath); @@ -1197,9 +1246,9 @@ namespace N64RecompLauncher.Services foreach (var game in Games) { - if (game != null && game.IsExperimental == false && !settings.HiddenGames.Contains(game.Name)) + if (game != null && game.IsExperimental == false && !IsGameHidden(settings, game)) { - settings.HiddenGames.Add(game.Name); + AddHiddenGame(settings, game); } } AppSettings.Save(settings); @@ -1219,9 +1268,9 @@ namespace N64RecompLauncher.Services foreach (var game in Games) { - if (game != null && !game.IsCustom && !settings.HiddenGames.Contains(game.Name)) + if (game != null && !game.IsCustom && !IsGameHidden(settings, game)) { - settings.HiddenGames.Add(game.Name); + AddHiddenGame(settings, game); } } AppSettings.Save(settings); @@ -1241,9 +1290,9 @@ namespace N64RecompLauncher.Services foreach (var game in Games) { - if (game != null && game.IsCustom && !settings.HiddenGames.Contains(game.Name)) + if (game != null && game.IsCustom && !IsGameHidden(settings, game)) { - settings.HiddenGames.Add(game.Name); + AddHiddenGame(settings, game); } } @@ -1258,7 +1307,7 @@ namespace N64RecompLauncher.Services for (int i = Games.Count - 1; i >= 0; i--) { - if (Games[i] != null && settings.HiddenGames.Contains(Games[i].Name)) + if (Games[i] != null && IsGameHidden(settings, Games[i])) { Games.RemoveAt(i); }