// SPDX-License-Identifier: GPL-3.0-or-later #import "VCCLibraryArchive.h" #include #include #include #include #include #include #include #include #include #include // A narrow adapter for the stable system libarchive ABI. Apple's SDK exports // these functions in libarchive.tbd but does not supply libarchive headers. // No external program, Homebrew installation, or bundled library is required. extern "C" { struct archive; struct archive_entry; struct archive *archive_read_new(void); int archive_read_support_format_zip_seekable(struct archive *); int archive_read_open_fd(struct archive *, int, size_t); int archive_read_next_header(struct archive *, struct archive_entry **); ssize_t archive_read_data(struct archive *, void *, size_t); int archive_read_close(struct archive *); int archive_read_free(struct archive *); const char *archive_error_string(struct archive *); const char *archive_entry_pathname_utf8(struct archive_entry *); const char *archive_entry_pathname(struct archive_entry *); const char *archive_entry_symlink(struct archive_entry *); const char *archive_entry_hardlink(struct archive_entry *); mode_t archive_entry_filetype(struct archive_entry *); int64_t archive_entry_size(struct archive_entry *); int archive_entry_size_is_set(struct archive_entry *); int archive_entry_is_encrypted(struct archive_entry *); } NSErrorDomain const VCCLibraryArchiveErrorDomain = @"com.brianholman.vccplus.library.archive"; namespace { constexpr int archiveOK = 0, archiveEOF = 1; struct Descriptor { int fd = -1; explicit Descriptor(int value = -1): fd(value) {} ~Descriptor() { if (fd >= 0) close(fd); } Descriptor(const Descriptor &) = delete; Descriptor &operator=(const Descriptor &) = delete; void reset(int value) { if (fd >= 0) close(fd); fd = value; } }; struct Reader { struct archive *value = archive_read_new(); ~Reader() { if (value) archive_read_free(value); } }; bool fail(NSError **error, VCCLibraryArchiveError code, NSString *message) { if (error) *error = [NSError errorWithDomain:VCCLibraryArchiveErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey:message}]; return false; } bool cancelled(BOOL (^check)(void), NSError **error) { return check && check() ? !fail(error, VCCLibraryArchiveErrorCancelled, @"Installation was cancelled.") : false; } NSString *archiveMessage(struct archive *value, NSString *fallback) { const char *text = archive_error_string(value); return text ? [NSString stringWithFormat:@"%@: %s", fallback, text] : fallback; } uint16_t u16(const uint8_t *p) { return uint16_t(p[0]) | uint16_t(p[1]) << 8; } uint32_t u32(const uint8_t *p) { return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24; } bool readAt(int fd, uint64_t offset, void *buffer, size_t count) { size_t done = 0; while (done < count) { ssize_t n = pread(fd, (uint8_t *)buffer + done, count - done, (off_t)(offset + done)); if (n < 0 && errno == EINTR) continue; if (n <= 0) return false; done += (size_t)n; } return true; } // Require the complete central directory. A streaming unzip reader can otherwise // accept a truncated ZIP with intact local headers. Inspect raw names too: C APIs // cannot expose embedded NULs, and ZIP readers may normalize Windows separators. bool checkContainer(int fd, uint64_t fileSize, NSUInteger maxEntries, BOOL (^check)(void), uint64_t &entryCount, NSError **error) { if (fileSize < 22) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP file is truncated or invalid."); size_t tailSize = (size_t)MIN(fileSize, uint64_t(65557)); std::vector tail(tailSize); if (!readAt(fd, fileSize - tailSize, tail.data(), tailSize)) return fail(error, VCCLibraryArchiveErrorIO, @"The ZIP file could not be read."); int64_t end = -1; for (int64_t i = (int64_t)tailSize - 22; i >= 0; --i) { if (u32(tail.data() + i) == 0x06054b50 && (uint64_t)i + 22 + u16(tail.data() + i + 20) == tailSize) { end = i; break; } } if (end < 0) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP file has no complete end-of-directory record."); const uint8_t *e = tail.data() + end; uint64_t count = u16(e + 10), centralSize = u32(e + 12), centralOffset = u32(e + 16); if (u16(e + 4) || u16(e + 6) || u16(e + 8) != count || count == 65535 || centralSize == UINT32_MAX || centralOffset == UINT32_MAX) return fail(error, VCCLibraryArchiveErrorUnsupported, @"Multi-volume and ZIP64 packages are not supported by this installer."); if (count > maxEntries) return fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP file contains too many entries."); const uint64_t endOffset = fileSize - tailSize + (uint64_t)end; if (centralOffset > endOffset || centralSize != endOffset - centralOffset) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP central directory is incomplete or inconsistent."); uint64_t offset = centralOffset; for (uint64_t index = 0; index < count; ++index) { if (cancelled(check, error)) return false; uint8_t header[46]; if (offset > endOffset || endOffset - offset < sizeof(header) || !readAt(fd, offset, header, sizeof(header)) || u32(header) != 0x02014b50) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP central directory contains a damaged entry."); const uint64_t nameLength = u16(header + 28), extraLength = u16(header + 30), commentLength = u16(header + 32); uint64_t length = sizeof(header) + nameLength + extraLength + commentLength; if (length > endOffset - offset || nameLength == 0 || nameLength > 4096) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP file contains an invalid filename."); if ((u16(header + 8) & 1) || (u16(header + 8) & 0x40)) return fail(error, VCCLibraryArchiveErrorUnsupported, @"Encrypted ZIP packages are not supported."); // Some readers normalize unsupported Unix entry kinds into regular // files. Reject those kinds from the original central attributes too. const mode_t storedType = (mode_t)((u32(header + 38) >> 16) & S_IFMT); if (storedType && storedType != S_IFREG && storedType != S_IFDIR) return fail(error, VCCLibraryArchiveErrorUnsupported, @"ZIP packages containing links or special files cannot be installed."); if (u16(header + 34) || u32(header + 20) == UINT32_MAX || u32(header + 24) == UINT32_MAX || u32(header + 42) == UINT32_MAX) return fail(error, VCCLibraryArchiveErrorUnsupported, @"Multi-volume and ZIP64 packages are not supported by this installer."); std::vector name((size_t)nameLength); if (!readAt(fd, offset + sizeof(header), name.data(), name.size())) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP filename is truncated."); for (auto byte : name) if (byte == 0 || byte == '\\' || byte == ':') return fail(error, VCCLibraryArchiveErrorUnsafePath, @"The ZIP file contains an unsafe filename."); // Ensure local and central names agree, before the reader chooses one. uint8_t local[30]; const uint64_t localOffset = u32(header + 42); if (localOffset > centralOffset || centralOffset - localOffset < sizeof(local) || !readAt(fd, localOffset, local, sizeof(local)) || u32(local) != 0x04034b50 || u16(local + 26) != nameLength) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP local header does not match its directory entry."); const uint64_t dataStart = localOffset + sizeof(local) + nameLength + u16(local + 28); if (dataStart > centralOffset || u32(header + 20) > centralOffset - dataStart || u16(local + 6) != u16(header + 8) || u16(local + 8) != u16(header + 10)) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP entry extends beyond its stored data."); std::vector localName((size_t)nameLength); if (!readAt(fd, localOffset + sizeof(local), localName.data(), localName.size()) || localName != name) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP filename differs between its headers."); offset += length; } if (offset != endOffset) return fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP directory length does not match its entries."); entryCount = count; return true; } NSArray *pathComponents(NSString *path, bool directory, NSError **error) { if (directory && [path hasSuffix:@"/"]) path = [path substringToIndex:path.length - 1]; if (!path.length || [path hasPrefix:@"/"] || [path rangeOfString:@"\\"].location != NSNotFound || [path rangeOfString:@":"].location != NSNotFound || [path rangeOfCharacterFromSet:NSCharacterSet.controlCharacterSet].location != NSNotFound) { fail(error, VCCLibraryArchiveErrorUnsafePath, @"The ZIP file contains an unsafe path."); return nil; } NSArray *parts = [path componentsSeparatedByString:@"/"]; if (parts.count > 64) { fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP directory nesting is too deep."); return nil; } for (NSString *part in parts) { if (!part.length || [part isEqualToString:@"."] || [part isEqualToString:@".."] || [part lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 255) { fail(error, VCCLibraryArchiveErrorUnsafePath, @"The ZIP file contains an unsafe or unsupported path component."); return nil; } } return parts; } NSString *collisionKey(NSString *path) { return [[path precomposedStringWithCanonicalMapping] stringByFoldingWithOptions:NSCaseInsensitiveSearch locale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]]; } bool writeAll(int fd, const void *bytes, size_t size) { size_t done = 0; while (done < size) { ssize_t n = write(fd, (const uint8_t *)bytes + done, size - done); if (n < 0 && errno == EINTR) continue; if (n <= 0) return false; done += (size_t)n; } return true; } } @implementation VCCLibraryArchive + (NSArray *)extractZIPAtURL:(NSURL *)archiveURL toNewDirectory:(NSURL *)destinationURL maximumExpandedBytes:(uint64_t)maximumExpandedBytes maximumEntries:(NSUInteger)maximumEntries shouldCancel:(BOOL (^)(void))shouldCancel error:(NSError **)error { if (error) *error = nil; if (!archiveURL.isFileURL || !destinationURL.isFileURL || !maximumEntries || !maximumExpandedBytes) { fail(error, VCCLibraryArchiveErrorInvalid, @"A local ZIP file, new local destination, and positive extraction limits are required."); return nil; } if (cancelled(shouldCancel, error)) return nil; Descriptor source(open(archiveURL.fileSystemRepresentation, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)); struct stat sourceInfo; if (source.fd < 0 || fstat(source.fd, &sourceInfo) != 0 || !S_ISREG(sourceInfo.st_mode) || sourceInfo.st_size < 0) { fail(error, VCCLibraryArchiveErrorIO, @"The downloaded ZIP is not a readable regular file."); return nil; } uint64_t expectedEntries = 0; if (!checkContainer(source.fd, (uint64_t)sourceInfo.st_size, maximumEntries, shouldCancel, expectedEntries, error)) return nil; if (mkdir(destinationURL.fileSystemRepresentation, 0700) != 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extraction destination already exists or could not be created."); return nil; } bool success = false; @try { Descriptor root(open(destinationURL.fileSystemRepresentation, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)); Reader reader; if (root.fd < 0 || !reader.value || archive_read_support_format_zip_seekable(reader.value) != archiveOK || archive_read_open_fd(reader.value, source.fd, 65536) != archiveOK) { fail(error, VCCLibraryArchiveErrorInvalid, @"The ZIP package could not be opened."); return nil; } std::map paths; std::set explicitEntries; NSMutableArray *files = [NSMutableArray array]; uint64_t total = 0, count = 0; struct archive_entry *entry = nullptr; int status; while ((status = archive_read_next_header(reader.value, &entry)) == archiveOK) { if (cancelled(shouldCancel, error)) return nil; if (++count > maximumEntries) { fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP file contains too many entries."); return nil; } mode_t type = archive_entry_filetype(entry); bool directory = type == S_IFDIR; if ((type != S_IFREG && !directory) || archive_entry_symlink(entry) || archive_entry_hardlink(entry)) { fail(error, VCCLibraryArchiveErrorUnsupported, @"ZIP packages containing links or special files cannot be installed."); return nil; } if (archive_entry_is_encrypted(entry)) { fail(error, VCCLibraryArchiveErrorUnsupported, @"Encrypted ZIP packages are not supported."); return nil; } const char *utf8 = archive_entry_pathname_utf8(entry); if (!utf8) utf8 = archive_entry_pathname(entry); NSString *path = utf8 ? [[NSString alloc] initWithUTF8String:utf8] : nil; if (!path) { fail(error, VCCLibraryArchiveErrorUnsupported, @"A ZIP filename cannot be represented safely on this Mac."); return nil; } NSArray *parts = pathComponents(path, directory, error); if (!parts) return nil; NSString *relative = [parts componentsJoinedByString:@"/"]; std::string fullKey(collisionKey(relative).UTF8String); if (!explicitEntries.insert(fullKey).second) { fail(error, VCCLibraryArchiveErrorCollision, @"The ZIP file contains duplicate or conflicting filenames."); return nil; } NSString *prefix = @""; for (NSString *part in parts) { prefix = prefix.length ? [prefix stringByAppendingFormat:@"/%@", part] : part; std::string key(collisionKey(prefix).UTF8String), original(prefix.UTF8String); auto prior = paths.find(key); if (prior != paths.end() && prior->second != original) { fail(error, VCCLibraryArchiveErrorCollision, @"ZIP paths differ only by letter case or Unicode spelling and would collide on a Mac."); return nil; } paths[key] = original; } int64_t declared = archive_entry_size(entry); if (!archive_entry_size_is_set(entry) || declared < 0 || (uint64_t)declared > maximumExpandedBytes - total || (directory && declared != 0)) { fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP package exceeds the expanded-size limit or has an invalid entry size."); return nil; } Descriptor parent(dup(root.fd)); if (parent.fd < 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extraction directory could not be opened."); return nil; } NSUInteger directories = directory ? parts.count : parts.count - 1; for (NSUInteger i = 0; i < directories; ++i) { const char *name = parts[i].fileSystemRepresentation; if (mkdirat(parent.fd, name, 0755) != 0 && errno != EEXIST) { fail(error, VCCLibraryArchiveErrorIO, @"A ZIP directory could not be created."); return nil; } int child = openat(parent.fd, name, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC); if (child < 0) { fail(error, VCCLibraryArchiveErrorCollision, @"A ZIP path conflicts with an existing file or link."); return nil; } parent.reset(child); if (fchmod(parent.fd, 0755) != 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extracted directory permissions could not be set."); return nil; } } Descriptor output; if (!directory) { output.reset(openat(parent.fd, parts.lastObject.fileSystemRepresentation, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600)); if (output.fd < 0) { fail(error, VCCLibraryArchiveErrorCollision, @"A ZIP output path already exists or could not be created."); return nil; } } uint8_t buffer[65536]; uint64_t written = 0; while (true) { if (cancelled(shouldCancel, error)) return nil; ssize_t bytes = archive_read_data(reader.value, buffer, sizeof(buffer)); if (bytes < 0) { fail(error, VCCLibraryArchiveErrorInvalid, archiveMessage(reader.value, @"A ZIP entry is damaged or uses unsupported compression")); return nil; } if (!bytes) break; if (directory || (uint64_t)bytes > maximumExpandedBytes - total || (uint64_t)bytes > (uint64_t)declared - written) { fail(error, VCCLibraryArchiveErrorLimit, @"The ZIP expanded data exceeds its declared size or the installation limit."); return nil; } if (!writeAll(output.fd, buffer, (size_t)bytes)) { fail(error, VCCLibraryArchiveErrorIO, @"The ZIP data could not be saved. Check available disk space."); return nil; } written += (uint64_t)bytes; total += (uint64_t)bytes; } if (written != (uint64_t)declared) { fail(error, VCCLibraryArchiveErrorInvalid, @"A ZIP entry is truncated."); return nil; } if (!directory) { if (fchmod(output.fd, 0644) != 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extracted file permissions could not be set."); return nil; } [files addObject:relative]; } } if (status != archiveEOF || count != expectedEntries || archive_read_close(reader.value) != archiveOK) { fail(error, VCCLibraryArchiveErrorInvalid, archiveMessage(reader.value, @"The ZIP package is incomplete or damaged")); return nil; } if (cancelled(shouldCancel, error)) return nil; if (fchmod(root.fd, 0755) != 0) { fail(error, VCCLibraryArchiveErrorIO, @"The extraction directory permissions could not be set."); return nil; } success = true; return files; } @finally { if (!success) [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:nil]; } } @end