PulseCanvas / app / Sources / PulseCanvas / UserBackupZIP.swift
| 1 | import Foundation |
| 2 | import ZIPFoundation |
| 3 | |
| 4 | extension UserBackup { |
| 5 | /// ZIP64-capable storage avoids base64-encoding an entire music folder in memory. |
| 6 | /// manifest.json is versioned structured metadata; every file has size and SHA-256. |
| 7 | static func writeZIP(_ archive: Archive, to url: URL, deterministic: Bool = false) throws { |
| 8 | try validate(archive) |
| 9 | var completed = false |
| 10 | defer { if !completed { try? FileManager.default.removeItem(at: url) } } |
| 11 | let zip = try ZIPFoundation.Archive(url: url, accessMode: .create) |
| 12 | let date = deterministic ? Calendar(identifier: .gregorian).date(from: DateComponents(year: 2000, month: 1, day: 1))! : Date() |
| 13 | for file in archive.files { |
| 14 | try zip.addEntry(with: file.path, type: .file, uncompressedSize: Int64(file.data.count), modificationDate: date) { offset, size in |
| 15 | file.data.subdata(in: Int(offset)..<Int(offset) + size) |
| 16 | } |
| 17 | } |
| 18 | var metadata = archive |
| 19 | for index in metadata.files.indices { metadata.files[index].data = Data() } |
| 20 | let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] |
| 21 | let manifest = try encoder.encode(metadata) |
| 22 | try zip.addEntry(with: "manifest.json", type: .file, uncompressedSize: Int64(manifest.count), modificationDate: date) { offset, size in |
| 23 | manifest.subdata(in: Int(offset)..<Int(offset) + size) |
| 24 | } |
| 25 | completed = true |
| 26 | } |
| 27 | |
| 28 | static func readZIP(_ url: URL, workspace: URL) throws -> Archive { |
| 29 | let zip = try ZIPFoundation.Archive(url: url, accessMode: .read) |
| 30 | var entries: [Entry] = [] |
| 31 | for entry in zip { |
| 32 | guard entries.count < 20_001 else { throw fail(String(localized: "Too many backup files.")) } |
| 33 | entries.append(entry) |
| 34 | } |
| 35 | guard entries.count <= 20_001, Set(entries.map { $0.path.lowercased() }).count == entries.count, |
| 36 | entries.allSatisfy({ $0.type == .file && !$0.isCompressed && $0.compressedSize == $0.uncompressedSize |
| 37 | && ($0.path == "manifest.json" || safePath($0.path)) }), |
| 38 | let manifestEntry = zip["manifest.json"], manifestEntry.uncompressedSize < 32_000_000 else { throw fail(String(localized: "Invalid backup ZIP contents.")) } |
| 39 | var manifest = Data() |
| 40 | let crc = try zip.extract(manifestEntry) { chunk in manifest.append(chunk) } |
| 41 | guard crc == manifestEntry.checksum else { throw fail(String(localized: "Damaged backup manifest.")) } |
| 42 | var archive = try JSONDecoder().decode(Archive.self, from: manifest) |
| 43 | guard archive.format == format, archive.version == 1, archive.files.count + 1 == entries.count, |
| 44 | Set(archive.files.map { $0.path.lowercased() }).count == archive.files.count else { throw fail(String(localized: "Choose a supported PulseCanvas backup ZIP.")) } |
| 45 | var total = 0 |
| 46 | for file in archive.files { |
| 47 | guard safePath(file.path), file.data.isEmpty, file.byteCount >= 0, file.byteCount <= maximumSourceBytes, |
| 48 | let entry = zip[file.path], entry.uncompressedSize == UInt64(file.byteCount) else { throw fail(String(localized: "A backup file is missing or has an invalid size.")) } |
| 49 | total += file.byteCount |
| 50 | guard total <= maximumSourceBytes else { throw fail(String(localized: "This backup exceeds 100 GB.")) } |
| 51 | } |
| 52 | // Check parent/file conflicts before creating any paths. Only our own fresh |
| 53 | // private workspace is used; never extract directly into the user's data. |
| 54 | let paths = Set(archive.files.map { $0.path.lowercased() }) |
| 55 | for path in paths { |
| 56 | var parts = path.split(separator: "/"); parts.removeLast() |
| 57 | while parts.count > 1 { |
| 58 | guard !paths.contains(parts.joined(separator: "/")) else { throw fail(String(localized: "Conflicting backup paths.")) } |
| 59 | parts.removeLast() |
| 60 | } |
| 61 | } |
| 62 | guard !FileManager.default.fileExists(atPath: workspace.path) else { throw fail(String(localized: "The backup workspace is already in use.")) } |
| 63 | try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) |
| 64 | var complete = false |
| 65 | defer { if !complete { try? FileManager.default.removeItem(at: workspace) } } |
| 66 | for index in archive.files.indices { |
| 67 | let file = archive.files[index], destination = workspace.appendingPathComponent(file.path) |
| 68 | try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 69 | let entry = zip[file.path]! |
| 70 | let checksum = try zip.extract(entry, to: destination) |
| 71 | guard checksum == entry.checksum else { throw fail(String(localized: "A backup file is damaged.")) } |
| 72 | archive.files[index].data = try Data(contentsOf: destination, options: .alwaysMapped) |
| 73 | } |
| 74 | try validate(archive) |
| 75 | complete = true |
| 76 | return archive |
| 77 | } |
| 78 | } |