game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
file_download_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// file_download_service.cpp
4// ==============================================================================
5// File download service implementation
6// ==============================================================================
7
9#include "logger.h"
10#include "shell_utils.h"
11
12#include <array>
13#include <cctype>
14#include <chrono>
15#include <cstdio>
16#include <cstdlib>
17#include <cstring>
18#include <filesystem>
19#include <fstream>
20#include <future>
21#include <memory>
22#include <mutex>
23#include <regex>
24#include <sstream>
25#include <vector>
26
27namespace fs = std::filesystem;
28
29namespace
30{
31// Hot-path regexes wrapped in function-local statics. Building std::regex
32// is O(pattern size) and these are called once per progress line —
33// recompiling on every line dominates the parse cost of a multi-MB curl
34// output stream. The function-local-static form initializes on first use
35// (Meyer's singleton, thread-safe per [stmt.dcl]/4) so any malformed-
36// pattern std::regex_error propagates from the caller instead of an
37// uncatchable program-start crash (bugprone-throwing-static-initialization,
38// CERT ERR58-CPP). All regexes are stateless and the matching APIs are
39// const-thread-safe.
40const std::regex& kPercentRegex()
41{
42 static const std::regex re{R"((\d+(?:\.\d+)?)\s*%)"};
43 return re;
44}
45const std::regex& kSpeedRegex()
46{
47 static const std::regex re{R"((\d+(?:\.\d+)?)\s*([kMG])?/s)"};
48 return re;
49}
50const std::regex& kSpeedRegexWithB()
51{
52 static const std::regex re{R"((\d+(?:\.\d+)?)\s*([kMG])?B?/s)"};
53 return re;
54}
55const std::regex& kContentLengthRegex()
56{
57 static const std::regex re{R"(content-length:\s*(\d+))", std::regex::icase};
58 return re;
59}
60
61std::vector<std::shared_ptr<std::future<void>>> activeFutures_;
62std::mutex futuresMutex_;
63
64void storeFuture(std::shared_ptr<std::future<void>> f)
65{
66 std::lock_guard<std::mutex> lock(futuresMutex_);
67 activeFutures_.erase(std::remove_if(activeFutures_.begin(), activeFutures_.end(),
68 [](const std::shared_ptr<std::future<void>>& fu)
69 {
70 return fu->wait_for(std::chrono::seconds(0)) ==
71 std::future_status::ready;
72 }),
73 activeFutures_.end());
74 activeFutures_.push_back(std::move(f));
75}
76
77// SECURITY (CWE-88, argument injection): every download/HEAD/accessibility
78// path passes the URL to the curl CLI. curl treats any argument beginning
79// with '-' as an option, and ShellUtils::escapeArg() returns such a value
80// UNQUOTED because '-' is a "safe" character — so a URL like
81// "-K/tmp/evil" (read a config file) or "-o/home/user/.bashrc" (redirect
82// output) would be parsed as a curl option, not a URL, defeating the
83// "--proto =https" guard (which only restricts URL schemes). We require an
84// explicit http(s):// scheme here and additionally emit the "--"
85// end-of-options marker at each call site.
86// curl(1): "The first argument that is exactly two dashes ("--"), marks
87// the end of options; any argument after the end of options is
88// interpreted as a URL argument even if it starts with a dash."
89bool isHttpUrl(const std::string& url)
90{
91 const auto startsWithCI = [&url](const char* prefix)
92 {
93 const size_t n = std::strlen(prefix);
94 if (url.size() < n)
95 return false;
96 for (size_t i = 0; i < n; ++i)
97 {
98 if (std::tolower(static_cast<unsigned char>(url[i])) != prefix[i])
99 return false;
100 }
101 return true;
102 };
103 return startsWithCI("http://") || startsWithCI("https://");
104}
105} // namespace
106
107// ==============================================================================
108// Static Member Initialization
109// ==============================================================================
110
111std::atomic<bool> FileDownloadService::cancelled_{false};
112std::atomic<bool> FileDownloadService::downloading_{false};
113std::mutex FileDownloadService::downloadMutex_;
114
115// ==============================================================================
116// Synchronous Downloads
117// ==============================================================================
118
120 const ProgressCallback& progressCallback)
121{
122 std::lock_guard<std::mutex> lock(downloadMutex_);
123
124 DownloadResult result;
125 result.localPath = request.localPath;
126 cancelled_ = false;
127 downloading_ = true;
128
129 // Create parent directory if needed
130 fs::path parentDir = fs::path(request.localPath).parent_path();
131 if (!parentDir.empty() && !fs::exists(parentDir))
132 {
133 std::error_code ec;
134 fs::create_directories(parentDir, ec);
135 if (ec)
136 {
137 result.errorMessage = "Failed to create directory: " + parentDir.string();
138 Logger::error("FileDownload: {}", result.errorMessage);
139 downloading_ = false;
140 return result;
141 }
142 }
143
144 // Check for existing partial download (for resume)
145 uint64_t existingSize = 0;
146 if (request.allowResume && fs::exists(request.localPath))
147 {
148 std::error_code fileSizeEc;
149 existingSize = fs::file_size(request.localPath, fileSizeEc);
150 if (fileSizeEc)
151 existingSize = 0;
152 Logger::info("FileDownload: Found existing file ({} bytes), attempting resume",
153 existingSize);
154 }
155
156 // SECURITY (CWE-88): reject anything that isn't an http(s) URL before it
157 // reaches the curl CLI, so an attacker-supplied installer URL cannot be
158 // parsed as a curl option (see isHttpUrl above).
159 if (!isHttpUrl(request.url))
160 {
161 result.errorMessage = "Refusing non-http(s) download URL: " + request.url;
162 Logger::error("FileDownload: {}", result.errorMessage);
163 downloading_ = false;
164 return result;
165 }
166
167 // Build curl command
168 std::ostringstream cmd;
169 cmd << "curl -L --fail --connect-timeout 30 ";
170 cmd << "--max-time " << request.timeoutSeconds << " ";
171
172 // Progress output for parsing
173 cmd << "--progress-bar ";
174
175 // Resume support
176 if (existingSize > 0 && request.allowResume)
177 {
178 cmd << "-C " << existingSize << " ";
179 }
180
181 // Protocol restriction and redirect limit
182 cmd << "--proto =https --max-redirs 10 ";
183
184 // Custom headers
185 for (const auto& [key, value] : request.headers)
186 {
187 cmd << "-H " << ShellUtils::escapeArg(key + ": " + value) << " ";
188 }
189
190 // Output file
191 cmd << "-o " << ShellUtils::escapeArg(request.localPath) << " ";
192
193 // URL. The literal "--" ends option parsing so the URL can never be
194 // interpreted as a curl option even if it slips past isHttpUrl (CWE-88).
195 cmd << "-- " << ShellUtils::escapeArg(request.url) << " ";
196
197 // Redirect stderr to stdout for progress parsing
198 cmd << "2>&1";
199
200 Logger::info("FileDownload: Starting download of {}", request.url);
201 // Do NOT log the full command at debug level: when callers attach
202 // `-H "Authorization: Bearer …"` headers (e.g. SteamGridDB API key),
203 // the full cmd would put the bearer token in the log file. Log a
204 // sanitised summary instead. URL alone is OK — paths and download
205 // URLs are not secret.
206 Logger::debug("FileDownload: GET {} (headers: {})", request.url,
207 request.headers.empty() ? "none" : "redacted");
208
209 // Execute curl with progress parsing
210 FILE* rawPipe = popen(cmd.str().c_str(), "r");
211 if (!rawPipe)
212 {
213 result.errorMessage = "Failed to execute curl command";
214 Logger::error("FileDownload: {}", result.errorMessage);
215 downloading_ = false;
216 return result;
217 }
218
219 std::array<char, 256> buffer;
220 std::string currentLine;
221 DownloadProgress progress;
222 progress.currentFile = fs::path(request.localPath).filename().string();
223
224 auto lastProgressUpdate = std::chrono::steady_clock::now();
225 const auto progressInterval = std::chrono::milliseconds(100);
226
227 // downloadMutex_ is held intentionally to serialize downloads to one
228 // at a time; the blocking fgets IS the work being performed under
229 // the lock. Cancellation is checked each iteration so the lock is
230 // not unbounded.
231 // NOLINTNEXTLINE(clang-analyzer-unix.BlockInCriticalSection) - see comment above.
232 while (fgets(buffer.data(), static_cast<int>(buffer.size()), rawPipe) != nullptr)
233 {
234 if (cancelled_)
235 {
236 pclose(rawPipe);
237 result.errorMessage = "Download cancelled by user";
238 Logger::info("FileDownload: {}", result.errorMessage);
239 downloading_ = false;
240 // Remove partial file so the next attempt starts fresh (not a corrupt resume)
241 if (!request.allowResume)
242 {
243 std::error_code removeEc;
244 fs::remove(request.localPath, removeEc);
245 }
246 return result;
247 }
248
249 currentLine = buffer.data();
250
251 // Parse curl progress bar output
252 // Format: "### 2.3%"
253 // Or newer: " % Total % Received % Xferd Average Speed..."
254 if (currentLine.find('%') != std::string::npos)
255 {
256 // Try to extract percentage. Regexes hoisted to file scope.
257 std::smatch match;
258 if (std::regex_search(currentLine, match, kPercentRegex()))
259 {
260 try
261 {
262 progress.percentComplete =
263 std::max(0, std::min(100, static_cast<int>(std::stof(match[1].str()))));
264 }
265 catch (...)
266 {
267 // Ignore parse errors
268 }
269 }
270
271 // Try to extract speed (e.g., "45.2M" or "1234k")
272 if (std::regex_search(currentLine, match, kSpeedRegex()))
273 {
274 try
275 {
276 double speed = std::stod(match[1].str());
277 std::string unit = match[2].str();
278 if (unit == "k" || unit == "K")
279 speed *= 1024;
280 else if (unit == "M")
281 speed *= 1024 * 1024;
282 else if (unit == "G")
283 speed *= 1024 * 1024 * 1024;
284 progress.speedBytesPerSec = speed;
285 }
286 catch (...)
287 {
288 // Ignore parse errors
289 }
290 }
291
292 // Throttle progress callbacks
293 auto now = std::chrono::steady_clock::now();
294 if (progressCallback && (now - lastProgressUpdate) >= progressInterval)
295 {
296 progressCallback(progress);
297 lastProgressUpdate = now;
298 }
299 }
300 }
301
302 int status = pclose(rawPipe);
303 downloading_ = false;
304
305 // Check result
306 if (status == -1)
307 {
308 // pclose() itself failed (waitpid error) — curl status is unknown
309 result.errorMessage = "Failed to wait for curl process";
310 Logger::error("FileDownload: pclose failed: {}", strerror(errno));
311 return result;
312 }
313 if (status != 0)
314 {
315 int exitCode = -1;
316 if (WIFEXITED(status))
317 {
318 exitCode = WEXITSTATUS(status);
319 }
320 else if (WIFSIGNALED(status))
321 {
322 exitCode = 128 + WTERMSIG(status);
323 }
324 result.httpStatusCode = exitCode;
325
326 // curl exit codes
327 switch (exitCode)
328 {
329 case 6:
330 result.errorMessage = "Could not resolve host";
331 break;
332 case 7:
333 result.errorMessage = "Failed to connect to host";
334 break;
335 case 22:
336 result.errorMessage = "HTTP error (file not found or access denied)";
337 break;
338 case 28:
339 result.errorMessage = "Operation timed out";
340 break;
341 case 33:
342 result.errorMessage = "Range request not supported (resume failed)";
343 break;
344 case 56:
345 result.errorMessage = "Network error during transfer";
346 break;
347 default:
348 result.errorMessage = "curl failed with exit code " + std::to_string(exitCode);
349 }
350
351 Logger::error("FileDownload: {}", result.errorMessage);
352 return result;
353 }
354
355 // Verify file exists and has content
356 if (!fs::exists(request.localPath))
357 {
358 result.errorMessage = "Downloaded file not found";
359 Logger::error("FileDownload: {}", result.errorMessage);
360 return result;
361 }
362
363 // Use the error_code form: between fs::exists above and the size query
364 // here a parallel writer (antivirus quarantine, ENOSPC mid-write,
365 // user-initiated delete) can disappear the file. The throwing form
366 // would propagate filesystem_error from this `return`-by-value path
367 // and crash the caller; error_code surfaces it cleanly.
368 {
369 std::error_code sizeEc;
370 // fs::file_size returns uintmax_t; bytesDownloaded is uint64_t —
371 // both unsigned, no signedness conversion. uintmax_t is at least 64
372 // bits and on every platform we target == uint64_t exactly.
373 result.bytesDownloaded = fs::file_size(request.localPath, sizeEc);
374 if (sizeEc)
375 {
376 result.errorMessage = "file_size failed: " + sizeEc.message();
377 Logger::error("FileDownload: {}", result.errorMessage);
378 std::error_code rmEc;
379 fs::remove(request.localPath, rmEc);
380 return result;
381 }
382 }
383 if (result.bytesDownloaded == 0)
384 {
385 result.errorMessage = "Downloaded file is empty";
386 Logger::error("FileDownload: {}", result.errorMessage);
387 std::error_code rmEc;
388 fs::remove(request.localPath, rmEc);
389 return result;
390 }
391
392 // Verify checksum if provided
393 if (!request.expectedChecksum.empty() && !request.checksumType.empty())
394 {
395 Logger::info("FileDownload: Verifying {} checksum...", request.checksumType);
396 if (verifyChecksum(request.localPath, request.expectedChecksum, request.checksumType))
397 {
398 result.checksumVerified = true;
399 Logger::info("FileDownload: Checksum verified successfully");
400 }
401 else
402 {
403 result.errorMessage = "Checksum verification failed";
404 Logger::error("FileDownload: {}", result.errorMessage);
405 fs::remove(request.localPath);
406 return result;
407 }
408 }
409
410 result.success = true;
411 Logger::info("FileDownload: Successfully downloaded {} ({} bytes)", request.localPath,
412 result.bytesDownloaded);
413
414 // Final progress callback
415 if (progressCallback)
416 {
417 progress.percentComplete = 100;
418 progress.bytesDownloaded = result.bytesDownloaded;
419 progress.totalBytes = result.bytesDownloaded;
420 progressCallback(progress);
421 }
422
423 return result;
424}
425
426std::vector<DownloadResult>
427FileDownloadService::downloadBatch(const std::vector<DownloadRequest>& requests,
428 ProgressCallback progressCallback)
429{
430 std::vector<DownloadResult> results;
431 results.reserve(requests.size());
432
433 uint64_t totalSize = 0;
434 uint64_t downloadedSize = 0;
435
436 // Try to get total size for all files
437 for (const auto& req : requests)
438 {
439 uint64_t size = getRemoteFileSize(req.url);
440 totalSize += size;
441 }
442
443 int fileIndex = 0;
444 for (const auto& request : requests)
445 {
446 if (cancelled_)
447 {
448 DownloadResult cancelled;
449 cancelled.errorMessage = "Batch download cancelled";
450 results.push_back(cancelled);
451 continue;
452 }
453
454 // Wrapper callback to provide batch progress
455 auto batchProgress = [&](const DownloadProgress& fileProgress)
456 {
457 if (progressCallback)
458 {
459 DownloadProgress batchProg = fileProgress;
460 batchProg.statusMessage = "Downloading file " + std::to_string(fileIndex + 1) +
461 " of " + std::to_string(requests.size());
462
463 if (totalSize > 0)
464 {
465 batchProg.totalBytes = totalSize;
466 batchProg.bytesDownloaded = downloadedSize + fileProgress.bytesDownloaded;
467 batchProg.percentComplete =
468 static_cast<int>((batchProg.bytesDownloaded * 100) / totalSize);
469 }
470
471 progressCallback(batchProg);
472 }
473 };
474
475 DownloadResult result = download(request, batchProgress);
476 results.push_back(result);
477
478 if (result.success)
479 {
480 downloadedSize += result.bytesDownloaded;
481 }
482
483 fileIndex++;
484 }
485
486 return results;
487}
488
489// ==============================================================================
490// Asynchronous Downloads
491// ==============================================================================
492
494 const CompletionCallback& onComplete,
495 const ProgressCallback& onProgress)
496{
497 auto future =
498 std::make_shared<std::future<void>>(std::async(std::launch::async,
499 [request, onComplete, onProgress]()
500 {
501 DownloadResult result =
502 download(request, onProgress);
503 if (onComplete)
504 onComplete(result);
505 }));
506 storeFuture(std::move(future));
507}
508
510 const std::vector<DownloadRequest>& requests,
511 const std::function<void(std::vector<DownloadResult>)>& onComplete,
512 const ProgressCallback& onProgress)
513{
514 auto future =
515 std::make_shared<std::future<void>>(std::async(std::launch::async,
516 [requests, onComplete, onProgress]()
517 {
518 auto results =
519 downloadBatch(requests, onProgress);
520 if (onComplete)
521 onComplete(results);
522 }));
523 storeFuture(std::move(future));
524}
525
526// ==============================================================================
527// Control
528// ==============================================================================
529
531{
532 cancelled_ = true;
533 Logger::info("FileDownload: Cancel requested");
534}
535
537{
538 return downloading_;
539}
540
541// ==============================================================================
542// Utilities
543// ==============================================================================
544
545bool FileDownloadService::verifyChecksum(const std::string& filePath, const std::string& expected,
546 const std::string& type)
547{
548 std::string calculated = calculateChecksum(filePath, type);
549 if (calculated.empty())
550 {
551 return false;
552 }
553
554 // Case-insensitive comparison
555 std::string expectedLower = expected;
556 std::string calculatedLower = calculated;
557 std::transform(expectedLower.begin(), expectedLower.end(), expectedLower.begin(),
558 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
559 std::transform(calculatedLower.begin(), calculatedLower.end(), calculatedLower.begin(),
560 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
561
562 return expectedLower == calculatedLower;
563}
564
565std::string FileDownloadService::calculateChecksum(const std::string& filePath,
566 const std::string& type)
567{
568 std::string command;
569
570 std::string escapedPath = ShellUtils::escapeArg(filePath);
571
572 if (type == "md5")
573 {
574 command = "md5sum " + escapedPath + " 2>/dev/null";
575 }
576 else if (type == "sha256")
577 {
578 command = "sha256sum " + escapedPath + " 2>/dev/null";
579 }
580 else if (type == "sha1")
581 {
582 command = "sha1sum " + escapedPath + " 2>/dev/null";
583 }
584 else
585 {
586 Logger::error("FileDownload: Unknown checksum type: {}", type);
587 return "";
588 }
589
590 std::unique_ptr<FILE, int (*)(FILE*)> pipe(popen(command.c_str(), "r"), pclose);
591 if (!pipe)
592 {
593 Logger::error("FileDownload: Failed to run checksum command");
594 return "";
595 }
596
597 std::array<char, 256> buffer;
598 std::string result;
599 // calculateChecksum() takes no mutex itself; the analyzer flags this
600 // because callers (download()) invoke it while holding
601 // downloadMutex_, which intentionally serializes downloads. The
602 // checksum computation IS the work being serialized.
603 // NOLINTNEXTLINE(clang-analyzer-unix.BlockInCriticalSection) - see comment above.
604 if (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()) != nullptr)
605 {
606 result = buffer.data();
607 }
608
609 // Extract checksum (first field before space)
610 size_t spacePos = result.find(' ');
611 if (spacePos != std::string::npos)
612 {
613 result = result.substr(0, spacePos);
614 }
615
616 // Trim whitespace
617 while (!result.empty() && std::isspace(static_cast<unsigned char>(result.back())))
618 {
619 result.pop_back();
620 }
621
622 return result;
623}
624
625uint64_t FileDownloadService::getRemoteFileSize(const std::string& url)
626{
627 if (!isHttpUrl(url))
628 return 0;
629 // Use curl to get Content-Length header. "--" ends option parsing (CWE-88).
630 std::string command = "curl -sI -L --connect-timeout 10 --proto =https --max-redirs 10 -- " +
632 " 2>/dev/null | grep -i content-length | tail -1";
633
634 std::unique_ptr<FILE, int (*)(FILE*)> pipe(popen(command.c_str(), "r"), pclose);
635 if (!pipe)
636 {
637 return 0;
638 }
639
640 std::array<char, 256> buffer;
641 std::string result;
642 if (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()) != nullptr)
643 {
644 result = buffer.data();
645 }
646
647 // Parse "Content-Length: 12345"
648 std::smatch match;
649 if (std::regex_search(result, match, kContentLengthRegex()))
650 {
651 try
652 {
653 return std::stoull(match[1].str());
654 }
655 catch (...)
656 {
657 return 0;
658 }
659 }
660
661 return 0;
662}
663
664bool FileDownloadService::isUrlAccessible(const std::string& url)
665{
666 if (!isHttpUrl(url))
667 return false;
668 // "--" ends option parsing so the URL cannot be read as an option (CWE-88).
669 std::string command =
670 "curl -sI -L --connect-timeout 10 --max-time 15 --proto =https --max-redirs 10 "
671 "-o /dev/null -w \"%{http_code}\" -- " +
672 ShellUtils::escapeArg(url) + " 2>/dev/null";
673
674 std::unique_ptr<FILE, int (*)(FILE*)> pipe(popen(command.c_str(), "r"), pclose);
675 if (!pipe)
676 {
677 return false;
678 }
679
680 std::array<char, 16> buffer;
681 std::string result;
682 if (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()) != nullptr)
683 {
684 result = buffer.data();
685 }
686
687 // Check for 2xx status codes
688 try
689 {
690 int statusCode = std::stoi(result);
691 return statusCode >= 200 && statusCode < 300;
692 }
693 catch (...)
694 {
695 return false;
696 }
697}
698
699// ==============================================================================
700// Private Helpers
701// ==============================================================================
702
703DownloadProgress FileDownloadService::parseProgressOutput(const std::string& line,
704 const std::string& filename)
705{
706 DownloadProgress progress;
707 progress.currentFile = filename;
708
709 // Try to parse curl progress output
710 // This handles both old and new curl formats
711
712 // Look for percentage (hoisted regex)
713 std::smatch match;
714 if (std::regex_search(line, match, kPercentRegex()))
715 {
716 try
717 {
718 progress.percentComplete = static_cast<int>(std::stof(match[1].str()));
719 }
720 catch (...)
721 {
722 }
723 }
724
725 // Look for speed
726 if (std::regex_search(line, match, kSpeedRegexWithB()))
727 {
728 try
729 {
730 double speed = std::stod(match[1].str());
731 std::string unit = match.size() > 2 ? match[2].str() : "";
732 if (unit == "k" || unit == "K")
733 speed *= 1024;
734 else if (unit == "M")
735 speed *= 1024 * 1024;
736 else if (unit == "G")
737 speed *= 1024 * 1024 * 1024;
738 progress.speedBytesPerSec = speed;
739 }
740 catch (...)
741 {
742 }
743 }
744
745 return progress;
746}
747
748std::string FileDownloadService::buildCurlCommand(const DownloadRequest& request, bool withProgress)
749{
750 std::ostringstream cmd;
751 cmd << "curl -L --fail --connect-timeout 30 ";
752 cmd << "--proto =https --max-redirs 10 ";
753 cmd << "--max-time " << request.timeoutSeconds << " ";
754
755 if (withProgress)
756 {
757 cmd << "--progress-bar ";
758 }
759 else
760 {
761 cmd << "-s ";
762 }
763
764 for (const auto& [key, value] : request.headers)
765 {
766 cmd << "-H " << ShellUtils::escapeArg(key + ": " + value) << " ";
767 }
768
769 cmd << "-o " << ShellUtils::escapeArg(request.localPath) << " ";
770 cmd << ShellUtils::escapeArg(request.url);
771
772 return cmd.str();
773}
static DownloadResult download(const DownloadRequest &request, const ProgressCallback &progressCallback=nullptr)
Download a file with optional progress tracking.
static void downloadBatchAsync(const std::vector< DownloadRequest > &requests, const std::function< void(std::vector< DownloadResult >)> &onComplete, const ProgressCallback &onProgress=nullptr)
Download multiple files asynchronously.
static std::vector< DownloadResult > downloadBatch(const std::vector< DownloadRequest > &requests, ProgressCallback progressCallback=nullptr)
Download multiple files sequentially.
static bool isDownloading()
Check if a download is currently in progress.
static std::string calculateChecksum(const std::string &filePath, const std::string &type)
Calculate file checksum.
static void cancel()
Cancel the current download operation.
std::function< void(const DownloadResult &)> CompletionCallback
static bool isUrlAccessible(const std::string &url)
Check if URL is accessible.
static uint64_t getRemoteFileSize(const std::string &url)
Get file size from URL without downloading.
static bool verifyChecksum(const std::string &filePath, const std::string &expected, const std::string &type)
Verify file checksum.
static void downloadAsync(const DownloadRequest &request, const CompletionCallback &onComplete, const ProgressCallback &onProgress=nullptr)
Download a file asynchronously.
std::function< void(const DownloadProgress &)> ProgressCallback
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 std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
std::vector< std::shared_ptr< std::future< void > > > activeFutures_
void storeFuture(std::shared_ptr< std::future< void > > f)
Progress information for downloads.
std::string currentFile
Current file being processed.
std::map< std::string, std::string > headers