game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
archive_extract_service.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// archive_extract_service.cpp
4// ==============================================================================
5// Archive extraction service implementation
6// ==============================================================================
7
9#include "logger.h"
10#include "shell_utils.h"
11
12#include <array>
13#include <cstdio>
14#include <cstdlib>
15#include <filesystem>
16#include <fstream>
17#include <future>
18#include <mutex>
19#include <regex>
20#include <sstream>
21#include <sys/wait.h>
22#include <utility>
23#include <vector>
24
25namespace fs = std::filesystem;
26
27namespace
28{
29std::vector<std::shared_ptr<std::future<void>>> activeFutures_;
30std::mutex futuresMutex_;
31
32void storeFuture(std::shared_ptr<std::future<void>> f)
33{
34 std::lock_guard<std::mutex> lock(futuresMutex_);
35 activeFutures_.erase(std::remove_if(activeFutures_.begin(), activeFutures_.end(),
36 [](const std::shared_ptr<std::future<void>>& fu)
37 {
38 return fu->wait_for(std::chrono::seconds(0)) ==
39 std::future_status::ready;
40 }),
41 activeFutures_.end());
42 activeFutures_.push_back(std::move(f));
43}
44} // namespace
45
46// ==============================================================================
47// Extraction
48// ==============================================================================
49
51 const ProgressCallback& progressCallback)
52{
53 ExtractResult result;
54 result.destinationDir = request.destinationDir;
55
56 // Validate archive exists
57 if (!fs::exists(request.archivePath))
58 {
59 result.errorMessage = "Archive not found: " + request.archivePath;
60 Logger::error("ArchiveExtract: {}", result.errorMessage);
61 return result;
62 }
63
64 // Detect type if not specified
65 ArchiveType type = request.type;
66 if (type == ArchiveType::Unknown)
67 {
68 type = detectType(request.archivePath);
69 if (type == ArchiveType::Unknown)
70 {
71 result.errorMessage = "Could not detect archive type: " + request.archivePath;
72 Logger::error("ArchiveExtract: {}", result.errorMessage);
73 return result;
74 }
75 }
76
77 Logger::info("ArchiveExtract: Extracting {} as {}", request.archivePath, getTypeName(type));
78
79 // Check if tool is available
80 if (!isSupported(type))
81 {
82 std::string tool = getToolName(type);
83 result.errorMessage = "Required tool not installed: " + tool;
84 std::string installCmd = getInstallCommand(tool);
85 if (!installCmd.empty())
86 {
87 result.errorMessage += " (install with: " + installCmd + ")";
88 }
89 Logger::error("ArchiveExtract: {}", result.errorMessage);
90 return result;
91 }
92
93 // SECURITY (CWE-22 Zip-Slip / CWE-59): reject archives whose members would
94 // resolve outside the destination directory before extracting anything.
95 if (hasUnsafeEntries(request.archivePath, type))
96 {
97 result.errorMessage =
98 "Archive contains unsafe (path-traversal or absolute) entries; refusing to extract";
99 Logger::error("ArchiveExtract: {}", result.errorMessage);
100 return result;
101 }
102
103 // Create destination directory
104 if (!request.destinationDir.empty() && !fs::exists(request.destinationDir))
105 {
106 std::error_code ec;
107 fs::create_directories(request.destinationDir, ec);
108 if (ec)
109 {
110 result.errorMessage = "Failed to create destination directory";
111 Logger::error("ArchiveExtract: {}", result.errorMessage);
112 return result;
113 }
114 }
115
116 // Dispatch to type-specific extractor
117 ExtractRequest modRequest = request;
118 modRequest.type = type;
119
120 switch (type)
121 {
122 case ArchiveType::Zip:
123 result = extractZip(modRequest, progressCallback);
124 break;
125
126 case ArchiveType::Tar:
131 result = extractTar(modRequest, progressCallback);
132 break;
133
135 result = extractSevenZip(modRequest, progressCallback);
136 break;
137
138 case ArchiveType::Rar:
139 result = extractRar(modRequest, progressCallback);
140 break;
141
142 case ArchiveType::Cab:
143 result = extractCab(modRequest, progressCallback);
144 break;
145
147 result = extractInnoSetup(modRequest, progressCallback);
148 break;
149
151 result = extractNSIS(modRequest, progressCallback);
152 break;
153
156 case ArchiveType::Xz:
157 result = extractGzip(modRequest, progressCallback);
158 break;
159
160 default:
161 result.errorMessage = "Unsupported archive type";
162 Logger::error("ArchiveExtract: {}", result.errorMessage);
163 break;
164 }
165
166 return result;
167}
168
170 const ExtractRequest& request, const std::function<void(const ExtractResult&)>& onComplete,
171 const ProgressCallback& onProgress)
172{
173 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
174 [request, onComplete, onProgress]()
175 {
176 ExtractResult result = extract(
177 request, onProgress);
178 if (onComplete)
179 onComplete(result);
180 }));
181 storeFuture(std::move(future));
182}
183
184// ==============================================================================
185// Archive Type Detection
186// ==============================================================================
187
189{
190 // Try magic bytes first (more reliable)
191 ArchiveType type = detectFromMagicBytes(filePath);
192 if (type != ArchiveType::Unknown)
193 {
194 return type;
195 }
196
197 // Fall back to extension
198 return detectFromExtension(filePath);
199}
200
201// Helper for C++17 (ends_with is C++20)
202static bool endsWith(const std::string& str, const std::string& suffix)
203{
204 if (suffix.size() > str.size())
205 return false;
206 return str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
207}
208
209ArchiveType ArchiveExtractService::detectFromExtension(const std::string& filePath)
210{
211 std::string path = filePath;
212 std::transform(path.begin(), path.end(), path.begin(),
213 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
214
215 if (endsWith(path, ".zip") || endsWith(path, ".zipx"))
216 return ArchiveType::Zip;
217 if (endsWith(path, ".tar.gz") || endsWith(path, ".tgz"))
218 return ArchiveType::TarGz;
219 if (endsWith(path, ".tar.bz2") || endsWith(path, ".tbz2") || endsWith(path, ".tbz"))
220 return ArchiveType::TarBz2;
221 if (endsWith(path, ".tar.xz") || endsWith(path, ".txz"))
222 return ArchiveType::TarXz;
223 if (endsWith(path, ".tar.zst") || endsWith(path, ".tzst"))
224 return ArchiveType::TarZst;
225 if (endsWith(path, ".tar"))
226 return ArchiveType::Tar;
227 if (endsWith(path, ".7z"))
229 if (endsWith(path, ".rar"))
230 return ArchiveType::Rar;
231 if (endsWith(path, ".cab"))
232 return ArchiveType::Cab;
233 if (endsWith(path, ".gz") && !endsWith(path, ".tar.gz"))
234 return ArchiveType::Gzip;
235 if (endsWith(path, ".bz2") && !endsWith(path, ".tar.bz2"))
236 return ArchiveType::Bzip2;
237 if (endsWith(path, ".xz") && !endsWith(path, ".tar.xz"))
238 return ArchiveType::Xz;
239
240 // .exe files need magic byte detection
241 if (endsWith(path, ".exe"))
242 {
243 return detectFromMagicBytes(filePath);
244 }
245
247}
248
249ArchiveType ArchiveExtractService::detectFromMagicBytes(const std::string& filePath)
250{
251 std::ifstream file(filePath, std::ios::binary);
252 if (!file)
253 {
255 }
256
257 std::array<unsigned char, 16> magic{};
258 file.read(reinterpret_cast<char*>(magic.data()), magic.size());
259
260 // ZIP: PK\x03\x04 or PK\x05\x06 (empty) or PK\x07\x08 (spanned)
261 if (magic[0] == 'P' && magic[1] == 'K' &&
262 (magic[2] == 0x03 || magic[2] == 0x05 || magic[2] == 0x07))
263 {
264 return ArchiveType::Zip;
265 }
266
267 // 7z: 7z\xBC\xAF\x27\x1C
268 if (magic[0] == '7' && magic[1] == 'z' && magic[2] == 0xBC && magic[3] == 0xAF)
269 {
271 }
272
273 // RAR: Rar!\x1A\x07
274 if (magic[0] == 'R' && magic[1] == 'a' && magic[2] == 'r' && magic[3] == '!' &&
275 magic[4] == 0x1A && magic[5] == 0x07)
276 {
277 return ArchiveType::Rar;
278 }
279
280 // GZIP: \x1F\x8B
281 if (magic[0] == 0x1F && magic[1] == 0x8B)
282 {
283 // Could be .tar.gz or standalone .gz
284 // Check filename for hint
285 std::string lower = filePath;
286 std::transform(lower.begin(), lower.end(), lower.begin(),
287 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
288 if (lower.find(".tar") != std::string::npos)
289 {
290 return ArchiveType::TarGz;
291 }
292 return ArchiveType::Gzip;
293 }
294
295 // BZIP2: BZh
296 if (magic[0] == 'B' && magic[1] == 'Z' && magic[2] == 'h')
297 {
298 std::string lower = filePath;
299 std::transform(lower.begin(), lower.end(), lower.begin(),
300 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
301 if (lower.find(".tar") != std::string::npos)
302 {
303 return ArchiveType::TarBz2;
304 }
305 return ArchiveType::Bzip2;
306 }
307
308 // XZ: \xFD7zXZ\x00
309 if (magic[0] == 0xFD && magic[1] == '7' && magic[2] == 'z' && magic[3] == 'X' &&
310 magic[4] == 'Z' && magic[5] == 0x00)
311 {
312 std::string lower = filePath;
313 std::transform(lower.begin(), lower.end(), lower.begin(),
314 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
315 if (lower.find(".tar") != std::string::npos)
316 {
317 return ArchiveType::TarXz;
318 }
319 return ArchiveType::Xz;
320 }
321
322 // Zstandard: little-endian magic 0x28 0xB5 0x2F 0xFD (per RFC 8878 §3.1.1).
323 // We only treat it as TarZst — there is no standalone-zstd ArchiveType
324 // because every caller that produces .zst here pairs it with tar.
325 if (magic[0] == 0x28 && magic[1] == 0xB5 && magic[2] == 0x2F && magic[3] == 0xFD)
326 {
327 std::string lower = filePath;
328 std::transform(lower.begin(), lower.end(), lower.begin(),
329 [](unsigned char c) { return static_cast<char>(::tolower(c)); });
330 if (lower.find(".tar") != std::string::npos || endsWith(lower, ".tzst"))
331 {
332 return ArchiveType::TarZst;
333 }
334 // Bare .zst with no .tar in the name — leave Unknown so callers don't
335 // accidentally invoke tar on a file that may be a single-file zstd
336 // payload (e.g. a Linux kernel module or pacman package).
338 }
339
340 // CAB: MSCF
341 if (magic[0] == 'M' && magic[1] == 'S' && magic[2] == 'C' && magic[3] == 'F')
342 {
343 return ArchiveType::Cab;
344 }
345
346 // Windows EXE: MZ
347 if (magic[0] == 'M' && magic[1] == 'Z')
348 {
349 // This is a Windows executable - could be InnoSetup, NSIS, or self-extracting
350 // We need to check for specific signatures
351
352 // Read more of the file to detect installer type
353 file.seekg(0, std::ios::end);
354 auto fileSize = file.tellg();
355
356 // InnoSetup: Look for "Inno Setup" string near the end
357 if (fileSize > 1024)
358 {
359 file.seekg(-1024, std::ios::end);
360 std::string tail(1024, '\0');
361 file.read(tail.data(), 1024);
362
363 if (tail.find("Inno Setup") != std::string::npos ||
364 tail.find("inno setup") != std::string::npos)
365 {
367 }
368
369 // NSIS: Look for "Nullsoft" or "NSIS"
370 if (tail.find("Nullsoft") != std::string::npos ||
371 tail.find("NSIS") != std::string::npos)
372 {
373 return ArchiveType::NSIS;
374 }
375 }
376
377 // Generic self-extracting exe
378 return ArchiveType::Exe;
379 }
380
382}
383
385{
386 switch (type)
387 {
388 case ArchiveType::Zip:
389 return "ZIP";
391 return "TAR.GZ";
393 return "TAR.BZ2";
395 return "TAR.XZ";
397 return "TAR.ZST";
398 case ArchiveType::Tar:
399 return "TAR";
401 return "7Z";
402 case ArchiveType::Rar:
403 return "RAR";
404 case ArchiveType::Cab:
405 return "CAB";
407 return "InnoSetup";
409 return "NSIS";
410 case ArchiveType::Exe:
411 return "Self-extracting EXE";
413 return "GZIP";
415 return "BZIP2";
416 case ArchiveType::Xz:
417 return "XZ";
418 default:
419 return "Unknown";
420 }
421}
422
423// ==============================================================================
424// Archive Information
425// ==============================================================================
426
427ArchiveInfo ArchiveExtractService::getInfo(const std::string& archivePath)
428{
429 ArchiveInfo info;
430 info.type = detectType(archivePath);
431 info.typeName = getTypeName(info.type);
432
433 if (!fs::exists(archivePath))
434 {
435 return info;
436 }
437
438 info.compressedSize = fs::file_size(archivePath);
439 info.contents = listContents(archivePath);
440 info.fileCount = static_cast<int>(info.contents.size());
441
442 return info;
443}
444
445std::vector<std::string> ArchiveExtractService::listContents(const std::string& archivePath)
446{
447 ArchiveType type = detectType(archivePath);
448 std::string command;
449 std::string output;
450
451 switch (type)
452 {
453 case ArchiveType::Zip:
454 command = "unzip -l " + ShellUtils::escapeArg(archivePath) + " 2>/dev/null";
455 break;
456
457 case ArchiveType::Tar:
462 // GNU tar auto-detects the compression here, but listing zstd archives
463 // still needs --zstd on some older builds; tar treats unknown -t flags
464 // as no-ops, so use the explicit form for TarZst.
465 if (type == ArchiveType::TarZst)
466 {
467 command = "tar --zstd -tf " + ShellUtils::escapeArg(archivePath) + " 2>/dev/null";
468 }
469 else
470 {
471 command = "tar -tf " + ShellUtils::escapeArg(archivePath) + " 2>/dev/null";
472 }
473 break;
474
476 case ArchiveType::Rar:
477 command = "7z l -slt " + ShellUtils::escapeArg(archivePath) + " 2>/dev/null";
478 break;
479
481 command = "innoextract -l " + ShellUtils::escapeArg(archivePath) + " 2>/dev/null";
482 break;
483
484 case ArchiveType::Cab:
485 command = "cabextract -l " + ShellUtils::escapeArg(archivePath) + " 2>/dev/null";
486 break;
487
488 default:
489 return {};
490 }
491
492 runCommand(command, output);
493 return parseFileList(output, type);
494}
495
496// ==============================================================================
497// Tool Availability
498// ==============================================================================
499
501{
502 std::string tool = getToolName(type);
503 return isToolInstalled(tool);
504}
505
506namespace
507{
508// True if an archive entry path is absolute or contains a ".." component,
509// i.e. it could escape the extraction root (CWE-22 path traversal).
510bool isUnsafeArchivePath(const std::string& entry)
511{
512 fs::path p(entry);
513 if (p.is_absolute())
514 return true;
515 for (const auto& part : p)
516 {
517 if (part == "..")
518 return true;
519 }
520 return false;
521}
522} // namespace
523
524bool ArchiveExtractService::hasUnsafeEntries(const std::string& archivePath, ArchiveType type)
525{
526 // List members with the *extraction* tool so NSIS/EXE (which route to 7z
527 // but are absent from listContents()) are also scanned.
528 const std::string tool = getToolName(type);
529 std::string command;
530 if (tool == "tar")
531 {
532 command = (type == ArchiveType::TarZst ? std::string("tar --zstd -tf ")
533 : std::string("tar -tf ")) +
534 ShellUtils::escapeArg(archivePath) + " 2>/dev/null";
535 }
536 else if (tool == "unzip")
537 {
538 // `unzip -Z1` (zipinfo mode) prints one member name per line and ships
539 // with unzip itself.
540 command = "unzip -Z1 " + ShellUtils::escapeArg(archivePath) + " 2>/dev/null";
541 }
542 else if (tool == "7z")
543 {
544 command = "7z l -slt " + ShellUtils::escapeArg(archivePath) + " 2>/dev/null";
545 }
546 else
547 {
548 // cabextract / innoextract produce flat file names with no directory
549 // component in practice; nothing to traverse.
550 return false;
551 }
552
553 std::string output;
554 runCommand(command, output);
555
556 const bool sevenZip = (tool == "7z");
557 std::istringstream stream(output);
558 std::string line;
559 while (std::getline(stream, line))
560 {
561 std::string entry;
562 if (sevenZip)
563 {
564 if (line.rfind("Path = ", 0) != 0)
565 continue;
566 entry = line.substr(7);
567 }
568 else
569 {
570 entry = line;
571 }
572 // 7z / zipinfo can emit CRLF; drop a trailing CR.
573 if (!entry.empty() && entry.back() == '\r')
574 entry.pop_back();
575 if (entry.empty())
576 continue;
577 if (isUnsafeArchivePath(entry))
578 {
579 Logger::error("ArchiveExtract: refusing archive with unsafe entry '{}' in {}", entry,
580 archivePath);
581 return true;
582 }
583 }
584 return false;
585}
586
588{
589 switch (type)
590 {
591 case ArchiveType::Zip:
592 return "unzip";
593 case ArchiveType::Tar:
600 case ArchiveType::Xz:
601 return "tar";
603 return "7z";
604 case ArchiveType::Rar:
605 return "7z"; // 7z can handle RAR
606 case ArchiveType::Cab:
607 return "cabextract";
609 return "innoextract";
611 return "7z"; // 7z can handle NSIS
612 case ArchiveType::Exe:
613 return "7z"; // Try 7z for generic exe
614 default:
615 return "";
616 }
617}
618
619bool ArchiveExtractService::isToolInstalled(const std::string& toolName)
620{
621 if (toolName.empty())
622 {
623 return false;
624 }
625
626 std::string command = "command -v " + ShellUtils::escapeArg(toolName) + " >/dev/null 2>&1";
627 int result = std::system(command.c_str());
628 return result != -1 && WIFEXITED(result) && WEXITSTATUS(result) == 0;
629}
630
631std::string ArchiveExtractService::getInstallCommand(const std::string& toolName)
632{
633 // Common package names for Arch-based systems
634 static const std::map<std::string, std::string> packages = {
635 {"unzip", "sudo pacman -S unzip"},
636 {"7z", "sudo pacman -S p7zip"},
637 {"cabextract", "sudo pacman -S cabextract"},
638 {"innoextract", "sudo pacman -S innoextract"},
639 {"tar", "sudo pacman -S tar"}, // Usually pre-installed
640 };
641
642 auto it = packages.find(toolName);
643 if (it != packages.end())
644 {
645 return it->second;
646 }
647 return "";
648}
649
650// ==============================================================================
651// Type-Specific Extractors
652// ==============================================================================
653
654ExtractResult ArchiveExtractService::extractZip(const ExtractRequest& request,
655 const ProgressCallback& /*progress*/)
656{
657 // Note: progress callback not yet implemented for zip extraction
658 ExtractResult result;
659 result.destinationDir = request.destinationDir;
660
661 std::ostringstream cmd;
662 cmd << "unzip ";
663
664 if (request.overwriteExisting)
665 {
666 cmd << "-o ";
667 }
668 else
669 {
670 cmd << "-n ";
671 }
672
673 if (!request.password.empty())
674 {
675 cmd << "-P " << ShellUtils::escapeArg(request.password) << " ";
676 }
677
678 cmd << ShellUtils::escapeArg(request.archivePath) << " ";
679 cmd << "-d " << ShellUtils::escapeArg(request.destinationDir) << " ";
680 cmd << "2>&1";
681
682 std::string output;
683 result.exitCode = runCommand(cmd.str(), output);
684 result.success = (result.exitCode == 0);
685
686 if (!result.success)
687 {
688 result.errorMessage = "unzip failed: " + output;
689 Logger::error("ArchiveExtract: {}", result.errorMessage);
690 }
691 else
692 {
693 Logger::info("ArchiveExtract: Successfully extracted ZIP to {}", request.destinationDir);
694 }
695
696 return result;
697}
698
699ExtractResult ArchiveExtractService::extractTar(const ExtractRequest& request,
700 const ProgressCallback& progress)
701{
702 ExtractResult result;
703 result.destinationDir = request.destinationDir;
704
705 std::ostringstream cmd;
706 cmd << "tar ";
707
708 // Zstd uses a long-form flag (`--zstd`) rather than a single-letter
709 // shortcut, so it is composed before the bundled `-x[zjJ]f`. GNU tar
710 // accepts the long flag adjacent to the bundled short flags.
711 if (request.type == ArchiveType::TarZst)
712 {
713 cmd << "--zstd ";
714 }
715
716 cmd << "-x";
717
718 // Compression flag for the formats with a dedicated short option.
719 // TarZst already had its compression handled via --zstd above.
720 switch (request.type)
721 {
723 cmd << "z";
724 break;
726 cmd << "j";
727 break;
729 cmd << "J";
730 break;
731 default:
732 break;
733 }
734
735 // --no-absolute-filenames: strips leading '/' from absolute paths in the archive
736 // GNU tar >= 1.14 also strips '../' sequences by default, but this is explicit defense
737 cmd << "f " << ShellUtils::escapeArg(request.archivePath) << " ";
738 cmd << "--no-absolute-filenames ";
739 cmd << "-C " << ShellUtils::escapeArg(request.destinationDir) << " ";
740
741 if (progress)
742 {
743 cmd << "-v "; // Verbose for progress
744 }
745
746 cmd << "2>&1";
747
748 std::string output;
749 result.exitCode = runCommand(cmd.str(), output);
750 result.success = (result.exitCode == 0);
751
752 if (!result.success)
753 {
754 result.errorMessage = "tar failed: " + output;
755 Logger::error("ArchiveExtract: {}", result.errorMessage);
756 }
757 else
758 {
759 Logger::info("ArchiveExtract: Successfully extracted TAR to {}", request.destinationDir);
760 }
761
762 return result;
763}
764
765ExtractResult ArchiveExtractService::extractSevenZip(const ExtractRequest& request,
766 const ProgressCallback& /*progress*/)
767{
768 // Note: progress callback not yet implemented for 7z extraction
769 ExtractResult result;
770 result.destinationDir = request.destinationDir;
771
772 std::ostringstream cmd;
773 cmd << "7z x ";
774
775 if (request.overwriteExisting)
776 {
777 cmd << "-aoa "; // Overwrite all
778 }
779 else
780 {
781 cmd << "-aos "; // Skip existing
782 }
783
784 if (!request.password.empty())
785 {
786 cmd << "-p" << ShellUtils::escapeArg(request.password) << " ";
787 }
788
789 cmd << "-o" << ShellUtils::escapeArg(request.destinationDir) << " ";
790 cmd << ShellUtils::escapeArg(request.archivePath) << " ";
791 cmd << "2>&1";
792
793 std::string output;
794 result.exitCode = runCommand(cmd.str(), output);
795
796 // 7z returns 0 for success, 1 for warning, 2+ for error
797 result.success = (result.exitCode == 0 || result.exitCode == 1);
798
799 if (!result.success)
800 {
801 result.errorMessage = "7z failed: " + output;
802 Logger::error("ArchiveExtract: {}", result.errorMessage);
803 }
804 else
805 {
806 Logger::info("ArchiveExtract: Successfully extracted 7z to {}", request.destinationDir);
807 }
808
809 return result;
810}
811
812ExtractResult ArchiveExtractService::extractRar(const ExtractRequest& request,
813 const ProgressCallback& progress)
814{
815 // Use 7z for RAR extraction
816 return extractSevenZip(request, progress);
817}
818
819ExtractResult ArchiveExtractService::extractCab(const ExtractRequest& request,
820 const ProgressCallback& /*progress*/)
821{
822 // Note: progress callback not yet implemented for cab extraction
823 ExtractResult result;
824 result.destinationDir = request.destinationDir;
825
826 std::ostringstream cmd;
827 cmd << "cabextract -d " << ShellUtils::escapeArg(request.destinationDir) << " ";
828 cmd << ShellUtils::escapeArg(request.archivePath) << " ";
829 cmd << "2>&1";
830
831 std::string output;
832 result.exitCode = runCommand(cmd.str(), output);
833 result.success = (result.exitCode == 0);
834
835 if (!result.success)
836 {
837 result.errorMessage = "cabextract failed: " + output;
838 Logger::error("ArchiveExtract: {}", result.errorMessage);
839 }
840 else
841 {
842 Logger::info("ArchiveExtract: Successfully extracted CAB to {}", request.destinationDir);
843 }
844
845 return result;
846}
847
848ExtractResult ArchiveExtractService::extractInnoSetup(const ExtractRequest& request,
849 const ProgressCallback& progress)
850{
851 ExtractResult result;
852 result.destinationDir = request.destinationDir;
853
854 std::ostringstream cmd;
855 cmd << "innoextract ";
856 cmd << "-d " << ShellUtils::escapeArg(request.destinationDir) << " ";
857
858 if (progress)
859 {
860 cmd << "--progress ";
861 }
862
863 cmd << ShellUtils::escapeArg(request.archivePath) << " ";
864 cmd << "2>&1";
865
866 std::string output;
867 result.exitCode = runCommand(cmd.str(), output);
868 result.success = (result.exitCode == 0);
869
870 if (!result.success)
871 {
872 result.errorMessage = "innoextract failed: " + output;
873 Logger::error("ArchiveExtract: {}", result.errorMessage);
874 }
875 else
876 {
877 Logger::info("ArchiveExtract: Successfully extracted InnoSetup to {}",
878 request.destinationDir);
879 }
880
881 return result;
882}
883
884ExtractResult ArchiveExtractService::extractNSIS(const ExtractRequest& request,
885 const ProgressCallback& progress)
886{
887 // Use 7z for NSIS extraction
888 return extractSevenZip(request, progress);
889}
890
891ExtractResult ArchiveExtractService::extractGzip(const ExtractRequest& request,
892 const ProgressCallback& /*progress*/)
893{
894 // Note: progress callback not yet implemented for gzip extraction
895 ExtractResult result;
896 result.destinationDir = request.destinationDir;
897
898 // For single-file compression, decompress to destination
899 std::string outputFile =
900 request.destinationDir + "/" + fs::path(request.archivePath).stem().string();
901
902 std::string decompressor;
903 switch (request.type)
904 {
906 decompressor = "gunzip -c";
907 break;
909 decompressor = "bunzip2 -c";
910 break;
911 case ArchiveType::Xz:
912 decompressor = "unxz -c";
913 break;
914 default:
915 result.errorMessage = "Unknown compression type";
916 return result;
917 }
918
919 std::ostringstream cmd;
920 cmd << decompressor << " " << ShellUtils::escapeArg(request.archivePath) << " > "
921 << ShellUtils::escapeArg(outputFile) << " 2>&1";
922
923 std::string output;
924 result.exitCode = runCommand(cmd.str(), output);
925 result.success = (result.exitCode == 0);
926
927 if (!result.success)
928 {
929 result.errorMessage = "Decompression failed: " + output;
930 Logger::error("ArchiveExtract: {}", result.errorMessage);
931 }
932 else
933 {
934 result.extractedFiles.push_back(outputFile);
935 std::error_code sizeEc;
936 result.totalBytesExtracted = fs::file_size(outputFile, sizeEc);
937 Logger::info("ArchiveExtract: Successfully decompressed to {}", outputFile);
938 }
939
940 return result;
941}
942
943// ==============================================================================
944// Helpers
945// ==============================================================================
946
947std::vector<std::string> ArchiveExtractService::parseFileList(const std::string& output,
948 ArchiveType type)
949{
950 std::vector<std::string> files;
951 std::istringstream stream(output);
952 std::string line;
953
954 switch (type)
955 {
956 case ArchiveType::Tar:
960 // tar -tf output is just filenames, one per line
961 while (std::getline(stream, line))
962 {
963 if (!line.empty())
964 {
965 files.push_back(line);
966 }
967 }
968 break;
969
970 case ArchiveType::Zip:
971 // unzip -l output has header and footer, files are indented
972 while (std::getline(stream, line))
973 {
974 // Skip header lines and total line
975 if (line.find("Archive:") != std::string::npos)
976 continue;
977 if (line.find("Length") != std::string::npos)
978 continue;
979 if (line.find("-------") != std::string::npos)
980 continue;
981 if (line.find(" files") != std::string::npos)
982 continue;
983 if (line.empty())
984 continue;
985
986 // Parse " length date time name" format
987 // The filename is at the end after the date/time
988 size_t nameStart = line.rfind(" ");
989 if (nameStart != std::string::npos)
990 {
991 std::string name = line.substr(nameStart + 2);
992 if (!name.empty())
993 {
994 files.push_back(name);
995 }
996 }
997 }
998 break;
999
1001 case ArchiveType::Rar:
1002 // 7z l -slt output: "Path = filename" lines
1003 while (std::getline(stream, line))
1004 {
1005 if (line.find("Path = ") == 0)
1006 {
1007 files.push_back(line.substr(7));
1008 }
1009 }
1010 break;
1011
1013 // innoextract -l output: " - "filename""
1014 while (std::getline(stream, line))
1015 {
1016 if (line.find(" - \"") == 0)
1017 {
1018 size_t start = 4;
1019 size_t end = line.rfind('"');
1020 if (end > start)
1021 {
1022 files.push_back(line.substr(start, end - start));
1023 }
1024 }
1025 }
1026 break;
1027
1028 default:
1029 break;
1030 }
1031
1032 return files;
1033}
1034
1035int ArchiveExtractService::runCommand(const std::string& command, std::string& output)
1036{
1037 FILE* pipe = popen(command.c_str(), "r");
1038 if (!pipe)
1039 {
1040 output = "Failed to execute command";
1041 return -1;
1042 }
1043
1044 std::array<char, 4096> buffer;
1045 output.clear();
1046
1047 constexpr size_t kMaxOutput = 16u * 1024 * 1024; // 16 MB cap
1048 while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
1049 {
1050 output += buffer.data();
1051 if (output.size() > kMaxOutput)
1052 break;
1053 }
1054
1055 int status = pclose(pipe);
1056 if (status == -1 || !WIFEXITED(status))
1057 {
1058 return -1;
1059 }
1060 return WEXITSTATUS(status);
1061}
static bool endsWith(const std::string &str, const std::string &suffix)
static std::string getToolName(ArchiveType type)
Get the command-line tool used for a type.
static std::string getTypeName(ArchiveType type)
Get human-readable name for archive type.
static void extractAsync(const ExtractRequest &request, const std::function< void(const ExtractResult &)> &onComplete, const ProgressCallback &onProgress=nullptr)
Extract an archive asynchronously.
std::function< void(int percent, const std::string &currentFile)> ProgressCallback
static ExtractResult extract(const ExtractRequest &request, const ProgressCallback &progressCallback=nullptr)
Extract an archive.
static bool isSupported(ArchiveType type)
Check if extraction for a type is supported.
static ArchiveType detectType(const std::string &filePath)
Detect archive type from file.
static ArchiveInfo getInfo(const std::string &archivePath)
Get archive information without extracting.
static bool isToolInstalled(const std::string &toolName)
Check if a tool is installed.
static std::vector< std::string > listContents(const std::string &archivePath)
List archive contents without extracting.
static std::string getInstallCommand(const std::string &toolName)
Get installation command for a tool.
static void info(const std::string &message, Args &&... args)
Log info message (general information).
Definition logger.h:108
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
Definition logger.h:124
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
Definition shell_utils.h:65
void storeFuture(std::shared_ptr< std::future< void > > f)
std::vector< std::shared_ptr< std::future< void > > > activeFutures_
std::vector< std::string > contents
std::vector< std::string > extractedFiles