25namespace fs = std::filesystem;
36 [](
const std::shared_ptr<std::future<void>>& fu)
38 return fu->wait_for(std::chrono::seconds(0)) ==
39 std::future_status::ready;
83 result.
errorMessage =
"Required tool not installed: " + tool;
85 if (!installCmd.empty())
87 result.
errorMessage +=
" (install with: " + installCmd +
")";
98 "Archive contains unsafe (path-traversal or absolute) entries; refusing to extract";
110 result.
errorMessage =
"Failed to create destination directory";
118 modRequest.
type = type;
123 result = extractZip(modRequest, progressCallback);
131 result = extractTar(modRequest, progressCallback);
135 result = extractSevenZip(modRequest, progressCallback);
139 result = extractRar(modRequest, progressCallback);
143 result = extractCab(modRequest, progressCallback);
147 result = extractInnoSetup(modRequest, progressCallback);
151 result = extractNSIS(modRequest, progressCallback);
157 result = extractGzip(modRequest, progressCallback);
173 auto future = std::make_shared<std::future<void>>(std::async(std::launch::async,
174 [request, onComplete, onProgress]()
177 request, onProgress);
181 storeFuture(std::move(future));
198 return detectFromExtension(filePath);
202static bool endsWith(
const std::string& str,
const std::string& suffix)
204 if (suffix.size() > str.size())
206 return str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
209ArchiveType ArchiveExtractService::detectFromExtension(
const std::string& filePath)
211 std::string path = filePath;
212 std::transform(path.begin(), path.end(), path.begin(),
213 [](
unsigned char c) { return static_cast<char>(::tolower(c)); });
243 return detectFromMagicBytes(filePath);
249ArchiveType ArchiveExtractService::detectFromMagicBytes(
const std::string& filePath)
251 std::ifstream file(filePath, std::ios::binary);
257 std::array<unsigned char, 16> magic{};
258 file.read(
reinterpret_cast<char*
>(magic.data()), magic.size());
261 if (magic[0] ==
'P' && magic[1] ==
'K' &&
262 (magic[2] == 0x03 || magic[2] == 0x05 || magic[2] == 0x07))
268 if (magic[0] ==
'7' && magic[1] ==
'z' && magic[2] == 0xBC && magic[3] == 0xAF)
274 if (magic[0] ==
'R' && magic[1] ==
'a' && magic[2] ==
'r' && magic[3] ==
'!' &&
275 magic[4] == 0x1A && magic[5] == 0x07)
281 if (magic[0] == 0x1F && magic[1] == 0x8B)
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)
296 if (magic[0] ==
'B' && magic[1] ==
'Z' && magic[2] ==
'h')
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)
309 if (magic[0] == 0xFD && magic[1] ==
'7' && magic[2] ==
'z' && magic[3] ==
'X' &&
310 magic[4] ==
'Z' && magic[5] == 0x00)
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)
325 if (magic[0] == 0x28 && magic[1] == 0xB5 && magic[2] == 0x2F && magic[3] == 0xFD)
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"))
341 if (magic[0] ==
'M' && magic[1] ==
'S' && magic[2] ==
'C' && magic[3] ==
'F')
347 if (magic[0] ==
'M' && magic[1] ==
'Z')
353 file.seekg(0, std::ios::end);
354 auto fileSize = file.tellg();
359 file.seekg(-1024, std::ios::end);
360 std::string tail(1024,
'\0');
361 file.read(tail.data(), 1024);
363 if (tail.find(
"Inno Setup") != std::string::npos ||
364 tail.find(
"inno setup") != std::string::npos)
370 if (tail.find(
"Nullsoft") != std::string::npos ||
371 tail.find(
"NSIS") != std::string::npos)
411 return "Self-extracting EXE";
433 if (!fs::exists(archivePath))
492 runCommand(command, output);
493 return parseFileList(output, type);
515 for (
const auto& part : p)
524bool ArchiveExtractService::hasUnsafeEntries(
const std::string& archivePath,
ArchiveType type)
533 : std::string(
"tar -tf ")) +
534 ShellUtils::escapeArg(archivePath) +
" 2>/dev/null";
536 else if (tool ==
"unzip")
542 else if (tool ==
"7z")
554 runCommand(command, output);
556 const bool sevenZip = (tool ==
"7z");
557 std::istringstream stream(output);
559 while (std::getline(stream, line))
564 if (line.rfind(
"Path = ", 0) != 0)
566 entry = line.substr(7);
573 if (!entry.empty() && entry.back() ==
'\r')
579 Logger::error(
"ArchiveExtract: refusing archive with unsafe entry '{}' in {}", entry,
609 return "innoextract";
621 if (toolName.empty())
627 int result = std::system(command.c_str());
628 return result != -1 && WIFEXITED(result) && WEXITSTATUS(result) == 0;
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"},
642 auto it = packages.find(toolName);
643 if (it != packages.end())
655 const ProgressCallback& )
661 std::ostringstream cmd;
683 result.
exitCode = runCommand(cmd.str(), output);
700 const ProgressCallback& progress)
702 ExtractResult result;
705 std::ostringstream cmd;
720 switch (request.
type)
738 cmd <<
"--no-absolute-filenames ";
749 result.
exitCode = runCommand(cmd.str(), output);
766 const ProgressCallback& )
769 ExtractResult result;
772 std::ostringstream cmd;
794 result.
exitCode = runCommand(cmd.str(), output);
813 const ProgressCallback& progress)
816 return extractSevenZip(request, progress);
820 const ProgressCallback& )
823 ExtractResult result;
826 std::ostringstream cmd;
832 result.
exitCode = runCommand(cmd.str(), output);
849 const ProgressCallback& progress)
851 ExtractResult result;
854 std::ostringstream cmd;
855 cmd <<
"innoextract ";
860 cmd <<
"--progress ";
867 result.
exitCode = runCommand(cmd.str(), output);
877 Logger::info(
"ArchiveExtract: Successfully extracted InnoSetup to {}",
885 const ProgressCallback& progress)
888 return extractSevenZip(request, progress);
892 const ProgressCallback& )
895 ExtractResult result;
899 std::string outputFile =
902 std::string decompressor;
903 switch (request.
type)
906 decompressor =
"gunzip -c";
909 decompressor =
"bunzip2 -c";
912 decompressor =
"unxz -c";
919 std::ostringstream cmd;
924 result.
exitCode = runCommand(cmd.str(), output);
929 result.
errorMessage =
"Decompression failed: " + output;
935 std::error_code sizeEc;
937 Logger::info(
"ArchiveExtract: Successfully decompressed to {}", outputFile);
947std::vector<std::string> ArchiveExtractService::parseFileList(
const std::string& output,
950 std::vector<std::string> files;
951 std::istringstream stream(output);
961 while (std::getline(stream, line))
965 files.push_back(line);
972 while (std::getline(stream, line))
975 if (line.find(
"Archive:") != std::string::npos)
977 if (line.find(
"Length") != std::string::npos)
979 if (line.find(
"-------") != std::string::npos)
981 if (line.find(
" files") != std::string::npos)
988 size_t nameStart = line.rfind(
" ");
989 if (nameStart != std::string::npos)
991 std::string name = line.substr(nameStart + 2);
994 files.push_back(name);
1003 while (std::getline(stream, line))
1005 if (line.find(
"Path = ") == 0)
1007 files.push_back(line.substr(7));
1014 while (std::getline(stream, line))
1016 if (line.find(
" - \"") == 0)
1019 size_t end = line.rfind(
'"');
1022 files.push_back(line.substr(start, end - start));
1035int ArchiveExtractService::runCommand(
const std::string& command, std::string& output)
1037 FILE* pipe = popen(command.c_str(),
"r");
1040 output =
"Failed to execute command";
1044 std::array<char, 4096> buffer;
1047 constexpr size_t kMaxOutput = 16u * 1024 * 1024;
1048 while (fgets(buffer.data(),
static_cast<int>(buffer.size()), pipe) !=
nullptr)
1050 output += buffer.data();
1051 if (output.size() > kMaxOutput)
1055 int status = pclose(pipe);
1056 if (status == -1 || !WIFEXITED(status))
1060 return WEXITSTATUS(status);
static void info(const std::string &message, Args &&... args)
Log info message (general information).
static void error(const std::string &message, Args &&... args)
Log error message (recoverable failure).
static std::string escapeArg(const std::string &arg)
Escape a string for safe use as a shell argument.
std::vector< std::string > contents