game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
file_verification_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// file_verification_service.cpp
4// ==============================================================================
5// Implementation of game file verification service
6// ==============================================================================
7
9#include "logger.h"
10
11#include <algorithm>
12#include <atomic>
13#include <cstring>
14#include <fstream>
15#include <iomanip>
16#include <map>
17#include <mutex>
18#include <nlohmann/json.hpp>
19#include <openssl/evp.h>
20#include <openssl/md5.h>
21#include <openssl/sha.h>
22#include <set>
23#include <sstream>
24#include <thread>
25
26using json = nlohmann::json;
27namespace fs = std::filesystem;
28
29// ==============================================================================
30// Helper Functions
31// ==============================================================================
32
34{
35 switch (status)
36 {
38 return "Unknown";
40 return "Valid";
42 return "Invalid";
44 return "Missing";
46 return "Size Mismatch";
48 return "Extra File";
50 return "Repairable";
52 return "Skipped";
53 default:
54 return "Unknown";
55 }
56}
57
59{
60 switch (state)
61 {
62 case State::Starting:
63 return "Starting";
65 return "Loading Manifest";
67 return "Verifying Files";
69 return "Completed";
70 case State::Failed:
71 return "Failed";
73 return "Cancelled";
74 default:
75 return "Unknown";
76 }
77}
78
79// ==============================================================================
80// Implementation Details
81// ==============================================================================
82
84{
85 mutable std::mutex mutex;
86 std::map<std::string, std::atomic<bool>> cancelFlags;
87 std::map<std::string, GameVerificationResult> resultCache;
88 std::chrono::system_clock::time_point cacheTime;
89 int cacheValiditySeconds = 3600; // 1 hour default
90
91 fs::path manifestDir;
92
94 {
95 // Default manifest directory
96 const char* home = std::getenv("HOME");
97 if (home)
98 {
99 manifestDir = fs::path(home) / ".local/share/gamelauncher/manifests";
100 }
101 }
102};
103
104// ==============================================================================
105// Constructor/Destructor
106// ==============================================================================
107
109{
110 // Create manifest directory if it doesn't exist
111 if (!impl_->manifestDir.empty())
112 {
113 std::error_code ec;
114 fs::create_directories(impl_->manifestDir, ec);
115 }
116}
117
119{
120 // Cancel any ongoing verifications
121 for (auto& [gameId, flag] : impl_->cancelFlags)
122 {
123 flag.store(true);
124 }
125}
126
127// ==============================================================================
128// Checksum Calculation
129// ==============================================================================
130
131std::string FileVerificationService::calculateChecksum(const fs::path& path,
132 const std::string& type)
133{
134 std::ifstream file(path, std::ios::binary);
135 if (!file.is_open())
136 {
137 return "";
138 }
139
140 EVP_MD_CTX* ctx = EVP_MD_CTX_new();
141 if (!ctx)
142 {
143 return "";
144 }
145
146 const EVP_MD* md = nullptr;
147 if (type == "md5")
148 {
149 md = EVP_md5();
150 }
151 else if (type == "sha1")
152 {
153 md = EVP_sha1();
154 }
155 else if (type == "sha256")
156 {
157 md = EVP_sha256();
158 }
159 else
160 {
161 EVP_MD_CTX_free(ctx);
162 Logger::error("[FileVerification] Unknown checksum type: {}", type);
163 return "";
164 }
165
166 if (EVP_DigestInit_ex(ctx, md, nullptr) != 1)
167 {
168 EVP_MD_CTX_free(ctx);
169 return "";
170 }
171
172 char buffer[65536]; // 64KB buffer for efficiency
173 while (file.read(buffer, sizeof(buffer)) || file.gcount() > 0)
174 {
175 if (EVP_DigestUpdate(ctx, buffer, static_cast<size_t>(file.gcount())) != 1)
176 {
177 EVP_MD_CTX_free(ctx);
178 return "";
179 }
180 }
181
182 unsigned char hash[EVP_MAX_MD_SIZE];
183 unsigned int hashLen = 0;
184 if (EVP_DigestFinal_ex(ctx, hash, &hashLen) != 1)
185 {
186 EVP_MD_CTX_free(ctx);
187 return "";
188 }
189
190 EVP_MD_CTX_free(ctx);
191
192 // Convert to hex string
193 std::stringstream ss;
194 for (unsigned int i = 0; i < hashLen; i++)
195 {
196 ss << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(hash[i]);
197 }
198
199 return ss.str();
200}
201
202// ==============================================================================
203// File Verification
204// ==============================================================================
205
207 const FileVerificationResult& expected)
208{
209 FileVerificationResult result = expected;
210 auto startTime = std::chrono::steady_clock::now();
211
212 fs::path fullPath = basePath / expected.path;
213
214 // Reject manifest paths that escape the base directory (path traversal).
215 // Use separate error codes — sharing one variable causes the second call to
216 // clear the first call's error, masking a failed canonicalization.
217 {
218 std::error_code ec1, ec2;
219 fs::path canonical = fs::weakly_canonical(fullPath, ec1);
220 fs::path canonBase = fs::weakly_canonical(basePath, ec2);
221 if (ec1 || ec2)
222 {
223 // Cannot verify containment — reject to be safe
225 Logger::error("[FileVerify] Rejected manifest path (canonicalization failed): {}",
226 expected.path);
227 return result;
228 }
229 std::error_code relEc;
230 fs::path rel = fs::relative(canonical, canonBase, relEc);
231 if (relEc || rel.empty() || *rel.begin() == "..")
232 {
234 Logger::error("[FileVerify] Rejected manifest path escaping base: {}", expected.path);
235 return result;
236 }
237
238 // weakly_canonical() does not resolve symlinks, so a symlink within the
239 // game directory pointing outside would pass the relative-path check above.
240 // Resolve fully and re-check if the file actually exists.
241 std::error_code symEc;
242 fs::path resolved = fs::canonical(fullPath, symEc);
243 if (!symEc)
244 {
245 // File exists — verify its resolved (symlink-free) path is still inside base
246 std::error_code relEc2;
247 fs::path rel2 = fs::relative(resolved, canonBase, relEc2);
248 if (relEc2 || rel2.empty() || *rel2.begin() == "..")
249 {
251 Logger::error("[FileVerify] Rejected manifest path (symlink escapes base): {}",
252 expected.path);
253 return result;
254 }
255 }
256 // If symEc is set the file doesn't exist; the Missing check below handles it.
257 }
258
259 // Check if file exists
260 std::error_code ec;
261 if (!fs::exists(fullPath, ec))
262 {
264 result.actualSize = -1;
265 return result;
266 }
267
268 // Get actual file size
269 result.actualSize = static_cast<int64_t>(fs::file_size(fullPath, ec));
270 if (ec)
271 {
273 return result;
274 }
275
276 // Check size first (faster than checksum)
277 if (expected.expectedSize >= 0 && result.actualSize != expected.expectedSize)
278 {
280 auto endTime = std::chrono::steady_clock::now();
281 result.verificationTimeMs = static_cast<int>(
282 std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count());
283 return result;
284 }
285
286 // Calculate checksum if expected
287 if (!expected.expectedChecksum.empty() && !expected.checksumType.empty())
288 {
289 result.actualChecksum = calculateChecksum(fullPath, expected.checksumType);
290
291 if (result.actualChecksum.empty())
292 {
294 }
295 else if (result.actualChecksum == expected.expectedChecksum)
296 {
298 }
299 else
300 {
302 }
303 }
304 else
305 {
306 // No checksum to verify, size was correct
308 }
309
310 auto endTime = std::chrono::steady_clock::now();
311 result.verificationTimeMs = static_cast<int>(
312 std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count());
313
314 return result;
315}
316
317// ==============================================================================
318// Game Verification
319// ==============================================================================
320
321GameVerificationResult FileVerificationService::verifyAgainstManifest(
322 const GameManifest& manifest, const fs::path& gamePath, const ProgressCallback& callback,
323 std::atomic<bool>& cancelled)
324{
326 result.gameId = manifest.gameId;
327 result.gamePath = gamePath;
328 result.totalFiles = static_cast<int>(manifest.files.size());
329
330 auto startTime = std::chrono::steady_clock::now();
331
332 // Calculate total bytes
333 for (const auto& file : manifest.files)
334 {
335 if (file.expectedSize > 0)
336 {
337 result.totalBytes += file.expectedSize;
338 }
339 }
340
341 // Report starting
342 if (callback)
343 {
344 VerificationProgress progress;
346 progress.totalFiles = result.totalFiles;
347 progress.totalBytes = result.totalBytes;
348 callback(progress);
349 }
350
351 // Verify each file
352 for (const auto& expected : manifest.files)
353 {
354 if (cancelled.load())
355 {
356 break;
357 }
358
359 auto fileResult = verifyFile(gamePath, expected);
360 result.files.push_back(fileResult);
361
362 // Update statistics
363 switch (fileResult.status)
364 {
366 result.validFiles++;
367 break;
370 result.invalidFiles++;
371 break;
373 result.missingFiles++;
374 break;
375 default:
376 break;
377 }
378
379 if (fileResult.actualSize > 0)
380 {
381 result.verifiedBytes += fileResult.actualSize;
382 }
383
384 // Report progress
385 if (callback)
386 {
387 VerificationProgress progress;
389 progress.currentFile = expected.path.string();
390 progress.filesProcessed = static_cast<int>(result.files.size());
391 progress.totalFiles = result.totalFiles;
392 progress.bytesProcessed = result.verifiedBytes;
393 progress.totalBytes = result.totalBytes;
394 progress.percentComplete =
395 result.totalFiles > 0 ? static_cast<int>((result.files.size() * 100) /
396 static_cast<size_t>(result.totalFiles))
397 : 0;
398 callback(progress);
399 }
400 }
401
402 // Scan for extra files if verification wasn't cancelled
403 if (!cancelled.load())
404 {
405 scanExtraFiles(result, manifest, gamePath);
406 }
407
408 auto endTime = std::chrono::steady_clock::now();
409 result.totalTimeMs = static_cast<int>(
410 std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count());
411 result.verificationTime = std::chrono::system_clock::now();
412
413 // Report completion
414 if (callback)
415 {
416 VerificationProgress progress;
417 progress.state = cancelled.load() ? VerificationProgress::State::Cancelled
419 progress.filesProcessed = static_cast<int>(result.files.size());
420 progress.totalFiles = result.totalFiles;
421 progress.percentComplete = 100;
422 callback(progress);
423 }
424
425 return result;
426}
427
428void FileVerificationService::scanExtraFiles(GameVerificationResult& result,
429 const GameManifest& manifest, const fs::path& gamePath)
430{
431 // Build set of expected files for fast lookup
432 std::set<fs::path> expectedFiles;
433 for (const auto& file : manifest.files)
434 {
435 expectedFiles.insert(file.path);
436 }
437
438 // Scan game directory for extra files
439 std::error_code ec;
440 for (const auto& entry : fs::recursive_directory_iterator(gamePath, ec))
441 {
442 // Skip symlinks: is_regular_file() returns true for symlinks-to-files,
443 // which would cause symlinks outside the tree to be counted.
444 if (entry.is_symlink() || !entry.is_regular_file())
445 {
446 continue;
447 }
448
449 fs::path relativePath = fs::relative(entry.path(), gamePath);
450 if (expectedFiles.find(relativePath) == expectedFiles.end())
451 {
452 FileVerificationResult extraFile;
453 extraFile.path = relativePath;
455 extraFile.actualSize = static_cast<int64_t>(entry.file_size());
456 result.files.push_back(extraFile);
457 result.extraFiles++;
458 }
459 }
460 if (ec)
461 {
462 Logger::error("[FileVerification] Directory traversal error scanning for extra files: {}",
463 ec.message());
464 }
465}
466
468 const fs::path& gamePath,
469 const ProgressCallback& progressCallback)
470{
471 Logger::info("[FileVerification] Starting verification for game: {}", gameId);
472
473 // Set up cancel flag (mutex protects map structure; atomic protects the flag value)
474 std::atomic<bool>* cancelledPtr;
475 {
476 std::lock_guard<std::mutex> lock(impl_->mutex);
477 impl_->cancelFlags[gameId].store(false);
478 cancelledPtr = &impl_->cancelFlags[gameId];
479 }
480 auto& cancelled = *cancelledPtr;
481
482 // Report loading manifest
483 if (progressCallback)
484 {
485 VerificationProgress progress;
487 progressCallback(progress);
488 }
489
490 // Try to load existing manifest
491 auto manifest = loadManifest(getManifestPath(gameId));
492
493 if (!manifest || !manifest->isValid())
494 {
495 // No manifest - generate one on the fly (size-only verification)
496 Logger::info("[FileVerification] No manifest found, generating size-only manifest");
497
498 manifest = generateManifest(gameId, gamePath, "", progressCallback);
499 if (!manifest->isValid())
500 {
502 result.gameId = gameId;
503 result.gamePath = gamePath;
504 if (progressCallback)
505 {
506 VerificationProgress progress;
508 progress.errorMessage = "Failed to generate manifest";
509 progressCallback(progress);
510 }
511 {
512 std::lock_guard<std::mutex> lock(impl_->mutex);
513 impl_->cancelFlags.erase(gameId);
514 }
515 return result;
516 }
517 }
518
519 // Verify against manifest
520 auto result = verifyAgainstManifest(*manifest, gamePath, progressCallback, cancelled);
521 result.gameName = gameId; // Set from game data if available
522
523 // Cache result and remove the cancel flag so isVerifying() returns false.
524 // The entry is created at the start of verifyGame(); leaving it in place
525 // would make isVerifying() return true forever for completed verifications.
526 {
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);
531 }
532
533 Logger::info("[FileVerification] Verification complete: {} valid, {} invalid, {} missing",
534 result.validFiles, result.invalidFiles, result.missingFiles);
535
536 return result;
537}
538
539std::future<GameVerificationResult>
540FileVerificationService::verifyGameAsync(const std::string& gameId, const fs::path& gamePath,
541 const ProgressCallback& progressCallback)
542{
543 return std::async(std::launch::async, [this, gameId, gamePath, progressCallback]()
544 { return verifyGame(gameId, gamePath, progressCallback); });
545}
546
547void FileVerificationService::cancelVerification(const std::string& gameId)
548{
549 std::lock_guard<std::mutex> lock(impl_->mutex);
550 auto it = impl_->cancelFlags.find(gameId);
551 if (it != impl_->cancelFlags.end())
552 {
553 it->second.store(true);
554 Logger::info("[FileVerification] Cancelled verification for: {}", gameId);
555 }
556}
557
558bool FileVerificationService::isVerifying(const std::string& gameId) const
559{
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();
563}
564
565// ==============================================================================
566// Steam Integration
567// ==============================================================================
568
570FileVerificationService::verifySteamGame(uint32_t appId, const fs::path& gamePath,
571 const ProgressCallback& progressCallback)
572{
573 std::string gameId = "steam_" + std::to_string(appId);
574 Logger::info("[FileVerification] Verifying Steam game {} at {}", appId, gamePath.string());
575
576 // Try to load Steam manifest
577 auto manifest = loadSteamManifest(appId);
578
579 if (manifest && manifest->isValid())
580 {
581 // Take the cancel flag's address under the lock (std::map has stable node addresses).
582 // Using the pointer outside the lock is safe because the atomic itself is always valid
583 // as long as the gameId entry exists, and we never erase entries mid-operation.
584 std::atomic<bool>* cancelledPtr;
585 {
586 std::lock_guard<std::mutex> lock(impl_->mutex);
587 impl_->cancelFlags[gameId].store(false);
588 cancelledPtr = &impl_->cancelFlags[gameId];
589 }
590 auto result = verifyAgainstManifest(*manifest, gamePath, progressCallback, *cancelledPtr);
591 {
592 std::lock_guard<std::mutex> lock(impl_->mutex);
593 impl_->cancelFlags.erase(gameId);
594 }
595 return result;
596 }
597
598 // Fall back to regular verification
599 return verifyGame(gameId, gamePath, progressCallback);
600}
601
602std::optional<GameManifest> FileVerificationService::loadSteamManifest(uint32_t appId,
603 uint32_t /*depotId*/)
604{
605 // Steam manifests are located in steamapps
606 const char* home = std::getenv("HOME");
607 if (!home)
608 {
609 return std::nullopt;
610 }
611
612 fs::path steamDir = fs::path(home) / ".steam/steam/steamapps";
613
614 // Look for depot manifest files
615 // Format: depotcache/XXXXX_XXXXX.manifest
616 // or appmanifest_XXXXX.acf for basic info
617
618 fs::path appManifest = steamDir / ("appmanifest_" + std::to_string(appId) + ".acf");
619 if (!fs::exists(appManifest))
620 {
621 Logger::debug("[FileVerification] Steam app manifest not found: {}", appManifest.string());
622 return std::nullopt;
623 }
624
625 // Parse ACF file to get installed depots
626 // For now, return empty - full Steam manifest parsing is complex
627 // Users can generate their own manifests
628
629 Logger::debug("[FileVerification] Steam manifest parsing not fully implemented for app {}",
630 appId);
631 return std::nullopt;
632}
633
634// ==============================================================================
635// Manifest Management
636// ==============================================================================
637
639 const fs::path& gamePath,
640 const std::string& checksumType,
641 const ProgressCallback& progressCallback)
642{
643 GameManifest manifest;
644 manifest.gameId = gameId;
645 manifest.checksumType = checksumType;
646 manifest.created = std::chrono::system_clock::now();
647
648 if (!fs::exists(gamePath) || !fs::is_directory(gamePath))
649 {
650 Logger::error("[FileVerification] Invalid game path: {}", gamePath.string());
651 return manifest;
652 }
653
654 // Count files first for progress reporting
655 int totalFiles = 0;
656 int64_t totalBytes = 0;
657 std::error_code ec;
658
659 for (const auto& entry : fs::recursive_directory_iterator(gamePath, ec))
660 {
661 if (!entry.is_symlink() && entry.is_regular_file())
662 {
663 totalFiles++;
664 totalBytes += static_cast<int64_t>(entry.file_size());
665 }
666 }
667 if (ec)
668 {
669 Logger::error("[FileVerification] Directory traversal error: {}", ec.message());
670 }
671
672 // Report starting
673 if (progressCallback)
674 {
675 VerificationProgress progress;
677 progress.totalFiles = totalFiles;
678 progress.totalBytes = totalBytes;
679 progressCallback(progress);
680 }
681
682 // Scan all files
683 int processedFiles = 0;
684 int64_t processedBytes = 0;
685
686 for (const auto& entry : fs::recursive_directory_iterator(gamePath, ec))
687 {
688 // Skip symlinks: is_regular_file() returns true for symlinks-to-files;
689 // checksumming them would read an external target rather than a game file.
690 if (entry.is_symlink() || !entry.is_regular_file())
691 {
692 continue;
693 }
694
696 file.path = fs::relative(entry.path(), gamePath);
697 file.expectedSize = static_cast<int64_t>(entry.file_size());
698 file.checksumType = checksumType;
699
700 // Calculate checksum if requested
701 if (!checksumType.empty())
702 {
703 file.expectedChecksum = calculateChecksum(entry.path(), checksumType);
704 }
705
706 manifest.files.push_back(file);
707
708 processedFiles++;
709 processedBytes += file.expectedSize;
710
711 // Report progress
712 if (progressCallback)
713 {
714 VerificationProgress progress;
716 progress.currentFile = file.path.string();
717 progress.filesProcessed = processedFiles;
718 progress.totalFiles = totalFiles;
719 progress.bytesProcessed = processedBytes;
720 progress.totalBytes = totalBytes;
721 progress.percentComplete = totalFiles > 0 ? (processedFiles * 100) / totalFiles : 0;
722 progressCallback(progress);
723 }
724 }
725 if (ec)
726 {
727 Logger::error("[FileVerification] Directory traversal error during scan: {}", ec.message());
728 }
729
730 Logger::info("[FileVerification] Generated manifest with {} files for {}",
731 manifest.files.size(), gameId);
732
733 return manifest;
734}
735
736bool FileVerificationService::saveManifest(const GameManifest& manifest, const fs::path& path)
737{
738 try
739 {
740 json j;
741 j["gameId"] = manifest.gameId;
742 j["version"] = manifest.version;
743 j["checksumType"] = manifest.checksumType;
744 j["created"] =
745 std::chrono::duration_cast<std::chrono::seconds>(manifest.created.time_since_epoch())
746 .count();
747
748 json filesArray = json::array();
749 for (const auto& file : manifest.files)
750 {
751 json fileObj;
752 fileObj["path"] = file.path.string();
753 fileObj["size"] = file.expectedSize;
754 if (!file.expectedChecksum.empty())
755 {
756 fileObj["checksum"] = file.expectedChecksum;
757 fileObj["checksumType"] = file.checksumType;
758 }
759 filesArray.push_back(fileObj);
760 }
761 j["files"] = filesArray;
762
763 // Ensure directory exists
764 fs::create_directories(path.parent_path());
765
766 std::ofstream file(path);
767 if (!file.is_open())
768 {
769 Logger::error("[FileVerification] Failed to open manifest for writing: {}",
770 path.string());
771 return false;
772 }
773
774 file << j.dump(2);
775 Logger::info("[FileVerification] Saved manifest to: {}", path.string());
776 return true;
777 }
778 catch (const std::exception& e)
779 {
780 Logger::error("[FileVerification] Failed to save manifest: {}", e.what());
781 return false;
782 }
783}
784
785std::optional<GameManifest> FileVerificationService::loadManifest(const fs::path& path)
786{
787 try
788 {
789 if (!fs::exists(path))
790 {
791 return std::nullopt;
792 }
793
794 std::ifstream file(path);
795 if (!file.is_open())
796 {
797 return std::nullopt;
798 }
799
800 json j = json::parse(file);
801
802 GameManifest manifest;
803 manifest.gameId = j.value("gameId", "");
804 manifest.version = j.value("version", "");
805 manifest.checksumType = j.value("checksumType", "");
806
807 if (j.contains("created"))
808 {
809 int64_t created = j["created"].get<int64_t>();
810 manifest.created = std::chrono::system_clock::time_point(std::chrono::seconds(created));
811 }
812
813 if (j.contains("files") && j["files"].is_array())
814 {
815 for (const auto& fileObj : j["files"])
816 {
817 FileVerificationResult fileResult;
818 fileResult.path = fileObj.value("path", "");
819 fileResult.expectedSize = fileObj.value("size", -1);
820 fileResult.expectedChecksum = fileObj.value("checksum", "");
821 fileResult.checksumType = fileObj.value("checksumType", manifest.checksumType);
822 manifest.files.push_back(fileResult);
823 }
824 }
825
826 Logger::info("[FileVerification] Loaded manifest from: {} ({} files)", path.string(),
827 manifest.files.size());
828 return manifest;
829 }
830 catch (const std::exception& e)
831 {
832 Logger::error("[FileVerification] Failed to load manifest: {}", e.what());
833 return std::nullopt;
834 }
835}
836
837fs::path FileVerificationService::getManifestPath(const std::string& gameId) const
838{
839 return impl_->manifestDir / (gameId + ".manifest.json");
840}
841
842// ==============================================================================
843// Cache Management
844// ==============================================================================
845
846std::optional<GameVerificationResult>
847FileVerificationService::getCachedResult(const std::string& gameId) const
848{
849 std::lock_guard<std::mutex> lock(impl_->mutex);
850
851 auto it = impl_->resultCache.find(gameId);
852 if (it == impl_->resultCache.end())
853 {
854 return std::nullopt;
855 }
856
857 // Check if cache is still valid
858 auto now = std::chrono::system_clock::now();
859 auto age = std::chrono::duration_cast<std::chrono::seconds>(now - it->second.verificationTime);
860
861 if (age.count() > impl_->cacheValiditySeconds)
862 {
863 return std::nullopt;
864 }
865
866 return it->second;
867}
868
869void FileVerificationService::clearCache(const std::string& gameId)
870{
871 std::lock_guard<std::mutex> lock(impl_->mutex);
872
873 if (gameId.empty())
874 {
875 impl_->resultCache.clear();
876 Logger::info("[FileVerification] Cleared all verification cache");
877 }
878 else
879 {
880 impl_->resultCache.erase(gameId);
881 Logger::info("[FileVerification] Cleared verification cache for: {}", gameId);
882 }
883}
884
886{
887 std::lock_guard<std::mutex> lock(impl_->mutex);
888 impl_->cacheValiditySeconds = seconds;
889}
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.
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.
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).
Definition logger.h:108
static void debug(const std::string &message, Args &&... args)
Log debug message (verbose development info).
Definition logger.h:100
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
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.
@ Skipped
Verification was skipped.
nlohmann::json json
Result of verifying a single file.
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
Progress information during verification.