|
| 1 | +import Foundation |
| 2 | +import Starscream |
| 3 | + |
| 4 | +/// A Starscream `Engine` backed by `URLSessionWebSocketTask`, used for mTLS connections. |
| 5 | +/// |
| 6 | +/// The URL Loading System supports modern TLS versions and presents the client certificate through |
| 7 | +/// the standard authentication challenge, the same path the REST API uses. |
| 8 | +internal final class HAURLSessionWebSocketEngine: NSObject, Engine, URLSessionDataDelegate, |
| 9 | + URLSessionWebSocketDelegate { |
| 10 | + private var task: URLSessionWebSocketTask? |
| 11 | + private var session: URLSession? |
| 12 | + private weak var delegate: EngineDelegate? |
| 13 | + |
| 14 | + private let clientIdentity: HAConnectionInfo.ClientIdentityProvider? |
| 15 | + private let evaluateCertificate: HAConnectionInfo.EvaluateCertificate? |
| 16 | + |
| 17 | + init( |
| 18 | + clientIdentity: HAConnectionInfo.ClientIdentityProvider?, |
| 19 | + evaluateCertificate: HAConnectionInfo.EvaluateCertificate? |
| 20 | + ) { |
| 21 | + self.clientIdentity = clientIdentity |
| 22 | + self.evaluateCertificate = evaluateCertificate |
| 23 | + super.init() |
| 24 | + } |
| 25 | + |
| 26 | + func register(delegate: EngineDelegate) { |
| 27 | + self.delegate = delegate |
| 28 | + } |
| 29 | + |
| 30 | + func start(request: URLRequest) { |
| 31 | + if session == nil { |
| 32 | + session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) |
| 33 | + } |
| 34 | + task = session?.webSocketTask(with: request) |
| 35 | + doRead() |
| 36 | + task?.resume() |
| 37 | + } |
| 38 | + |
| 39 | + func stop(closeCode: UInt16) { |
| 40 | + let closeCode = URLSessionWebSocketTask.CloseCode(rawValue: Int(closeCode)) ?? .normalClosure |
| 41 | + task?.cancel(with: closeCode, reason: nil) |
| 42 | + } |
| 43 | + |
| 44 | + func forceStop() { |
| 45 | + stop(closeCode: UInt16(URLSessionWebSocketTask.CloseCode.abnormalClosure.rawValue)) |
| 46 | + } |
| 47 | + |
| 48 | + func write(string: String, completion: (() -> Void)?) { |
| 49 | + task?.send(.string(string), completionHandler: sendCompletion(completion)) |
| 50 | + } |
| 51 | + |
| 52 | + func write(data: Data, opcode: FrameOpCode, completion: (() -> Void)?) { |
| 53 | + switch opcode { |
| 54 | + case .binaryFrame: |
| 55 | + task?.send(.data(data), completionHandler: sendCompletion(completion)) |
| 56 | + case .textFrame: |
| 57 | + write(string: String(decoding: data, as: UTF8.self), completion: completion) |
| 58 | + case .ping: |
| 59 | + task?.sendPing(pongReceiveHandler: sendCompletion(completion)) |
| 60 | + default: |
| 61 | + break |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + func sendCompletion(_ completion: (() -> Void)?) -> (Error?) -> Void { |
| 66 | + { _ in completion?() } |
| 67 | + } |
| 68 | + |
| 69 | + private func doRead() { |
| 70 | + task?.receive { [weak self] result in |
| 71 | + self?.handleReceiveResult(result) |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + func handleReceiveResult(_ result: Result<URLSessionWebSocketTask.Message, Error>) { |
| 76 | + switch result { |
| 77 | + case let .success(message): |
| 78 | + if case let .string(string) = message { |
| 79 | + broadcast(event: .text(string)) |
| 80 | + } else if case let .data(data) = message { |
| 81 | + broadcast(event: .binary(data)) |
| 82 | + } |
| 83 | + doRead() |
| 84 | + case let .failure(error): |
| 85 | + broadcast(event: .error(error)) |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + private func broadcast(event: WebSocketEvent) { |
| 90 | + delegate?.didReceive(event: event) |
| 91 | + } |
| 92 | + |
| 93 | + func urlSession( |
| 94 | + _ session: URLSession, |
| 95 | + webSocketTask: URLSessionWebSocketTask, |
| 96 | + didOpenWithProtocol protocol: String? |
| 97 | + ) { |
| 98 | + broadcast(event: .connected(["Sec-WebSocket-Protocol": `protocol` ?? ""])) |
| 99 | + } |
| 100 | + |
| 101 | + func urlSession( |
| 102 | + _ session: URLSession, |
| 103 | + webSocketTask: URLSessionWebSocketTask, |
| 104 | + didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, |
| 105 | + reason: Data? |
| 106 | + ) { |
| 107 | + let reasonString = reason.flatMap { String(data: $0, encoding: .utf8) } ?? "" |
| 108 | + broadcast(event: .disconnected(reasonString, UInt16(closeCode.rawValue))) |
| 109 | + } |
| 110 | + |
| 111 | + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { |
| 112 | + broadcast(event: .error(error)) |
| 113 | + } |
| 114 | + |
| 115 | + func urlSession( |
| 116 | + _ session: URLSession, |
| 117 | + didReceive challenge: URLAuthenticationChallenge, |
| 118 | + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void |
| 119 | + ) { |
| 120 | + switch challenge.protectionSpace.authenticationMethod { |
| 121 | + case NSURLAuthenticationMethodClientCertificate: |
| 122 | + if let identity = clientIdentity?() { |
| 123 | + completionHandler( |
| 124 | + .useCredential, |
| 125 | + URLCredential(identity: identity, certificates: nil, persistence: .forSession) |
| 126 | + ) |
| 127 | + } else { |
| 128 | + completionHandler(.performDefaultHandling, nil) |
| 129 | + } |
| 130 | + case NSURLAuthenticationMethodServerTrust: |
| 131 | + guard let evaluateCertificate, let serverTrust = challenge.protectionSpace.serverTrust else { |
| 132 | + completionHandler(.performDefaultHandling, nil) |
| 133 | + return |
| 134 | + } |
| 135 | + evaluateCertificate(serverTrust) { result in |
| 136 | + switch result { |
| 137 | + case .success: |
| 138 | + completionHandler(.useCredential, URLCredential(trust: serverTrust)) |
| 139 | + case .failure: |
| 140 | + completionHandler(.cancelAuthenticationChallenge, nil) |
| 141 | + } |
| 142 | + } |
| 143 | + default: |
| 144 | + completionHandler(.performDefaultHandling, nil) |
| 145 | + } |
| 146 | + } |
| 147 | +} |
0 commit comments