game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
installation_executor.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// installation_executor.cpp
4// ==============================================================================
5// Installation executor implementation
6// ==============================================================================
7
9#include "logger.h"
13#include "util/shell_utils.h"
14
15#include <array>
16#include <chrono>
17#include <cstdio>
18#include <cstdlib>
19#include <filesystem>
20#include <fstream>
21#include <future>
22#include <mutex>
23#include <regex>
24#include <sstream>
25#include <sys/wait.h>
26#include <thread>
27#include <utility>
28#include <vector>
29
30namespace fs = std::filesystem;
31
32namespace
33{
34std::vector<std::shared_ptr<std::future<void>>> activeFutures_;
35std::mutex futuresMutex_;
36
37void storeFuture(std::shared_ptr<std::future<void>> f)
38{
39 std::lock_guard<std::mutex> lock(futuresMutex_);
40 activeFutures_.erase(std::remove_if(activeFutures_.begin(), activeFutures_.end(),
41 [](const std::shared_ptr<std::future<void>>& fu)
42 {
43 return fu->wait_for(std::chrono::seconds(0)) ==
44 std::future_status::ready;
45 }),
46 activeFutures_.end());
47 activeFutures_.push_back(std::move(f));
48}
49} // namespace
50
51// Validate that a path, after canonicalization, stays within the user's home directory.
52// This prevents installer scripts from escaping to /etc, /usr, /proc, etc.
53static bool isPathWithinHome(const std::string& rawPath)
54{
55 if (rawPath.empty())
56 return false;
57 const char* homeEnv = std::getenv("HOME");
58 if (!homeEnv || homeEnv[0] == '\0')
59 return false;
60 std::error_code ec;
61 fs::path canonical = fs::weakly_canonical(fs::path(rawPath), ec);
62 if (ec)
63 return false;
64 const std::string canonStr = canonical.string();
65 const std::string homeStr = fs::path(homeEnv).string();
66 // Must start with home and not equal home itself (avoid deleting home root)
67 return canonStr.size() > homeStr.size() && canonStr.compare(0, homeStr.size(), homeStr) == 0 &&
68 (homeStr.back() == '/' || canonStr[homeStr.size()] == '/');
69}
70
71// SECURITY (CWE-22, path traversal): a Lutris installer's file entries
72// (`filename`, `id`, `url`) are read verbatim from remote JSON. Any value
73// used to build a local cache path must be reduced to a single path
74// component so a payload like "../../../.config/autostart/x.desktop" cannot
75// escape the cache directory. Returns the basename, or "" if the value has
76// no usable component (empty / "." / "..").
77static std::string safeCacheComponent(const std::string& raw)
78{
79 const std::string component = fs::path(raw).filename().string();
80 if (component.empty() || component == "." || component == "..")
81 return {};
82 return component;
83}
84
85// Verify that `candidate`, once canonicalized, stays inside `root`. Uses the
86// project's standard weakly_canonical + relative + first-component check.
87static bool isPathWithin(const std::string& candidate, const std::string& root)
88{
89 std::error_code ec;
90 fs::path canon = fs::weakly_canonical(fs::path(candidate), ec);
91 if (ec)
92 return false;
93 fs::path canonRoot = fs::weakly_canonical(fs::path(root), ec);
94 if (ec)
95 return false;
96 fs::path rel = fs::relative(canon, canonRoot, ec);
97 if (ec || rel.empty())
98 return false;
99 return *rel.begin() != "..";
100}
101
102// Local aliases for the shared XDG helpers in models/desktop_entry_utils.h.
103// Pre-existing call sites use the unqualified names extensively; the using
104// statements keep diffs small while letting tests reach the helpers via
105// the canonical namespace.
107static inline std::string sanitizeDesktopField(const std::string& s)
108{
109 return ::desktop_entry::sanitizeField(s);
110}
111static inline std::string escapeDesktopExec(const std::string& s)
112{
113 return ::desktop_entry::escapeExec(s);
114}
115
116// Helper for C++17 (ends_with is C++20)
117static bool endsWith(const std::string& str, const std::string& suffix)
118{
119 if (suffix.size() > str.size())
120 return false;
121 return str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
122}
123
124// ==============================================================================
125// Static Members
126// ==============================================================================
127
128std::atomic<InstallState> InstallationExecutor::currentState_{InstallState::Idle};
129std::atomic<bool> InstallationExecutor::cancelRequested_{false};
130InstallProgress InstallationExecutor::currentProgress_;
131std::mutex InstallationExecutor::progressMutex_;
132
133// ==============================================================================
134// Main Installation Methods
135// ==============================================================================
136
138 const InstallConfig& config,
139 const ProgressCallback& progressCallback)
140{
141 InstallResult result;
142 result.gameName = script.gameName;
143 result.gameSlug = script.gameSlug;
144 result.runner = script.runner;
145
146 auto startTime = std::chrono::steady_clock::now();
147
148 // Reset state
149 currentState_ = InstallState::Preparing;
150 cancelRequested_ = false;
151
152 InstallProgress progress;
154 progress.totalSteps =
155 static_cast<int>(script.steps.size()) + 3; // +3 for prepare, download, finalize
156
157 // Build variables
158 InstallConfig mutableConfig = config;
159 std::map<std::string, std::string> variables = buildVariables(script, config);
160
161 // Phase 1: Prepare
162 addLogMessage(progress, result, "Preparing installation...");
163 progress.stateDescription = "Preparing";
164 updateProgress(progress, progressCallback);
165
166 if (!executePrepare(script, mutableConfig, result, variables, progressCallback))
167 {
168 currentState_ = InstallState::Failed;
169 return result;
170 }
171
172 if (cancelRequested_)
173 {
174 result.errorMessage = "Installation cancelled by user";
175 currentState_ = InstallState::Cancelled;
176 return result;
177 }
178
179 // Phase 2: Download files
180 currentState_ = InstallState::DownloadingFiles;
182 progress.stateDescription = "Downloading files";
183 progress.currentStep = 1;
184 updateProgress(progress, progressCallback);
185
186 if (!executeDownloads(script, mutableConfig, result, variables, progressCallback))
187 {
188 currentState_ = InstallState::Failed;
189 return result;
190 }
191
192 if (cancelRequested_)
193 {
194 result.errorMessage = "Installation cancelled by user";
195 currentState_ = InstallState::Cancelled;
196 return result;
197 }
198
199 // Phase 3: Execute installation steps
200 currentState_ = InstallState::ExecutingSteps;
202 progress.stateDescription = "Installing";
203 updateProgress(progress, progressCallback);
204
205 if (!executeSteps(script, mutableConfig, result, variables, progressCallback))
206 {
207 currentState_ = InstallState::Failed;
208 return result;
209 }
210
211 if (cancelRequested_)
212 {
213 result.errorMessage = "Installation cancelled by user";
214 currentState_ = InstallState::Cancelled;
215 return result;
216 }
217
218 // Phase 4: Finalize
219 currentState_ = InstallState::Finalizing;
221 progress.stateDescription = "Finalizing";
222 updateProgress(progress, progressCallback);
223
224 if (!executeFinalize(script, mutableConfig, result, variables, progressCallback))
225 {
226 currentState_ = InstallState::Failed;
227 return result;
228 }
229
230 // Success!
231 auto endTime = std::chrono::steady_clock::now();
232 result.elapsedSeconds = static_cast<int>(
233 std::chrono::duration_cast<std::chrono::seconds>(endTime - startTime).count());
234
235 result.success = true;
236 result.installPath = substituteVariables("$GAMEDIR", variables);
237 result.winePrefixPath =
238 substituteVariables(script.prefix.empty() ? "$GAMEDIR/prefix" : script.prefix, variables);
239 result.executablePath = substituteVariables(script.executable, variables);
240 result.arguments = script.arguments;
241 result.workingDir = substituteVariables(script.workingDir, variables);
243
244 // Add wine config env vars
245 for (const auto& [key, value] : script.wineConfig.environment)
246 {
247 result.environmentVariables[key] = value;
248 }
249 result.dllOverrides = script.wineConfig.dllOverrides;
250
251 currentState_ = InstallState::Completed;
253 progress.overallPercent = 100;
254 progress.stateDescription = "Installation complete";
255 addLogMessage(progress, result, "Installation completed successfully!");
256 updateProgress(progress, progressCallback);
257
258 Logger::info("Installation: Completed {} in {} seconds", script.gameName,
259 result.elapsedSeconds);
260 return result;
261}
262
264 const InstallConfig& config,
265 const CompletionCallback& onComplete,
266 const ProgressCallback& onProgress)
267{
268 auto future =
269 std::make_shared<std::future<void>>(std::async(std::launch::async,
270 [script, config, onComplete, onProgress]()
271 {
272 InstallResult result =
273 install(script, config, onProgress);
274 if (onComplete)
275 onComplete(result);
276 }));
277 storeFuture(std::move(future));
278}
279
280// ==============================================================================
281// Control Methods
282// ==============================================================================
283
285{
286 cancelRequested_ = true;
288 Logger::info("Installation: Cancel requested");
289}
290
292{
293 InstallState state = currentState_;
294 return state != InstallState::Idle && state != InstallState::Completed &&
296}
297
299{
300 return currentState_;
301}
302
304{
305 std::lock_guard<std::mutex> lock(progressMutex_);
306 return currentProgress_;
307}
308
309// ==============================================================================
310// Validation
311// ==============================================================================
312
313std::vector<std::string> InstallationExecutor::validate(const LutrisInstallerScript& script,
314 const InstallConfig& config)
315{
316 std::vector<std::string> errors;
317
318 if (script.installerSlug.empty())
319 {
320 errors.push_back("Invalid installer script");
321 }
322
323 if (config.installPath.empty())
324 {
325 errors.push_back("Installation path is required");
326 }
327
328 // Check disk space
329 uint64_t required = estimateRequiredSpace(script);
330 uint64_t available = getAvailableSpace(config.installPath);
331
332 if (available > 0 && required > available)
333 {
334 std::ostringstream oss;
335 oss << "Insufficient disk space. Required: " << (required / (1024 * 1024)) << " MB, "
336 << "Available: " << (available / (1024 * 1024)) << " MB";
337 errors.push_back(oss.str());
338 }
339
340 // Check for manual files
341 for (const auto& file : script.files)
342 {
343 if (file.isManual)
344 {
345 errors.push_back("This installer requires manual file: " + file.id +
346 ". Automatic installation not supported.");
347 }
348 }
349
350 // Check for required tools.
351 // No-op for `extract`: the file path is only inspectable once the
352 // archive itself is downloaded; we leave a TODO so the placeholder
353 // loop body documents the intent, but skip the unused-variable lint
354 // by not naming a local that we won't read.
355 for (const auto& step : script.steps)
356 {
357 if (step.task == "extract")
358 {
359 // TODO: validate `step.params.at("file")` against the on-disk
360 // download once the install staging step has populated it.
361 }
362 }
363
364 // Check Wine availability if needed
365 if (script.runner == "wine")
366 {
367 std::string wineCheck = "command -v wine >/dev/null 2>&1";
368 if (std::system(wineCheck.c_str()) != 0)
369 {
370 errors.push_back("Wine is not installed");
371 }
372 }
373
374 return errors;
375}
376
378{
379 uint64_t total = 0;
380
381 // Sum download sizes
382 for (const auto& file : script.files)
383 {
384 total += file.size;
385 }
386
387 // Estimate extracted size (assume 2x compression ratio)
388 total *= 2;
389
390 // Add buffer for Wine prefix, etc.
391 total += 500 * 1024 * 1024; // 500 MB buffer
392
393 return total;
394}
395
396uint64_t InstallationExecutor::getAvailableSpace(const std::string& path)
397{
398 try
399 {
400 // Find existing parent directory
401 fs::path p(path);
402 while (!fs::exists(p) && p.has_parent_path())
403 {
404 p = p.parent_path();
405 }
406
407 if (fs::exists(p))
408 {
409 fs::space_info si = fs::space(p);
410 return si.available;
411 }
412 }
413 catch (const std::exception& e)
414 {
415 Logger::warn("Installation: Failed to get disk space: {}", e.what());
416 }
417
418 return 0;
419}
420
421// ==============================================================================
422// Phase Executors
423// ==============================================================================
424
425bool InstallationExecutor::executePrepare(const LutrisInstallerScript& /*script*/,
426 InstallConfig& /*config*/, InstallResult& result,
427 std::map<std::string, std::string>& variables,
428 const ProgressCallback& progress)
429{
430 // Note: script and config reserved for future use
431 InstallProgress prog;
433 prog.stateDescription = "Creating directories...";
434
435 // Create install directory
436 std::string installDir = substituteVariables("$GAMEDIR", variables);
437 try
438 {
439 fs::create_directories(installDir);
440 addLogMessage(prog, result, "Created install directory: " + installDir);
441 }
442 catch (const std::exception& e)
443 {
444 result.errorMessage = "Failed to create install directory: " + std::string(e.what());
445 Logger::error("Installation: {}", result.errorMessage);
446 return false;
447 }
448
449 // Create download cache directory
450 std::string cacheDir = substituteVariables("$CACHE", variables);
451 try
452 {
453 fs::create_directories(cacheDir);
454 }
455 catch (const std::exception& e)
456 {
457 result.errorMessage = "Failed to create cache directory: " + std::string(e.what());
458 Logger::error("Installation: {}", result.errorMessage);
459 return false;
460 }
461
462 // Update variables with actual paths
463 variables["GAMEDIR"] = installDir;
464 variables["CACHE"] = cacheDir;
465
466 updateProgress(prog, progress);
467 return true;
468}
469
470bool InstallationExecutor::executeDownloads(const LutrisInstallerScript& script,
471 const InstallConfig& config, InstallResult& result,
472 std::map<std::string, std::string>& variables,
473 const ProgressCallback& progress)
474{
475 if (script.files.empty())
476 {
477 return true; // Nothing to download
478 }
479
480 InstallProgress prog;
482 prog.totalSteps = static_cast<int>(script.files.size());
483
484 std::string cacheDir = variables["CACHE"];
485
486 int fileIndex = 0;
487 for (const auto& file : script.files)
488 {
489 if (cancelRequested_)
490 {
491 return false;
492 }
493
494 if (file.isManual)
495 {
496 result.errorMessage = "Manual file required: " + file.id;
497 return false;
498 }
499
500 prog.currentStep = fileIndex + 1;
501
502 // SECURITY (CWE-22): derive the on-disk name from the (untrusted)
503 // installer entry as a single path component so it cannot traverse
504 // out of the cache directory. Fall back to a deterministic name when
505 // the entry carries no usable component.
506 std::string safeName = safeCacheComponent(file.filename);
507 if (safeName.empty())
508 safeName = safeCacheComponent(file.id);
509 if (safeName.empty())
510 safeName = "file_" + std::to_string(fileIndex);
511 prog.currentFileName = safeName;
512 prog.currentOperation = "Downloading " + prog.currentFileName;
513 addLogMessage(prog, result, prog.currentOperation);
514 updateProgress(prog, progress);
515
516 // Determine local path
517 std::string localPath = cacheDir + "/" + prog.currentFileName;
518
519 // Defense-in-depth: reject anything that still resolves outside the
520 // cache directory (e.g. a symlinked cacheDir component).
521 if (!isPathWithin(localPath, cacheDir))
522 {
523 result.errorMessage = "Rejected unsafe download path for installer file: " + file.id;
524 Logger::error("Install: {}", result.errorMessage);
525 return false;
526 }
527
528 // Check if already downloaded
529 if (fs::exists(localPath))
530 {
531 bool valid = true;
532 if (!file.checksum.empty() && !config.skipHashVerification)
533 {
534 std::string checksumType = (file.checksum.length() == 32) ? "md5"
535 : (file.checksum.length() == 40) ? "sha1"
536 : "sha256";
537 valid = FileDownloadService::verifyChecksum(localPath, file.checksum, checksumType);
538 }
539
540 if (valid)
541 {
542 addLogMessage(prog, result, "Using cached file: " + prog.currentFileName);
543 variables[file.id] = localPath;
544 fileIndex++;
545 continue;
546 }
547 else
548 {
549 addLogMessage(prog, result, "Cached file failed checksum, re-downloading");
550 fs::remove(localPath);
551 }
552 }
553
554 // Download
555 DownloadRequest req;
556 req.url = file.url;
557 req.localPath = localPath;
558 req.expectedChecksum = file.checksum;
559 req.checksumType = file.checksum.length() == 32 ? "md5" : "sha256";
560
561 auto downloadProgress = [&prog, &progress](const DownloadProgress& dp)
562 {
563 prog.bytesDownloaded = dp.bytesDownloaded;
564 prog.totalBytes = dp.totalBytes;
565 prog.downloadSpeedBytesPerSec = dp.speedBytesPerSec;
566 prog.operationPercent = dp.percentComplete;
567 updateProgress(prog, progress);
568 };
569
570 DownloadResult dlResult = FileDownloadService::download(req, downloadProgress);
571
572 if (!dlResult.success)
573 {
574 result.errorMessage = "Download failed: " + dlResult.errorMessage;
575 Logger::error("Installation: {}", result.errorMessage);
576 return false;
577 }
578
579 result.totalBytesDownloaded += dlResult.bytesDownloaded;
580 variables[file.id] = localPath;
581
582 addLogMessage(prog, result, "Downloaded: " + prog.currentFileName);
583 fileIndex++;
584 }
585
586 return true;
587}
588
589bool InstallationExecutor::executeSteps(const LutrisInstallerScript& script,
590 const InstallConfig& config, InstallResult& result,
591 std::map<std::string, std::string>& variables,
592 const ProgressCallback& progress)
593{
594 InstallProgress prog;
596 prog.totalSteps = static_cast<int>(script.steps.size());
597
598 // Create Wine prefix if needed (for wine runner)
599 if (script.runner == "wine")
600 {
601 prog.currentOperation = "Creating Wine prefix...";
602 addLogMessage(prog, result, prog.currentOperation);
603 updateProgress(prog, progress);
604
605 std::string prefixPath = substituteVariables(
606 script.prefix.empty() ? "$GAMEDIR/prefix" : script.prefix, variables);
607
608 std::string arch = script.wineConfig.arch.empty() ? "win64" : script.wineConfig.arch;
609
610 if (!createWinePrefix(prefixPath, arch, config.wineVersion, result))
611 {
612 return false;
613 }
614
615 variables["WINEPREFIX"] = prefixPath;
616 variables["PREFIX"] = prefixPath;
617
618 // Run winetricks if specified in any task step
619 for (const auto& step : script.steps)
620 {
621 if (step.task == "task")
622 {
623 auto nameIt = step.params.find("name");
624 if (nameIt != step.params.end() && nameIt->second == "winetricks")
625 {
626 std::string verbs;
627 auto appIt = step.params.find("app");
628 if (appIt != step.params.end())
629 {
630 verbs = appIt->second;
631 }
632 else
633 {
634 auto argsIt = step.params.find("args");
635 if (argsIt != step.params.end())
636 {
637 verbs = argsIt->second;
638 }
639 }
640
641 if (!verbs.empty())
642 {
643 std::vector<std::string> verbList;
644 std::istringstream iss(verbs);
645 std::string verb;
646 while (iss >> verb)
647 {
648 verbList.push_back(verb);
649 }
650
651 prog.currentOperation = "Installing Wine components: " + verbs;
652 addLogMessage(prog, result, prog.currentOperation);
653 updateProgress(prog, progress);
654
655 runWinetricks(prefixPath, config.wineVersion, verbList, result);
656 }
657 }
658 }
659 }
660 }
661
662 // Execute each step
663 int stepIndex = 0;
664 for (const auto& step : script.steps)
665 {
666 if (cancelRequested_)
667 {
668 return false;
669 }
670
671 // Skip winetricks tasks (already handled above)
672 if (step.task == "task")
673 {
674 auto nameIt = step.params.find("name");
675 if (nameIt != step.params.end() && nameIt->second == "winetricks")
676 {
677 stepIndex++;
678 continue;
679 }
680 }
681
682 prog.currentStep = stepIndex + 1;
683 prog.currentOperation = step.description;
684 prog.operationPercent = 0;
685 addLogMessage(prog, result,
686 "Step " + std::to_string(stepIndex + 1) + ": " + step.description);
687 updateProgress(prog, progress);
688
689 if (!executeStep(step, variables, result))
690 {
691 // Non-fatal steps: log warning and continue
692 addWarning(prog, result, "Step failed: " + step.description);
693 Logger::warn("Installation: Step failed but continuing: {}", step.description);
694 }
695
696 prog.operationPercent = 100;
697 prog.overallPercent = ((stepIndex + 1) * 100) / prog.totalSteps;
698 updateProgress(prog, progress);
699
700 stepIndex++;
701 }
702
703 return true;
704}
705
706bool InstallationExecutor::executeFinalize(const LutrisInstallerScript& /*script*/,
707 const InstallConfig& config, InstallResult& result,
708 std::map<std::string, std::string>& variables,
709 const ProgressCallback& progress)
710{
711 InstallProgress prog;
713 prog.stateDescription = "Finalizing installation";
714
715 // Clean up download cache if requested
716 if (!config.keepDownloadedFiles)
717 {
718 std::string cacheDir = variables["CACHE"];
719 if (fs::exists(cacheDir))
720 {
721 addLogMessage(prog, result, "Cleaning up downloaded files...");
722 try
723 {
724 fs::remove_all(cacheDir);
725 }
726 catch (const std::exception& e)
727 {
728 addWarning(prog, result, "Failed to clean up cache: " + std::string(e.what()));
729 }
730 }
731 }
732
733 // Create desktop shortcut if requested
734 if (config.createDesktopShortcut)
735 {
736 addLogMessage(prog, result, "Creating desktop shortcut...");
737 if (!createDesktopShortcut(result))
738 {
739 result.warnings.push_back("Failed to create desktop shortcut");
740 }
741 }
742
743 // Create menu entry if requested
744 if (config.createMenuEntry)
745 {
746 addLogMessage(prog, result, "Creating menu entry...");
747 if (!createMenuEntry(result))
748 {
749 result.warnings.push_back("Failed to create menu entry");
750 }
751 }
752
753 updateProgress(prog, progress);
754 return true;
755}
756
757// ==============================================================================
758// Step Executors
759// ==============================================================================
760
761bool InstallationExecutor::executeStep(const LutrisInstallStep& step,
762 std::map<std::string, std::string>& variables,
763 InstallResult& result)
764{
765 Logger::debug("Installation: Executing step '{}' with {} params", step.task,
766 step.params.size());
767
768 if (step.task == "extract")
769 {
770 return stepExtract(step, variables, result);
771 }
772 else if (step.task == "copy" || step.task == "merge")
773 {
774 return stepCopy(step, variables, result);
775 }
776 else if (step.task == "move")
777 {
778 return stepMove(step, variables, result);
779 }
780 else if (step.task == "execute")
781 {
782 return stepExecute(step, variables, result);
783 }
784 else if (step.task == "write_file" || step.task == "write_json" || step.task == "write_config")
785 {
786 return stepWriteFile(step, variables, result);
787 }
788 else if (step.task == "chmodx")
789 {
790 return stepChmodx(step, variables, result);
791 }
792 else if (step.task == "delete")
793 {
794 return stepDelete(step, variables, result);
795 }
796 else if (step.task == "rename")
797 {
798 return stepRename(step, variables, result);
799 }
800 else if (step.task == "task")
801 {
802 return stepTask(step, variables, result);
803 }
804 else
805 {
806 Logger::warn("Installation: Unknown step type: {}", step.task);
807 return true; // Don't fail on unknown steps
808 }
809}
810
811bool InstallationExecutor::stepExtract(const LutrisInstallStep& step,
812 std::map<std::string, std::string>& variables,
813 InstallResult& result)
814{
815 std::string fileRef = step.params.count("file") ? step.params.at("file") : "";
816 std::string dst = step.params.count("dst") ? step.params.at("dst") : "$GAMEDIR";
817
818 std::string archivePath = substituteVariables(fileRef, variables);
819 std::string destPath = substituteVariables(dst, variables);
820
821 Logger::info("Installation: Extracting {} to {}", archivePath, destPath);
822
823 if (!fs::exists(archivePath))
824 {
825 result.errorMessage = "Archive not found: " + archivePath;
826 return false;
827 }
828
829 if (!isPathWithinHome(destPath))
830 {
831 result.errorMessage = "Extract destination outside home directory: " + destPath;
832 Logger::error("Installation: Blocked extract to unsafe path: {}", destPath);
833 return false;
834 }
835
836 ExtractRequest req;
837 req.archivePath = archivePath;
838 req.destinationDir = destPath;
839
840 ExtractResult extractResult = ArchiveExtractService::extract(req);
841
842 if (!extractResult.success)
843 {
844 result.errorMessage = "Extraction failed: " + extractResult.errorMessage;
845 return false;
846 }
847
848 result.totalBytesExtracted += extractResult.totalBytesExtracted;
849 return true;
850}
851
852bool InstallationExecutor::stepCopy(const LutrisInstallStep& step,
853 std::map<std::string, std::string>& variables,
854 InstallResult& result)
855{
856 std::string src = step.params.count("src") ? step.params.at("src") : "";
857 std::string dst = step.params.count("dst") ? step.params.at("dst") : "";
858
859 std::string srcPath = substituteVariables(src, variables);
860 std::string dstPath = substituteVariables(dst, variables);
861
862 // Destination must stay within home; source is validated by the filesystem (copy will fail if
863 // inaccessible)
864 if (!isPathWithinHome(dstPath))
865 {
866 Logger::error("Installation: stepCopy refused dst '{}': path outside home directory",
867 dstPath);
868 result.errorMessage = "Copy refused: destination path outside home directory";
869 return false;
870 }
871
872 Logger::info("Installation: Copying {} to {}", srcPath, dstPath);
873
874 try
875 {
876 // Handle glob patterns
877 if (srcPath.find('*') != std::string::npos)
878 {
879 // Simple glob handling. The naive prior implementation just
880 // substituted `*` -> `.*` and constructed a regex, which left
881 // `.`, `+`, `(`, `?`, etc. as regex metacharacters. A glob like
882 // `mygame.exe` then incorrectly matched `mygame_exe` (and
883 // `mygame.exe.bak`). Proper translation:
884 // 1. Escape every regex metacharacter EXCEPT `*`.
885 // 2. Translate `*` -> `.*` and `?` -> `.` (POSIX glob).
886 // 3. Anchor with ^...$ so we match the whole filename.
887 fs::path srcDir = fs::path(srcPath).parent_path();
888 std::string pattern = fs::path(srcPath).filename().string();
889
890 std::string regexPattern;
891 regexPattern.reserve(pattern.size() * 2 + 2);
892 regexPattern.push_back('^');
893 for (char c : pattern)
894 {
895 switch (c)
896 {
897 case '*':
898 regexPattern += ".*";
899 break;
900 case '?':
901 regexPattern += '.';
902 break;
903 // ECMAScript regex (std::regex default) metachars to escape
904 case '.':
905 case '+':
906 case '(':
907 case ')':
908 case '[':
909 case ']':
910 case '{':
911 case '}':
912 case '|':
913 case '^':
914 case '$':
915 case '\\':
916 regexPattern.push_back('\\');
917 regexPattern.push_back(c);
918 break;
919 default:
920 regexPattern.push_back(c);
921 }
922 }
923 regexPattern.push_back('$');
924
925 std::regex fileRegex(regexPattern);
926
927 for (const auto& entry : fs::directory_iterator(srcDir))
928 {
929 if (std::regex_match(entry.path().filename().string(), fileRegex))
930 {
931 fs::path target = fs::path(dstPath) / entry.path().filename();
932 fs::create_directories(target.parent_path());
933 fs::copy(entry.path(), target,
934 fs::copy_options::recursive | fs::copy_options::overwrite_existing);
935 }
936 }
937 }
938 else
939 {
940 fs::create_directories(fs::path(dstPath).parent_path());
941 fs::copy(srcPath, dstPath,
942 fs::copy_options::recursive | fs::copy_options::overwrite_existing);
943 }
944 }
945 catch (const std::exception& e)
946 {
947 result.errorMessage = "Copy failed: " + std::string(e.what());
948 return false;
949 }
950
951 return true;
952}
953
954bool InstallationExecutor::stepMove(const LutrisInstallStep& step,
955 std::map<std::string, std::string>& variables,
956 InstallResult& result)
957{
958 std::string src = step.params.count("src") ? step.params.at("src") : "";
959 std::string dst = step.params.count("dst") ? step.params.at("dst") : "";
960
961 std::string srcPath = substituteVariables(src, variables);
962 std::string dstPath = substituteVariables(dst, variables);
963
964 if (!isPathWithinHome(srcPath) || !isPathWithinHome(dstPath))
965 {
966 Logger::error("Installation: stepMove refused '{}' -> '{}': path outside home directory",
967 srcPath, dstPath);
968 result.errorMessage = "Move refused: path outside home directory";
969 return false;
970 }
971
972 Logger::info("Installation: Moving {} to {}", srcPath, dstPath);
973
974 try
975 {
976 fs::create_directories(fs::path(dstPath).parent_path());
977 fs::rename(srcPath, dstPath);
978 }
979 catch (const std::exception& e)
980 {
981 result.errorMessage = "Move failed: " + std::string(e.what());
982 return false;
983 }
984
985 return true;
986}
987
988bool InstallationExecutor::stepExecute(const LutrisInstallStep& step,
989 std::map<std::string, std::string>& variables,
990 InstallResult& /*result*/)
991{
992 std::string file = step.params.count("file") ? step.params.at("file") : "";
993 std::string args = step.params.count("args") ? step.params.at("args") : "";
994
995 std::string exePath = substituteVariables(file, variables);
996 std::string arguments = substituteVariables(args, variables);
997
998 Logger::info("Installation: Executing {} {}", exePath, arguments);
999
1000 // For Windows executables, run with Wine
1001 if (endsWith(exePath, ".exe") || endsWith(exePath, ".msi"))
1002 {
1003 std::string prefix = variables.count("WINEPREFIX") ? variables["WINEPREFIX"] : "";
1004
1005 std::ostringstream cmd;
1006 if (!prefix.empty())
1007 {
1008 cmd << "WINEPREFIX=" << ShellUtils::escapeArg(prefix) << " ";
1009 }
1010 cmd << "wine " << ShellUtils::escapeArg(exePath) << " " << ShellUtils::escapeArg(arguments);
1011 cmd << " 2>&1";
1012
1013 std::string output;
1014 int exitCode = runCommand(cmd.str(), output);
1015
1016 if (exitCode != 0)
1017 {
1018 Logger::warn("Installation: Execute returned non-zero: {}", exitCode);
1019 // Don't fail - many installers return non-zero even on success
1020 }
1021 }
1022 else
1023 {
1024 // Native executable
1025 std::ostringstream cmd;
1026 cmd << ShellUtils::escapeArg(exePath) << " " << ShellUtils::escapeArg(arguments) << " 2>&1";
1027
1028 std::string output;
1029 int exitCode = runCommand(cmd.str(), output);
1030
1031 if (exitCode != 0)
1032 {
1033 Logger::warn("Installation: Execute returned non-zero: {}", exitCode);
1034 }
1035 }
1036
1037 return true;
1038}
1039
1040bool InstallationExecutor::stepWriteFile(const LutrisInstallStep& step,
1041 std::map<std::string, std::string>& variables,
1042 InstallResult& result)
1043{
1044 std::string file = step.params.count("file") ? step.params.at("file") : "";
1045 std::string content = step.params.count("content") ? step.params.at("content") : "";
1046
1047 std::string filePath = substituteVariables(file, variables);
1048 std::string fileContent = substituteVariables(content, variables);
1049
1050 if (!isPathWithinHome(filePath))
1051 {
1052 Logger::error("Installation: stepWriteFile refused '{}': path outside home directory",
1053 filePath);
1054 result.errorMessage = "Write file refused: path outside home directory";
1055 return false;
1056 }
1057
1058 Logger::info("Installation: Writing file {}", filePath);
1059
1060 try
1061 {
1062 fs::create_directories(fs::path(filePath).parent_path());
1063 std::ofstream out(filePath);
1064 // ofstream silently sets failbit on open / write failure; explicitly
1065 // probe so a permission-denied / read-only-FS / ENOSPC mid-write
1066 // surfaces as an error instead of returning success on a truncated
1067 // or unwritten file.
1068 if (!out.is_open())
1069 {
1070 result.errorMessage = "Failed to open " + filePath + " for writing";
1071 return false;
1072 }
1073 out << fileContent;
1074 if (!out.good())
1075 {
1076 result.errorMessage = "Write to " + filePath + " failed (disk full or I/O error)";
1077 // Best-effort cleanup of the partial/truncated file.
1078 std::error_code rmEc;
1079 fs::remove(filePath, rmEc);
1080 return false;
1081 }
1082 out.close();
1083 if (!out.good())
1084 {
1085 result.errorMessage = "Failed to flush " + filePath + " on close";
1086 return false;
1087 }
1088 }
1089 catch (const std::exception& e)
1090 {
1091 result.errorMessage = "Write file failed: " + std::string(e.what());
1092 return false;
1093 }
1094
1095 return true;
1096}
1097
1098bool InstallationExecutor::stepTask(const LutrisInstallStep& step,
1099 std::map<std::string, std::string>& variables,
1100 InstallResult& result)
1101{
1102 std::string name = step.params.count("name") ? step.params.at("name") : "";
1103
1104 if (name == "create_prefix")
1105 {
1106 std::string prefix =
1107 step.params.count("prefix") ? step.params.at("prefix") : "$GAMEDIR/prefix";
1108 std::string arch = step.params.count("arch") ? step.params.at("arch") : "win64";
1109
1110 std::string prefixPath = substituteVariables(prefix, variables);
1111 return createWinePrefix(prefixPath, arch, "", result);
1112 }
1113 else if (name == "set_regedit")
1114 {
1115 std::string prefix = variables.count("WINEPREFIX") ? variables["WINEPREFIX"] : "";
1116 std::string path = step.params.count("path") ? step.params.at("path") : "";
1117 std::string key = step.params.count("key") ? step.params.at("key") : "";
1118 std::string value = step.params.count("value") ? step.params.at("value") : "";
1119 std::string type = step.params.count("type") ? step.params.at("type") : "REG_SZ";
1120
1121 return setWineRegistry(prefix, "", path, key, value, type, result);
1122 }
1123 else if (name == "winekill")
1124 {
1125 std::string prefix = variables.count("WINEPREFIX") ? variables["WINEPREFIX"] : "";
1126 std::ostringstream cmd;
1127 if (!prefix.empty())
1128 {
1129 cmd << "WINEPREFIX=" << ShellUtils::escapeArg(prefix) << " ";
1130 }
1131 cmd << "wineserver -k 2>/dev/null";
1132 [[maybe_unused]] int ret = std::system(cmd.str().c_str()); // Best effort cleanup
1133 return true;
1134 }
1135
1136 Logger::warn("Installation: Unknown task: {}", name);
1137 return true;
1138}
1139
1140bool InstallationExecutor::stepChmodx(const LutrisInstallStep& step,
1141 std::map<std::string, std::string>& variables,
1142 InstallResult& result)
1143{
1144 std::string file = step.params.count("file") ? step.params.at("file") : "";
1145 std::string filePath = substituteVariables(file, variables);
1146
1147 if (!isPathWithinHome(filePath))
1148 {
1149 Logger::error("Installation: stepChmodx refused '{}': path outside home directory",
1150 filePath);
1151 result.errorMessage = "chmod refused: path outside home directory";
1152 return false;
1153 }
1154
1155 Logger::info("Installation: Making executable: {}", filePath);
1156
1157 try
1158 {
1159 fs::permissions(filePath,
1160 fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec,
1161 fs::perm_options::add);
1162 }
1163 catch (const std::exception& e)
1164 {
1165 result.errorMessage = "chmod failed: " + std::string(e.what());
1166 return false;
1167 }
1168
1169 return true;
1170}
1171
1172bool InstallationExecutor::stepDelete(const LutrisInstallStep& step,
1173 std::map<std::string, std::string>& variables,
1174 InstallResult& /*result*/)
1175{
1176 std::string file = step.params.count("file") ? step.params.at("file") : "";
1177 std::string filePath = substituteVariables(file, variables);
1178
1179 if (!isPathWithinHome(filePath))
1180 {
1181 Logger::error("Installation: stepDelete refused '{}': path outside home directory",
1182 filePath);
1183 return false;
1184 }
1185
1186 Logger::info("Installation: Deleting: {}", filePath);
1187
1188 try
1189 {
1190 fs::remove_all(filePath);
1191 }
1192 catch (const std::exception& e)
1193 {
1194 Logger::warn("Installation: Delete failed: {}", e.what());
1195 // Don't fail on delete errors
1196 }
1197
1198 return true;
1199}
1200
1201bool InstallationExecutor::stepRename(const LutrisInstallStep& step,
1202 std::map<std::string, std::string>& variables,
1203 InstallResult& result)
1204{
1205 std::string src = step.params.count("src") ? step.params.at("src") : "";
1206 std::string dst = step.params.count("dst") ? step.params.at("dst") : "";
1207
1208 std::string srcPath = substituteVariables(src, variables);
1209 std::string dstPath = substituteVariables(dst, variables);
1210
1211 if (!isPathWithinHome(srcPath) || !isPathWithinHome(dstPath))
1212 {
1213 Logger::error("Installation: stepRename refused '{}' -> '{}': path outside home directory",
1214 srcPath, dstPath);
1215 result.errorMessage = "Rename refused: path outside home directory";
1216 return false;
1217 }
1218
1219 Logger::info("Installation: Renaming {} to {}", srcPath, dstPath);
1220
1221 try
1222 {
1223 fs::rename(srcPath, dstPath);
1224 }
1225 catch (const std::exception& e)
1226 {
1227 result.errorMessage = "Rename failed: " + std::string(e.what());
1228 return false;
1229 }
1230
1231 return true;
1232}
1233
1234// ==============================================================================
1235// Wine Management
1236// ==============================================================================
1237
1238bool InstallationExecutor::createWinePrefix(const std::string& prefixPath, const std::string& arch,
1239 const std::string& wineVersion, InstallResult& result)
1240{
1241 Logger::info("Installation: Creating Wine prefix at {} ({})", prefixPath, arch);
1242
1243 // Create prefix directory
1244 try
1245 {
1246 fs::create_directories(prefixPath);
1247 }
1248 catch (const std::exception& e)
1249 {
1250 result.errorMessage = "Failed to create prefix directory: " + std::string(e.what());
1251 return false;
1252 }
1253
1254 // Initialize Wine prefix
1255 std::ostringstream cmd;
1256 cmd << "WINEPREFIX=" << ShellUtils::escapeArg(prefixPath) << " ";
1257 cmd << "WINEARCH=" << ShellUtils::escapeArg(arch) << " ";
1258
1259 if (!wineVersion.empty())
1260 {
1261 std::string winePath = getWinePath(wineVersion);
1262 if (!winePath.empty())
1263 {
1264 cmd << "WINE=" << ShellUtils::escapeArg(winePath) << " ";
1265 }
1266 }
1267
1268 cmd << "wineboot -u 2>&1";
1269
1270 std::string output;
1271 int exitCode = runCommand(cmd.str(), output);
1272
1273 if (exitCode != 0)
1274 {
1275 Logger::warn("Installation: wineboot returned non-zero: {}", exitCode);
1276 // Don't fail - wineboot sometimes returns non-zero even on success
1277 }
1278
1279 // Wait for wineserver to finish
1280 std::this_thread::sleep_for(std::chrono::seconds(2));
1281
1282 return true;
1283}
1284
1285bool InstallationExecutor::runWinetricks(const std::string& prefixPath,
1286 const std::string& /*wineVersion*/,
1287 const std::vector<std::string>& verbs,
1288 InstallResult& result)
1289{
1290 if (verbs.empty())
1291 {
1292 return true;
1293 }
1294
1295 // Check if winetricks is installed
1296 if (std::system("command -v winetricks >/dev/null 2>&1") != 0)
1297 {
1298 result.warnings.push_back("winetricks not installed, skipping component installation");
1299 return true;
1300 }
1301
1302 std::ostringstream verbsStr;
1303 for (size_t i = 0; i < verbs.size(); ++i)
1304 {
1305 if (i > 0)
1306 verbsStr << " ";
1307 verbsStr << verbs[i];
1308 }
1309
1310 Logger::info("Installation: Running winetricks: {}", verbsStr.str());
1311
1312 std::ostringstream cmd;
1313 cmd << "WINEPREFIX=" << ShellUtils::escapeArg(prefixPath) << " ";
1314 cmd << "winetricks -q";
1315 for (const auto& verb : verbs)
1316 {
1317 cmd << " " << ShellUtils::escapeArg(verb);
1318 }
1319 cmd << " 2>&1";
1320
1321 std::string output;
1322 int exitCode = runCommand(cmd.str(), output);
1323
1324 if (exitCode != 0)
1325 {
1326 Logger::warn("Installation: winetricks returned non-zero: {}", exitCode);
1327 result.warnings.push_back("winetricks may have failed for some components");
1328 }
1329
1330 return true;
1331}
1332
1333bool InstallationExecutor::setWineRegistry(const std::string& prefixPath,
1334 const std::string& /*wineVersion*/,
1335 const std::string& path, const std::string& key,
1336 const std::string& value, const std::string& type,
1337 InstallResult& /*result*/)
1338{
1339 Logger::info("Installation: Setting registry {}\\{} = {}", path, key, value);
1340
1341 std::ostringstream cmd;
1342 cmd << "WINEPREFIX=" << ShellUtils::escapeArg(prefixPath) << " ";
1343 cmd << "wine reg add " << ShellUtils::escapeArg(path) << " ";
1344 cmd << "/v " << ShellUtils::escapeArg(key) << " ";
1345 cmd << "/t " << ShellUtils::escapeArg(type) << " ";
1346 cmd << "/d " << ShellUtils::escapeArg(value) << " /f 2>&1";
1347
1348 std::string output;
1349 int exitCode = runCommand(cmd.str(), output);
1350
1351 return exitCode == 0;
1352}
1353
1354// ==============================================================================
1355// Desktop Integration
1356// ==============================================================================
1357
1358bool InstallationExecutor::createDesktopShortcut(const InstallResult& result)
1359{
1360 const char* home = std::getenv("HOME");
1361 if (!home)
1362 {
1363 Logger::warn("Installation: Cannot create desktop shortcut - HOME not set");
1364 return false;
1365 }
1366
1367 std::string desktopDir = std::string(home) + "/Desktop";
1368
1369 // Check if Desktop directory exists, try XDG if not
1370 if (!fs::exists(desktopDir))
1371 {
1372 // Try XDG user dirs
1373 std::string xdgConfig = std::string(home) + "/.config/user-dirs.dirs";
1374 if (fs::exists(xdgConfig))
1375 {
1376 std::ifstream file(xdgConfig);
1377 std::string line;
1378 while (std::getline(file, line))
1379 {
1380 if (line.find("XDG_DESKTOP_DIR") != std::string::npos)
1381 {
1382 size_t start = line.find('"');
1383 size_t end = line.rfind('"');
1384 if (start != std::string::npos && end > start)
1385 {
1386 desktopDir = line.substr(start + 1, end - start - 1);
1387 // Expand $HOME
1388 size_t homePos = desktopDir.find("$HOME");
1389 if (homePos != std::string::npos)
1390 {
1391 desktopDir.replace(homePos, 5, home);
1392 }
1393 break;
1394 }
1395 }
1396 }
1397 }
1398 }
1399
1400 if (!fs::exists(desktopDir))
1401 {
1402 Logger::warn("Installation: Desktop directory not found: {}", desktopDir);
1403 return false;
1404 }
1405
1406 // Create .desktop file
1407 std::string safeName = result.gameName;
1408 // Sanitize filename
1409 for (char& c : safeName)
1410 {
1411 if (!std::isalnum(static_cast<unsigned char>(c)) && c != ' ' && c != '-' && c != '_')
1412 {
1413 c = '_';
1414 }
1415 }
1416
1417 std::string desktopFile = desktopDir + "/" + safeName + ".desktop";
1418
1419 std::ofstream file(desktopFile);
1420 if (!file.is_open())
1421 {
1422 Logger::warn("Installation: Failed to create desktop file: {}", desktopFile);
1423 return false;
1424 }
1425
1426 const std::string safeDisplayName = sanitizeDesktopField(result.gameName);
1427 file << "[Desktop Entry]\n";
1428 file << "Type=Application\n";
1429 file << "Name=" << safeDisplayName << "\n";
1430 file << "Comment=Launch " << safeDisplayName << " via Game Launcher\n";
1431
1432 // Build exec command — use escapeDesktopExec (XDG-spec-compliant double-
1433 // quote form) for each token. The Exec= field is *not* a shell command;
1434 // ShellUtils::escapeArg's single-quote form would violate the spec.
1435 if (result.runner == "wine" || result.runner == "proton")
1436 {
1437 file << "Exec=env " << escapeDesktopExec("WINEPREFIX=" + result.winePrefixPath) << " wine "
1439 }
1440 else
1441 {
1442 file << "Exec=" << escapeDesktopExec(result.executablePath);
1443 }
1444
1445 if (!result.arguments.empty())
1446 {
1447 std::istringstream argStream(result.arguments);
1448 std::string arg;
1449 while (argStream >> arg)
1450 file << " " << escapeDesktopExec(arg);
1451 }
1452 file << "\n";
1453
1454 const std::string safePath =
1455 sanitizeDesktopField(result.workingDir.empty() ? result.installPath : result.workingDir);
1456 file << "Path=" << safePath << "\n";
1457 file << "Terminal=false\n";
1458 file << "Categories=Game;\n";
1459
1460 file.close();
1461
1462 // Mark the .desktop as executable so file managers will offer to launch it.
1463 // error_code form so an EACCES (e.g. AppArmor revoked perms between create
1464 // and chmod, or a concurrent helper renamed the file) doesn't propagate as
1465 // a filesystem_error and abort the install — the file is already written.
1466 std::error_code permEc;
1467 fs::permissions(desktopFile,
1468 fs::perms::owner_exec | fs::perms::group_exec | fs::perms::others_exec,
1469 fs::perm_options::add, permEc);
1470 if (permEc)
1471 {
1472 Logger::warn("Installation: chmod +x on {} failed: {} (file still created)", desktopFile,
1473 permEc.message());
1474 }
1475
1476 Logger::info("Installation: Created desktop shortcut: {}", desktopFile);
1477 return true;
1478}
1479
1480bool InstallationExecutor::createMenuEntry(const InstallResult& result)
1481{
1482 const char* home = std::getenv("HOME");
1483 if (!home)
1484 {
1485 Logger::warn("Installation: Cannot create menu entry - HOME not set");
1486 return false;
1487 }
1488
1489 // XDG applications directory
1490 std::string applicationsDir = std::string(home) + "/.local/share/applications";
1491
1492 // Create directory if it doesn't exist
1493 if (!fs::exists(applicationsDir))
1494 {
1495 try
1496 {
1497 fs::create_directories(applicationsDir);
1498 }
1499 catch (const std::exception& e)
1500 {
1501 Logger::warn("Installation: Failed to create applications dir: {}", e.what());
1502 return false;
1503 }
1504 }
1505
1506 // Create .desktop file with unique name
1507 std::string safeName = result.gameSlug.empty() ? result.gameName : result.gameSlug;
1508 // Sanitize filename
1509 for (char& c : safeName)
1510 {
1511 if (!std::isalnum(static_cast<unsigned char>(c)) && c != '-' && c != '_')
1512 {
1513 c = '_';
1514 }
1515 }
1516 // Convert to lowercase
1517 std::transform(safeName.begin(), safeName.end(), safeName.begin(),
1518 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
1519
1520 std::string desktopFile = applicationsDir + "/gamelauncher-" + safeName + ".desktop";
1521
1522 std::ofstream file(desktopFile);
1523 if (!file.is_open())
1524 {
1525 Logger::warn("Installation: Failed to create menu entry: {}", desktopFile);
1526 return false;
1527 }
1528
1529 const std::string safeDisplayName = sanitizeDesktopField(result.gameName);
1530 file << "[Desktop Entry]\n";
1531 file << "Type=Application\n";
1532 file << "Name=" << safeDisplayName << "\n";
1533 file << "Comment=Launch " << safeDisplayName << " via Game Launcher\n";
1534
1535 // Build exec command — use escapeDesktopExec (XDG-spec-compliant double-
1536 // quote form) for each token. See createDesktopShortcut for rationale.
1537 if (result.runner == "wine" || result.runner == "proton")
1538 {
1539 file << "Exec=env " << escapeDesktopExec("WINEPREFIX=" + result.winePrefixPath) << " wine "
1541 }
1542 else
1543 {
1544 file << "Exec=" << escapeDesktopExec(result.executablePath);
1545 }
1546
1547 if (!result.arguments.empty())
1548 {
1549 std::istringstream argStream(result.arguments);
1550 std::string arg;
1551 while (argStream >> arg)
1552 file << " " << escapeDesktopExec(arg);
1553 }
1554 file << "\n";
1555
1556 const std::string safeWorkDir =
1557 sanitizeDesktopField(result.workingDir.empty() ? result.installPath : result.workingDir);
1558 file << "Path=" << safeWorkDir << "\n";
1559 file << "Terminal=false\n";
1560 file << "Categories=Game;\n";
1561 file << "Keywords=game;gaming;wine;\n";
1562
1563 file.close();
1564
1565 Logger::info("Installation: Created menu entry: {}", desktopFile);
1566
1567 // Update desktop database using the already-expanded path (avoids shell tilde expansion)
1568 [[maybe_unused]] int ret = std::system(
1569 ("update-desktop-database " + ShellUtils::escapeArg(applicationsDir) + " 2>/dev/null &")
1570 .c_str());
1571
1572 return true;
1573}
1574
1575// ==============================================================================
1576// Variable Handling
1577// ==============================================================================
1578
1579std::map<std::string, std::string>
1580InstallationExecutor::buildVariables(const LutrisInstallerScript& script,
1581 const InstallConfig& config)
1582{
1583 std::map<std::string, std::string> vars;
1584
1585 // Standard variables
1586 vars["HOME"] = expandPath("~");
1587 const char* userEnv = getenv("USER");
1588 vars["USER"] = userEnv ? userEnv : "user";
1589
1590 // Installation paths
1591 vars["GAMEDIR"] = expandPath(config.installPath);
1592 vars["CACHE"] = config.downloadCachePath.empty()
1593 ? expandPath("~/.cache/gamelauncher/downloads/" + script.gameSlug)
1594 : expandPath(config.downloadCachePath);
1595
1596 // Wine prefix
1597 if (!config.winePrefixPath.empty())
1598 {
1599 vars["WINEPREFIX"] = expandPath(config.winePrefixPath);
1600 vars["PREFIX"] = vars["WINEPREFIX"];
1601 }
1602
1603 // Game info
1604 vars["GAME_SLUG"] = script.gameSlug;
1605 vars["INSTALLER_SLUG"] = script.installerSlug;
1606
1607 // Custom variables from config
1608 for (const auto& [key, value] : config.customVariables)
1609 {
1610 vars[key] = expandPath(value);
1611 }
1612
1613 return vars;
1614}
1615
1616std::string
1617InstallationExecutor::substituteVariables(const std::string& input,
1618 const std::map<std::string, std::string>& variables)
1619{
1620 std::string result = input;
1621
1622 // Replace $VAR and ${VAR} patterns
1623 for (const auto& [key, value] : variables)
1624 {
1625 // Replace $VAR
1626 std::string pattern1 = "$" + key;
1627 size_t pos = 0;
1628 while ((pos = result.find(pattern1, pos)) != std::string::npos)
1629 {
1630 // Check it's not part of a longer variable name
1631 size_t nextPos = pos + pattern1.length();
1632 if (nextPos >= result.length() ||
1633 !std::isalnum(static_cast<unsigned char>(result[nextPos])))
1634 {
1635 result.replace(pos, pattern1.length(), value);
1636 pos += value.length();
1637 }
1638 else
1639 {
1640 pos++;
1641 }
1642 }
1643
1644 // Replace ${VAR}
1645 std::string pattern2 = "${" + key + "}";
1646 pos = 0;
1647 while ((pos = result.find(pattern2, pos)) != std::string::npos)
1648 {
1649 result.replace(pos, pattern2.length(), value);
1650 pos += value.length();
1651 }
1652 }
1653
1654 // Expand ~ to home
1655 if (!result.empty() && result[0] == '~')
1656 {
1657 result = expandPath(result);
1658 }
1659
1660 return result;
1661}
1662
1663std::string InstallationExecutor::expandPath(const std::string& path)
1664{
1665 if (path.empty())
1666 {
1667 return path;
1668 }
1669
1670 std::string result = path;
1671
1672 // Expand ~
1673 if (result[0] == '~')
1674 {
1675 const char* home = getenv("HOME");
1676 if (home)
1677 {
1678 result = std::string(home) + result.substr(1);
1679 }
1680 }
1681
1682 return result;
1683}
1684
1685// ==============================================================================
1686// Utility Methods
1687// ==============================================================================
1688
1689void InstallationExecutor::updateProgress(InstallProgress& progress,
1690 const ProgressCallback& callback)
1691{
1692 {
1693 std::lock_guard<std::mutex> lock(progressMutex_);
1694 currentProgress_ = progress;
1695 }
1696
1697 if (callback)
1698 {
1699 callback(progress);
1700 }
1701}
1702
1703void InstallationExecutor::addLogMessage(InstallProgress& progress, InstallResult& result,
1704 const std::string& message)
1705{
1706 auto now = std::chrono::system_clock::now();
1707 auto time = std::chrono::system_clock::to_time_t(now);
1708 std::tm tm{};
1709 localtime_r(&time, &tm);
1710
1711 char timestamp[32];
1712 std::strftime(timestamp, sizeof(timestamp), "[%H:%M:%S]", &tm);
1713
1714 std::string logLine = std::string(timestamp) + " " + message;
1715 progress.logMessages.push_back(logLine);
1716 result.logMessages.push_back(logLine);
1717
1718 Logger::info("Installation: {}", message);
1719}
1720
1721void InstallationExecutor::addWarning(InstallProgress& progress, InstallResult& result,
1722 const std::string& warning)
1723{
1724 progress.warnings.push_back(warning);
1725 result.warnings.push_back(warning);
1726 Logger::warn("Installation: {}", warning);
1727}
1728
1729int InstallationExecutor::runCommand(const std::string& command, std::string& output)
1730{
1731 FILE* pipe = popen(command.c_str(), "r");
1732 if (!pipe)
1733 {
1734 output = "Failed to execute command";
1735 return -1;
1736 }
1737
1738 std::array<char, 4096> buffer;
1739 output.clear();
1740
1741 constexpr size_t kMaxOutput = 16u * 1024 * 1024; // 16 MB
1742 while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
1743 {
1744 output += buffer.data();
1745 if (output.size() > kMaxOutput)
1746 break;
1747 }
1748
1749 int status = pclose(pipe);
1750 if (status == -1)
1751 return 255; // pclose failed — treat as error
1752 if (WIFEXITED(status))
1753 return WEXITSTATUS(status);
1754 if (WIFSIGNALED(status))
1755 return 128 + WTERMSIG(status);
1756 return 255;
1757}
1758
1759std::string InstallationExecutor::getWinePath(const std::string& version)
1760{
1761 // Check common Wine installation paths
1762 std::vector<std::string> searchPaths = {
1763 "/usr/bin/wine",
1764 "/usr/local/bin/wine",
1765 expandPath("~/.local/share/lutris/runners/wine/" + version + "/bin/wine"),
1766 expandPath("~/.steam/steam/compatibilitytools.d/" + version + "/proton"),
1767 };
1768
1769 for (const auto& path : searchPaths)
1770 {
1771 if (fs::exists(path))
1772 {
1773 return path;
1774 }
1775 }
1776
1777 // Return empty for system default
1778 return "";
1779}
static bool endsWith(const std::string &str, const std::string &suffix)
static ExtractResult extract(const ExtractRequest &request, const ProgressCallback &progressCallback=nullptr)
Extract an archive.
static DownloadResult download(const DownloadRequest &request, const ProgressCallback &progressCallback=nullptr)
Download a file with optional progress tracking.
static void cancel()
Cancel the current download operation.
static bool verifyChecksum(const std::string &filePath, const std::string &expected, const std::string &type)
Verify file checksum.
std::function< void(const InstallProgress &)> ProgressCallback
static bool isInstalling()
Check if an installation is in progress.
static InstallState getCurrentState()
Get current installation state.
std::function< void(const InstallResult &)> CompletionCallback
static uint64_t getAvailableSpace(const std::string &path)
Get available disk space at path.
static uint64_t estimateRequiredSpace(const LutrisInstallerScript &script)
Calculate required disk space.
static std::vector< std::string > validate(const LutrisInstallerScript &script, const InstallConfig &config)
Validate that an installation can proceed.
static InstallProgress getCurrentProgress()
Get current progress.
static void cancel()
Cancel current installation.
static void installAsync(const LutrisInstallerScript &script, const InstallConfig &config, const CompletionCallback &onComplete, const ProgressCallback &onProgress=nullptr)
Execute an installation asynchronously.
static InstallResult install(const LutrisInstallerScript &script, const InstallConfig &config, const ProgressCallback &progressCallback=nullptr)
Execute an installation (blocking).
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
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
static bool isPathWithin(const std::string &candidate, const std::string &root)
static std::string safeCacheComponent(const std::string &raw)
static std::string sanitizeDesktopField(const std::string &s)
static std::string escapeDesktopExec(const std::string &s)
static bool endsWith(const std::string &str, const std::string &suffix)
static bool isPathWithinHome(const std::string &rawPath)
std::vector< std::shared_ptr< std::future< void > > > activeFutures_
void storeFuture(std::shared_ptr< std::future< void > > f)
std::string escapeExec(const std::string &s)
std::string downloadCachePath
std::string winePrefixPath
std::map< std::string, std::string > customVariables
std::vector< std::string > logMessages
std::vector< std::string > warnings
std::vector< std::string > warnings
std::map< std::string, std::string > dllOverrides
std::map< std::string, std::string > environmentVariables
std::vector< std::string > logMessages
std::map< std::string, std::string > params
std::map< std::string, std::string > environmentVariables
LutrisWineConfig wineConfig
std::vector< LutrisInstallerFile > files
std::vector< LutrisInstallStep > steps
std::map< std::string, std::string > dllOverrides
std::map< std::string, std::string > environment