game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
runner_download_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// runner_download_service.cpp
4// ==============================================================================
5// Implementation of runner download and installation service
6// ==============================================================================
7
9#include "logger.h"
10#include "platform/paths.h"
11#include "proton_cache.h"
12#include "shell_utils.h"
13#include "util/atomic_write.h"
14
15#include <algorithm>
16#include <atomic>
17#include <cerrno>
18#include <chrono>
19#include <cstdio>
20#include <cstdlib> // For std::atexit (curl_global_cleanup registration)
21#include <cstring>
22#include <ctime> // gmtime_r, std::strftime — used by the ETag cache timestamper
23#include <curl/curl.h>
24#include <fstream>
25#include <future>
26#include <linux/limits.h>
27#include <map>
28#include <mutex>
29#include <nlohmann/json.hpp>
30#include <openssl/crypto.h> // For CRYPTO_memcmp (constant-time compare)
31#include <openssl/evp.h>
32#include <set>
33#include <sstream>
34#include <sys/wait.h>
35#include <unistd.h>
36#include <utility>
37#include <vector>
38
39using json = nlohmann::json;
40namespace fs = std::filesystem;
41
42namespace
43{
44std::vector<std::shared_ptr<std::future<void>>> activeFutures_;
45std::mutex futuresMutex_;
46
47void storeFuture(std::shared_ptr<std::future<void>> f)
48{
49 std::lock_guard<std::mutex> lock(futuresMutex_);
50 activeFutures_.erase(std::remove_if(activeFutures_.begin(), activeFutures_.end(),
51 [](const std::shared_ptr<std::future<void>>& fu)
52 {
53 return fu->wait_for(std::chrono::seconds(0)) ==
54 std::future_status::ready;
55 }),
56 activeFutures_.end());
57 activeFutures_.push_back(std::move(f));
58}
59
60// ===========================================================================
61// GitHub release-poller cache (ETag / If-Modified-Since)
62// ===========================================================================
63//
64// GitHub's REST API rate-limits unauthenticated callers to 60 requests/hour
65// per IP; the launcher polls 7 repos so it can blow that budget in well under
66// an hour on a busy session. Per the official GitHub docs ("Best practices for
67// using the REST API"), conditional requests with If-None-Match (ETag) or
68// If-Modified-Since do not count against the rate limit when the response is
69// 304 Not Modified.
70//
71// We persist the last-seen ETag, Last-Modified, and (compressed-by-default
72// over the wire — libcurl handles transparent decompression) response body
73// to <cacheDir>/github_release_etags.json so the cache survives across runs.
74//
75// Setting GITHUB_TOKEN in the environment lifts the limit to 5000/hr. We
76// honour it by attaching `Authorization: Bearer <token>` when present.
77//
78// Refs:
79// https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api
80// https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api
81// RFC 9110 §13 (Conditional Requests)
82
84{
85 std::string etag; ///< Value of the response ETag header
86 std::string lastModified; ///< Value of the response Last-Modified header
87 std::string body; ///< Last successful response body (JSON array)
88 std::string fetchedAt; ///< ISO-8601 UTC timestamp of last 200/304
89};
90
92
93std::filesystem::path gitHubCacheFilePath()
94{
95 // platform::Paths centralises XDG_CACHE_HOME logic. Keep the file inside
96 // the launcher's cache dir so `clearCache` / user clean-ups behave like
97 // every other transient artifact.
99 return dir / "github_release_etags.json";
100}
101
102std::string nowIsoUtc()
103{
104 using namespace std::chrono;
105 auto now = system_clock::now();
106 auto t = system_clock::to_time_t(now);
107 std::tm tm{};
108 gmtime_r(&t, &tm);
109 char buf[32];
110 std::strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm);
111 return buf;
112}
113
114// Load the entire on-disk cache. Returns empty map if the file is missing,
115// unreadable, or malformed — callers must handle the cache-miss case anyway,
116// so a corrupt cache simply degrades to "fetch fresh" rather than crashing.
117std::map<std::string, GitHubCacheEntry> loadGitHubCache()
118{
119 std::map<std::string, GitHubCacheEntry> out;
120 auto path = gitHubCacheFilePath();
121 std::error_code ec;
122 if (!std::filesystem::exists(path, ec) || ec)
123 {
124 return out;
125 }
126
127 std::ifstream f(path);
128 if (!f)
129 {
130 return out;
131 }
132 try
133 {
134 json j;
135 f >> j;
136 if (!j.is_object())
137 return out;
138 for (auto it = j.begin(); it != j.end(); ++it)
139 {
140 const auto& v = it.value();
141 if (!v.is_object())
142 continue;
143 GitHubCacheEntry entry;
144 entry.etag = v.value("etag", "");
145 entry.lastModified = v.value("last_modified", "");
146 entry.body = v.value("body", "");
147 entry.fetchedAt = v.value("fetched_at", "");
148 out.emplace(it.key(), std::move(entry));
149 }
150 }
151 catch (const std::exception& e)
152 {
153 Logger::warn("[RunnerDownload] github_release_etags.json is malformed "
154 "({}); ignoring cache.",
155 e.what());
156 return {};
157 }
158 return out;
159}
160
161// Durable cache writer. Uses core::atomicWriteFile for write+fsync+rename+
162// fsync(parent_dir) per POSIX best practice — the prior implementation
163// open-coded a temp+rename pair that was atomic at the directory-entry
164// level but missed fsync, leaving a power-loss window for zero-length
165// cache files. The shared helper now backs both this cache and the
166// settings controller.
167void saveGitHubCache(const std::map<std::string, GitHubCacheEntry>& cache)
168{
169 auto path = gitHubCacheFilePath();
170 std::error_code ec;
171 std::filesystem::create_directories(path.parent_path(), ec);
172 if (ec)
173 {
174 Logger::warn("[RunnerDownload] Cannot create cache dir {}: {}", path.parent_path().string(),
175 ec.message());
176 return;
177 }
178
179 json j = json::object();
180 for (const auto& [key, e] : cache)
181 {
182 j[key] = {
183 {"etag", e.etag},
184 {"last_modified", e.lastModified},
185 {"body", e.body},
186 {"fetched_at", e.fetchedAt},
187 };
188 }
189
190 std::string err;
191 if (!::core::atomicWriteFile(path, j.dump(), &err))
192 {
193 Logger::warn("[RunnerDownload] Failed to persist {}: {}", path.string(), err);
194 }
195}
196
197// Header-callback for libcurl. Writes captured ETag / Last-Modified into the
198// out-params. Per libcurl docs, headers arrive with trailing CRLF; we strip
199// it. Names are case-insensitive in HTTP, so we lowercase before compare.
201{
202 std::string etag;
203 std::string lastModified;
204};
205
206size_t headerCaptureCallback(char* buffer, size_t size, size_t nitems, void* userdata)
207{
208 auto* ctx = static_cast<HeaderCaptureCtx*>(userdata);
209 size_t total = size * nitems;
210 if (total == 0 || !ctx)
211 return total;
212
213 std::string line(buffer, total);
214 while (!line.empty() && (line.back() == '\n' || line.back() == '\r'))
215 {
216 line.pop_back();
217 }
218 auto colon = line.find(':');
219 if (colon == std::string::npos)
220 return total;
221
222 std::string name = line.substr(0, colon);
223 std::string value = line.substr(colon + 1);
224
225 // Lowercase the header name for case-insensitive comparison
226 std::transform(name.begin(), name.end(), name.begin(),
227 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
228 // Trim leading whitespace from the value (RFC 9110 OWS)
229 size_t firstNonSpace = value.find_first_not_of(" \t");
230 if (firstNonSpace != std::string::npos)
231 value.erase(0, firstNonSpace);
232
233 if (name == "etag")
234 {
235 ctx->etag = value;
236 }
237 else if (name == "last-modified")
238 {
239 ctx->lastModified = value;
240 }
241 return total;
242}
243} // namespace
244
245// ==============================================================================
246// Helper Functions
247// ==============================================================================
248
249std::string runnerTypeName(RunnerType type)
250{
251 switch (type)
252 {
254 return "Proton-GE";
256 return "Wine-GE";
258 return "Proton-TKG";
260 return "Luxtorpeda";
261 case RunnerType::DXVK:
262 return "DXVK";
264 return "VKD3D-Proton";
265 case RunnerType::UMU:
266 return "UMU";
267 default:
268 return "Unknown";
269 }
270}
271
273{
274 // Verified 2026-05-02 against upstream repos:
275 // Wine-GE: archived 2025-07-11 (final tag GE-Proton8-26, 2024-02-04).
276 // wine-tkg-git: README explicitly tells users not to target release
277 // tags; GitHub releases have been placeholder-only since
278 // 2022. AUR / PKGBUILD is the canonical channel.
279 switch (type)
280 {
285 default:
287 }
288}
289
291{
292 switch (status)
293 {
295 return "active";
297 return "archived";
299 return "manual-only";
300 default:
301 return "unknown";
302 }
303}
304
305std::string RunnerRelease::getSizeStr() const
306{
307 // Constants typed int64_t up-front. Plain `1024 * 1024 * 1024`
308 // computes in int and risks signed-int overflow on TB-scale
309 // builds — clang-tidy flags this as
310 // bugprone-implicit-widening-of-multiplication-result.
311 constexpr int64_t kKB = 1024;
312 constexpr int64_t kMB = kKB * kKB;
313 constexpr int64_t kGB = kMB * kKB;
314
315 if (size < kKB)
316 return std::to_string(size) + " B";
317 if (size < kMB)
318 return std::to_string(size / kKB) + " KB";
319 if (size < kGB)
320 return std::to_string(size / kMB) + " MB";
321 return std::to_string(size / kGB) + " GB";
322}
323
325{
326 switch (state)
327 {
328 case State::Pending:
329 return "Pending";
331 return "Downloading";
332 case State::Verifying:
333 return "Verifying";
335 return "Extracting";
337 return "Installing";
338 case State::Completed:
339 return "Completed";
340 case State::Failed:
341 return "Failed";
342 case State::Cancelled:
343 return "Cancelled";
344 default:
345 return "Unknown";
346 }
347}
348
349// ==============================================================================
350// Implementation Details
351// ==============================================================================
352
354{
355 mutable std::mutex mutex;
356 std::map<RunnerType, fs::path> customPaths;
357 std::map<RunnerType, std::atomic<bool>> cancelFlags;
358 std::set<RunnerType> activeDownloads; // tracks in-progress downloads
359 std::map<RunnerType, std::vector<RunnerRelease>> releaseCache;
360 std::chrono::system_clock::time_point cacheTime;
361 std::vector<InstalledRunner> installedCache;
363
364 static constexpr int CACHE_VALIDITY_SEC = 300; // 5 minutes
365};
366
367// ==============================================================================
368// CURL Callbacks
369// ==============================================================================
370
371namespace
372{
373
375{
376 std::ofstream* file = nullptr;
377 std::string* buffer = nullptr;
379 std::atomic<bool>* cancelled = nullptr;
380 int64_t totalBytes = 0;
381 int64_t downloadedBytes = 0;
382 bool writeFailed = false; // Set by writeCallback on ofstream failure (disk-full / I/O error)
383};
384
385size_t writeCallback(void* contents, size_t size, size_t nmemb, void* userp)
386{
387 auto* ctx = static_cast<DownloadContext*>(userp);
388 size_t realsize = size * nmemb;
389
390 // Cancellation: paired with cancelDownload()'s release-store via
391 // memory_order_acquire so prior writes from the cancelling thread are
392 // visible here. Returning a short count tells libcurl to abort with
393 // CURLE_WRITE_ERROR — caller treats that as cancel/disk-full.
394 if (ctx->cancelled && ctx->cancelled->load(std::memory_order_acquire))
395 {
396 return 0; // Abort transfer
397 }
398
399 if (ctx->file)
400 {
401 ctx->file->write(static_cast<char*>(contents), static_cast<std::streamsize>(realsize));
402 // Detect disk-full and other write failures — fstream silently sets
403 // failbit/badbit otherwise, leaving the caller to discover a
404 // truncated file only via post-hoc size checks. Returning a short
405 // count signals CURLE_WRITE_ERROR so curl_easy_perform aborts.
406 if (!ctx->file->good())
407 {
408 ctx->writeFailed = true;
409 return 0;
410 }
411 }
412 else if (ctx->buffer)
413 {
414 ctx->buffer->append(static_cast<char*>(contents), realsize);
415 }
416
417 ctx->downloadedBytes += static_cast<int64_t>(realsize);
418
419 if (ctx->callback && ctx->totalBytes > 0)
420 {
421 DownloadProgress progress;
423 progress.bytesDownloaded = ctx->downloadedBytes;
424 progress.bytesTotal = ctx->totalBytes;
425 progress.percentComplete = static_cast<int>(
426 std::min(static_cast<int64_t>(100), (ctx->downloadedBytes * 100) / ctx->totalBytes));
427 ctx->callback(progress);
428 }
429
430 return realsize;
431}
432
433int progressCallback(void* userp, curl_off_t dltotal, curl_off_t /*dlnow*/, curl_off_t /*ultotal*/,
434 curl_off_t /*ulnow*/)
435{
436 auto* ctx = static_cast<DownloadContext*>(userp);
437
438 // Acquire-load to pair with cancelDownload()'s release-store; non-zero
439 // return aborts curl_easy_perform with CURLE_ABORTED_BY_CALLBACK.
440 if (ctx->cancelled && ctx->cancelled->load(std::memory_order_acquire))
441 {
442 return 1; // Abort transfer
443 }
444
445 if (dltotal > 0)
446 {
447 ctx->totalBytes = dltotal;
448 }
449
450 return 0;
451}
452
453} // namespace
454
455// ==============================================================================
456// Constructor/Destructor
457// ==============================================================================
458
460{
461 // Initialize libcurl globally exactly once per process and balance it
462 // with curl_global_cleanup() at exit. Per upstream docs:
463 // "curl_global_init() and curl_global_cleanup() are not thread-safe
464 // [...] you should call them just once per program run."
465 // We use std::call_once to satisfy the once-per-program requirement
466 // without holding a mutex across the whole call, and std::atexit for
467 // the cleanup so it survives any object-destruction ordering quirks.
468 static std::once_flag curlInitFlag;
469 std::call_once(curlInitFlag,
470 []()
471 {
472 if (curl_global_init(CURL_GLOBAL_DEFAULT) == CURLE_OK)
473 {
474 std::atexit([]() { curl_global_cleanup(); });
475 }
476 });
477}
478
480{
481 // Cancel any ongoing downloads — release-store so the curl callback
482 // threads see the flag flip on their next acquire-load.
483 for (auto& [type, flag] : impl_->cancelFlags)
484 {
485 flag.store(true, std::memory_order_release);
486 }
487}
488
489// ==============================================================================
490// GitHub API Helpers
491// ==============================================================================
492
493std::string RunnerDownloadService::getGitHubOwner(RunnerType type)
494{
495 switch (type)
496 {
499 return "GloriousEggroll";
501 return "Frogging-Family";
503 return "luxtorpeda-dev";
504 case RunnerType::DXVK:
505 return "doitsujin";
507 return "HansKristian-Work";
508 case RunnerType::UMU:
509 return "Open-Wine-Components";
510 default:
511 return "";
512 }
513}
514
515std::string RunnerDownloadService::getGitHubRepo(RunnerType type)
516{
517 switch (type)
518 {
520 return "proton-ge-custom";
522 return "wine-ge-custom";
524 return "wine-tkg-git";
526 return "luxtorpeda";
527 case RunnerType::DXVK:
528 return "dxvk";
530 return "vkd3d-proton";
531 case RunnerType::UMU:
532 return "umu-launcher";
533 default:
534 return "";
535 }
536}
537
538std::vector<RunnerRelease>
539RunnerDownloadService::fetchGitHubReleases(const std::string& owner, const std::string& repo,
540 RunnerType type, bool includePrerelease, int maxResults)
541{
542 std::vector<RunnerRelease> releases;
543
544 std::string url = "https://api.github.com/repos/" + owner + "/" + repo +
545 "/releases?per_page=" + std::to_string(maxResults);
546
547 // ----- Conditional-request setup (ETag / If-Modified-Since) -----
548 //
549 // We persist headers + body across runs in <cacheDir>/github_release_etags.json
550 // so a 304 response can be served from disk without re-parsing or counting
551 // against the 60/hr unauth rate limit. Cache key is owner/repo; per-page
552 // count is part of the URL so we re-use the same cache entry as long as
553 // maxResults matches the cached call.
554 //
555 // We hold gitHubCacheMutex_ only for the load/save pair, never across the
556 // network call — a slow GitHub response shouldn't serialise with the
557 // rest of the app.
558 const std::string cacheKey = owner + "/" + repo + "?per_page=" + std::to_string(maxResults);
559 GitHubCacheEntry cached;
560 bool haveCachedEntry = false;
561 {
562 std::lock_guard<std::mutex> lock(gitHubCacheMutex_);
563 auto allCache = loadGitHubCache();
564 auto it = allCache.find(cacheKey);
565 if (it != allCache.end())
566 {
567 cached = it->second;
568 haveCachedEntry =
569 !cached.body.empty() && (!cached.etag.empty() || !cached.lastModified.empty());
570 }
571 }
572
573 CURL* curl = curl_easy_init();
574 if (!curl)
575 {
576 Logger::error("[RunnerDownload] Failed to initialize CURL");
577 return releases;
578 }
579
580 std::string response;
581 DownloadContext ctx;
582 ctx.buffer = &response;
583
584 HeaderCaptureCtx hctx;
585
586 curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
587 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
588 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ctx);
589 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, headerCaptureCallback);
590 curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hctx);
591 curl_easy_setopt(curl, CURLOPT_USERAGENT, "GameLauncher/1.0");
592 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
593 curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
594 // Defence-in-depth: bound connection establishment and redirect chain,
595 // and restrict transfer schemes to HTTPS so a malicious GitHub redirect
596 // can't downgrade us. The download path at line ~944 already has these;
597 // the release-poll path was missing them.
598 curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
599 curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10L);
600#if CURL_AT_LEAST_VERSION(7, 85, 0)
601 curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, "https");
602 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "https");
603#else
604 curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
605 curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS);
606#endif
607 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
608 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);
609
610 // Build request headers. Per GitHub REST docs, the recommended Accept
611 // header on the modern API is application/vnd.github+json (the explicit
612 // v3 form is still served but considered legacy as of 2022). We send
613 // X-GitHub-Api-Version too, which is harmless on older endpoints.
614 struct curl_slist* headers = nullptr;
615 headers = curl_slist_append(headers, "Accept: application/vnd.github+json");
616 headers = curl_slist_append(headers, "X-GitHub-Api-Version: 2022-11-28");
617
618 if (haveCachedEntry)
619 {
620 if (!cached.etag.empty())
621 {
622 std::string h = "If-None-Match: " + cached.etag;
623 headers = curl_slist_append(headers, h.c_str());
624 }
625 if (!cached.lastModified.empty())
626 {
627 std::string h = "If-Modified-Since: " + cached.lastModified;
628 headers = curl_slist_append(headers, h.c_str());
629 }
630 }
631
632 // Optional auth: GITHUB_TOKEN lifts the limit from 60/hr to 5000/hr.
633 // Fine-grained PATs work; classic PATs work; GitHub Actions tokens work.
634 // We accept either GITHUB_TOKEN or GH_TOKEN (the latter is gh-cli's name).
635 const char* tokenEnv = std::getenv("GITHUB_TOKEN");
636 if (!tokenEnv || tokenEnv[0] == '\0')
637 {
638 tokenEnv = std::getenv("GH_TOKEN");
639 }
640 if (tokenEnv && tokenEnv[0] != '\0')
641 {
642 std::string h = std::string("Authorization: Bearer ") + tokenEnv;
643 headers = curl_slist_append(headers, h.c_str());
644 }
645
646 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
647
648 CURLcode res = curl_easy_perform(curl);
649 long httpStatus = 0;
650 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStatus);
651 curl_slist_free_all(headers);
652 curl_easy_cleanup(curl);
653
654 if (res != CURLE_OK)
655 {
656 Logger::error("[RunnerDownload] GitHub API request failed: {}", curl_easy_strerror(res));
657 // On transport failure, fall back to the cached body if we have one
658 // — better stale results than a blank list.
659 if (haveCachedEntry)
660 {
661 Logger::info("[RunnerDownload] Falling back to disk-cached releases for {}", cacheKey);
662 response = cached.body;
663 }
664 else
665 {
666 return releases;
667 }
668 }
669 else if (httpStatus == 304)
670 {
671 // Not Modified: serve the cached body. Refresh fetched_at so the next
672 // load() can prune very stale entries if we ever add a TTL. (None today.)
673 Logger::debug("[RunnerDownload] 304 Not Modified for {} — serving cached releases",
674 cacheKey);
675 response = cached.body;
676 std::lock_guard<std::mutex> lock(gitHubCacheMutex_);
677 auto all = loadGitHubCache();
678 auto it = all.find(cacheKey);
679 if (it != all.end())
680 {
681 it->second.fetchedAt = nowIsoUtc();
682 saveGitHubCache(all);
683 }
684 }
685 else if (httpStatus >= 200 && httpStatus < 300)
686 {
687 // Persist the new ETag/Last-Modified/body so the next call can be
688 // conditional. Skip persistence if both validators are missing
689 // (some proxies strip them) — sending IMS without a server-supplied
690 // value would just produce false-positive 200s.
691 if (!hctx.etag.empty() || !hctx.lastModified.empty())
692 {
693 std::lock_guard<std::mutex> lock(gitHubCacheMutex_);
694 auto all = loadGitHubCache();
695 GitHubCacheEntry entry;
696 entry.etag = hctx.etag;
697 entry.lastModified = hctx.lastModified;
698 entry.body = response;
699 entry.fetchedAt = nowIsoUtc();
700 all[cacheKey] = std::move(entry);
701 saveGitHubCache(all);
702 }
703 }
704 else
705 {
706 // 4xx / 5xx — log and fall back to cache if available.
707 Logger::warn("[RunnerDownload] GitHub API returned HTTP {} for {}", httpStatus, cacheKey);
708 if (httpStatus == 403 || httpStatus == 429)
709 {
710 Logger::warn("[RunnerDownload] Likely rate-limit; set GITHUB_TOKEN to lift "
711 "the cap from 60/hr to 5000/hr.");
712 }
713 if (haveCachedEntry)
714 {
715 response = cached.body;
716 }
717 else
718 {
719 return releases;
720 }
721 }
722
723 // Parse JSON response
724 try
725 {
726 auto jsonReleases = json::parse(response);
727
728 for (const auto& release : jsonReleases)
729 {
730 bool isPrerelease = release.value("prerelease", false);
731 if (isPrerelease && !includePrerelease)
732 {
733 continue;
734 }
735
736 RunnerRelease rel;
737 rel.type = type;
738 rel.tag = release.value("tag_name", "");
739 rel.version = rel.tag;
740 rel.releaseDate = release.value("published_at", "");
741 rel.releaseNotes = release.value("body", "");
742 rel.isPrerelease = isPrerelease;
743
744 // Find the appropriate asset. Use value() with an array default:
745 // `release` is a const json and may come from the user-writable
746 // on-disk ETag cache, so a missing/!array "assets" key must not
747 // hit const operator[] (undefined behaviour, not caught by the
748 // surrounding json::exception handler).
749 for (const auto& asset : release.value("assets", nlohmann::json::array()))
750 {
751 std::string name = asset.value("name", "");
752 std::string assetUrl = asset.value("browser_download_url", "");
753
754 // Look for the main archive (tar.gz or tar.xz)
755 bool isMainAsset = false;
756
757 switch (type)
758 {
760 isMainAsset = (name.find(".tar.gz") != std::string::npos &&
761 name.find("sha512sum") == std::string::npos);
762 break;
764 isMainAsset = (name.find(".tar.xz") != std::string::npos &&
765 name.find("sha512sum") == std::string::npos);
766 break;
767 case RunnerType::DXVK:
769 isMainAsset = (name.find(".tar.gz") != std::string::npos ||
770 name.find(".tar.zst") != std::string::npos);
771 break;
772 default:
773 isMainAsset = (name.find(".tar.") != std::string::npos &&
774 name.find("sum") == std::string::npos);
775 break;
776 }
777
778 if (isMainAsset)
779 {
780 rel.downloadUrl = assetUrl;
781 rel.size = asset.value("size", 0);
782 }
783
784 // Look for checksum file
785 if (name.find("sha512sum") != std::string::npos ||
786 name.find(".sha512") != std::string::npos)
787 {
788 rel.checksumType = "sha512";
789 // We'd need to download this file to get the actual checksum
790 }
791 }
792
793 if (!rel.downloadUrl.empty())
794 {
795 // Check if installed
796 auto installPath = getInstallDir(type) / rel.version;
797 rel.isInstalled = fs::exists(installPath);
798 if (rel.isInstalled)
799 {
800 rel.installPath = installPath;
801 }
802
803 releases.push_back(rel);
804 }
805 }
806 }
807 catch (const json::exception& e)
808 {
809 Logger::error("[RunnerDownload] Failed to parse GitHub API response: {}", e.what());
810 }
811
812 return releases;
813}
814
815// ==============================================================================
816// Release Discovery
817// ==============================================================================
818
819std::vector<RunnerRelease>
820RunnerDownloadService::getAvailableReleases(RunnerType type, bool includePrerelease, int maxResults)
821{
822 // ManualOnly runners (e.g. wine-tkg-git) do not publish usable artifacts on
823 // GitHub Releases. Skip the API call entirely so we don't waste the 60/hr
824 // unauthenticated rate-limit budget on guaranteed-empty responses.
825 const RunnerStatus status = runnerStatus(type);
826 if (status == RunnerStatus::ManualOnly)
827 {
828 Logger::info("[RunnerDownload] {} is manual-only (no GitHub release polling); "
829 "install via distro packaging (e.g. AUR).",
830 runnerTypeName(type));
831 return {};
832 }
833
834 std::lock_guard<std::mutex> lock(impl_->mutex);
835
836 // Check cache
837 auto now = std::chrono::system_clock::now();
838 auto age = std::chrono::duration_cast<std::chrono::seconds>(now - impl_->cacheTime).count();
839
840 if (impl_->releaseCache.count(type) > 0 && age < Impl::CACHE_VALIDITY_SEC)
841 {
842 return impl_->releaseCache[type];
843 }
844
845 // Fetch fresh data
846 std::string owner = getGitHubOwner(type);
847 std::string repo = getGitHubRepo(type);
848
849 if (owner.empty() || repo.empty())
850 {
851 Logger::error("[RunnerDownload] Unknown runner type");
852 return {};
853 }
854
855 auto releases = fetchGitHubReleases(owner, repo, type, includePrerelease, maxResults);
856
857 // Tag every result from an archived upstream so the UI can label it
858 // accordingly. Wine-GE's final release is still installable but no new
859 // versions will ever appear.
860 if (status == RunnerStatus::Archived)
861 {
862 for (auto& rel : releases)
863 {
864 rel.isArchived = true;
865 }
866 if (!releases.empty())
867 {
868 Logger::info("[RunnerDownload] {} upstream is archived — final release is {}",
869 runnerTypeName(type), releases.front().version);
870 }
871 }
872
873 // Update cache
874 impl_->releaseCache[type] = releases;
875 impl_->cacheTime = now;
876
877 Logger::info("[RunnerDownload] Found {} {} releases", releases.size(), runnerTypeName(type));
878
879 return releases;
880}
881
883 const ReleaseCallback& callback,
884 bool includePrerelease)
885{
886 auto future = std::make_shared<std::future<void>>(
887 std::async(std::launch::async,
888 [this, type, callback, includePrerelease]()
889 {
890 auto releases = getAvailableReleases(type, includePrerelease);
891 if (callback)
892 callback(releases);
893 }));
894 storeFuture(std::move(future));
895}
896
897std::optional<RunnerRelease> RunnerDownloadService::getLatestRelease(RunnerType type,
898 bool includePrerelease)
899{
900 auto releases = getAvailableReleases(type, includePrerelease, 1);
901 if (releases.empty())
902 {
903 return std::nullopt;
904 }
905 return releases[0];
906}
907
908// ==============================================================================
909// Download and Installation
910// ==============================================================================
911
912bool RunnerDownloadService::downloadFile(const std::string& url, const fs::path& dest,
913 ProgressCallback callback, std::atomic<bool>& cancelled)
914{
915 // Ensure parent directory exists. Check the result so a permission /
916 // EROFS failure surfaces cleanly instead of silently leaving the
917 // download in a "started but never wrote" state.
918 std::error_code ec;
919 fs::create_directories(dest.parent_path(), ec);
920 if (ec)
921 {
922 Logger::error("[RunnerDownload] Cannot create parent directory {}: {}",
923 dest.parent_path().string(), ec.message());
924 return false;
925 }
926
927 std::ofstream file(dest, std::ios::binary);
928 if (!file.is_open())
929 {
930 Logger::error("[RunnerDownload] Failed to open file for writing: {}", dest.string());
931 return false;
932 }
933
934 // Wrap CURL handle in unique_ptr so any early-return / exception path
935 // between init and cleanup releases the handle. curl_easy_cleanup is
936 // null-safe per official docs.
937 using CurlHandle = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>;
938 CurlHandle curl(curl_easy_init(), &curl_easy_cleanup);
939 if (!curl)
940 {
941 Logger::error("[RunnerDownload] Failed to initialize CURL");
942 return false;
943 }
944
945 DownloadContext ctx;
946 ctx.file = &file;
947 ctx.callback = std::move(callback);
948 ctx.cancelled = &cancelled;
949
950 curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
951 curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, writeCallback);
952 curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &ctx);
953 curl_easy_setopt(curl.get(), CURLOPT_XFERINFOFUNCTION, progressCallback);
954 curl_easy_setopt(curl.get(), CURLOPT_XFERINFODATA, &ctx);
955 curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L);
956 curl_easy_setopt(curl.get(), CURLOPT_USERAGENT, "GameLauncher/1.0");
957 curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
958 curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, 3600L); // 1 hour for large downloads
959
960 // Security hardening (per libcurl official documentation):
961 // - PROTOCOLS_STR (curl >= 7.85.0): restrict transfer schemes so a
962 // malicious or buggy URL builder can't redirect us into file://,
963 // ftp://, gopher://, etc. We download release archives over HTTPS
964 // only; HTTPS-only also enforces TLS for the redirect chain.
965 // - MAXREDIRS=10: cap follow-location loops. libcurl's default became
966 // 30 in 8.3.0 and was unlimited before — neither matches what we
967 // actually need for a single-hop GitHub release redirect.
968 // - SSL_VERIFYPEER/HOST=on: defense-in-depth; these are libcurl
969 // defaults but spelled out so a future build against a less-secure
970 // libcurl/ssl backend can't silently regress.
971 // CURLOPT_PROTOCOLS_STR / REDIR_PROTOCOLS_STR are enum values (not
972 // preprocessor symbols), so use libcurl's CURL_AT_LEAST_VERSION guard
973 // to keep older distros buildable while letting modern libcurl take
974 // the non-deprecated path. 7.85.0 introduced the *_STR variants and
975 // deprecated the bitmask form; 8.10.0 dropped the bitmask form's
976 // deprecation warnings into actual removal on some builds.
977#if CURL_AT_LEAST_VERSION(7, 85, 0)
978 curl_easy_setopt(curl.get(), CURLOPT_PROTOCOLS_STR, "https");
979 curl_easy_setopt(curl.get(), CURLOPT_REDIR_PROTOCOLS_STR, "https");
980#else
981 curl_easy_setopt(curl.get(), CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
982 curl_easy_setopt(curl.get(), CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS);
983#endif
984 curl_easy_setopt(curl.get(), CURLOPT_MAXREDIRS, 10L);
985 curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYPEER, 1L);
986 curl_easy_setopt(curl.get(), CURLOPT_SSL_VERIFYHOST, 2L);
987
988 CURLcode res = curl_easy_perform(curl.get());
989 file.close();
990
991 if (cancelled.load(std::memory_order_acquire))
992 {
993 fs::remove(dest, ec);
994 Logger::info("[RunnerDownload] Download cancelled");
995 return false;
996 }
997
998 if (ctx.writeFailed)
999 {
1000 // Write callback aborted curl because the underlying ofstream
1001 // hit failbit/badbit — most commonly disk-full (ENOSPC). Always
1002 // remove the partial file so the next attempt starts fresh.
1003 fs::remove(dest, ec);
1004 Logger::error("[RunnerDownload] Write failed mid-transfer for {} "
1005 "(likely disk-full or I/O error)",
1006 dest.string());
1007 return false;
1008 }
1009
1010 if (res != CURLE_OK)
1011 {
1012 fs::remove(dest, ec);
1013 Logger::error("[RunnerDownload] Download failed: {}", curl_easy_strerror(res));
1014 return false;
1015 }
1016
1017 return true;
1018}
1019
1020bool RunnerDownloadService::verifyChecksum(const fs::path& file, const std::string& expected,
1021 const std::string& type)
1022{
1023 if (expected.empty())
1024 {
1025 return true; // No checksum to verify
1026 }
1027
1028 std::ifstream ifs(file, std::ios::binary);
1029 if (!ifs.is_open())
1030 {
1031 return false;
1032 }
1033
1034 EVP_MD_CTX* ctx = EVP_MD_CTX_new();
1035 if (!ctx)
1036 {
1037 return false;
1038 }
1039
1040 const EVP_MD* md = nullptr;
1041 if (type == "sha512")
1042 {
1043 md = EVP_sha512();
1044 }
1045 else if (type == "sha256")
1046 {
1047 md = EVP_sha256();
1048 }
1049 else
1050 {
1051 EVP_MD_CTX_free(ctx);
1052 Logger::error("[RunnerDownload] Unknown checksum type '{}' — verification failed", type);
1053 return false; // Unknown checksum type, fail closed
1054 }
1055
1056 EVP_DigestInit_ex(ctx, md, nullptr);
1057
1058 char buffer[8192];
1059 while (ifs.read(buffer, sizeof(buffer)) || ifs.gcount() > 0)
1060 {
1061 EVP_DigestUpdate(ctx, buffer, static_cast<size_t>(ifs.gcount()));
1062 }
1063
1064 unsigned char hash[EVP_MAX_MD_SIZE];
1065 unsigned int hashLen = 0;
1066 EVP_DigestFinal_ex(ctx, hash, &hashLen);
1067 EVP_MD_CTX_free(ctx);
1068
1069 // Convert to hex string
1070 std::stringstream ss;
1071 for (unsigned int i = 0; i < hashLen; i++)
1072 {
1073 ss << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(hash[i]);
1074 }
1075
1076 std::string computed = ss.str();
1077
1078 // Constant-time comparison so an attacker cannot use timing side-
1079 // channels to brute-force a forged checksum byte-by-byte. CRYPTO_memcmp
1080 // (OpenSSL) is the documented portable primitive for this — std::equal
1081 // / operator== short-circuit on first mismatch and leak position info.
1082 if (computed.size() != expected.size())
1083 return false;
1084 return CRYPTO_memcmp(computed.data(), expected.data(), computed.size()) == 0;
1085}
1086
1087// C++17 compatible ends_with helper
1088static bool endsWith(const std::string& str, const std::string& suffix)
1089{
1090 if (suffix.size() > str.size())
1091 return false;
1092 return str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
1093}
1094
1095bool RunnerDownloadService::extractArchive(const fs::path& archive, const fs::path& dest,
1096 const ProgressCallback& callback)
1097{
1098 // Create destination directory
1099 fs::create_directories(dest);
1100
1101 // Determine extraction command based on archive type
1102 std::string cmd;
1103 std::string archiveStr = archive.string();
1104
1105 if (endsWith(archiveStr, ".tar.gz") || endsWith(archiveStr, ".tgz"))
1106 {
1107 cmd = "tar -xzf " + ShellUtils::escapeArg(archiveStr) + " -C " +
1108 ShellUtils::escapeArg(dest.string());
1109 }
1110 else if (endsWith(archiveStr, ".tar.xz"))
1111 {
1112 cmd = "tar -xJf " + ShellUtils::escapeArg(archiveStr) + " -C " +
1113 ShellUtils::escapeArg(dest.string());
1114 }
1115 else if (endsWith(archiveStr, ".tar.zst"))
1116 {
1117 cmd = "tar --zstd -xf " + ShellUtils::escapeArg(archiveStr) + " -C " +
1118 ShellUtils::escapeArg(dest.string());
1119 }
1120 else
1121 {
1122 Logger::error("[RunnerDownload] Unsupported archive format: {}", archiveStr);
1123 return false;
1124 }
1125
1126 if (callback)
1127 {
1128 DownloadProgress progress;
1130 progress.currentFile = archive.filename().string();
1131 callback(progress);
1132 }
1133
1134 int result = std::system(cmd.c_str());
1135
1136 if (result == -1 || !WIFEXITED(result) || WEXITSTATUS(result) != 0)
1137 {
1138 Logger::error("[RunnerDownload] Extraction failed with code {}", result);
1139 return false;
1140 }
1141
1142 if (callback)
1143 {
1144 DownloadProgress progress;
1146 progress.percentComplete = 100;
1147 callback(progress);
1148 }
1149
1150 return true;
1151}
1152
1155{
1156 Logger::info("[RunnerDownload] Starting download of {} {}", runnerTypeName(release.type),
1157 release.version);
1158
1159 // Set up cancel flag — protect map structural modification with mutex.
1160 // After insertion the element is stable (nothing erases from cancelFlags),
1161 // so we can safely hold a reference to the atomic without the lock.
1162 std::atomic<bool>* cancelledPtr;
1163 {
1164 std::lock_guard<std::mutex> lock(impl_->mutex);
1165 // Reset cancel flag for this new download. relaxed is sufficient
1166 // here — no callback thread has been started yet to observe it.
1167 impl_->cancelFlags[release.type].store(false, std::memory_order_relaxed);
1168 cancelledPtr = &impl_->cancelFlags[release.type];
1169 impl_->activeDownloads.insert(release.type);
1170 }
1171 auto& cancelled = *cancelledPtr;
1172 // RAII guard: remove from activeDownloads when this function exits for any reason
1173 struct ActiveGuard
1174 {
1175 Impl* impl;
1176 RunnerType type;
1177 ~ActiveGuard()
1178 {
1179 std::lock_guard<std::mutex> lock(impl->mutex);
1180 impl->activeDownloads.erase(type);
1181 }
1182 } activeGuard{impl_.get(), release.type};
1183
1184 // Create temp directory for download using mkdtemp() for atomic, unpredictable creation.
1185 // A timestamp-based suffix is predictable and vulnerable to symlink pre-creation attacks.
1186 std::string tmplPath = (fs::temp_directory_path() / "gamelauncher_dl_XXXXXX").string();
1187 char tmplBuf[PATH_MAX];
1188 std::snprintf(tmplBuf, sizeof(tmplBuf), "%s", tmplPath.c_str());
1189 if (mkdtemp(tmplBuf) == nullptr)
1190 {
1191 Logger::error("[RunnerDownload] Failed to create temp directory: {}", strerror(errno));
1192 return false;
1193 }
1194 fs::path tempDir(tmplBuf);
1195
1196 // Extract filename from URL (guard against npos + 1 wrapping to 0 on URLs with no '/')
1197 std::string filename;
1198 {
1199 size_t slashPos = release.downloadUrl.find_last_of('/');
1200 filename = (slashPos != std::string::npos) ? release.downloadUrl.substr(slashPos + 1)
1201 : release.downloadUrl;
1202 }
1203 fs::path downloadPath = tempDir / filename;
1204
1205 // Report starting
1206 if (progressCallback)
1207 {
1208 DownloadProgress progress;
1210 progress.currentFile = filename;
1211 progress.bytesTotal = release.size;
1212 progressCallback(progress);
1213 }
1214
1215 // Download
1216 if (!downloadFile(release.downloadUrl, downloadPath, progressCallback, cancelled))
1217 {
1218 std::error_code cleanEc;
1219 fs::remove_all(tempDir, cleanEc);
1220
1221 if (cancelled.load(std::memory_order_acquire))
1222 {
1223 if (progressCallback)
1224 {
1225 DownloadProgress progress;
1227 progressCallback(progress);
1228 }
1229 return false;
1230 }
1231
1232 if (progressCallback)
1233 {
1234 DownloadProgress progress;
1236 progress.errorMessage = "Download failed";
1237 progressCallback(progress);
1238 }
1239 return false;
1240 }
1241
1242 // Verify checksum
1243 if (!release.checksum.empty())
1244 {
1245 if (progressCallback)
1246 {
1247 DownloadProgress progress;
1249 progress.currentFile = filename;
1250 progressCallback(progress);
1251 }
1252
1253 if (!verifyChecksum(downloadPath, release.checksum, release.checksumType))
1254 {
1255 Logger::error("[RunnerDownload] Checksum verification failed");
1256 std::error_code cleanEc;
1257 fs::remove_all(tempDir, cleanEc);
1258
1259 if (progressCallback)
1260 {
1261 DownloadProgress progress;
1263 progress.errorMessage = "Checksum verification failed";
1264 progressCallback(progress);
1265 }
1266 return false;
1267 }
1268 }
1269
1270 // Extract to a temp directory, then move into installDir on success.
1271 // This prevents leaving partial runner installs in the shared installDir.
1272 fs::path installDir = getInstallDir(release.type);
1273 fs::path tempExtractDir = installDir / ("_extract_tmp_" + release.version);
1274
1275 std::error_code mkdirEc;
1276 fs::create_directories(tempExtractDir, mkdirEc);
1277 if (mkdirEc)
1278 {
1279 fs::remove(downloadPath);
1280 Logger::error("[RunnerDownload] Failed to create temp extract dir: {}", mkdirEc.message());
1281 if (progressCallback)
1282 {
1283 DownloadProgress progress;
1285 progress.errorMessage = "Failed to create temp directory";
1286 progressCallback(progress);
1287 }
1288 return false;
1289 }
1290
1291 if (!extractArchive(downloadPath, tempExtractDir, progressCallback))
1292 {
1293 std::error_code rmEc;
1294 fs::remove(downloadPath);
1295 fs::remove_all(tempExtractDir, rmEc);
1296 fs::remove_all(tempDir, rmEc); // clean up the mkdtemp dir too
1297
1298 if (progressCallback)
1299 {
1300 DownloadProgress progress;
1302 progress.errorMessage = "Extraction failed";
1303 progressCallback(progress);
1304 }
1305 return false;
1306 }
1307
1308 // Move extracted entries from temp dir into installDir
1309 std::error_code moveEc;
1310 for (const auto& entry : fs::directory_iterator(tempExtractDir, moveEc))
1311 {
1312 fs::path dest = installDir / entry.path().filename();
1313 std::error_code renameEc;
1314 fs::rename(entry.path(), dest, renameEc);
1315 if (renameEc)
1316 {
1317 Logger::warn("[RunnerDownload] Failed to move {} to {}: {}", entry.path().string(),
1318 dest.string(), renameEc.message());
1319 }
1320 }
1321 fs::remove_all(tempExtractDir, moveEc);
1322
1323 // Clean up downloaded archive
1324 fs::remove(downloadPath);
1325
1326 // Invalidate caches
1327 {
1328 std::lock_guard<std::mutex> lock(impl_->mutex);
1329 impl_->installedCacheValid = false;
1330 }
1332
1333 Logger::info("[RunnerDownload] Successfully installed {} {}", runnerTypeName(release.type),
1334 release.version);
1335
1336 if (progressCallback)
1337 {
1338 DownloadProgress progress;
1340 progress.percentComplete = 100;
1341 progressCallback(progress);
1342 }
1343
1344 return true;
1345}
1346
1347std::future<bool>
1350{
1351 return std::async(std::launch::async, [this, release, progressCallback]()
1352 { return downloadRunner(release, progressCallback); });
1353}
1354
1356{
1357 std::lock_guard<std::mutex> lock(impl_->mutex);
1358 if (impl_->cancelFlags.count(type) > 0)
1359 {
1360 // Release-store pairs with the acquire-load in writeCallback /
1361 // progressCallback, so any state mutated on this thread before
1362 // the flag flip is visible to the curl callback thread the next
1363 // time it polls. Default seq_cst would also work; explicit
1364 // acquire/release documents the synchronisation contract.
1365 impl_->cancelFlags[type].store(true, std::memory_order_release);
1366 Logger::info("[RunnerDownload] Cancelled download for {}", runnerTypeName(type));
1367 }
1368}
1369
1371{
1372 std::lock_guard<std::mutex> lock(impl_->mutex);
1373 return impl_->activeDownloads.count(type) > 0;
1374}
1375
1376// ==============================================================================
1377// Installed Runner Management
1378// ==============================================================================
1379
1381{
1382 const char* homeEnv = std::getenv("HOME");
1383 if (!homeEnv)
1384 {
1385 Logger::error("[RunnerDownload] HOME environment variable not set");
1386 return {};
1387 }
1388 fs::path home = homeEnv;
1389
1390 switch (type)
1391 {
1392 // All Steam compat tools install under the same compatibilitytools.d
1393 // directory; group the cases so the intent is explicit rather than
1394 // relying on three identical-body branches (clang-tidy
1395 // bugprone-branch-clone).
1399 return home / ".steam/root/compatibilitytools.d";
1400 case RunnerType::WineGE:
1401 return home / ".local/share/lutris/runners/wine";
1402 case RunnerType::DXVK:
1403 return home / ".local/share/dxvk";
1405 return home / ".local/share/vkd3d-proton";
1406 case RunnerType::UMU:
1407 return home / ".local/share/umu";
1408 default:
1409 return home / ".local/share/gamelauncher/runners";
1410 }
1411}
1412
1413fs::path RunnerDownloadService::getInstallDir(RunnerType type) const
1414{
1415 std::lock_guard<std::mutex> lock(impl_->mutex);
1416
1417 if (impl_->customPaths.count(type) > 0)
1418 {
1419 return impl_->customPaths.at(type);
1420 }
1421 return getDefaultInstallPath(type);
1422}
1423
1425{
1426 std::lock_guard<std::mutex> lock(impl_->mutex);
1427 impl_->customPaths[type] = path;
1428 impl_->installedCacheValid = false;
1429}
1430
1431std::vector<InstalledRunner> RunnerDownloadService::getInstalledRunners() const
1432{
1433 std::vector<InstalledRunner> all;
1434
1435 // Scan all runner types
1436 for (auto type :
1439 {
1440 auto runners = getInstalledRunners(type);
1441 all.insert(all.end(), runners.begin(), runners.end());
1442 }
1443
1444 return all;
1445}
1446
1447std::vector<InstalledRunner> RunnerDownloadService::getInstalledRunners(RunnerType type) const
1448{
1449 std::vector<InstalledRunner> runners;
1450 fs::path installDir = getInstallDir(type);
1451
1452 if (!fs::exists(installDir))
1453 {
1454 return runners;
1455 }
1456
1457 try
1458 {
1459 for (const auto& entry : fs::directory_iterator(installDir))
1460 {
1461 if (!entry.is_directory())
1462 {
1463 continue;
1464 }
1465
1466 std::string name = entry.path().filename().string();
1467
1468 // Check if this looks like a valid runner directory
1469 bool isValid = false;
1470 switch (type)
1471 {
1474 isValid = fs::exists(entry.path() / "proton");
1475 break;
1476 case RunnerType::WineGE:
1477 isValid = fs::exists(entry.path() / "bin" / "wine");
1478 break;
1479 // DXVK and VKD3DProton both ship an x64/ subdirectory as the
1480 // canonical "installed" marker. Group the cases (clang-tidy
1481 // bugprone-branch-clone).
1482 case RunnerType::DXVK:
1484 isValid = fs::exists(entry.path() / "x64");
1485 break;
1486 default:
1487 isValid = true;
1488 break;
1489 }
1490
1491 if (isValid)
1492 {
1493 InstalledRunner runner;
1494 runner.type = type;
1495 runner.name = name;
1496 runner.version = name;
1497 runner.path = entry.path();
1498
1499 // Get install date from directory modification time
1500 // C++17 compatible: use time_t conversion
1501 auto ftime = fs::last_write_time(entry.path());
1502 auto sctp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
1503 ftime - fs::file_time_type::clock::now() + std::chrono::system_clock::now());
1504 runner.installDate = sctp;
1505
1506 // Calculate size (simplified - just directory size)
1507 runner.sizeBytes = 0;
1508 for (const auto& file : fs::recursive_directory_iterator(entry.path()))
1509 {
1510 if (file.is_regular_file())
1511 {
1512 runner.sizeBytes += static_cast<int64_t>(file.file_size());
1513 }
1514 }
1515
1516 runners.push_back(runner);
1517 }
1518 }
1519 }
1520 catch (const fs::filesystem_error& e)
1521 {
1522 Logger::error("[RunnerDownload] Error scanning {}: {}", installDir.string(), e.what());
1523 }
1524
1525 // Sort by version (newest first)
1526 std::sort(runners.begin(), runners.end(), [](const InstalledRunner& a, const InstalledRunner& b)
1527 { return a.version > b.version; });
1528
1529 return runners;
1530}
1531
1532bool RunnerDownloadService::isInstalled(RunnerType type, const std::string& version) const
1533{
1534 auto runners = getInstalledRunners(type);
1535 return std::any_of(runners.begin(), runners.end(),
1536 [&version](const InstalledRunner& r) { return r.version == version; });
1537}
1538
1539bool RunnerDownloadService::uninstallRunner(RunnerType type, const std::string& version)
1540{
1541 fs::path installDir = getInstallDir(type);
1542 fs::path runnerPath = installDir / version;
1543
1544 // Validate that the resolved path is strictly inside installDir to prevent traversal.
1545 // Use separate error codes — sharing one variable causes the second call to
1546 // clear the first call's error, masking a failed canonicalization.
1547 std::error_code ec1, ec2;
1548 fs::path canonical = fs::weakly_canonical(runnerPath, ec1);
1549 fs::path canonicalInstall = fs::weakly_canonical(installDir, ec2);
1550 if (ec1 || ec2)
1551 {
1552 Logger::error("[RunnerDownload] Refused to uninstall '{}': cannot canonicalize path",
1553 version);
1554 return false;
1555 }
1556 // Use fs::relative to properly detect if canonical is inside canonicalInstall
1557 // (string prefix match alone is vulnerable to "/runners-extra" matching "/runners")
1558 std::error_code relEc;
1559 fs::path rel = fs::relative(canonical, canonicalInstall, relEc);
1560 if (relEc || rel.empty() || rel.string().find("..") == 0)
1561 {
1562 Logger::error("[RunnerDownload] Refused to uninstall '{}': path outside install dir",
1563 version);
1564 return false;
1565 }
1566
1567 if (!fs::exists(runnerPath))
1568 {
1569 Logger::error("[RunnerDownload] Runner not found: {}", runnerPath.string());
1570 return false;
1571 }
1572
1573 try
1574 {
1575 fs::remove_all(runnerPath);
1576 Logger::info("[RunnerDownload] Uninstalled {} {}", runnerTypeName(type), version);
1577
1578 // Invalidate caches
1579 {
1580 std::lock_guard<std::mutex> lock(impl_->mutex);
1581 impl_->installedCacheValid = false;
1582 }
1584
1585 return true;
1586 }
1587 catch (const fs::filesystem_error& e)
1588 {
1589 Logger::error("[RunnerDownload] Failed to uninstall {}: {}", version, e.what());
1590 return false;
1591 }
1592}
1593
1595{
1596 auto runners = getInstalledRunners(type);
1597
1598 if (static_cast<int>(runners.size()) <= keepCount)
1599 {
1600 return 0;
1601 }
1602
1603 int removed = 0;
1604 for (size_t i = static_cast<size_t>(keepCount); i < runners.size(); i++)
1605 {
1606 if (uninstallRunner(type, runners[i].version))
1607 {
1608 removed++;
1609 }
1610 }
1611
1612 return removed;
1613}
1614
1616{
1617 std::lock_guard<std::mutex> lock(impl_->mutex);
1618 impl_->releaseCache.clear();
1619 impl_->installedCacheValid = false;
1620}
1621
1623{
1624 std::lock_guard<std::mutex> lock(impl_->mutex);
1625 impl_->installedCacheValid = false;
1626}
static bool endsWith(const std::string &str, const std::string &suffix)
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 void invalidate()
Invalidate the cache.
std::function< void(const DownloadProgress &)> ProgressCallback
bool uninstallRunner(RunnerType type, const std::string &version)
Uninstall a runner version.
bool isInstalled(RunnerType type, const std::string &version) const
Check if a specific version is installed.
bool downloadRunner(const RunnerRelease &release, const ProgressCallback &progressCallback=nullptr)
Download and install a runner.
std::function< void(const std::vector< RunnerRelease > &)> ReleaseCallback
void setInstallPath(RunnerType type, const std::filesystem::path &path)
Set custom installation directory.
void refreshInstalled()
Refresh installed runners list.
std::future< bool > downloadRunnerAsync(const RunnerRelease &release, const ProgressCallback &progressCallback=nullptr)
Download and install a runner asynchronously.
std::vector< RunnerRelease > getAvailableReleases(RunnerType type, bool includePrerelease=false, int maxResults=20)
Get available releases for a runner type.
bool isDownloading(RunnerType type) const
Check if a download is in progress.
void clearCache()
Clear the releases cache.
void getAvailableReleasesAsync(RunnerType type, const ReleaseCallback &callback, bool includePrerelease=false)
Get available releases asynchronously.
static std::filesystem::path getDefaultInstallPath(RunnerType type)
Get default installation directory for a runner type.
int cleanupOldVersions(RunnerType type, int keepCount=3)
Clean up old versions, keeping newest N.
void cancelDownload(RunnerType type)
Cancel an ongoing download.
std::optional< RunnerRelease > getLatestRelease(RunnerType type, bool includePrerelease=false)
Get the latest release for a runner type.
std::vector< InstalledRunner > getInstalledRunners() const
Get all installed runners.
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
virtual std::filesystem::path getCacheDir() const =0
static Paths & instance()
nlohmann::json json
std::map< std::string, GitHubCacheEntry > loadGitHubCache()
void saveGitHubCache(const std::map< std::string, GitHubCacheEntry > &cache)
void storeFuture(std::shared_ptr< std::future< void > > f)
int progressCallback(void *userp, curl_off_t dltotal, curl_off_t, curl_off_t, curl_off_t)
size_t writeCallback(void *contents, size_t size, size_t nmemb, void *userp)
size_t headerCaptureCallback(char *buffer, size_t size, size_t nitems, void *userdata)
std::vector< std::shared_ptr< std::future< void > > > activeFutures_
bool atomicWriteFile(const std::filesystem::path &targetPath, std::string_view contents, std::string *errOut=nullptr)
Atomically and durably write contents to targetPath.
std::string runnerStatusName(RunnerStatus status)
Convenience: human-readable status string ("active" / "archived" / "manual-only").
std::string runnerTypeName(RunnerType type)
Get human-readable name for runner type.
RunnerStatus runnerStatus(RunnerType type)
Get the upstream maintenance status for a runner type.
static bool endsWith(const std::string &str, const std::string &suffix)
RunnerType
Types of compatibility tools that can be downloaded.
@ UMU
Unified Proton Runner.
@ ProtonGE
GloriousEggroll Proton builds (active).
@ Luxtorpeda
Native game engine replacements.
@ ProtonTKG
TkGlitch custom Proton builds (no usable GitHub releases — AUR / PKGBUILD only).
@ WineGE
GloriousEggroll Wine builds for Lutris (archived 2025-07; final tag GE-Proton8-26).
@ DXVK
DirectX 9/10/11 to Vulkan.
@ VKD3DProton
DirectX 12 to Vulkan.
std::string runnerTypeName(RunnerType type)
Get human-readable name for runner type.
RunnerStatus runnerStatus(RunnerType type)
Get the upstream maintenance status for a runner type.
RunnerStatus
Upstream maintenance status of a runner type.
@ Active
Repo actively publishes releases on GitHub.
@ Archived
Repo is archived but the final release is still usable.
@ ManualOnly
No usable GitHub releases — install via distro packaging.
Progress information for downloads.
std::string getStateStr() const
std::string currentFile
Current file being processed.
std::string errorMessage
Error message if failed.
Information about an installed runner.
std::filesystem::path path
Installation path.
std::chrono::system_clock::time_point installDate
std::string version
Version string.
std::string name
Display name.
int64_t sizeBytes
Size on disk.
std::chrono::system_clock::time_point cacheTime
std::map< RunnerType, std::vector< RunnerRelease > > releaseCache
std::map< RunnerType, fs::path > customPaths
std::vector< InstalledRunner > installedCache
std::map< RunnerType, std::atomic< bool > > cancelFlags
Information about an available runner release.
std::string releaseDate
Release date ISO string.
std::string checksum
SHA512 or SHA256 checksum if available.
bool isInstalled
Whether this version is currently installed.
int64_t size
Download size in bytes.
bool isArchived
True when sourced from an archived upstream repo (Wine-GE).
std::string releaseNotes
Release notes/changelog.
std::string checksumType
"sha512" or "sha256"
std::string tag
GitHub release tag.
std::string downloadUrl
Direct download URL.
bool isPrerelease
Whether this is a pre-release.
std::string getSizeStr() const
std::string version
Version string (e.g., "GE-Proton9-20").
std::filesystem::path installPath
Path if installed.
std::string body
Last successful response body (JSON array).
std::string lastModified
Value of the response Last-Modified header.