403 lines
19 KiB
Swift
403 lines
19 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 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 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)
|
|
}
|
|
}
|