18#include <nlohmann/json.hpp>
19#include <openssl/evp.h>
20#include <openssl/md5.h>
21#include <openssl/sha.h>
26using json = nlohmann::json;
27namespace fs = std::filesystem;
46 return "Size Mismatch";
65 return "Loading Manifest";
67 return "Verifying Files";
96 const char* home = std::getenv(
"HOME");
99 manifestDir = fs::path(home) /
".local/share/gamelauncher/manifests";
111 if (!impl_->manifestDir.empty())
114 fs::create_directories(impl_->manifestDir, ec);
121 for (
auto& [gameId, flag] : impl_->cancelFlags)
132 const std::string& type)
134 std::ifstream file(path, std::ios::binary);
140 EVP_MD_CTX* ctx = EVP_MD_CTX_new();
146 const EVP_MD* md =
nullptr;
151 else if (type ==
"sha1")
155 else if (type ==
"sha256")
161 EVP_MD_CTX_free(ctx);
162 Logger::error(
"[FileVerification] Unknown checksum type: {}", type);
166 if (EVP_DigestInit_ex(ctx, md,
nullptr) != 1)
168 EVP_MD_CTX_free(ctx);
173 while (file.read(buffer,
sizeof(buffer)) || file.gcount() > 0)
175 if (EVP_DigestUpdate(ctx, buffer,
static_cast<size_t>(file.gcount())) != 1)
177 EVP_MD_CTX_free(ctx);
182 unsigned char hash[EVP_MAX_MD_SIZE];
183 unsigned int hashLen = 0;
184 if (EVP_DigestFinal_ex(ctx, hash, &hashLen) != 1)
186 EVP_MD_CTX_free(ctx);
190 EVP_MD_CTX_free(ctx);
193 std::stringstream ss;
194 for (
unsigned int i = 0; i < hashLen; i++)
196 ss << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(hash[i]);
210 auto startTime = std::chrono::steady_clock::now();
212 fs::path fullPath = basePath / expected.
path;
218 std::error_code ec1, ec2;
219 fs::path canonical = fs::weakly_canonical(fullPath, ec1);
220 fs::path canonBase = fs::weakly_canonical(basePath, ec2);
225 Logger::error(
"[FileVerify] Rejected manifest path (canonicalization failed): {}",
229 std::error_code relEc;
230 fs::path rel = fs::relative(canonical, canonBase, relEc);
231 if (relEc || rel.empty() || *rel.begin() ==
"..")
234 Logger::error(
"[FileVerify] Rejected manifest path escaping base: {}", expected.
path);
241 std::error_code symEc;
242 fs::path resolved = fs::canonical(fullPath, symEc);
246 std::error_code relEc2;
247 fs::path rel2 = fs::relative(resolved, canonBase, relEc2);
248 if (relEc2 || rel2.empty() || *rel2.begin() ==
"..")
251 Logger::error(
"[FileVerify] Rejected manifest path (symlink escapes base): {}",
261 if (!fs::exists(fullPath, ec))
269 result.
actualSize =
static_cast<int64_t
>(fs::file_size(fullPath, ec));
280 auto endTime = std::chrono::steady_clock::now();
282 std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count());
310 auto endTime = std::chrono::steady_clock::now();
312 std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count());
322 const GameManifest& manifest,
const fs::path& gamePath,
const ProgressCallback& callback,
323 std::atomic<bool>& cancelled)
330 auto startTime = std::chrono::steady_clock::now();
333 for (
const auto& file : manifest.
files)
335 if (file.expectedSize > 0)
344 VerificationProgress progress;
352 for (
const auto& expected : manifest.
files)
354 if (cancelled.load())
359 auto fileResult =
verifyFile(gamePath, expected);
360 result.
files.push_back(fileResult);
363 switch (fileResult.status)
379 if (fileResult.actualSize > 0)
387 VerificationProgress progress;
403 if (!cancelled.load())
405 scanExtraFiles(result, manifest, gamePath);
408 auto endTime = std::chrono::steady_clock::now();
410 std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count());
416 VerificationProgress progress;
432 std::set<fs::path> expectedFiles;
433 for (
const auto& file : manifest.
files)
435 expectedFiles.insert(file.path);
440 for (
const auto& entry : fs::recursive_directory_iterator(gamePath, ec))
444 if (entry.is_symlink() || !entry.is_regular_file())
449 fs::path relativePath = fs::relative(entry.path(), gamePath);
450 if (expectedFiles.find(relativePath) == expectedFiles.end())
452 FileVerificationResult extraFile;
453 extraFile.
path = relativePath;
455 extraFile.
actualSize =
static_cast<int64_t
>(entry.file_size());
456 result.
files.push_back(extraFile);
462 Logger::error(
"[FileVerification] Directory traversal error scanning for extra files: {}",
468 const fs::path& gamePath,
471 Logger::info(
"[FileVerification] Starting verification for game: {}", gameId);
474 std::atomic<bool>* cancelledPtr;
476 std::lock_guard<std::mutex> lock(impl_->mutex);
477 impl_->cancelFlags[gameId].store(
false);
478 cancelledPtr = &impl_->cancelFlags[gameId];
480 auto& cancelled = *cancelledPtr;
483 if (progressCallback)
487 progressCallback(progress);
493 if (!manifest || !manifest->
isValid())
496 Logger::info(
"[FileVerification] No manifest found, generating size-only manifest");
504 if (progressCallback)
509 progressCallback(progress);
512 std::lock_guard<std::mutex> lock(impl_->mutex);
513 impl_->cancelFlags.erase(gameId);
520 auto result = verifyAgainstManifest(*manifest, gamePath, progressCallback, cancelled);
527 std::lock_guard<std::mutex> lock(impl_->mutex);
528 impl_->resultCache[gameId] = result;
529 impl_->cacheTime = std::chrono::system_clock::now();
530 impl_->cancelFlags.erase(gameId);
533 Logger::info(
"[FileVerification] Verification complete: {} valid, {} invalid, {} missing",
539std::future<GameVerificationResult>
543 return std::async(std::launch::async, [
this, gameId, gamePath, progressCallback]()
544 {
return verifyGame(gameId, gamePath, progressCallback); });
549 std::lock_guard<std::mutex> lock(impl_->mutex);
550 auto it = impl_->cancelFlags.find(gameId);
551 if (it != impl_->cancelFlags.end())
553 it->second.store(
true);
554 Logger::info(
"[FileVerification] Cancelled verification for: {}", gameId);
560 std::lock_guard<std::mutex> lock(impl_->mutex);
561 auto it = impl_->cancelFlags.find(gameId);
562 return it != impl_->cancelFlags.end() && !it->second.load();
573 std::string gameId =
"steam_" + std::to_string(appId);
574 Logger::info(
"[FileVerification] Verifying Steam game {} at {}", appId, gamePath.string());
579 if (manifest && manifest->
isValid())
584 std::atomic<bool>* cancelledPtr;
586 std::lock_guard<std::mutex> lock(impl_->mutex);
587 impl_->cancelFlags[gameId].store(
false);
588 cancelledPtr = &impl_->cancelFlags[gameId];
590 auto result = verifyAgainstManifest(*manifest, gamePath, progressCallback, *cancelledPtr);
592 std::lock_guard<std::mutex> lock(impl_->mutex);
593 impl_->cancelFlags.erase(gameId);
599 return verifyGame(gameId, gamePath, progressCallback);
606 const char* home = std::getenv(
"HOME");
612 fs::path steamDir = fs::path(home) /
".steam/steam/steamapps";
618 fs::path appManifest = steamDir / (
"appmanifest_" + std::to_string(appId) +
".acf");
619 if (!fs::exists(appManifest))
621 Logger::debug(
"[FileVerification] Steam app manifest not found: {}", appManifest.string());
629 Logger::debug(
"[FileVerification] Steam manifest parsing not fully implemented for app {}",
639 const fs::path& gamePath,
640 const std::string& checksumType,
646 manifest.
created = std::chrono::system_clock::now();
648 if (!fs::exists(gamePath) || !fs::is_directory(gamePath))
650 Logger::error(
"[FileVerification] Invalid game path: {}", gamePath.string());
656 int64_t totalBytes = 0;
659 for (
const auto& entry : fs::recursive_directory_iterator(gamePath, ec))
661 if (!entry.is_symlink() && entry.is_regular_file())
664 totalBytes +=
static_cast<int64_t
>(entry.file_size());
669 Logger::error(
"[FileVerification] Directory traversal error: {}", ec.message());
673 if (progressCallback)
679 progressCallback(progress);
683 int processedFiles = 0;
684 int64_t processedBytes = 0;
686 for (
const auto& entry : fs::recursive_directory_iterator(gamePath, ec))
690 if (entry.is_symlink() || !entry.is_regular_file())
696 file.
path = fs::relative(entry.path(), gamePath);
697 file.
expectedSize =
static_cast<int64_t
>(entry.file_size());
701 if (!checksumType.empty())
706 manifest.
files.push_back(file);
712 if (progressCallback)
721 progress.
percentComplete = totalFiles > 0 ? (processedFiles * 100) / totalFiles : 0;
722 progressCallback(progress);
727 Logger::error(
"[FileVerification] Directory traversal error during scan: {}", ec.message());
730 Logger::info(
"[FileVerification] Generated manifest with {} files for {}",
731 manifest.
files.size(), gameId);
741 j[
"gameId"] = manifest.
gameId;
742 j[
"version"] = manifest.
version;
745 std::chrono::duration_cast<std::chrono::seconds>(manifest.
created.time_since_epoch())
748 json filesArray = json::array();
749 for (
const auto& file : manifest.
files)
752 fileObj[
"path"] = file.path.string();
753 fileObj[
"size"] = file.expectedSize;
754 if (!file.expectedChecksum.empty())
756 fileObj[
"checksum"] = file.expectedChecksum;
757 fileObj[
"checksumType"] = file.checksumType;
759 filesArray.push_back(fileObj);
761 j[
"files"] = filesArray;
764 fs::create_directories(path.parent_path());
766 std::ofstream file(path);
769 Logger::error(
"[FileVerification] Failed to open manifest for writing: {}",
775 Logger::info(
"[FileVerification] Saved manifest to: {}", path.string());
778 catch (
const std::exception& e)
780 Logger::error(
"[FileVerification] Failed to save manifest: {}", e.what());
789 if (!fs::exists(path))
794 std::ifstream file(path);
800 json j = json::parse(file);
803 manifest.
gameId = j.value(
"gameId",
"");
804 manifest.
version = j.value(
"version",
"");
807 if (j.contains(
"created"))
809 int64_t created = j[
"created"].get<int64_t>();
810 manifest.
created = std::chrono::system_clock::time_point(std::chrono::seconds(created));
813 if (j.contains(
"files") && j[
"files"].is_array())
815 for (
const auto& fileObj : j[
"files"])
818 fileResult.
path = fileObj.value(
"path",
"");
822 manifest.
files.push_back(fileResult);
826 Logger::info(
"[FileVerification] Loaded manifest from: {} ({} files)", path.string(),
827 manifest.
files.size());
830 catch (
const std::exception& e)
832 Logger::error(
"[FileVerification] Failed to load manifest: {}", e.what());
839 return impl_->manifestDir / (gameId +
".manifest.json");
846std::optional<GameVerificationResult>
849 std::lock_guard<std::mutex> lock(impl_->mutex);
851 auto it = impl_->resultCache.find(gameId);
852 if (it == impl_->resultCache.end())
858 auto now = std::chrono::system_clock::now();
859 auto age = std::chrono::duration_cast<std::chrono::seconds>(now - it->second.verificationTime);
861 if (age.count() > impl_->cacheValiditySeconds)
871 std::lock_guard<std::mutex> lock(impl_->mutex);
875 impl_->resultCache.clear();
876 Logger::info(
"[FileVerification] Cleared all verification cache");
880 impl_->resultCache.erase(gameId);
881 Logger::info(
"[FileVerification] Cleared verification cache for: {}", gameId);
887 std::lock_guard<std::mutex> lock(impl_->mutex);
888 impl_->cacheValiditySeconds = seconds;
GameVerificationResult verifySteamGame(uint32_t appId, const std::filesystem::path &gamePath, const ProgressCallback &progressCallback=nullptr)
Verify a Steam game using depot manifests.
GameVerificationResult verifyGame(const std::string &gameId, const std::filesystem::path &gamePath, const ProgressCallback &progressCallback=nullptr)
Verify a game's file integrity.
static std::string calculateChecksum(const std::filesystem::path &path, const std::string &type)
Calculate checksum of a file.
std::function< void(const VerificationProgress &)> ProgressCallback
bool isVerifying(const std::string &gameId) const
Check if verification is in progress.
void clearCache(const std::string &gameId="")
Clear verification cache.
FileVerificationService()
std::optional< GameManifest > loadSteamManifest(uint32_t appId, uint32_t depotId=0)
Load Steam depot manifest for a game.
std::optional< GameVerificationResult > getCachedResult(const std::string &gameId) const
Get cached verification result.
std::optional< GameManifest > loadManifest(const std::filesystem::path &path)
Load a manifest from file.
void setCacheValidity(int seconds)
Set cache validity duration.
std::filesystem::path getManifestPath(const std::string &gameId) const
Get default manifest path for a game.
std::future< GameVerificationResult > verifyGameAsync(const std::string &gameId, const std::filesystem::path &gamePath, const ProgressCallback &progressCallback=nullptr)
Verify a game asynchronously.
void cancelVerification(const std::string &gameId)
Cancel an ongoing verification.
bool saveManifest(const GameManifest &manifest, const std::filesystem::path &path)
Save a manifest to file.
~FileVerificationService()
GameManifest generateManifest(const std::string &gameId, const std::filesystem::path &gamePath, const std::string &checksumType="sha256", const ProgressCallback &progressCallback=nullptr)
Generate a manifest for a game installation.
FileVerificationResult verifyFile(const std::filesystem::path &basePath, const FileVerificationResult &expected)
Verify a single file.
static void info(const std::string &message, Args &&... args)
Log info message (general information).
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
std::string verificationStatusName(VerificationStatus status)
Get human-readable name for verification status.
VerificationStatus
Status of a file verification check.
@ Missing
File doesn't exist.
@ Valid
File matches expected checksum/size.
@ Invalid
File doesn't match (corrupted or modified).
@ Repairable
Invalid but can be repaired.
@ ExtraFile
File exists but not in manifest.
@ SizeMismatch
File exists but wrong size.
@ Unknown
Not yet verified.
@ Skipped
Verification was skipped.
Result of verifying a single file.
VerificationStatus status
std::string actualChecksum
std::string expectedChecksum
std::string checksumType
"md5", "sha1", "sha256"
std::filesystem::path path
File path (relative to game root).
std::chrono::system_clock::time_point cacheTime
std::map< std::string, GameVerificationResult > resultCache
std::map< std::string, std::atomic< bool > > cancelFlags
Manifest file containing expected file checksums.
std::chrono::system_clock::time_point created
std::vector< FileVerificationResult > files
std::string checksumType
Default checksum type for files.
Complete verification result for a game.
std::vector< FileVerificationResult > files
std::chrono::system_clock::time_point verificationTime
std::filesystem::path gamePath
Progress information during verification.
std::string getStateStr() const