548 lines
28 KiB
Swift
548 lines
28 KiB
Swift
import CryptoKit
|
|
import Foundation
|
|
import Network
|
|
import OSLog
|
|
import UniformTypeIdentifiers
|
|
|
|
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.http")
|
|
private let maxHeaderSize = 8192
|
|
private let diagnostics = Logger(subsystem: "EzServerMac", category: "HTTP")
|
|
private let store: ServerStore
|
|
private let diskSpaceToken: SHA256.Digest
|
|
private let webConsole = WebConsoleAPI()
|
|
private var connections: [ObjectIdentifier: NWConnection] = [:]
|
|
private var diagnosticRoutes: [ObjectIdentifier: String] = [:]
|
|
private static let legacyGroups: Set<String> = [
|
|
"auth", "info", "e2ds", "e3ds", "fs", "settings", "analytics", "consultds",
|
|
"implantds", "iosensor", "orthods", "thirdparty", "device", "pay",
|
|
]
|
|
|
|
init(port: UInt16, configuration: ServerConfiguration) throws {
|
|
store = configuration.store
|
|
diskSpaceToken = SHA256.hash(data: Data(configuration.token.utf8))
|
|
let parameters = NWParameters.tcp
|
|
(parameters.defaultProtocolStack.internetProtocol as? NWProtocolIP.Options)?.version = .v4
|
|
parameters.requiredLocalEndpoint = .hostPort(host: "0.0.0.0", port: NWEndpoint.Port(rawValue: port)!)
|
|
listener = try NWListener(using: parameters)
|
|
}
|
|
|
|
func start(onStateChange: @escaping (Result<UInt16, Error>) -> 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)
|
|
self?.diagnosticRoutes.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(completion: (() -> Void)? = nil) {
|
|
queue.async { [self] in
|
|
listener.cancel()
|
|
connections.values.forEach { $0.cancel() }
|
|
connections.removeAll()
|
|
diagnosticRoutes.removeAll()
|
|
completion?()
|
|
}
|
|
}
|
|
|
|
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, let host = Self.requestHost(hosts[0]) else {
|
|
send(["error": "Invalid request or host"], status: "400 Bad Request", on: connection)
|
|
return
|
|
}
|
|
let localConsole = Self.isLoopback(host: host, peer: connection.endpoint)
|
|
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
|
|
let lower = segments.map { $0.lowercased() }
|
|
let apiPrefix = lower.starts(with: ["api", "index.php", "v1"]) ? 3 : 2
|
|
if lower.starts(with: ["api", "v1"]) || apiPrefix == 3 {
|
|
let route = Array(lower.dropFirst(apiPrefix))
|
|
if route.count >= 2, Self.legacyGroups.contains(route[0]),
|
|
route[1].range(of: #"\A[a-z][a-z0-9]{0,63}\z"#, options: .regularExpression) != nil,
|
|
["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"].contains(method) {
|
|
diagnosticRoutes[ObjectIdentifier(connection)] = "\(method) /api/v1/\(route[0])/\(route[1])"
|
|
}
|
|
if route.first == "fs", route.count >= 2 {
|
|
let operation = route[1]
|
|
if method == "GET", ["filesbytypeandpath", "ctfilesbypath"].contains(operation) {
|
|
guard webConsole.isSignedIn(bearer) else { sendUnauthorized(on: connection); return }
|
|
var arguments: [String: String] = [:]
|
|
let tail = Array(segments.dropFirst(apiPrefix + 2))
|
|
for index in stride(from: 0, to: max(0, tail.count - 1), by: 2) {
|
|
arguments[tail[index].lowercased()] = tail[index + 1]
|
|
}
|
|
for item in target.queryItems ?? [] { arguments[item.name.lowercased()] = item.value }
|
|
downloadLegacyFile(ct: operation == "ctfilesbypath", arguments: arguments, on: connection)
|
|
return
|
|
}
|
|
if method == "POST", route.count == 2, ["filesbychartno", "ctfilesbychartno"].contains(operation) {
|
|
guard webConsole.isSignedIn(bearer) else { sendUnauthorized(on: connection); return }
|
|
guard let type = headers["content-type"]?.first, let boundary = LegacyMultipart.boundary(in: type) else {
|
|
send(["errorCode": -1021], status: "400 Bad Request", on: connection)
|
|
return
|
|
}
|
|
acceptBody(headers, initial: initialBody, maximum: 2 * 1024 * 1024 * 1024, on: connection) { url in
|
|
self.uploadLegacyFile(url, boundary: boundary, ct: operation == "ctfilesbychartno", on: connection)
|
|
}
|
|
return
|
|
}
|
|
}
|
|
if webConsole.handles(route, method: method) {
|
|
guard localConsole || webConsole.allowsNetworkAccess(route, method: method) else {
|
|
send(["error": "Web Console is local only"], status: "403 Forbidden", on: connection)
|
|
return
|
|
}
|
|
let reply: (Data) -> Void = { [self] body in
|
|
let response = webConsole.reply(path: route, method: method, body: body,
|
|
authorization: bearer, query: target.queryItems ?? [],
|
|
queryPathLast: segments.last, store: store)
|
|
guard let json = try? JSONSerialization.data(withJSONObject: response.body) else {
|
|
connection.cancel()
|
|
return
|
|
}
|
|
sendBody(json, status: response.status, on: connection)
|
|
}
|
|
if method == "GET" {
|
|
reply(Data())
|
|
} else {
|
|
guard headers["content-type"]?.first?.lowercased().hasPrefix("application/json") == true else {
|
|
send(["errorMessage": "Expected application/json"],
|
|
status: "415 Unsupported Media Type", on: connection)
|
|
return
|
|
}
|
|
acceptBody(headers, initial: initialBody, maximum: 32 * 1024, on: connection) { url in
|
|
reply(try Data(contentsOf: url))
|
|
}
|
|
}
|
|
return
|
|
}
|
|
}
|
|
guard method == "GET" else {
|
|
send(["error": "Only GET is supported"], status: "405 Method Not Allowed",
|
|
extraHeaders: "Allow: GET\r\n", on: connection)
|
|
return
|
|
}
|
|
|
|
if target.path == "/webconsole" || target.path.hasPrefix("/webconsole/") {
|
|
guard localConsole else {
|
|
send(["error": "Web Console is local only"], status: "403 Forbidden", on: connection)
|
|
return
|
|
}
|
|
serveWebConsole(path: segments, 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 versionPath = Array(lower.dropFirst(apiPrefix))
|
|
let versionNameInPath = versionPath.count == 4 &&
|
|
versionPath.starts(with: ["info", "versionsbyname", "name"]) &&
|
|
(lower.starts(with: ["api", "v1"]) || apiPrefix == 3) ? segments.last : nil
|
|
let path = versionNameInPath == nil
|
|
? target.path.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "/"))
|
|
: "api/v1/info/versionsbyname"
|
|
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 isAuthorizedForDiskSpace(bearer) else { sendUnauthorized(on: connection); return }
|
|
let values = try? 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 = versionNameInPath
|
|
?? 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 static func requestHost(_ authority: String) -> String? {
|
|
let parts = authority.split(separator: ":", omittingEmptySubsequences: false)
|
|
guard let name = parts.first?.lowercased(), name.utf8.count <= 253,
|
|
name.range(of: #"\A[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\z"#,
|
|
options: .regularExpression) != nil,
|
|
parts.count == 1 || (parts.count == 2 && parts[1].utf8.count <= 5 &&
|
|
parts[1].utf8.allSatisfy({ (48...57).contains($0) }) &&
|
|
UInt16(parts[1]).map({ $0 > 0 }) == true) else { return nil }
|
|
return name
|
|
}
|
|
|
|
private static func isLoopback(host: String, peer: NWEndpoint) -> Bool {
|
|
guard host == "localhost" || IPv4Address(host)?.rawValue.first == 127,
|
|
case let .hostPort(address, _) = peer,
|
|
case let .ipv4(ip) = address else { return false }
|
|
return ip.rawValue.first == 127
|
|
}
|
|
|
|
private func serveWebConsole(path: [String], on connection: NWConnection) {
|
|
guard let root = Bundle.main.resourceURL?.appendingPathComponent("webconsole", isDirectory: true)
|
|
.resolvingSymlinksInPath() else {
|
|
send(["error": "Web Console assets are unavailable"], status: "404 Not Found", on: connection)
|
|
return
|
|
}
|
|
let components = path.count == 1 ? ["index.html"] : Array(path.dropFirst())
|
|
let file = components.reduce(root) { $0.appendingPathComponent($1) }.resolvingSymlinksInPath()
|
|
guard file.path.hasPrefix(root.path + "/"),
|
|
let metadata = try? file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]),
|
|
metadata.isRegularFile == true, let bytes = metadata.fileSize,
|
|
let handle = try? FileHandle(forReadingFrom: file) else {
|
|
send(["error": "Web Console asset not found"], status: "404 Not Found", on: connection)
|
|
return
|
|
}
|
|
let type = UTType(filenameExtension: file.pathExtension)?.preferredMIMEType ?? "application/octet-stream"
|
|
let policy = "Content-Security-Policy: connect-src 'self'; frame-ancestors 'none'; object-src 'none'\r\n"
|
|
let headers = responseHeaders(status: "200 OK", type: type, bytes: bytes, extra: policy)
|
|
connection.send(content: headers, completion: .contentProcessed { [weak self] error in
|
|
guard let self, error == nil else { connection.cancel(); return }
|
|
self.stream(handle, remaining: bytes, on: connection)
|
|
})
|
|
}
|
|
|
|
private struct LegacyPing: Encodable {
|
|
let errorCode = 0
|
|
let message = "Pong"
|
|
}
|
|
|
|
private func isAuthorizedForDiskSpace(_ authorization: String?) -> Bool {
|
|
guard let authorization, authorization.hasPrefix("Bearer ") else { return false }
|
|
let candidate = SHA256.hash(data: Data(authorization.dropFirst(7).utf8))
|
|
return zip(candidate, diskSpaceToken).reduce(UInt8(0)) { $0 | ($1.0 ^ $1.1) } == 0
|
|
}
|
|
|
|
private func sendUnauthorized(on connection: NWConnection) {
|
|
send(["error": "Bearer token required"], status: "401 Unauthorized",
|
|
extraHeaders: "WWW-Authenticate: Bearer\r\n", on: connection)
|
|
}
|
|
|
|
private func uploadLegacyFile(_ url: URL, boundary: String, ct: Bool, on connection: NWConnection) {
|
|
do {
|
|
let form = try LegacyMultipart(url: url, boundary: boundary)
|
|
let fields = form.fields
|
|
guard let chart = fields["chartNo"], !chart.isEmpty,
|
|
ct || fields["fileType"]?.uppercased() == "IMG",
|
|
let suppliedName = fields["attachedFileName"] ?? form.filename else { throw StoreError.invalid }
|
|
guard let patient = try store.patient(chartNumber: chart) else { throw StoreError.notFound }
|
|
let rawExtension = ct ? "CT" : (suppliedName as NSString).pathExtension
|
|
let ext = rawExtension.isEmpty ? (fields["fileExt"] ?? "dcm").trimmingCharacters(in: CharacterSet(charactersIn: ".")) : rawExtension
|
|
guard ext.range(of: #"\A[A-Za-z0-9]{1,12}\z"#, options: .regularExpression) != nil else { throw StoreError.invalid }
|
|
if ct && !form.file.starts(with: [0x50, 0x4b, 0x03, 0x04]) { throw StoreError.invalid }
|
|
let file = try IncomingFile(in: store.directory)
|
|
try file.handle.write(contentsOf: form.file)
|
|
try file.handle.close()
|
|
if ct {
|
|
let zip = Process()
|
|
zip.executableURL = URL(fileURLWithPath: "/usr/bin/unzip")
|
|
zip.arguments = ["-Z", "-1", file.url.path]
|
|
zip.standardOutput = FileHandle.nullDevice
|
|
zip.standardError = FileHandle.nullDevice
|
|
try zip.run()
|
|
zip.waitUntilExit()
|
|
guard zip.terminationStatus == 0 else { throw StoreError.invalid }
|
|
}
|
|
let id = UUID()
|
|
let wireName = id.uuidString + "." + ext
|
|
let modality = ct ? "eCT" : (fields["modality"] ?? "")
|
|
let uid = fields["studyInstanceUID"] ?? ""
|
|
guard modality.utf8.count <= 64, uid.utf8.count <= 64,
|
|
!modality.contains("\0"), !uid.contains("\0") else { throw StoreError.invalid }
|
|
_ = try store.addFile(from: file.url, patient: patient.record.id, imageID: id, name: wireName,
|
|
dicom: !ct && ext.lowercased() == "dcm", studyUID: uid, modality: modality)
|
|
sendLegacyReply(["updatedFileType": ct ? "CT" : "IMG", "updatedFileName": wireName],
|
|
code: 0, status: "200 OK", on: connection)
|
|
} catch StoreError.invalid {
|
|
send(["errorCode": -1021], status: "400 Bad Request", on: connection)
|
|
} catch StoreError.notFound {
|
|
send(["errorCode": -100037], status: "404 Not Found", on: connection)
|
|
} catch {
|
|
send(["errorCode": -1005], status: "503 Service Unavailable", on: connection)
|
|
}
|
|
}
|
|
|
|
private func sendLegacyReply(_ values: [String: String], code: Int, status: String, on connection: NWConnection) {
|
|
var response: [String: Any] = values
|
|
response["errorCode"] = code
|
|
guard let bytes = try? JSONSerialization.data(withJSONObject: response) else { connection.cancel(); return }
|
|
sendBody(bytes, status: status, on: connection)
|
|
}
|
|
|
|
private func downloadLegacyFile(ct: Bool, arguments: [String: String], on connection: NWConnection) {
|
|
guard ct || arguments["type"]?.uppercased() == "IMG",
|
|
let raw = arguments["path"]?.removingPercentEncoding else {
|
|
send(["errorCode": -1021], status: "400 Bad Request", on: connection)
|
|
return
|
|
}
|
|
let basename = (raw.replacingOccurrences(of: "\\", with: "/") as NSString).lastPathComponent
|
|
let identifier = UUID(uuidString: (basename as NSString).deletingPathExtension)
|
|
do {
|
|
let matches = try store.legacyImages(imageID: identifier).filter {
|
|
(identifier == nil ? $0.name == basename : $0.wireName.caseInsensitiveCompare(basename) == .orderedSame)
|
|
&& (ct == $0.wireName.uppercased().hasSuffix(".CT"))
|
|
}
|
|
guard matches.count == 1, let image = matches.first else {
|
|
send(["errorCode": -1002], status: "404 Not Found", on: connection)
|
|
return
|
|
}
|
|
if ct && (image.dicomCount ?? 0) > 1 {
|
|
DispatchQueue.global(qos: .utility).async { [self] in
|
|
do {
|
|
let directory = store.directory.appendingPathComponent(".ct-download-\(UUID().uuidString)")
|
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false)
|
|
defer { try? FileManager.default.removeItem(at: directory) }
|
|
let archive = directory.appendingPathComponent(image.wireName)
|
|
let zip = Process()
|
|
zip.executableURL = URL(fileURLWithPath: "/usr/bin/zip")
|
|
zip.currentDirectoryURL = image.firstFile.deletingLastPathComponent()
|
|
zip.arguments = ["-q", "-0", "-r", archive.path, "."]
|
|
zip.standardError = FileHandle.nullDevice
|
|
try zip.run()
|
|
zip.waitUntilExit()
|
|
guard zip.terminationStatus == 0 else { throw StoreError.database }
|
|
let file = try Self.openTransfer(archive)
|
|
queue.async { self.sendLegacyFile(file, name: image.wireName, ct: true, on: connection) }
|
|
} catch {
|
|
queue.async { self.send(["errorCode": -1005], status: "503 Service Unavailable", on: connection) }
|
|
}
|
|
}
|
|
} else {
|
|
let file = try Self.openTransfer(image.firstFile)
|
|
sendLegacyFile(file, name: image.wireName, ct: ct, on: connection)
|
|
}
|
|
} catch {
|
|
send(["errorCode": -1002], status: "404 Not Found", on: connection)
|
|
}
|
|
}
|
|
|
|
private static func openTransfer(_ url: URL) throws -> (handle: FileHandle, bytes: Int) {
|
|
let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK)
|
|
guard fd >= 0 else { throw StoreError.notFound }
|
|
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
|
|
var info = stat()
|
|
guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG else { throw StoreError.notFound }
|
|
return (handle, Int(info.st_size))
|
|
}
|
|
|
|
private func sendLegacyFile(_ file: (handle: FileHandle, bytes: Int), name: String, ct: Bool,
|
|
on connection: NWConnection) {
|
|
let ext = (name as NSString).pathExtension
|
|
let type = ct ? "application/zip" : (UTType(filenameExtension: ext)?.preferredMIMEType ?? "application/octet-stream")
|
|
let safeName = name.addingPercentEncoding(withAllowedCharacters: .alphanumerics.union(CharacterSet(charactersIn: "-._"))) ?? "file"
|
|
let headers = responseHeaders(status: "200 OK", type: type, bytes: file.bytes,
|
|
extra: "Content-Disposition: attachment; filename=\(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)
|
|
})
|
|
}
|
|
|
|
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: 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 {
|
|
send(["error": "Could not read request body"], status: "503 Service Unavailable", 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()
|
|
send(["error": "Could not read request body"], status: "503 Service Unavailable", 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: Encodable>(_ 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 }
|
|
sendBody(body, status: status, extraHeaders: extraHeaders, on: connection)
|
|
}
|
|
|
|
private func sendBody(_ body: Data, status: String, extraHeaders: String = "", on connection: NWConnection) {
|
|
if let route = diagnosticRoutes[ObjectIdentifier(connection)],
|
|
let code = Int(status.prefix(3)), code >= 400 {
|
|
diagnostics.notice("\(route, privacy: .public) → \(code, privacy: .public)")
|
|
}
|
|
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)
|
|
}
|
|
}
|