Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / ZipArchive.swift
| 1 | import CArchive |
| 2 | import Darwin |
| 3 | import Foundation |
| 4 | |
| 5 | struct ZipArchive { |
| 6 | static let jsonLimit: Int64 = 100 * 1024 * 1024 |
| 7 | static let mediaLimit: Int64 = 4 * 1024 * 1024 * 1024 |
| 8 | static let totalLimit: Int64 = 64 * 1024 * 1024 * 1024 + jsonLimit |
| 9 | |
| 10 | static func write(to url: URL, files: [(path: String, file: URL, size: Int64)]) throws { |
| 11 | guard let archive = archive_write_new() else { throw WorkspaceError("Could not create the backup ZIP.") } |
| 12 | defer { _ = archive_write_free(archive) } |
| 13 | try check(archive_write_set_format_zip(archive), archive) |
| 14 | try check(archive_write_zip_set_compression_store(archive), archive) |
| 15 | let output = open(url.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600) |
| 16 | guard output >= 0 else { throw WorkspaceError("Couldn’t create a private backup file at this destination.") } |
| 17 | defer { close(output) } |
| 18 | try check(archive_write_open_fd(archive, output), archive) |
| 19 | for file in files { try writeEntry(file, archive: archive) } |
| 20 | try check(archive_write_close(archive), archive) |
| 21 | } |
| 22 | |
| 23 | static func extract(from url: URL, to directory: URL) throws -> [String: URL] { |
| 24 | guard let archive = archive_read_new() else { throw WorkspaceError("Could not open the backup ZIP.") } |
| 25 | defer { _ = archive_read_free(archive) } |
| 26 | try check(archive_read_support_format_zip(archive), archive) |
| 27 | try check(archive_read_open_filename(archive, url.path, 64 * 1024), archive) |
| 28 | var files: [String: URL] = [:] |
| 29 | var total: Int64 = 0 |
| 30 | while true { |
| 31 | var header: OpaquePointer? |
| 32 | let result = archive_read_next_header(archive, &header) |
| 33 | if result == 1 { return files } |
| 34 | try check(result, archive) |
| 35 | guard let header, let pathname = archive_entry_pathname(header), |
| 36 | let path = String(validatingCString: pathname), safe(path), files[path] == nil, |
| 37 | files.count < 10_001, archive_entry_filetype(header) == 0o100000, |
| 38 | archive_entry_is_encrypted(header) == 0, archive_entry_hardlink(header) == nil else { |
| 39 | throw WorkspaceError("The backup ZIP contains a duplicate or unsupported entry.") |
| 40 | } |
| 41 | let size = archive_entry_size(header) |
| 42 | let limit = path == "data.json" ? jsonLimit : mediaLimit |
| 43 | guard size >= 0, size <= limit, total <= totalLimit - size else { |
| 44 | throw WorkspaceError("A file in this backup exceeds the allowed size.") |
| 45 | } |
| 46 | let target = directory.appending(path: String(files.count)) |
| 47 | try readEntry(archive, to: target, size: size) |
| 48 | files[path] = target |
| 49 | total += size |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | static func safe(_ name: String) -> Bool { |
| 54 | name.range(of: #"\A(?:data\.json|media/images/[a-f0-9-]{36}\.(?:png|jpe?g|webp)|media/videos/[a-f0-9-]{36}\.(?:mp4|mov|webm))\z"#, |
| 55 | options: .regularExpression) != nil |
| 56 | } |
| 57 | |
| 58 | private static func writeEntry(_ item: (path: String, file: URL, size: Int64), archive: OpaquePointer) throws { |
| 59 | guard let entry = archive_entry_new() else { throw WorkspaceError("Could not add a file to the backup.") } |
| 60 | defer { archive_entry_free(entry) } |
| 61 | archive_entry_set_pathname(entry, item.path) |
| 62 | archive_entry_set_size(entry, item.size) |
| 63 | archive_entry_set_filetype(entry, 0o100000) |
| 64 | archive_entry_set_perm(entry, 0o600) |
| 65 | try check(archive_write_header(archive, entry), archive) |
| 66 | let input = try FileHandle(forReadingFrom: item.file) |
| 67 | defer { try? input.close() } |
| 68 | var total: Int64 = 0 |
| 69 | while let chunk = try input.read(upToCount: 1024 * 1024), !chunk.isEmpty { |
| 70 | total += Int64(chunk.count) |
| 71 | guard total <= item.size else { throw WorkspaceError("A file changed during backup.") } |
| 72 | let count = chunk.withUnsafeBytes { archive_write_data(archive, $0.baseAddress, $0.count) } |
| 73 | guard count == chunk.count else { throw failure(archive) } |
| 74 | } |
| 75 | guard total == item.size else { throw WorkspaceError("A file changed during backup.") } |
| 76 | } |
| 77 | |
| 78 | private static func readEntry(_ archive: OpaquePointer, to url: URL, size: Int64) throws { |
| 79 | guard FileManager.default.createFile(atPath: url.path, contents: nil, attributes: [.posixPermissions: 0o600]) else { |
| 80 | throw WorkspaceError("Could not stage a file from the backup.") |
| 81 | } |
| 82 | let output = try FileHandle(forWritingTo: url) |
| 83 | defer { try? output.close() } |
| 84 | var buffer = Data(count: 1024 * 1024) |
| 85 | var total: Int64 = 0 |
| 86 | while true { |
| 87 | let count = buffer.withUnsafeMutableBytes { archive_read_data(archive, $0.baseAddress, $0.count) } |
| 88 | if count == 0 { break } |
| 89 | guard count > 0 else { throw failure(archive) } |
| 90 | total += Int64(count) |
| 91 | guard total <= size else { throw WorkspaceError("A ZIP entry exceeded its declared size.") } |
| 92 | try output.write(contentsOf: buffer.prefix(count)) |
| 93 | } |
| 94 | guard total == size else { throw WorkspaceError("A ZIP entry is incomplete.") } |
| 95 | try output.close() |
| 96 | } |
| 97 | |
| 98 | private static func check(_ status: Int32, _ archive: OpaquePointer) throws { |
| 99 | guard status == 0 else { throw failure(archive) } |
| 100 | } |
| 101 | |
| 102 | private static func failure(_ archive: OpaquePointer) -> WorkspaceError { |
| 103 | WorkspaceError(archive_error_string(archive).map { String(cString: $0) } ?? "Could not process the backup ZIP.") |
| 104 | } |
| 105 | } |