game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
prefix_snapshot_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// prefix_snapshot_service.cpp
4// ==============================================================================
5// Implementation of Wine prefix snapshot service
6// ==============================================================================
7
9#include "file_handle.h"
10#include "logger.h"
11#include "shell_utils.h"
12
13#include <atomic>
14#include <chrono>
15#include <ctime>
16#include <fstream>
17#include <iomanip>
18#include <map>
19#include <mutex>
20#include <nlohmann/json.hpp>
21#include <random>
22#include <set>
23#include <sstream>
24#include <sys/wait.h>
25#include <utility>
26
27using json = nlohmann::json;
28namespace fs = std::filesystem;
29
30// ==============================================================================
31// Helper Functions
32// ==============================================================================
33
35{
36 if (sizeBytes < 1024)
37 return std::to_string(sizeBytes) + " B";
38 if (sizeBytes < 1024 * 1024)
39 return std::to_string(sizeBytes / 1024) + " KB";
40 if (sizeBytes < 1024LL * 1024 * 1024)
41 return std::to_string(sizeBytes / (1024 * 1024)) + " MB";
42 return std::to_string(sizeBytes / (1024LL * 1024 * 1024)) + " GB";
43}
44
46{
47 auto time = std::chrono::system_clock::to_time_t(created);
48 std::tm tm{};
49 localtime_r(&time, &tm);
50 std::stringstream ss;
51 ss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
52 return ss.str();
53}
54
56{
57 switch (state)
58 {
59 case State::Starting:
60 return "Starting";
61 case State::Scanning:
62 return "Scanning";
63 case State::Copying:
64 return "Copying";
66 return "Compressing";
68 return "Completed";
69 case State::Failed:
70 return "Failed";
72 return "Cancelled";
73 default:
74 return "Unknown";
75 }
76}
77
78// ==============================================================================
79// Implementation Details
80// ==============================================================================
81
83{
84 mutable std::mutex mutex;
85
86 // Per-operation cancellation: each async operation holds a shared_ptr<atomic<bool>>.
87 // cancelOperation() sets all live tokens. Expired weak_ptrs are cleaned up lazily.
88 std::mutex cancelMutex;
89 std::vector<std::weak_ptr<std::atomic<bool>>> activeCancelFlags;
90
91 fs::path snapshotDir;
92 std::map<std::string, PrefixSnapshot> snapshots;
93 bool compressionEnabled = true;
94 int64_t maxStorageBytes = 0; // 0 = unlimited
95
97 {
98 const char* home = std::getenv("HOME");
99 if (home)
100 {
101 snapshotDir = fs::path(home) / ".local/share/gamelauncher/snapshots";
102 }
103 }
104};
105
106// ==============================================================================
107// Constructor/Destructor
108// ==============================================================================
109
111{
112 // Create snapshot directory
113 std::error_code ec;
114 if (!impl_->snapshotDir.empty())
115 {
116 fs::create_directories(impl_->snapshotDir, ec);
117 if (ec)
118 {
119 Logger::error("[PrefixSnapshot] Failed to create snapshot directory {}: {}",
120 impl_->snapshotDir.string(), ec.message());
121 }
122 }
123
124 // Load existing snapshot index
125 loadSnapshotIndex();
126}
127
132
133// ==============================================================================
134// Internal Helpers
135// ==============================================================================
136
137std::string PrefixSnapshotService::generateSnapshotId() const
138{
139 // Generate unique ID: timestamp + random suffix
140 auto now = std::chrono::system_clock::now();
141 auto timestamp =
142 std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
143
144 std::random_device rd;
145 std::mt19937 gen(rd());
146 std::uniform_int_distribution<> dis(1000, 9999);
147
148 std::stringstream ss;
149 ss << "snap_" << timestamp << "_" << dis(gen);
150 return ss.str();
151}
152
153std::string PrefixSnapshotService::detectWineVersion(const fs::path& prefixPath) const
154{
155 // Check system.reg for Wine version info
156 fs::path systemReg = prefixPath / "system.reg";
157 if (!fs::exists(systemReg))
158 {
159 return "unknown";
160 }
161
162 std::ifstream file(systemReg);
163 std::string line;
164 while (std::getline(file, line))
165 {
166 // Look for Wine version string
167 if (line.find("\"ProductName\"") != std::string::npos)
168 {
169 auto pos = line.find("Wine");
170 if (pos != std::string::npos)
171 {
172 // Extract version
173 return line.substr(pos);
174 }
175 }
176 }
177
178 return "unknown";
179}
180
181std::string PrefixSnapshotService::detectArchitecture(const fs::path& prefixPath) const
182{
183 // Check for win64 directory structure
184 if (fs::exists(prefixPath / "drive_c/windows/syswow64"))
185 {
186 return "win64";
187 }
188 return "win32";
189}
190
191void PrefixSnapshotService::loadSnapshotIndex()
192{
193 fs::path indexPath = impl_->snapshotDir / "index.json";
194
195 if (!fs::exists(indexPath))
196 {
197 return;
198 }
199
200 try
201 {
202 std::ifstream file(indexPath);
203 json j = json::parse(file);
204
205 for (const auto& item : j["snapshots"])
206 {
207 PrefixSnapshot snap;
208 snap.id = item.value("id", "");
209 snap.name = item.value("name", "");
210 snap.description = item.value("description", "");
211 snap.prefixPath = item.value("prefixPath", "");
212 snap.snapshotPath = item.value("snapshotPath", "");
213
214 // Validate snapshotPath is inside the managed snapshot directory
215 if (!snap.snapshotPath.empty())
216 {
217 std::error_code ec;
218 fs::path canonical = fs::weakly_canonical(snap.snapshotPath, ec);
219 if (ec || canonical.empty())
220 {
221 Logger::error("[PrefixSnapshot] Rejected snapshot '{}': invalid path '{}'",
222 snap.id, snap.snapshotPath);
223 continue;
224 }
225 fs::path rel = fs::relative(canonical, impl_->snapshotDir, ec);
226 if (ec || rel.empty() || *rel.begin() == "..")
227 {
228 Logger::error("[PrefixSnapshot] Rejected snapshot '{}': path '{}' is outside "
229 "snapshot directory",
230 snap.id, snap.snapshotPath);
231 continue;
232 }
233
234 // Skip if snapshot directory was deleted from disk
235 if (!fs::exists(snap.snapshotPath))
236 {
238 "[PrefixSnapshot] Skipping snapshot '{}': directory no longer exists",
239 snap.id);
240 continue;
241 }
242 }
243
244 snap.sizeBytes = item.value("sizeBytes", 0);
245 snap.fileCount = item.value("fileCount", 0);
246 snap.isIncremental = item.value("isIncremental", false);
247 snap.parentSnapshotId = item.value("parentSnapshotId", "");
248 snap.gameId = item.value("gameId", "");
249 snap.gameName = item.value("gameName", "");
250 snap.wineVersion = item.value("wineVersion", "");
251 snap.architecture = item.value("architecture", "");
252
253 if (item.contains("created"))
254 {
255 snap.created = std::chrono::system_clock::time_point(
256 std::chrono::seconds(item["created"].get<int64_t>()));
257 }
258
259 impl_->snapshots[snap.id] = snap;
260 }
261
262 Logger::info("[PrefixSnapshot] Loaded {} snapshots from index", impl_->snapshots.size());
263 }
264 catch (const std::exception& e)
265 {
266 Logger::error("[PrefixSnapshot] Failed to load snapshot index: {}", e.what());
267 }
268}
269
270void PrefixSnapshotService::saveSnapshotIndex()
271{
272 fs::path indexPath = impl_->snapshotDir / "index.json";
273
274 try
275 {
276 json j;
277 j["snapshots"] = json::array();
278
279 for (const auto& [id, snap] : impl_->snapshots)
280 {
281 json item;
282 item["id"] = snap.id;
283 item["name"] = snap.name;
284 item["description"] = snap.description;
285 item["prefixPath"] = snap.prefixPath.string();
286 item["snapshotPath"] = snap.snapshotPath.string();
287 item["created"] =
288 std::chrono::duration_cast<std::chrono::seconds>(snap.created.time_since_epoch())
289 .count();
290 item["sizeBytes"] = snap.sizeBytes;
291 item["fileCount"] = snap.fileCount;
292 item["isIncremental"] = snap.isIncremental;
293 item["parentSnapshotId"] = snap.parentSnapshotId;
294 item["gameId"] = snap.gameId;
295 item["gameName"] = snap.gameName;
296 item["wineVersion"] = snap.wineVersion;
297 item["architecture"] = snap.architecture;
298
299 j["snapshots"].push_back(item);
300 }
301
302 // Write to temp file then atomically rename to avoid corruption on crash
303 fs::path tmpPath = indexPath;
304 tmpPath += ".tmp";
305 {
306 std::ofstream file(tmpPath);
307 file << j.dump(2);
308 }
309 std::error_code renameEc;
310 fs::rename(tmpPath, indexPath, renameEc);
311 if (renameEc)
312 {
313 Logger::error("[PrefixSnapshot] Failed to atomically replace index: {}",
314 renameEc.message());
315 fs::remove(tmpPath, renameEc);
316 }
317 }
318 catch (const std::exception& e)
319 {
320 Logger::error("[PrefixSnapshot] Failed to save snapshot index: {}", e.what());
321 }
322}
323
324bool PrefixSnapshotService::copyPrefix(const fs::path& src, const fs::path& dest,
325 const ProgressCallback& callback,
326 std::atomic<bool>& cancelled)
327{
328 // First pass: count files and total size
329 int totalFiles = 0;
330 int64_t totalBytes = 0;
331 std::error_code ec;
332
333 for (const auto& entry : fs::recursive_directory_iterator(src, ec))
334 {
335 if (cancelled.load())
336 return false;
337 if (entry.is_regular_file())
338 {
339 totalFiles++;
340 totalBytes += static_cast<int64_t>(entry.file_size());
341 }
342 }
343 if (ec)
344 {
345 Logger::error("[PrefixSnapshot] Directory iteration error: {}", ec.message());
346 return false;
347 }
348
349 if (callback)
350 {
351 SnapshotProgress progress;
353 progress.totalFiles = totalFiles;
354 progress.totalBytes = totalBytes;
355 callback(progress);
356 }
357
358 // Second pass: copy files
359 int filesProcessed = 0;
360 int64_t bytesProcessed = 0;
361 int filesSkipped = 0;
362
363 for (const auto& entry : fs::recursive_directory_iterator(src, ec))
364 {
365 if (cancelled.load())
366 return false;
367
368 fs::path relativePath = fs::relative(entry.path(), src);
369 fs::path destPath = dest / relativePath;
370
371 if (entry.is_directory())
372 {
373 fs::create_directories(destPath, ec);
374 }
375 else if (entry.is_regular_file() && !entry.is_symlink())
376 {
377 // Explicitly exclude symlinks: is_regular_file() returns true for symlinks
378 // pointing to regular files, so we must check is_symlink() first to prevent
379 // copy_file() from following symlinks that escape the prefix.
380 fs::create_directories(destPath.parent_path(), ec);
381 fs::copy_file(entry.path(), destPath, fs::copy_options::overwrite_existing, ec);
382
383 if (ec)
384 {
385 Logger::error("[PrefixSnapshot] Failed to copy {}: {}", entry.path().string(),
386 ec.message());
387 filesSkipped++;
388 continue;
389 }
390
391 filesProcessed++;
392 bytesProcessed += static_cast<int64_t>(entry.file_size());
393
394 if (callback && filesProcessed % 100 == 0)
395 {
396 SnapshotProgress progress;
398 progress.currentFile = relativePath.string();
399 progress.filesProcessed = filesProcessed;
400 progress.totalFiles = totalFiles;
401 progress.bytesProcessed = bytesProcessed;
402 progress.totalBytes = totalBytes;
403 progress.percentComplete = totalFiles > 0 ? (filesProcessed * 100) / totalFiles : 0;
404 callback(progress);
405 }
406 }
407 else if (entry.is_symlink())
408 {
409 // Copy symlinks with validation
410 fs::path target = fs::read_symlink(entry.path(), ec);
411 if (!ec)
412 {
413 // Validate symlink target stays within prefix using proper path containment.
414 // Use separate error codes — sharing one variable causes the second call to
415 // clear the first call's error, masking a failed canonicalization.
416 std::error_code ec1, ec2;
417 auto resolvedTarget = fs::weakly_canonical(destPath.parent_path() / target, ec1);
418 auto resolvedDest = fs::weakly_canonical(dest, ec2);
419 std::error_code relEc;
420 fs::path rel =
421 (!ec1 && !ec2) ? fs::relative(resolvedTarget, resolvedDest, relEc) : fs::path{};
422 if (!ec1 && !ec2 && !relEc && !rel.empty() && *rel.begin() != "..")
423 {
424 fs::create_directories(destPath.parent_path(), ec);
425 fs::create_symlink(target, destPath, ec);
426 }
427 else
428 {
429 Logger::warn("[PrefixSnapshot] Skipping symlink pointing outside prefix: {}",
430 entry.path().string());
431 }
432 }
433 }
434 }
435 if (ec)
436 {
437 Logger::error("[PrefixSnapshot] Directory iteration error: {}", ec.message());
438 return false;
439 }
440
441 if (filesSkipped > 0)
442 {
443 Logger::error("[PrefixSnapshot] {} file(s) could not be copied — snapshot is incomplete",
444 filesSkipped);
445 return false;
446 }
447
448 return true;
449}
450
451// ==============================================================================
452// Snapshot Creation
453// ==============================================================================
454
455std::optional<PrefixSnapshot>
456PrefixSnapshotService::createSnapshot(const fs::path& prefixPath, const std::string& name,
457 const std::string& description,
458 const ProgressCallback& progressCallback)
459{
460 Logger::info("[PrefixSnapshot] Creating snapshot '{}' for {}", name, prefixPath.string());
461
462 if (!fs::exists(prefixPath) || !fs::is_directory(prefixPath))
463 {
464 Logger::error("[PrefixSnapshot] Invalid prefix path: {}", prefixPath.string());
465 if (progressCallback)
466 {
467 SnapshotProgress progress;
469 progress.errorMessage = "Invalid prefix path";
470 progressCallback(progress);
471 }
472 return std::nullopt;
473 }
474
475 // Per-operation cancel token
476 auto cancelToken = std::make_shared<std::atomic<bool>>(false);
477 {
478 std::lock_guard<std::mutex> lk(impl_->cancelMutex);
479 impl_->activeCancelFlags.erase(std::remove_if(impl_->activeCancelFlags.begin(),
480 impl_->activeCancelFlags.end(),
481 [](const auto& wp) { return wp.expired(); }),
482 impl_->activeCancelFlags.end());
483 impl_->activeCancelFlags.push_back(cancelToken);
484 }
485
486 // Generate snapshot info
487 PrefixSnapshot snapshot;
488 snapshot.id = generateSnapshotId();
489 snapshot.name = name;
490 snapshot.description = description;
491 snapshot.prefixPath = prefixPath;
492 snapshot.snapshotPath = impl_->snapshotDir / snapshot.id;
493 snapshot.created = std::chrono::system_clock::now();
494 snapshot.wineVersion = detectWineVersion(prefixPath);
495 snapshot.architecture = detectArchitecture(prefixPath);
496
497 // Report starting
498 if (progressCallback)
499 {
500 SnapshotProgress progress;
502 progressCallback(progress);
503 }
504
505 // Copy prefix to snapshot location
506 if (!copyPrefix(prefixPath, snapshot.snapshotPath, progressCallback, *cancelToken))
507 {
508 // Cleanup on failure
509 std::error_code ec;
510 fs::remove_all(snapshot.snapshotPath, ec);
511
512 if (progressCallback)
513 {
514 SnapshotProgress progress;
515 progress.state = cancelToken->load() ? SnapshotProgress::State::Cancelled
517 progressCallback(progress);
518 }
519 return std::nullopt;
520 }
521
522 // Calculate final size and file count
523 std::error_code ec;
524 for (const auto& entry : fs::recursive_directory_iterator(snapshot.snapshotPath, ec))
525 {
526 if (entry.is_regular_file())
527 {
528 snapshot.fileCount++;
529 snapshot.sizeBytes += static_cast<int64_t>(entry.file_size());
530 }
531 }
532 if (ec)
533 {
534 Logger::error("[PrefixSnapshot] Directory iteration error: {}", ec.message());
535 }
536
537 // Save to index
538 {
539 std::lock_guard<std::mutex> lock(impl_->mutex);
540 impl_->snapshots[snapshot.id] = snapshot;
541 saveSnapshotIndex();
542 }
543
544 Logger::info("[PrefixSnapshot] Created snapshot {} ({} files, {})", snapshot.id,
545 snapshot.fileCount, snapshot.getFormattedSize());
546
547 if (progressCallback)
548 {
549 SnapshotProgress progress;
551 progress.percentComplete = 100;
552 progressCallback(progress);
553 }
554
555 return snapshot;
556}
557
558std::future<std::optional<PrefixSnapshot>>
559PrefixSnapshotService::createSnapshotAsync(const fs::path& prefixPath, const std::string& name,
560 const std::string& description,
561 const ProgressCallback& progressCallback)
562{
563 return std::async(std::launch::async, [this, prefixPath, name, description, progressCallback]()
564 { return createSnapshot(prefixPath, name, description, progressCallback); });
565}
566
568 const fs::path& prefixPath, const std::string& parentSnapshotId, const std::string& name,
569 const ProgressCallback& progressCallback)
570{
571 auto parentOpt = getSnapshot(parentSnapshotId);
572 if (!parentOpt)
573 {
574 Logger::error("[PrefixSnapshot] Parent snapshot not found: {}", parentSnapshotId);
575 return std::nullopt;
576 }
577
578 // For incremental, we'd compare and only store changes
579 // For simplicity, create full snapshot but mark as incremental
580 auto snapshot = createSnapshot(prefixPath, name, "", progressCallback);
581 if (snapshot)
582 {
583 snapshot->isIncremental = true;
584 snapshot->parentSnapshotId = parentSnapshotId;
585
586 std::lock_guard<std::mutex> lock(impl_->mutex);
587 auto it = impl_->snapshots.find(snapshot->id);
588 if (it != impl_->snapshots.end())
589 {
590 it->second.isIncremental = true;
591 it->second.parentSnapshotId = parentSnapshotId;
592 saveSnapshotIndex();
593 }
594 }
595
596 return snapshot;
597}
598
599std::optional<PrefixSnapshot> PrefixSnapshotService::createAutoSnapshot(const fs::path& prefixPath,
600 const std::string& gameId,
601 const std::string& gameName,
602 const std::string& reason)
603{
604 std::string name = gameName + " - " + reason;
605
606 auto snapshot = createSnapshot(prefixPath, name);
607 if (snapshot)
608 {
609 snapshot->gameId = gameId;
610 snapshot->gameName = gameName;
611
612 std::lock_guard<std::mutex> lock(impl_->mutex);
613 auto it = impl_->snapshots.find(snapshot->id);
614 if (it != impl_->snapshots.end())
615 {
616 it->second.gameId = gameId;
617 it->second.gameName = gameName;
618 saveSnapshotIndex();
619 }
620 }
621
622 return snapshot;
623}
624
625// ==============================================================================
626// Snapshot Restoration
627// ==============================================================================
628
629bool PrefixSnapshotService::restoreSnapshot(const std::string& snapshotId,
630 const ProgressCallback& progressCallback)
631{
632 auto snapshotOpt = getSnapshot(snapshotId);
633 if (!snapshotOpt)
634 {
635 Logger::error("[PrefixSnapshot] Snapshot not found: {}", snapshotId);
636 return false;
637 }
638
639 const auto& snapshot = *snapshotOpt;
640 Logger::info("[PrefixSnapshot] Restoring snapshot {} to {}", snapshotId,
641 snapshot.prefixPath.string());
642
643 // Verify the snapshot directory is accessible before destroying the current prefix
644 if (!fs::exists(snapshot.snapshotPath) || !fs::is_directory(snapshot.snapshotPath))
645 {
646 Logger::error("[PrefixSnapshot] Snapshot directory not found: {}",
647 snapshot.snapshotPath.string());
648 if (progressCallback)
649 {
650 SnapshotProgress progress;
652 progress.errorMessage = "Snapshot directory not found";
653 progressCallback(progress);
654 }
655 return false;
656 }
657
658 // Per-operation cancel token
659 auto cancelToken = std::make_shared<std::atomic<bool>>(false);
660 {
661 std::lock_guard<std::mutex> lk(impl_->cancelMutex);
662 impl_->activeCancelFlags.erase(std::remove_if(impl_->activeCancelFlags.begin(),
663 impl_->activeCancelFlags.end(),
664 [](const auto& wp) { return wp.expired(); }),
665 impl_->activeCancelFlags.end());
666 impl_->activeCancelFlags.push_back(cancelToken);
667 }
668
669 // Create backup of current state first
670 auto backup =
671 createSnapshot(snapshot.prefixPath, "Auto-backup before restore", "", progressCallback);
672 if (!backup)
673 {
674 Logger::warn("[PrefixSnapshot] Failed to create backup, proceeding anyway");
675 }
676
677 // Remove current prefix contents
678 std::error_code ec;
679 for (const auto& entry : fs::directory_iterator(snapshot.prefixPath, ec))
680 {
681 fs::remove_all(entry.path(), ec);
682 }
683
684 // Copy snapshot back to prefix
685 if (!copyPrefix(snapshot.snapshotPath, snapshot.prefixPath, progressCallback, *cancelToken))
686 {
687 Logger::error("[PrefixSnapshot] Failed to restore snapshot");
688
689 // Try to restore backup
690 if (backup)
691 {
692 Logger::info("[PrefixSnapshot] Attempting to restore backup");
693 copyPrefix(backup->snapshotPath, snapshot.prefixPath, nullptr, *cancelToken);
694 }
695
696 if (progressCallback)
697 {
698 SnapshotProgress progress;
700 progress.errorMessage = "Failed to restore snapshot";
701 progressCallback(progress);
702 }
703 return false;
704 }
705
706 Logger::info("[PrefixSnapshot] Successfully restored snapshot {}", snapshotId);
707
708 if (progressCallback)
709 {
710 SnapshotProgress progress;
712 progress.percentComplete = 100;
713 progressCallback(progress);
714 }
715
716 return true;
717}
718
719std::future<bool>
721 const ProgressCallback& progressCallback)
722{
723 return std::async(std::launch::async, [this, snapshotId, progressCallback]()
724 { return restoreSnapshot(snapshotId, progressCallback); });
725}
726
727bool PrefixSnapshotService::restoreFiles(const std::string& snapshotId,
728 const std::vector<fs::path>& files)
729{
730 auto snapshotOpt = getSnapshot(snapshotId);
731 if (!snapshotOpt)
732 {
733 return false;
734 }
735
736 const auto& snapshot = *snapshotOpt;
737 std::error_code ec;
738
739 for (const auto& file : files)
740 {
741 // Validate relative path — reject any component that would escape the prefix dir
742 for (const auto& component : file)
743 {
744 if (component == "..")
745 {
746 Logger::error("[PrefixSnapshot] Rejected restore path with traversal: {}",
747 file.string());
748 return false;
749 }
750 }
751
752 fs::path srcPath = snapshot.snapshotPath / file;
753 fs::path destPath = snapshot.prefixPath / file;
754
755 if (!fs::exists(srcPath))
756 {
757 Logger::warn("[PrefixSnapshot] File not in snapshot: {}", file.string());
758 continue;
759 }
760
761 fs::create_directories(destPath.parent_path(), ec);
762 fs::copy_file(srcPath, destPath, fs::copy_options::overwrite_existing, ec);
763
764 if (ec)
765 {
766 Logger::error("[PrefixSnapshot] Failed to restore {}: {}", file.string(), ec.message());
767 }
768 }
769
770 return true;
771}
772
773// ==============================================================================
774// Snapshot Management
775// ==============================================================================
776
777std::vector<PrefixSnapshot> PrefixSnapshotService::getAllSnapshots() const
778{
779 std::lock_guard<std::mutex> lock(impl_->mutex);
780
781 std::vector<PrefixSnapshot> result;
782 result.reserve(impl_->snapshots.size());
783
784 for (const auto& [id, snap] : impl_->snapshots)
785 {
786 result.push_back(snap);
787 }
788
789 // Sort by creation time, newest first
790 std::sort(result.begin(), result.end(), [](const PrefixSnapshot& a, const PrefixSnapshot& b)
791 { return a.created > b.created; });
792
793 return result;
794}
795
796std::vector<PrefixSnapshot>
797PrefixSnapshotService::getSnapshotsForPrefix(const fs::path& prefixPath) const
798{
799 std::lock_guard<std::mutex> lock(impl_->mutex);
800
801 std::vector<PrefixSnapshot> result;
802 for (const auto& [id, snap] : impl_->snapshots)
803 {
804 if (snap.prefixPath == prefixPath)
805 {
806 result.push_back(snap);
807 }
808 }
809
810 std::sort(result.begin(), result.end(), [](const PrefixSnapshot& a, const PrefixSnapshot& b)
811 { return a.created > b.created; });
812
813 return result;
814}
815
816std::vector<PrefixSnapshot>
817PrefixSnapshotService::getSnapshotsForGame(const std::string& gameId) const
818{
819 std::lock_guard<std::mutex> lock(impl_->mutex);
820
821 std::vector<PrefixSnapshot> result;
822 for (const auto& [id, snap] : impl_->snapshots)
823 {
824 if (snap.gameId == gameId)
825 {
826 result.push_back(snap);
827 }
828 }
829
830 std::sort(result.begin(), result.end(), [](const PrefixSnapshot& a, const PrefixSnapshot& b)
831 { return a.created > b.created; });
832
833 return result;
834}
835
836std::optional<PrefixSnapshot>
837PrefixSnapshotService::getSnapshot(const std::string& snapshotId) const
838{
839 std::lock_guard<std::mutex> lock(impl_->mutex);
840
841 auto it = impl_->snapshots.find(snapshotId);
842 if (it != impl_->snapshots.end())
843 {
844 return it->second;
845 }
846 return std::nullopt;
847}
848
849// Internal helper — caller must hold impl_->mutex
850bool PrefixSnapshotService::deleteSnapshotUnlocked(const std::string& snapshotId)
851{
852 auto it = impl_->snapshots.find(snapshotId);
853 if (it == impl_->snapshots.end())
854 {
855 return false;
856 }
857
858 // Delete snapshot directory
859 std::error_code ec;
860 fs::remove_all(it->second.snapshotPath, ec);
861
862 if (ec)
863 {
864 Logger::error("[PrefixSnapshot] Failed to delete snapshot files: {}", ec.message());
865 }
866
867 impl_->snapshots.erase(it);
868 saveSnapshotIndex();
869
870 Logger::info("[PrefixSnapshot] Deleted snapshot {}", snapshotId);
871 return true;
872}
873
874bool PrefixSnapshotService::deleteSnapshot(const std::string& snapshotId)
875{
876 std::lock_guard<std::mutex> lock(impl_->mutex);
877 return deleteSnapshotUnlocked(snapshotId);
878}
879
881{
882 std::lock_guard<std::mutex> lock(impl_->mutex);
883
884 // Collect matching snapshot IDs under lock
885 std::vector<std::string> toDelete;
886 for (const auto& [id, snap] : impl_->snapshots)
887 {
888 if (snap.prefixPath == prefixPath)
889 {
890 toDelete.push_back(id);
891 }
892 }
893
894 int deleted = 0;
895 for (const auto& id : toDelete)
896 {
897 if (deleteSnapshotUnlocked(id))
898 {
899 deleted++;
900 }
901 }
902
903 return deleted;
904}
905
906bool PrefixSnapshotService::renameSnapshot(const std::string& snapshotId,
907 const std::string& newName)
908{
909 std::lock_guard<std::mutex> lock(impl_->mutex);
910
911 auto it = impl_->snapshots.find(snapshotId);
912 if (it == impl_->snapshots.end())
913 {
914 return false;
915 }
916
917 it->second.name = newName;
918 saveSnapshotIndex();
919 return true;
920}
921
922bool PrefixSnapshotService::updateDescription(const std::string& snapshotId,
923 const std::string& description)
924{
925 std::lock_guard<std::mutex> lock(impl_->mutex);
926
927 auto it = impl_->snapshots.find(snapshotId);
928 if (it == impl_->snapshots.end())
929 {
930 return false;
931 }
932
933 it->second.description = description;
934 saveSnapshotIndex();
935 return true;
936}
937
938// ==============================================================================
939// Comparison
940// ==============================================================================
941
943 const std::string& snapshotId2) const
944{
945 PrefixDiff diff;
946
947 auto snap1 = getSnapshot(snapshotId1);
948 auto snap2 = getSnapshot(snapshotId2);
949
950 if (!snap1 || !snap2)
951 {
952 return diff;
953 }
954
955 // Build file sets for each snapshot
956 std::set<fs::path> files1, files2;
957 std::map<fs::path, int64_t> sizes1, sizes2;
958 std::error_code ec;
959
960 for (const auto& entry : fs::recursive_directory_iterator(snap1->snapshotPath, ec))
961 {
962 if (entry.is_regular_file())
963 {
964 fs::path rel = fs::relative(entry.path(), snap1->snapshotPath);
965 files1.insert(rel);
966 sizes1[rel] = static_cast<int64_t>(entry.file_size());
967 }
968 }
969 if (ec)
970 {
971 Logger::error("[PrefixSnapshot] Directory iteration error: {}", ec.message());
972 return diff;
973 }
974
975 for (const auto& entry : fs::recursive_directory_iterator(snap2->snapshotPath, ec))
976 {
977 if (entry.is_regular_file())
978 {
979 fs::path rel = fs::relative(entry.path(), snap2->snapshotPath);
980 files2.insert(rel);
981 sizes2[rel] = static_cast<int64_t>(entry.file_size());
982 }
983 }
984 if (ec)
985 {
986 Logger::error("[PrefixSnapshot] Directory iteration error: {}", ec.message());
987 return diff;
988 }
989
990 // Find differences
991 for (const auto& file : files1)
992 {
993 if (files2.find(file) == files2.end())
994 {
995 diff.removedFiles.push_back(file);
996 }
997 else if (sizes1[file] != sizes2[file])
998 {
999 diff.modifiedFiles.push_back(file);
1000 }
1001 }
1002
1003 for (const auto& file : files2)
1004 {
1005 if (files1.find(file) == files1.end())
1006 {
1007 diff.addedFiles.push_back(file);
1008 }
1009 }
1010
1011 return diff;
1012}
1013
1015 const std::string& snapshotId) const
1016{
1017 // Create temporary snapshot of current state for comparison
1018 // This is a simplified version - we just compare file existence and sizes
1019
1020 PrefixDiff diff;
1021 auto snap = getSnapshot(snapshotId);
1022 if (!snap)
1023 {
1024 return diff;
1025 }
1026
1027 std::set<fs::path> currentFiles, snapshotFiles;
1028 std::map<fs::path, int64_t> currentSizes, snapshotSizes;
1029 std::error_code ec;
1030
1031 for (const auto& entry : fs::recursive_directory_iterator(prefixPath, ec))
1032 {
1033 if (entry.is_regular_file())
1034 {
1035 fs::path rel = fs::relative(entry.path(), prefixPath);
1036 currentFiles.insert(rel);
1037 currentSizes[rel] = static_cast<int64_t>(entry.file_size());
1038 }
1039 }
1040 if (ec)
1041 {
1042 Logger::error("[PrefixSnapshot] Directory iteration error: {}", ec.message());
1043 return diff;
1044 }
1045
1046 for (const auto& entry : fs::recursive_directory_iterator(snap->snapshotPath, ec))
1047 {
1048 if (entry.is_regular_file())
1049 {
1050 fs::path rel = fs::relative(entry.path(), snap->snapshotPath);
1051 snapshotFiles.insert(rel);
1052 snapshotSizes[rel] = static_cast<int64_t>(entry.file_size());
1053 }
1054 }
1055 if (ec)
1056 {
1057 Logger::error("[PrefixSnapshot] Directory iteration error: {}", ec.message());
1058 return diff;
1059 }
1060
1061 for (const auto& file : currentFiles)
1062 {
1063 if (snapshotFiles.find(file) == snapshotFiles.end())
1064 {
1065 diff.addedFiles.push_back(file);
1066 }
1067 else if (currentSizes[file] != snapshotSizes[file])
1068 {
1069 diff.modifiedFiles.push_back(file);
1070 }
1071 }
1072
1073 for (const auto& file : snapshotFiles)
1074 {
1075 if (currentFiles.find(file) == currentFiles.end())
1076 {
1077 diff.removedFiles.push_back(file);
1078 }
1079 }
1080
1081 return diff;
1082}
1083
1084std::vector<fs::path> PrefixSnapshotService::listSnapshotFiles(const std::string& snapshotId) const
1085{
1086 std::vector<fs::path> files;
1087
1088 auto snap = getSnapshot(snapshotId);
1089 if (!snap)
1090 {
1091 return files;
1092 }
1093
1094 std::error_code ec;
1095 for (const auto& entry : fs::recursive_directory_iterator(snap->snapshotPath, ec))
1096 {
1097 if (entry.is_regular_file())
1098 {
1099 files.push_back(fs::relative(entry.path(), snap->snapshotPath));
1100 }
1101 }
1102 if (ec)
1103 {
1104 Logger::error("[PrefixSnapshot] Directory iteration error: {}", ec.message());
1105 }
1106
1107 return files;
1108}
1109
1110// ==============================================================================
1111// Space Management
1112// ==============================================================================
1113
1115{
1116 std::lock_guard<std::mutex> lock(impl_->mutex);
1117
1118 int64_t total = 0;
1119 for (const auto& [id, snap] : impl_->snapshots)
1120 {
1121 total += snap.sizeBytes;
1122 }
1123 return total;
1124}
1125
1127{
1128 std::lock_guard<std::mutex> lock(impl_->mutex);
1129
1130 // Group snapshots by prefix
1131 std::map<std::string, std::vector<PrefixSnapshot>> byPrefix;
1132 for (const auto& [id, snap] : impl_->snapshots)
1133 {
1134 byPrefix[snap.prefixPath.string()].push_back(snap);
1135 }
1136
1137 int deleted = 0;
1138
1139 for (auto& [prefix, snaps] : byPrefix)
1140 {
1141 // Sort by date, newest first
1142 std::sort(snaps.begin(), snaps.end(), [](const PrefixSnapshot& a, const PrefixSnapshot& b)
1143 { return a.created > b.created; });
1144
1145 // Delete excess snapshots (use unlocked version since we hold the lock)
1146 for (size_t i = static_cast<size_t>(keepCount); i < snaps.size(); i++)
1147 {
1148 if (deleteSnapshotUnlocked(snaps[i].id))
1149 {
1150 deleted++;
1151 }
1152 }
1153 }
1154
1155 Logger::info("[PrefixSnapshot] Cleaned up {} old snapshots", deleted);
1156 return deleted;
1157}
1158
1160{
1161 auto now = std::chrono::system_clock::now();
1162 auto maxAge = std::chrono::hours(maxAgeDays * 24);
1163 int deleted = 0;
1164
1165 auto snapshots = getAllSnapshots();
1166 for (const auto& snap : snapshots)
1167 {
1168 // Only delete auto-snapshots (those with gameId set)
1169 if (snap.gameId.empty())
1170 {
1171 continue;
1172 }
1173
1174 auto age = now - snap.created;
1175 if (age > maxAge)
1176 {
1177 if (deleteSnapshot(snap.id))
1178 {
1179 deleted++;
1180 }
1181 }
1182 }
1183
1184 Logger::info("[PrefixSnapshot] Cleaned up {} old auto-snapshots", deleted);
1185 return deleted;
1186}
1187
1188bool PrefixSnapshotService::exportSnapshot(const std::string& snapshotId,
1189 const fs::path& outputPath,
1190 const ProgressCallback& /*progressCallback*/)
1191{
1192 auto snap = getSnapshot(snapshotId);
1193 if (!snap)
1194 {
1195 return false;
1196 }
1197
1198 // Create tar.gz archive
1199 std::string cmd = "tar -czf " + ShellUtils::escapeArg(outputPath.string()) + " -C " +
1200 ShellUtils::escapeArg(snap->snapshotPath.parent_path().string()) + " " +
1201 ShellUtils::escapeArg(snap->snapshotPath.filename().string());
1202
1203 int result = std::system(cmd.c_str());
1204 if (result == -1 || !WIFEXITED(result) || WEXITSTATUS(result) != 0)
1205 {
1206 Logger::error("[PrefixSnapshot] Failed to export snapshot");
1207 return false;
1208 }
1209
1210 Logger::info("[PrefixSnapshot] Exported snapshot to {}", outputPath.string());
1211 return true;
1212}
1213
1214std::optional<PrefixSnapshot>
1215PrefixSnapshotService::importSnapshot(const fs::path& archivePath,
1216 const ProgressCallback& /*progressCallback*/)
1217{
1218 if (!fs::exists(archivePath))
1219 {
1220 Logger::error("[PrefixSnapshot] Archive not found: {}", archivePath.string());
1221 return std::nullopt;
1222 }
1223
1224 // Extract to snapshot directory
1225 std::string id = generateSnapshotId();
1226 fs::path destDir = impl_->snapshotDir / id;
1227
1228 // Pre-validate archive: reject any entry with path traversal components,
1229 // and capture the top-level directory name so we can rename it to our new id.
1230 //
1231 // Use PipeHandle (RAII wrapper around popen/pclose) so an exception
1232 // thrown anywhere in the parsing loop releases the pipe — raw
1233 // popen/pclose pairing leaks the FILE* in that case. PipeHandle also
1234 // lets us inspect pclose's exit status, so a tar failure during
1235 // listing is surfaced rather than treated as "empty archive".
1236 std::string archiveTopDir;
1237 {
1238 std::string listCmd =
1239 "tar -tzf " + ShellUtils::escapeArg(archivePath.string()) + " 2>/dev/null";
1240 PipeHandle listPipe(listCmd, "r");
1241 if (!listPipe)
1242 {
1243 Logger::error("[PrefixSnapshot] Failed to list archive contents");
1244 return std::nullopt;
1245 }
1246 std::array<char, 4096> buf;
1247 bool traversalFound = false;
1248 while (fgets(buf.data(), static_cast<int>(buf.size()), listPipe.get()) != nullptr)
1249 {
1250 std::string entry(buf.data());
1251 if (!entry.empty() && entry.back() == '\n')
1252 entry.pop_back();
1253 // Capture first top-level component as the archive's root directory
1254 if (archiveTopDir.empty())
1255 {
1256 fs::path entryPath(entry);
1257 if (!entryPath.empty())
1258 archiveTopDir = entryPath.begin()->string();
1259 }
1260 for (const auto& component : fs::path(entry))
1261 {
1262 if (component == "..")
1263 {
1264 Logger::error("[PrefixSnapshot] Archive contains path traversal entry: {}",
1265 entry);
1266 traversalFound = true;
1267 break;
1268 }
1269 }
1270 if (traversalFound)
1271 break;
1272 }
1273 // PipeHandle::close() returns the pclose() exit status so we can
1274 // tell tar-listing-failed from valid-but-empty archive. Anything
1275 // non-zero (or -1 = wait/exec error) means the listing was
1276 // unreliable; bail before extraction.
1277 const int listStatus = listPipe.close();
1278 if (traversalFound)
1279 return std::nullopt;
1280 if (listStatus == -1 || (WIFEXITED(listStatus) && WEXITSTATUS(listStatus) != 0))
1281 {
1282 Logger::error("[PrefixSnapshot] tar listing failed (status={}); refusing to extract",
1283 listStatus);
1284 return std::nullopt;
1285 }
1286 }
1287
1288 if (archiveTopDir.empty())
1289 {
1290 Logger::error("[PrefixSnapshot] Archive appears to be empty");
1291 return std::nullopt;
1292 }
1293
1294 std::string cmd = "tar -xzf " + ShellUtils::escapeArg(archivePath.string()) +
1295 " --no-absolute-filenames" + " -C " +
1296 ShellUtils::escapeArg(impl_->snapshotDir.string());
1297
1298 int result = std::system(cmd.c_str());
1299 if (result == -1 || !WIFEXITED(result) || WEXITSTATUS(result) != 0)
1300 {
1301 Logger::error("[PrefixSnapshot] Failed to extract archive");
1302 return std::nullopt;
1303 }
1304
1305 // tar extracts using the archive's internal directory name; rename to our new id
1306 fs::path extractedDir = impl_->snapshotDir / archiveTopDir;
1307 if (extractedDir != destDir)
1308 {
1309 std::error_code renameEc;
1310 fs::rename(extractedDir, destDir, renameEc);
1311 if (renameEc)
1312 {
1313 Logger::error("[PrefixSnapshot] Failed to rename extracted dir '{}' to '{}': {}",
1314 extractedDir.string(), destDir.string(), renameEc.message());
1315 fs::remove_all(extractedDir, renameEc);
1316 return std::nullopt;
1317 }
1318 }
1319
1320 // SECURITY (CWE-22/CWE-59): the name pre-scan above rejects ".." members,
1321 // but a snapshot archive may still contain symlink members whose *target*
1322 // escapes the prefix (e.g. an attacker-planted `evil -> /home/user/.ssh`).
1323 // Wine prefixes legitimately contain escaping symlinks (dosdevices/z: -> /),
1324 // and the export/copy path already drops those on restore, so mirror that
1325 // policy here: after extraction, remove any symlink whose resolved target
1326 // leaves the imported prefix. This neutralises the write-through-symlink
1327 // vector without breaking legitimate in-prefix links.
1328 {
1329 std::error_code sweepEc;
1330 std::error_code canonRootEc;
1331 const fs::path canonRoot = fs::weakly_canonical(destDir, canonRootEc);
1332 for (auto it = fs::recursive_directory_iterator(
1333 destDir, fs::directory_options::skip_permission_denied, sweepEc);
1334 it != fs::recursive_directory_iterator(); it.increment(sweepEc))
1335 {
1336 if (sweepEc)
1337 break;
1338 std::error_code linkEc;
1339 if (!it->is_symlink(linkEc) || linkEc)
1340 continue;
1341 const fs::path linkPath = it->path();
1342 fs::path target = fs::read_symlink(linkPath, linkEc);
1343 if (linkEc)
1344 {
1345 fs::remove(linkPath, linkEc);
1346 continue;
1347 }
1348 // Resolve the target relative to the symlink's own directory when
1349 // it is relative, then canonicalize and containment-check.
1350 fs::path resolved = target.is_absolute() ? target : (linkPath.parent_path() / target);
1351 std::error_code canonEc;
1352 const fs::path canonTarget = fs::weakly_canonical(resolved, canonEc);
1353 std::error_code relEc;
1354 const fs::path rel =
1355 (canonRootEc || canonEc) ? fs::path() : fs::relative(canonTarget, canonRoot, relEc);
1356 const bool escapes =
1357 canonRootEc || canonEc || relEc || rel.empty() || *rel.begin() == "..";
1358 if (escapes)
1359 {
1360 Logger::warn("[PrefixSnapshot] Removing imported symlink escaping the prefix: "
1361 "{} -> {}",
1362 linkPath.string(), target.string());
1363 std::error_code rmEc;
1364 fs::remove(linkPath, rmEc);
1365 }
1366 }
1367 }
1368
1369 // Create snapshot entry
1370 PrefixSnapshot snapshot;
1371 snapshot.id = id;
1372 snapshot.name = "Imported: " + archivePath.filename().string();
1373 snapshot.snapshotPath = destDir;
1374 snapshot.created = std::chrono::system_clock::now();
1375
1376 // Calculate size
1377 std::error_code ec;
1378 for (const auto& entry : fs::recursive_directory_iterator(destDir, ec))
1379 {
1380 if (entry.is_regular_file())
1381 {
1382 snapshot.fileCount++;
1383 snapshot.sizeBytes += static_cast<int64_t>(entry.file_size());
1384 }
1385 }
1386 if (ec)
1387 {
1388 Logger::error("[PrefixSnapshot] Directory iteration error: {}", ec.message());
1389 }
1390
1391 {
1392 std::lock_guard<std::mutex> lock(impl_->mutex);
1393 impl_->snapshots[snapshot.id] = snapshot;
1394 saveSnapshotIndex();
1395 }
1396
1397 Logger::info("[PrefixSnapshot] Imported snapshot {}", snapshot.id);
1398 return snapshot;
1399}
1400
1401// ==============================================================================
1402// Configuration
1403// ==============================================================================
1404
1406{
1407 std::lock_guard<std::mutex> lock(impl_->mutex);
1408 impl_->snapshotDir = path;
1409
1410 std::error_code ec;
1411 fs::create_directories(path, ec);
1412}
1413
1415{
1416 std::lock_guard<std::mutex> lock(impl_->mutex);
1417 return impl_->snapshotDir;
1418}
1419
1421{
1422 std::lock_guard<std::mutex> lock(impl_->mutex);
1423 impl_->compressionEnabled = enabled;
1424}
1425
1427{
1428 std::lock_guard<std::mutex> lock(impl_->mutex);
1429 impl_->maxStorageBytes = maxBytes;
1430}
1431
1433{
1434 std::lock_guard<std::mutex> lk(impl_->cancelMutex);
1435 for (auto& wp : impl_->activeCancelFlags)
1436 {
1437 if (auto sp = wp.lock())
1438 sp->store(true);
1439 }
1440}
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
RAII wrapper for FILE* from popen().
int close()
Close the pipe early and return pclose's exit status.
FILE * get() const
Get raw FILE* pointer.
std::vector< PrefixSnapshot > getSnapshotsForGame(const std::string &gameId) const
Get snapshots for a specific game.
bool updateDescription(const std::string &snapshotId, const std::string &description)
Update snapshot description.
std::optional< PrefixSnapshot > importSnapshot(const std::filesystem::path &archivePath, const ProgressCallback &progressCallback=nullptr)
Import a snapshot from archive.
bool restoreSnapshot(const std::string &snapshotId, const ProgressCallback &progressCallback=nullptr)
Restore a prefix from snapshot.
bool exportSnapshot(const std::string &snapshotId, const std::filesystem::path &outputPath, const ProgressCallback &progressCallback=nullptr)
Export a snapshot to a portable archive.
void cancelOperation()
Cancel ongoing operation.
bool restoreFiles(const std::string &snapshotId, const std::vector< std::filesystem::path > &files)
Restore specific files from a snapshot.
PrefixDiff compareSnapshots(const std::string &snapshotId1, const std::string &snapshotId2) const
Compare two snapshots.
bool deleteSnapshot(const std::string &snapshotId)
Delete a snapshot.
std::vector< PrefixSnapshot > getSnapshotsForPrefix(const std::filesystem::path &prefixPath) const
Get snapshots for a specific prefix.
std::optional< PrefixSnapshot > getSnapshot(const std::string &snapshotId) const
Get a specific snapshot by ID.
std::optional< PrefixSnapshot > createAutoSnapshot(const std::filesystem::path &prefixPath, const std::string &gameId, const std::string &gameName, const std::string &reason)
Create automatic snapshot for a game.
PrefixDiff compareWithCurrent(const std::filesystem::path &prefixPath, const std::string &snapshotId) const
Compare current prefix state with a snapshot.
std::optional< PrefixSnapshot > createSnapshot(const std::filesystem::path &prefixPath, const std::string &name, const std::string &description="", const ProgressCallback &progressCallback=nullptr)
Create a full snapshot of a prefix.
std::future< std::optional< PrefixSnapshot > > createSnapshotAsync(const std::filesystem::path &prefixPath, const std::string &name, const std::string &description="", const ProgressCallback &progressCallback=nullptr)
Create a snapshot asynchronously.
std::vector< std::filesystem::path > listSnapshotFiles(const std::string &snapshotId) const
List files in a snapshot.
std::optional< PrefixSnapshot > createIncrementalSnapshot(const std::filesystem::path &prefixPath, const std::string &parentSnapshotId, const std::string &name, const ProgressCallback &progressCallback=nullptr)
Create an incremental snapshot (only changes since parent).
std::vector< PrefixSnapshot > getAllSnapshots() const
Get all snapshots.
int deleteSnapshotsForPrefix(const std::filesystem::path &prefixPath)
Delete all snapshots for a prefix.
void setCompressionEnabled(bool enabled)
Enable/disable compression for snapshots.
std::filesystem::path getSnapshotDirectory() const
Get current snapshot directory.
int64_t getTotalSnapshotSize() const
Get total space used by all snapshots.
void setSnapshotDirectory(const std::filesystem::path &path)
Set snapshot storage directory.
std::function< void(const SnapshotProgress &)> ProgressCallback
bool renameSnapshot(const std::string &snapshotId, const std::string &newName)
Rename a snapshot.
int cleanupOldAutoSnapshots(int maxAgeDays=30)
Clean up auto-snapshots older than specified days.
void setMaxStorageSize(int64_t maxBytes)
Set maximum total snapshot storage size.
int cleanupOldSnapshots(int keepCount=5)
Clean up old snapshots, keeping newest N per prefix.
std::future< bool > restoreSnapshotAsync(const std::string &snapshotId, const ProgressCallback &progressCallback=nullptr)
Restore a snapshot asynchronously.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
nlohmann::json json
Differences between two prefix states.
std::vector< std::filesystem::path > addedFiles
std::vector< std::filesystem::path > modifiedFiles
std::vector< std::filesystem::path > removedFiles
std::map< std::string, PrefixSnapshot > snapshots
std::vector< std::weak_ptr< std::atomic< bool > > > activeCancelFlags
Information about a saved prefix snapshot.
std::string description
Optional description.
std::filesystem::path prefixPath
Original prefix path.
std::string getFormattedDate() const
std::string parentSnapshotId
Parent snapshot for incremental.
int64_t sizeBytes
Snapshot size on disk.
std::string architecture
win32 or win64
std::string wineVersion
Wine/Proton version at snapshot time.
std::string getFormattedSize() const
std::string gameName
Associated game name.
bool isIncremental
Whether this is incremental.
std::string gameId
Associated game ID (if any).
std::chrono::system_clock::time_point created
std::string name
User-friendly name.
int fileCount
Number of files in snapshot.
std::filesystem::path snapshotPath
Where snapshot is stored.
std::string id
Unique snapshot ID.
Progress information during snapshot operations.
std::string getStateStr() const