| 1 | import AppKit |
| 2 | import CoreServices |
| 3 | |
| 4 | @_silgen_name("cage_file_has_writer") private func cageFileHasWriter(_ pid: Int32, _ path: UnsafePointer<CChar>) -> Int32 |
| 5 | |
| 6 | @MainActor |
| 7 | final class MacDesktopDownloads { |
| 8 | static let shared = MacDesktopDownloads(directory: FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support/dev.cage.DesktopDownloads", isDirectory: true)) |
| 9 | private struct Record: Codable { |
| 10 | let id: String |
| 11 | let name: String |
| 12 | var state = "downloading" |
| 13 | var error = "" |
| 14 | var openError: String? |
| 15 | var acknowledged: Bool? |
| 16 | var device: UInt64? |
| 17 | var inode: UInt64? |
| 18 | var size: Int64 = 0 |
| 19 | var modified: Int64 = 0 |
| 20 | var started = Date() |
| 21 | } |
| 22 | private struct Transfer { |
| 23 | let fd: Int32 |
| 24 | let record: Record |
| 25 | let epoch: UInt64 |
| 26 | var sequence = 0 |
| 27 | var offset: Int64 = 0 |
| 28 | var used = Date() |
| 29 | } |
| 30 | private var records: [Record] = [] |
| 31 | private var transfers: [String: Transfer] = [:] |
| 32 | private var watches: [String: MacDownloadWatch] = [:] |
| 33 | private var root: URL? |
| 34 | private let baseDirectory: URL |
| 35 | private var transferTimer: Timer? |
| 36 | private let timestamp = ISO8601DateFormatter() |
| 37 | private var openMetadata: Data? |
| 38 | private var metadataBound = Set<String>() |
| 39 | |
| 40 | init(directory: URL) { baseDirectory = directory } |
| 41 | deinit { |
| 42 | for watch in watches.values { watch.stop() } |
| 43 | for transfer in transfers.values { close(transfer.fd) } |
| 44 | transferTimer?.invalidate() |
| 45 | } |
| 46 | |
| 47 | nonisolated static func validName(_ name: String) -> Bool { |
| 48 | !name.isEmpty && name.utf8.count <= 255 && name != "." && name != ".." && |
| 49 | name.rangeOfCharacter(from: CharacterSet(charactersIn: "/\\").union(.controlCharacters)) == nil |
| 50 | } |
| 51 | |
| 52 | private func directory() throws -> URL { |
| 53 | if let root { return root } |
| 54 | try FileManager.default.createDirectory(at: baseDirectory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) |
| 55 | var info = stat() |
| 56 | guard lstat(baseDirectory.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR, info.st_uid == getuid(), |
| 57 | info.st_mode & 0o022 == 0, let canonical = realpath(baseDirectory.path, nil) else { throw Failure(8, "desktop_download_directory_invalid") } |
| 58 | let root = URL(fileURLWithPath: String(cString: canonical), isDirectory: true) |
| 59 | free(canonical) |
| 60 | let manifest = root.appendingPathComponent("downloads.json") |
| 61 | if FileManager.default.fileExists(atPath: manifest.path) { |
| 62 | var stored = stat() |
| 63 | guard lstat(manifest.path, &stored) == 0, stored.st_mode & S_IFMT == S_IFREG, stored.st_uid == getuid(), stored.st_size <= 1 << 20 else { |
| 64 | throw Failure(8, "desktop_download_catalog_invalid") |
| 65 | } |
| 66 | let data = try Data(contentsOf: manifest, options: .mappedIfSafe) |
| 67 | guard data.count <= 1 << 20 else { throw Failure(8, "desktop_download_catalog_invalid") } |
| 68 | let saved = try JSONDecoder().decode([Record].self, from: data) |
| 69 | guard saved.count <= 100 else { throw Failure(8, "desktop_download_catalog_invalid") } |
| 70 | records = saved.filter { UUID(uuidString: $0.id) != nil && Self.validName($0.name) } |
| 71 | for index in records.indices where records[index].state == "downloading" { |
| 72 | records[index].state = "failed" |
| 73 | records[index].error = "保存过程被中断,请从 Claude Desktop 重新下载。" |
| 74 | } |
| 75 | } |
| 76 | self.root = root |
| 77 | return root |
| 78 | } |
| 79 | private func source(_ record: Record) throws -> URL { try directory().appendingPathComponent(record.id, isDirectory: true).appendingPathComponent(record.name) } |
| 80 | private func persist() throws { |
| 81 | let path = try directory().appendingPathComponent("downloads.json") |
| 82 | try JSONEncoder().encode(records).write(to: path, options: .atomic) |
| 83 | try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path.path) |
| 84 | } |
| 85 | private func openSource(_ record: Record) throws -> (Int32, stat) { |
| 86 | let path = try source(record).path |
| 87 | let fd = open(path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK) |
| 88 | guard fd >= 0 else { throw Failure(8, "desktop_download_unavailable") } |
| 89 | var info = stat(), actual = [CChar](repeating: 0, count: Int(MAXPATHLEN)) |
| 90 | guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_size <= 2 * 1024 * 1024 * 1024, |
| 91 | fcntl(fd, F_GETPATH, &actual) == 0, String(cString: actual) == path else { |
| 92 | close(fd); throw Failure(8, "desktop_download_file_invalid") |
| 93 | } |
| 94 | return (fd, info) |
| 95 | } |
| 96 | private func modified(_ info: stat) -> Int64 { Int64(info.st_mtimespec.tv_sec) * 1_000_000_000 + Int64(info.st_mtimespec.tv_nsec) } |
| 97 | |
| 98 | private func removeSource(_ record: Record) throws { |
| 99 | let path = try source(record) |
| 100 | let folder = path.deletingLastPathComponent().path |
| 101 | let parent = open(folder, O_RDONLY | O_DIRECTORY | O_NOFOLLOW) |
| 102 | if parent < 0 && errno == ENOENT { return } |
| 103 | guard parent >= 0 else { throw Failure(8, "desktop_download_cleanup_failed") } |
| 104 | defer { close(parent) } |
| 105 | var directoryInfo = stat(), actual = [CChar](repeating: 0, count: Int(MAXPATHLEN)) |
| 106 | guard fstat(parent, &directoryInfo) == 0, directoryInfo.st_uid == getuid(), |
| 107 | fcntl(parent, F_GETPATH, &actual) == 0, String(cString: actual) == folder else { throw Failure(8, "desktop_download_directory_invalid") } |
| 108 | var info = stat() |
| 109 | let found = fstatat(parent, record.name, &info, AT_SYMLINK_NOFOLLOW) |
| 110 | if found != 0 && errno != ENOENT { throw Failure(8, "desktop_download_cleanup_failed") } |
| 111 | if found == 0 { |
| 112 | guard record.state == "saved", info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_size == record.size, |
| 113 | modified(info) == record.modified, record.device == UInt64(UInt32(bitPattern: info.st_dev)), |
| 114 | record.inode == UInt64(info.st_ino) else { throw Failure(8, "desktop_download_changed") } |
| 115 | guard unlinkat(parent, record.name, 0) == 0 else { throw Failure(8, "desktop_download_cleanup_failed") } |
| 116 | } |
| 117 | |
| 118 | |
| 119 | var current = stat() |
| 120 | guard lstat(folder, ¤t) == 0, current.st_dev == directoryInfo.st_dev, current.st_ino == directoryInfo.st_ino else { throw Failure(8, "desktop_download_directory_invalid") } |
| 121 | let removed = rmdir(folder) |
| 122 | if record.state == "failed" && removed != 0 { throw Failure(8, "desktop_download_cleanup_failed") } |
| 123 | } |
| 124 | |
| 125 | private func makeRoom() throws { |
| 126 | expireTransfers() |
| 127 | guard records.count >= 100 else { return } |
| 128 | for record in records { |
| 129 | let eligible = (record.state == "saved" && record.acknowledged == true) || (record.state == "failed" && watches[record.id] == nil) |
| 130 | guard eligible, !transfers.values.contains(where: { $0.record.id == record.id }) else { continue } |
| 131 | do { |
| 132 | try removeSource(record) |
| 133 | records.removeAll { $0.id == record.id } |
| 134 | metadataBound.remove(record.id) |
| 135 | return |
| 136 | } catch { } |
| 137 | } |
| 138 | throw Failure(8, "desktop_download_limit") |
| 139 | } |
| 140 | |
| 141 | private func bindOpenMetadata(_ metadata: Data, fd: Int32, info: stat) throws { |
| 142 | let name = "com.apple.LaunchServices.OpenWith" |
| 143 | guard !metadata.isEmpty, metadata.count <= 1 << 20 else { throw Failure(8, "desktop_download_open_metadata_failed") } |
| 144 | if fgetxattr(fd, name, nil, 0, 0, 0) == metadata.count { |
| 145 | var current = Data(count: metadata.count) |
| 146 | let count = current.withUnsafeMutableBytes { fgetxattr(fd, name, $0.baseAddress, $0.count, 0, 0) } |
| 147 | if count == metadata.count && current == metadata { return } |
| 148 | } |
| 149 | let written = metadata.withUnsafeBytes { fsetxattr(fd, name, $0.baseAddress, $0.count, 0, 0) } |
| 150 | var current = Data(count: metadata.count), after = stat() |
| 151 | let count = current.withUnsafeMutableBytes { fgetxattr(fd, name, $0.baseAddress, $0.count, 0, 0) } |
| 152 | guard written == 0, count == metadata.count, current == metadata else { throw Failure(8, "desktop_download_open_metadata_failed") } |
| 153 | guard fstat(fd, &after) == 0, after.st_dev == info.st_dev, after.st_ino == info.st_ino, |
| 154 | after.st_size == info.st_size, modified(after) == modified(info) else { throw Failure(8, "desktop_download_changed") } |
| 155 | } |
| 156 | |
| 157 | private func refreshOpenMetadata() throws { |
| 158 | guard let metadata = MacNativeOpen.shared.openWithMetadata else { return } |
| 159 | if openMetadata != metadata { openMetadata = metadata; metadataBound.removeAll() } |
| 160 | var changed = false |
| 161 | for index in records.indices where records[index].state == "saved" && !metadataBound.contains(records[index].id) { |
| 162 | let previous = records[index].openError |
| 163 | do { |
| 164 | let (fd, info) = try openSource(records[index]) |
| 165 | defer { close(fd) } |
| 166 | guard info.st_size == records[index].size, modified(info) == records[index].modified else { throw Failure(8, "desktop_download_changed") } |
| 167 | try bindOpenMetadata(metadata, fd: fd, info: info) |
| 168 | metadataBound.insert(records[index].id) |
| 169 | records[index].openError = nil |
| 170 | } catch { |
| 171 | records[index].openError = "文件打开关联未能完成,请在 Cage 下载列表中打开文件。" |
| 172 | } |
| 173 | changed = changed || previous != records[index].openError |
| 174 | } |
| 175 | if changed { try persist() } |
| 176 | } |
| 177 | |
| 178 | private func expireTransfers() { |
| 179 | let epoch = try? MacGUISession.shared.validate() |
| 180 | for (key, transfer) in transfers where epoch != transfer.epoch || Date().timeIntervalSince(transfer.used) > 120 { |
| 181 | close(transfer.fd); transfers.removeValue(forKey: key) |
| 182 | } |
| 183 | if transfers.isEmpty { transferTimer?.invalidate(); transferTimer = nil } |
| 184 | } |
| 185 | |
| 186 | func reserve(name: String, pid: Int32, submit: (String) async throws -> Void) async throws { |
| 187 | _ = try directory() |
| 188 | guard Self.validName(name), records.filter({ $0.state == "downloading" }).count < 12 else { throw Failure(8, "desktop_download_limit") } |
| 189 | try makeRoom() |
| 190 | let record = Record(id: UUID().uuidString.lowercased(), name: name) |
| 191 | let path = try source(record) |
| 192 | try FileManager.default.createDirectory(at: path.deletingLastPathComponent(), withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) |
| 193 | let watcher = try MacDownloadWatch(directory: path.deletingLastPathComponent().path, file: path.path) { [weak self] valid in |
| 194 | Task { @MainActor in |
| 195 | if valid { await self?.complete(record.id, pid: pid) } |
| 196 | else { self?.fail(record.id, message: "保存通知已中断,请从 Claude Desktop 重新下载。") } |
| 197 | } |
| 198 | } |
| 199 | records.append(record); watches[record.id] = watcher |
| 200 | do { try persist(); try await submit(path.path) } |
| 201 | catch { fail(record.id, message: "客机保存窗口未接收文件位置,请重新下载。"); throw error } |
| 202 | watcher.expiry = Task { @MainActor [weak self] in |
| 203 | try? await Task.sleep(nanoseconds: 1800 * 1_000_000_000) |
| 204 | if self?.records.first(where: { $0.id == record.id })?.state == "downloading" { |
| 205 | self?.fail(record.id, message: "未能确认文件保存完成,请从 Claude Desktop 重新下载。") |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | private func fail(_ id: String, message: String) { |
| 210 | watches.removeValue(forKey: id)?.stop() |
| 211 | if let index = records.firstIndex(where: { $0.id == id }) { |
| 212 | records[index].state = "failed"; records[index].error = message |
| 213 | try? persist() |
| 214 | } |
| 215 | } |
| 216 | private func complete(_ id: String, pid: Int32) async { |
| 217 | guard let record = records.first(where: { $0.id == id && $0.state == "downloading" }), |
| 218 | let watch = watches[id], !watch.completing else { return } |
| 219 | watch.completing = true |
| 220 | defer { watch.completing = false } |
| 221 | while Date().timeIntervalSince(record.started) < 1800 { |
| 222 | guard records.first(where: { $0.id == id })?.state == "downloading" else { return } |
| 223 | do { |
| 224 | let path = try source(record).path |
| 225 | let writing = path.withCString { cageFileHasWriter(pid, $0) } |
| 226 | if writing == 0 && !FileManager.default.fileExists(atPath: path + ".crdownload") { |
| 227 | let (fd, info) = try openSource(record) |
| 228 | defer { close(fd) } |
| 229 | guard let index = records.firstIndex(where: { $0.id == id }) else { return } |
| 230 | records[index].size = info.st_size; records[index].modified = modified(info); records[index].state = "saved" |
| 231 | records[index].device = UInt64(UInt32(bitPattern: info.st_dev)); records[index].inode = UInt64(info.st_ino) |
| 232 | if let metadata = MacNativeOpen.shared.openWithMetadata { |
| 233 | if openMetadata != metadata { openMetadata = metadata; metadataBound.removeAll() } |
| 234 | do { try bindOpenMetadata(metadata, fd: fd, info: info); metadataBound.insert(id) } |
| 235 | catch { records[index].openError = "文件打开关联未能完成,请在 Cage 下载列表中打开文件。" } |
| 236 | } |
| 237 | try persist(); watches.removeValue(forKey: id)?.stop(); return |
| 238 | } |
| 239 | } catch { } |
| 240 | try? await Task.sleep(nanoseconds: 250_000_000) |
| 241 | } |
| 242 | fail(id, message: "未能确认文件保存完成,请从 Claude Desktop 重新下载。") |
| 243 | } |
| 244 | func snapshot() throws -> [[String: Any]] { |
| 245 | _ = try directory() |
| 246 | try refreshOpenMetadata() |
| 247 | return records.suffix(100).reversed().map { record in |
| 248 | ["id": record.id, "name": record.name, "target": "desktop", "state": record.state, |
| 249 | "acknowledged": record.acknowledged ?? false, |
| 250 | "receivedBytes": record.size, "totalBytes": record.size, "retryable": false, |
| 251 | "error": record.error, "openError": record.openError ?? "", "startedAt": timestamp.string(from: record.started)] |
| 252 | } |
| 253 | } |
| 254 | func find(path: String) throws -> (id: String, directory: Bool)? { |
| 255 | _ = try directory() |
| 256 | for record in records { |
| 257 | let source = try source(record) |
| 258 | if source.path == path { return (record.id, false) } |
| 259 | if source.deletingLastPathComponent().path == path { return (record.id, true) } |
| 260 | } |
| 261 | return nil |
| 262 | } |
| 263 | func read(_ input: Request) throws -> [String: Any] { |
| 264 | let epoch = try MacGUISession.shared.validate() |
| 265 | _ = try directory() |
| 266 | for (key, transfer) in transfers where transfer.epoch != epoch || Date().timeIntervalSince(transfer.used) > 120 { |
| 267 | close(transfer.fd); transfers.removeValue(forKey: key) |
| 268 | } |
| 269 | if input.action == "files-download-ack" { |
| 270 | guard let ids = input.ids, ids.count <= 100, ids.allSatisfy({ UUID(uuidString: $0) != nil }) else { throw Failure(8, "desktop_download_ack_invalid") } |
| 271 | let previous = records |
| 272 | var changed = false |
| 273 | do { |
| 274 | for index in records.indices where ids.contains(records[index].id) && records[index].state == "saved" && records[index].acknowledged != true { |
| 275 | if records[index].device == nil || records[index].inode == nil { |
| 276 | if let (fd, info) = try? openSource(records[index]) { |
| 277 | defer { close(fd) } |
| 278 | if info.st_size == records[index].size && modified(info) == records[index].modified { |
| 279 | records[index].device = UInt64(UInt32(bitPattern: info.st_dev)); records[index].inode = UInt64(info.st_ino) |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | records[index].acknowledged = true |
| 284 | changed = true |
| 285 | } |
| 286 | if changed { try persist() } |
| 287 | } catch { records = previous; throw error } |
| 288 | return ["ok": true] |
| 289 | } |
| 290 | if input.action == "files-download-retry" { |
| 291 | guard let record = records.first(where: { $0.id == input.id }), record.state == "saved" else { throw Failure(8, "desktop_download_incomplete") } |
| 292 | let (fd, info) = try openSource(record) |
| 293 | defer { close(fd) } |
| 294 | guard info.st_size == record.size, modified(info) == record.modified else { throw Failure(8, "desktop_download_changed") } |
| 295 | return ["ok": true] |
| 296 | } |
| 297 | if input.action == "files-download-open" { |
| 298 | guard let record = records.first(where: { $0.id == input.id && $0.state == "saved" }), transfers.count < 12 else { throw Failure(8, "desktop_download_unavailable") } |
| 299 | let (fd, info) = try openSource(record) |
| 300 | guard info.st_size == record.size, modified(info) == record.modified else { close(fd); throw Failure(8, "desktop_download_changed") } |
| 301 | let key = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() |
| 302 | transfers[key] = Transfer(fd: fd, record: record, epoch: epoch) |
| 303 | if transferTimer == nil { |
| 304 | transferTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] timer in |
| 305 | Task { @MainActor in |
| 306 | guard let self else { timer.invalidate(); return } |
| 307 | self.expireTransfers() |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | return ["transfer": key, "size": record.size, "name": record.name] |
| 312 | } |
| 313 | let key = input.transfer ?? "" |
| 314 | if input.action == "files-download-close" { |
| 315 | if let transfer = transfers.removeValue(forKey: key) { close(transfer.fd) } |
| 316 | return ["ok": true] |
| 317 | } |
| 318 | guard input.action == "files-download-read", var transfer = transfers[key], transfer.sequence == input.sequence else { throw Failure(8, "desktop_download_transfer_invalid") } |
| 319 | var info = stat() |
| 320 | guard fstat(transfer.fd, &info) == 0, info.st_size == transfer.record.size, modified(info) == transfer.record.modified else { |
| 321 | close(transfer.fd); transfers.removeValue(forKey: key); throw Failure(8, "desktop_download_changed") |
| 322 | } |
| 323 | var data = Data(count: 64 << 10) |
| 324 | let count = data.withUnsafeMutableBytes { Darwin.read(transfer.fd, $0.baseAddress, $0.count) } |
| 325 | guard count >= 0 else { throw Failure(8, "desktop_download_read_failed") } |
| 326 | guard fstat(transfer.fd, &info) == 0, info.st_size == transfer.record.size, modified(info) == transfer.record.modified else { |
| 327 | close(transfer.fd); transfers.removeValue(forKey: key); throw Failure(8, "desktop_download_changed") |
| 328 | } |
| 329 | data.count = count; transfer.offset += Int64(count); transfer.sequence += 1; transfer.used = Date() |
| 330 | let eof = transfer.offset == transfer.record.size |
| 331 | if eof { close(transfer.fd); transfers.removeValue(forKey: key) } else { transfers[key] = transfer } |
| 332 | return ["data": data.base64EncodedString(), "sequence": transfer.sequence, "eof": eof] |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | private final class MacDownloadWatch { |
| 337 | private var stream: FSEventStreamRef? |
| 338 | private let file: String |
| 339 | private let changed: (Bool) -> Void |
| 340 | var completing = false |
| 341 | var expiry: Task<Void, Never>? |
| 342 | init(directory: String, file: String, changed: @escaping (Bool) -> Void) throws { |
| 343 | self.file = file; self.changed = changed |
| 344 | var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(self).toOpaque(), retain: { raw in |
| 345 | guard let raw else { return nil } |
| 346 | _ = Unmanaged<MacDownloadWatch>.fromOpaque(raw).retain() |
| 347 | return raw |
| 348 | }, release: { raw in |
| 349 | if let raw { Unmanaged<MacDownloadWatch>.fromOpaque(raw).release() } |
| 350 | }, copyDescription: nil) |
| 351 | stream = FSEventStreamCreate(nil, { _, raw, count, paths, flags, _ in |
| 352 | guard let raw else { return } |
| 353 | let watcher = Unmanaged<MacDownloadWatch>.fromOpaque(raw).takeUnretainedValue() |
| 354 | let names = Unmanaged<NSArray>.fromOpaque(paths).takeUnretainedValue() as? [String] ?? [] |
| 355 | let failure = FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs | kFSEventStreamEventFlagUserDropped | kFSEventStreamEventFlagKernelDropped | kFSEventStreamEventFlagRootChanged) |
| 356 | for index in 0..<count where flags[index] & failure != 0 { watcher.changed(false); return } |
| 357 | for index in 0..<min(count, names.count) where names[index] == watcher.file { |
| 358 | if flags[index] & FSEventStreamEventFlags(kFSEventStreamEventFlagItemModified | kFSEventStreamEventFlagItemRenamed) != 0 { watcher.changed(true) } |
| 359 | } |
| 360 | }, &context, [directory] as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 0.1, |
| 361 | FSEventStreamCreateFlags(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagWatchRoot)) |
| 362 | guard let stream else { throw Failure(8, "desktop_download_watch_failed") } |
| 363 | FSEventStreamSetDispatchQueue(stream, DispatchQueue.main) |
| 364 | guard FSEventStreamStart(stream) else { stop(); throw Failure(8, "desktop_download_watch_failed") } |
| 365 | } |
| 366 | func stop() { |
| 367 | expiry?.cancel(); expiry = nil |
| 368 | guard let stream else { return } |
| 369 | self.stream = nil |
| 370 | FSEventStreamStop(stream); FSEventStreamInvalidate(stream); FSEventStreamRelease(stream) |
| 371 | } |
| 372 | deinit { stop() } |
| 373 | } |