import Foundation import Network private struct APIVersion: Encodable { let name: String let url: String let supportStatus: String } private struct VersionList: Encodable { let errorCode = 0 let serverName = "EzWebServer" let currentVersionName = "3.0.6" let currentStageVersionName = "0" let versions: [APIVersion] } private struct VersionMatch: Encodable { let errorCode = 0 let serverName = "EzWebServer" let clientVersion: APIVersion let serverVersion: APIVersion } final class LocalServer { private let listener: NWListener private let queue = DispatchQueue(label: "ezserver.loopback") private let maxHeaderSize = 8192 private let library: LibraryAPI private var connections: [ObjectIdentifier: NWConnection] = [:] init(port: UInt16, library: LibraryAPI) throws { self.library = library let parameters = NWParameters.tcp parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: NWEndpoint.Port(rawValue: port)!) listener = try NWListener(using: parameters) } func start(onStateChange: @escaping (Result) -> Void) { listener.stateUpdateHandler = { [weak self] state in switch state { case .ready: if let port = self?.listener.port { onStateChange(.success(port.rawValue)) } case let .failed(error): onStateChange(.failure(error)) default: break } } listener.newConnectionHandler = { [weak self] connection in guard let self, self.connections.count < 64 else { connection.cancel(); return } let id = ObjectIdentifier(connection) self.connections[id] = connection connection.stateUpdateHandler = { [weak self] state in switch state { case .cancelled, .failed: self?.connections.removeValue(forKey: id) default: break } } connection.start(queue: self.queue) let timeout = DispatchWorkItem { [weak connection] in connection?.cancel() } self.queue.asyncAfter(deadline: .now() + 5, execute: timeout) self.receive(on: connection, buffer: Data(), timeout: timeout) } listener.start(queue: queue) } func stop() { queue.async { [self] in listener.cancel() connections.values.forEach { $0.cancel() } connections.removeAll() } } private func receive(on connection: NWConnection, buffer: Data, timeout: DispatchWorkItem) { connection.receive(minimumIncompleteLength: 1, maximumLength: maxHeaderSize - buffer.count) { [weak self] data, _, complete, failure in guard let self, failure == nil else { connection.cancel(); return } var request = buffer if let data { request.append(data) } if let boundary = request.range(of: Data("\r\n\r\n".utf8)) { timeout.cancel() self.handle(request.prefix(upTo: boundary.lowerBound), initialBody: request.suffix(from: boundary.upperBound), on: connection) } else if request.count >= self.maxHeaderSize { self.send(["error": "Request header too large"], status: "431 Request Header Fields Too Large", on: connection) } else if complete { connection.cancel() } else { self.receive(on: connection, buffer: request, timeout: timeout) } } } private func handle(_ request: Data, initialBody: Data, on connection: NWConnection) { let lines = String(decoding: request, as: UTF8.self).components(separatedBy: "\r\n") let requestLine = lines[0].split(separator: " ", omittingEmptySubsequences: false) var headers: [String: [String]] = [:] for line in lines.dropFirst() { let parts = line.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false) guard parts.count == 2 else { send(["error": "Invalid header"], status: "400 Bad Request", on: connection) return } headers[parts[0].lowercased(), default: []].append(parts[1].trimmingCharacters(in: .whitespaces)) } let hosts = headers["host"] ?? [] guard requestLine.count == 3, ["HTTP/1.0", "HTTP/1.1"].contains(requestLine[2]), requestLine[1].hasPrefix("/"), !requestLine[1].hasPrefix("//"), let target = URLComponents(string: String(requestLine[1])), hosts.count == 1, hosts[0].range(of: #"\A(?:127\.0\.0\.1|localhost)(?::[0-9]{1,5})?\z"#, options: [.regularExpression, .caseInsensitive]) != nil else { send(["error": "Invalid request or host"], status: "400 Bad Request", on: connection) return } let method = String(requestLine[0]) let segments = target.path.split(separator: "/").map(String.init) let authorization = headers["authorization"] ?? [] let bearer = authorization.count == 1 ? authorization[0] : nil if segments.starts(with: ["mac", "v1", "patients"]) { let path = Array(segments.dropFirst(3)) if method == "GET" { serveLibrary(path: path, query: target.queryItems ?? [], authorization: bearer, on: connection) } else { mutateLibrary(method: method, path: path, query: target.queryItems ?? [], authorization: bearer, headers: headers, initialBody: initialBody, on: connection) } return } guard method == "GET" else { send(["error": "Only GET is supported"], status: "405 Method Not Allowed", extraHeaders: "Allow: GET\r\n", on: connection) return } let apiURL = "http://\(hosts[0])/api/v1" let versions = [ "1.0.0", "1.0.1", "1.1.0", "1.2.0", "1.3.0", "1.3.1", "1.3.2", "2.0.0", "3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6" ].map { APIVersion(name: $0, url: apiURL, supportStatus: "supported") } let listing = VersionList(versions: versions) let path = target.path.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "/")) switch path { case "", "health": send(["service": "EzServer Mac", "status": "ok"], on: connection) case "api/v1/auth/ping", "api/index.php/v1/auth/ping": send(LegacyPing(), on: connection) case "api/v1/fs/sysinfofordiskspace", "api/index.php/v1/fs/sysinfofordiskspace": guard library.isAuthorized(bearer) else { sendUnauthorized(on: connection); return } let values = try? library.store.directory.resourceValues(forKeys: [ .volumeTotalCapacityKey, .volumeAvailableCapacityKey ]) guard let total = values?.volumeTotalCapacity, let free = values?.volumeAvailableCapacity else { send(["error": "Could not read disk capacity"], status: "503 Service Unavailable", on: connection) return } send(["errorCode": 0, "nTotalSpace": total, "nFreeSpace": free], on: connection) case "api/v1/info/versions", "api/index.php/v1/info/versions": send(listing, on: connection) case "api/v1/info/versionsbyname", "api/index.php/v1/info/versionsbyname": let name = target.queryItems?.first(where: { $0.name == "name" })?.value ?? "" let match = versions.first { $0.name == name } ?? APIVersion(name: name, url: "", supportStatus: "unknown") send(VersionMatch(clientVersion: match, serverVersion: versions[versions.count - 1]), on: connection) default: send(["error": "Route is unavailable in the macOS preview"], status: "404 Not Found", on: connection) } } private func serveLibrary(path: [String], query: [URLQueryItem], authorization: String?, on connection: NWConnection) { switch library.response(path: path, query: query, authorization: authorization) { case let .listing(listing): send(listing, on: connection) case let .patient(patient): send(patient, on: connection) case let .file(file): let safeName = file.filename.addingPercentEncoding(withAllowedCharacters: CharacterSet( charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" )) ?? "image" let headers = responseHeaders(status: "200 OK", type: file.contentType, bytes: file.bytes, extra: "Content-Disposition: attachment; filename*=UTF-8''\(safeName)\r\n") connection.send(content: headers, completion: .contentProcessed { [weak self] error in guard let self, error == nil else { connection.cancel(); return } self.stream(file.handle, remaining: file.bytes, on: connection) }) case .unauthorized: sendUnauthorized(on: connection) case .invalidRequest: send(["error": "Invalid limit, offset or search query"], status: "400 Bad Request", on: connection) case .notFound: send(["error": "Patient or image not found"], status: "404 Not Found", on: connection) case .unavailable: send(["error": "Could not read patient library"], status: "503 Service Unavailable", on: connection) } } private struct LegacyPing: Encodable { let errorCode = 0 let message = "Pong" } private struct PatientInput: Decodable { let name: String let chartNumber: String } private func sendUnauthorized(on connection: NWConnection) { send(["error": "Bearer token required"], status: "401 Unauthorized", extraHeaders: "WWW-Authenticate: Bearer\r\n", on: connection) } private func mutateLibrary(method: String, path: [String], query: [URLQueryItem], authorization: String?, headers: [String: [String]], initialBody: Data, on connection: NWConnection) { guard library.isAuthorized(authorization) else { sendUnauthorized(on: connection); return } if method == "POST", path.isEmpty { acceptBody(headers, initial: initialBody, maximum: 32 * 1024, on: connection) { url in guard let input = try? JSONDecoder().decode(PatientInput.self, from: Data(contentsOf: url)) else { throw StoreError.invalid } let patient = try self.library.store.createPatient(name: input.name, chartNumber: input.chartNumber) self.send(patient, status: "201 Created", on: connection) } return } guard path.count == 3, path[1] == "images", let patient = UUID(uuidString: path[0]), let image = UUID(uuidString: path[2]) else { send(["error": "Route or method unavailable"], status: "404 Not Found", on: connection) return } if method == "DELETE" { do { try library.store.deleteFile(patient: patient, imageID: image) send(["status": "deleted"], on: connection) } catch { sendMutationError(error, on: connection) } } else if method == "PUT" { guard let name = query.first(where: { $0.name == "name" })?.value, !name.isEmpty else { sendMutationError(StoreError.invalid, on: connection) return } let dicom = headers["content-type"]?.first?.lowercased() == "application/dicom" acceptBody(headers, initial: initialBody, maximum: 2 * 1024 * 1024 * 1024, on: connection) { url in let item = try self.library.store.addFile(from: url, patient: patient, imageID: image, name: name, dicom: dicom) self.send(item, status: "201 Created", on: connection) } } else { send(["error": "Method unavailable"], status: "405 Method Not Allowed", extraHeaders: "Allow: GET, PUT, DELETE\r\n", on: connection) } } private func sendMutationError(_ error: Error, on connection: NWConnection) { switch error { case StoreError.invalid: send(["error": "Invalid patient or file"], status: "400 Bad Request", on: connection) case StoreError.notFound: send(["error": "Patient or file not found"], status: "404 Not Found", on: connection) case StoreError.conflict: send(["error": "Duplicate chart number or file identifier"], status: "409 Conflict", on: connection) default: send(["error": "Could not update storage"], status: "503 Service Unavailable", on: connection) } } private func acceptBody(_ headers: [String: [String]], initial: Data, maximum: Int, on connection: NWConnection, finish: @escaping (URL) throws -> Void) { guard headers["transfer-encoding"] == nil, let lengths = headers["content-length"], lengths.count == 1, let length = Int(lengths[0]), length > 0, initial.count <= length else { send(["error": "A single valid Content-Length is required"], status: "400 Bad Request", on: connection) return } guard length <= maximum else { send(["error": "Request exceeds upload limit"], status: "413 Content Too Large", on: connection) return } do { let upload = try IncomingFile(in: library.store.directory) let timeout = DispatchWorkItem { [weak connection] in connection?.cancel() } queue.asyncAfter(deadline: .now() + 300, execute: timeout) if headers["expect"]?.first?.lowercased() == "100-continue" { connection.send(content: Data("HTTP/1.1 100 Continue\r\n\r\n".utf8), completion: .contentProcessed { _ in }) } receiveBody(upload, chunk: initial, remaining: length, on: connection, timeout: timeout, finish: finish) } catch { sendMutationError(error, on: connection) } } private func receiveBody(_ upload: IncomingFile, chunk: Data, remaining: Int, on connection: NWConnection, timeout: DispatchWorkItem, finish: @escaping (URL) throws -> Void) { do { try upload.handle.write(contentsOf: chunk) let remaining = remaining - chunk.count if remaining == 0 { timeout.cancel() try upload.handle.close() try finish(upload.url) return } connection.receive(minimumIncompleteLength: 1, maximumLength: min(remaining, 64 * 1024)) { [weak self] data, _, _, error in guard let self, error == nil, let data, !data.isEmpty else { timeout.cancel() connection.cancel() return } self.receiveBody(upload, chunk: data, remaining: remaining, on: connection, timeout: timeout, finish: finish) } } catch { timeout.cancel() sendMutationError(error, on: connection) } } private func stream(_ handle: FileHandle, remaining: Int, on connection: NWConnection) { guard remaining > 0, let chunk = try? handle.read(upToCount: min(remaining, 64 * 1024)), !chunk.isEmpty else { try? handle.close() connection.cancel() return } connection.send(content: chunk, completion: .contentProcessed { [weak self] error in guard let self, error == nil else { try? handle.close() connection.cancel() return } self.stream(handle, remaining: remaining - chunk.count, on: connection) }) } private func responseHeaders(status: String, type: String, bytes: Int, extra: String) -> Data { Data("HTTP/1.1 \(status)\r\nContent-Type: \(type)\r\nContent-Length: \(bytes)\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nConnection: close\r\n\(extra)\r\n".utf8) } private func send(_ response: Response, status: String = "200 OK", extraHeaders: String = "", on connection: NWConnection) { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 guard let body = try? encoder.encode(response) else { connection.cancel(); return } let headers = responseHeaders(status: status, type: "application/json; charset=utf-8", bytes: body.count, extra: extraHeaders) connection.send(content: headers + body, completion: .contentProcessed { _ in connection.cancel() }) } } private final class IncomingFile { let url: URL let handle: FileHandle init(in directory: URL) throws { url = directory.appendingPathComponent(".upload-\(UUID().uuidString)") let fd = open(url.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600) guard fd >= 0 else { throw StoreError.database } handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) } deinit { try? handle.close() try? FileManager.default.removeItem(at: url) } }