1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing for details. */
3 #include "cmArchiveWrite.h"
14 #include <cm/algorithm>
16 #include <cm3p/archive.h>
17 #include <cm3p/archive_entry.h>
19 #include "cmsys/Directory.hxx"
20 #include "cmsys/Encoding.hxx"
21 #include "cmsys/FStream.hxx"
23 #include "cm_get_date.h"
26 #include "cmStringAlgorithms.h"
27 #include "cmSystemTools.h"
30 # define __LA_SSIZE_T la_ssize_t
33 static std::string cm_archive_error_string(struct archive* a)
35 const char* e = archive_error_string(a);
36 return e ? e : "unknown error";
39 static void cm_archive_entry_copy_pathname(struct archive_entry* e,
40 const std::string& dest)
42 #if cmsys_STL_HAS_WSTRING
43 archive_entry_copy_pathname_w(e, cmsys::Encoding::ToWide(dest).c_str());
45 archive_entry_copy_pathname(e, dest.c_str());
49 static void cm_archive_entry_copy_sourcepath(struct archive_entry* e,
50 const std::string& file)
52 #if cmsys_STL_HAS_WSTRING
53 archive_entry_copy_sourcepath_w(e, cmsys::Encoding::ToWide(file).c_str());
55 archive_entry_copy_sourcepath(e, file.c_str());
59 class cmArchiveWrite::Entry
61 struct archive_entry* Object;
65 : Object(archive_entry_new())
68 ~Entry() { archive_entry_free(this->Object); }
69 Entry(const Entry&) = delete;
70 Entry& operator=(const Entry&) = delete;
71 operator struct archive_entry*() { return this->Object; }
74 struct cmArchiveWrite::Callback
76 // archive_write_callback
77 static __LA_SSIZE_T Write(struct archive* /*unused*/, void* cd,
78 const void* b, size_t n)
80 cmArchiveWrite* self = static_cast<cmArchiveWrite*>(cd);
81 if (self->Stream.write(static_cast<const char*>(b),
82 static_cast<std::streamsize>(n))) {
83 return static_cast<__LA_SSIZE_T>(n);
85 return static_cast<__LA_SSIZE_T>(-1);
89 cmArchiveWrite::cmArchiveWrite(std::ostream& os, Compress c,
90 std::string const& format, int compressionLevel,
93 , Archive(archive_write_new())
94 , Disk(archive_read_disk_new())
97 // Upstream fixed an issue with their integer parsing in 3.4.0
98 // which would cause spurious errors to be raised from `strtoull`.
100 if (numThreads < 1) {
101 int upperLimit = (numThreads == 0) ? std::numeric_limits<int>::max()
102 : std::abs(numThreads);
105 cm::clamp<int>(std::thread::hardware_concurrency(), 1, upperLimit);
108 std::string sNumThreads = std::to_string(numThreads);
112 if (archive_write_add_filter_none(this->Archive) != ARCHIVE_OK) {
113 this->Error = cmStrCat("archive_write_add_filter_none: ",
114 cm_archive_error_string(this->Archive));
118 case CompressCompress:
119 if (archive_write_add_filter_compress(this->Archive) != ARCHIVE_OK) {
120 this->Error = cmStrCat("archive_write_add_filter_compress: ",
121 cm_archive_error_string(this->Archive));
126 if (archive_write_add_filter_gzip(this->Archive) != ARCHIVE_OK) {
127 this->Error = cmStrCat("archive_write_add_filter_gzip: ",
128 cm_archive_error_string(this->Archive));
131 std::string source_date_epoch;
132 cmSystemTools::GetEnv("SOURCE_DATE_EPOCH", source_date_epoch);
133 if (!source_date_epoch.empty()) {
134 // We're not able to specify an arbitrary timestamp for gzip.
135 // The next best thing is to omit the timestamp entirely.
136 if (archive_write_set_filter_option(this->Archive, "gzip", "timestamp",
137 nullptr) != ARCHIVE_OK) {
138 this->Error = cmStrCat("archive_write_set_filter_option: ",
139 cm_archive_error_string(this->Archive));
145 if (archive_write_add_filter_bzip2(this->Archive) != ARCHIVE_OK) {
146 this->Error = cmStrCat("archive_write_add_filter_bzip2: ",
147 cm_archive_error_string(this->Archive));
152 if (archive_write_add_filter_lzma(this->Archive) != ARCHIVE_OK) {
153 this->Error = cmStrCat("archive_write_add_filter_lzma: ",
154 cm_archive_error_string(this->Archive));
159 if (archive_write_add_filter_xz(this->Archive) != ARCHIVE_OK) {
160 this->Error = cmStrCat("archive_write_add_filter_xz: ",
161 cm_archive_error_string(this->Archive));
165 #if ARCHIVE_VERSION_NUMBER >= 3004000
168 // FIXME: Using more than 2 threads creates an empty archive.
169 // Enforce this limit pending further investigation.
170 if (numThreads > 2) {
172 sNumThreads = std::to_string(numThreads);
175 if (archive_write_set_filter_option(this->Archive, "xz", "threads",
176 sNumThreads.c_str()) != ARCHIVE_OK) {
177 this->Error = cmStrCat("archive_compressor_xz_options: ",
178 cm_archive_error_string(this->Archive));
185 if (archive_write_add_filter_zstd(this->Archive) != ARCHIVE_OK) {
186 this->Error = cmStrCat("archive_write_add_filter_zstd: ",
187 cm_archive_error_string(this->Archive));
191 #if ARCHIVE_VERSION_NUMBER >= 3006000
192 if (archive_write_set_filter_option(this->Archive, "zstd", "threads",
193 sNumThreads.c_str()) != ARCHIVE_OK) {
194 this->Error = cmStrCat("archive_compressor_zstd_options: ",
195 cm_archive_error_string(this->Archive));
202 if (compressionLevel != 0) {
203 std::string compressionLevelStr = std::to_string(compressionLevel);
204 std::string archiveFilterName;
207 case CompressCompress:
210 archiveFilterName = "gzip";
213 archiveFilterName = "bzip2";
216 archiveFilterName = "lzma";
219 archiveFilterName = "xz";
222 archiveFilterName = "zstd";
225 if (!archiveFilterName.empty()) {
226 if (archive_write_set_filter_option(
227 this->Archive, archiveFilterName.c_str(), "compression-level",
228 compressionLevelStr.c_str()) != ARCHIVE_OK) {
229 this->Error = cmStrCat("archive_write_set_filter_option: ",
230 cm_archive_error_string(this->Archive));
236 #if !defined(_WIN32) || defined(__CYGWIN__)
237 if (archive_read_disk_set_standard_lookup(this->Disk) != ARCHIVE_OK) {
238 this->Error = cmStrCat("archive_read_disk_set_standard_lookup: ",
239 cm_archive_error_string(this->Archive));
244 if (archive_write_set_format_by_name(this->Archive, format.c_str()) !=
246 this->Error = cmStrCat("archive_write_set_format_by_name: ",
247 cm_archive_error_string(this->Archive));
251 // do not pad the last block!!
252 if (archive_write_set_bytes_in_last_block(this->Archive, 1)) {
253 this->Error = cmStrCat("archive_write_set_bytes_in_last_block: ",
254 cm_archive_error_string(this->Archive));
259 bool cmArchiveWrite::Open()
261 if (!this->Error.empty()) {
264 if (archive_write_open(
265 this->Archive, this, nullptr,
266 reinterpret_cast<archive_write_callback*>(&Callback::Write),
267 nullptr) != ARCHIVE_OK) {
269 cmStrCat("archive_write_open: ", cm_archive_error_string(this->Archive));
275 cmArchiveWrite::~cmArchiveWrite()
277 archive_read_free(this->Disk);
278 archive_write_free(this->Archive);
281 bool cmArchiveWrite::Add(std::string path, size_t skip, const char* prefix,
284 if (!path.empty() && path.back() == '/') {
285 path.erase(path.size() - 1);
287 this->AddPath(path.c_str(), skip, prefix, recursive);
291 bool cmArchiveWrite::AddPath(const char* path, size_t skip, const char* prefix,
294 if (strcmp(path, ".") != 0 ||
295 (this->Format != "zip" && this->Format != "7zip")) {
296 if (!this->AddFile(path, skip, prefix)) {
300 if ((!cmSystemTools::FileIsDirectory(path) || !recursive) ||
301 cmSystemTools::FileIsSymlink(path)) {
306 std::string next = cmStrCat(path, '/');
307 if (next == "./" && (this->Format == "zip" || this->Format == "7zip")) {
310 std::string::size_type end = next.size();
311 unsigned long n = d.GetNumberOfFiles();
312 for (unsigned long i = 0; i < n; ++i) {
313 const char* file = d.GetFile(i);
314 if (strcmp(file, ".") != 0 && strcmp(file, "..") != 0) {
317 if (!this->AddPath(next.c_str(), skip, prefix)) {
326 bool cmArchiveWrite::AddFile(const char* file, size_t skip, const char* prefix)
329 // Skip the file if we have no name for it. This may happen on a
330 // top-level directory, which does not need to be included anyway.
331 if (skip >= strlen(file)) {
334 const char* out = file + skip;
336 cmLocaleRAII localeRAII;
337 static_cast<void>(localeRAII);
340 std::string dest = cmStrCat(prefix ? prefix : "", out);
342 std::cout << dest << "\n";
345 cm_archive_entry_copy_sourcepath(e, file);
346 cm_archive_entry_copy_pathname(e, dest);
347 if (archive_read_disk_entry_from_file(this->Disk, e, -1, nullptr) !=
349 this->Error = cmStrCat("Unable to read from file '", file,
350 "': ", cm_archive_error_string(this->Disk));
353 if (!this->MTime.empty()) {
356 time_t t = cm_get_date(now, this->MTime.c_str());
358 this->Error = cmStrCat("unable to parse mtime '", this->MTime, '\'');
361 archive_entry_set_mtime(e, t, 0);
363 std::string source_date_epoch;
364 cmSystemTools::GetEnv("SOURCE_DATE_EPOCH", source_date_epoch);
365 if (!source_date_epoch.empty()) {
366 std::istringstream iss(source_date_epoch);
369 if (iss.eof() && !iss.fail()) {
370 // Set all of the file times to the epoch time to handle archive
371 // formats that include creation/access time.
372 archive_entry_set_mtime(e, epochTime, 0);
373 archive_entry_set_atime(e, epochTime, 0);
374 archive_entry_set_ctime(e, epochTime, 0);
375 archive_entry_set_birthtime(e, epochTime, 0);
380 // manages the uid/guid of the entry (if any)
381 if (this->Uid.IsSet() && this->Gid.IsSet()) {
382 archive_entry_set_uid(e, this->Uid.Get());
383 archive_entry_set_gid(e, this->Gid.Get());
386 if (!this->Uname.empty() && !this->Gname.empty()) {
387 archive_entry_set_uname(e, this->Uname.c_str());
388 archive_entry_set_gname(e, this->Gname.c_str());
391 // manages the permissions
392 if (this->Permissions.IsSet()) {
393 archive_entry_set_perm(e, this->Permissions.Get());
396 if (this->PermissionsMask.IsSet()) {
397 int perm = archive_entry_perm(e);
398 archive_entry_set_perm(e, perm & this->PermissionsMask.Get());
401 // Clear acl and xattr fields not useful for distribution.
402 archive_entry_acl_clear(e);
403 archive_entry_xattr_clear(e);
404 archive_entry_set_fflags(e, 0, 0);
406 if (this->Format == "pax" || this->Format == "paxr") {
407 // Sparse files are a GNU tar extension.
408 // Do not use them in standard tar files.
409 archive_entry_sparse_clear(e);
412 if (archive_write_header(this->Archive, e) != ARCHIVE_OK) {
413 this->Error = cmStrCat("archive_write_header: ",
414 cm_archive_error_string(this->Archive));
418 // do not copy content of symlink
419 if (!archive_entry_symlink(e)) {
421 if (size_t size = static_cast<size_t>(archive_entry_size(e))) {
422 return this->AddData(file, size);
428 bool cmArchiveWrite::AddData(const char* file, size_t size)
430 cmsys::ifstream fin(file, std::ios::in | std::ios::binary);
432 this->Error = cmStrCat("Error opening \"", file,
433 "\": ", cmSystemTools::GetLastSystemError());
440 using ssize_type = std::streamsize;
441 size_t const nnext = nleft > sizeof(buffer) ? sizeof(buffer) : nleft;
442 ssize_type const nnext_s = static_cast<ssize_type>(nnext);
443 fin.read(buffer, nnext_s);
444 // Some stream libraries (older HPUX) return failure at end of
445 // file on the last read even if some data were read. Check
446 // gcount instead of trusting the stream error status.
447 if (static_cast<size_t>(fin.gcount()) != nnext) {
450 if (archive_write_data(this->Archive, buffer, nnext) != nnext_s) {
451 this->Error = cmStrCat("archive_write_data: ",
452 cm_archive_error_string(this->Archive));
458 this->Error = cmStrCat("Error reading \"", file,
459 "\": ", cmSystemTools::GetLastSystemError());