From 656e9df50978f65c84e32806569efe5e8e21c2dd Mon Sep 17 00:00:00 2001 From: Michael Law <1365977+lawmicha@users.noreply.github.com> Date: Wed, 2 Feb 2022 14:49:22 -0500 Subject: [PATCH] feat: Upgrade Starscream to 4.0.4 --- .gitignore | 1 + AppSyncRealTimeClient.podspec | 2 +- .../StarscreamAdapter+Delegate.swift | 43 +- .../Starscream/StarscreamAdapter.swift | 39 +- Cartfile | 2 +- Package.resolved | 13 +- Package.swift | 2 +- Podfile | 2 +- Podfile.lock | 8 +- Pods/Manifest.lock | 8 +- Pods/Pods.xcodeproj/project.pbxproj | 540 ++++--- Pods/Starscream/README.md | 264 +--- .../Sources/Compression/Compression.swift | 29 + .../WSCompression.swift} | 104 +- .../Sources/DataBytes/Data+Extensions.swift | 53 + Pods/Starscream/Sources/Engine/Engine.swift | 22 + .../Sources/Engine/NativeEngine.swift | 96 ++ Pods/Starscream/Sources/Engine/WSEngine.swift | 234 +++ .../Framer/FoundationHTTPHandler.swift | 123 ++ .../Framer/FoundationHTTPServerHandler.swift | 99 ++ .../Sources/Framer/FrameCollector.swift | 107 ++ Pods/Starscream/Sources/Framer/Framer.swift | 365 +++++ .../Sources/Framer/HTTPHandler.swift | 148 ++ .../Sources/Framer/StringHTTPHandler.swift | 143 ++ .../Sources/Security/FoundationSecurity.swift | 101 ++ .../Sources/Security/Security.swift | 45 + Pods/Starscream/Sources/Server/Server.swift | 56 + .../Sources/Server/WebSocketServer.swift | 196 +++ .../Starscream/SSLClientCertificate.swift | 92 -- .../Sources/Starscream/SSLSecurity.swift | 266 ---- .../Sources/Starscream/WebSocket.swift | 1342 +---------------- .../Transport/FoundationTransport.swift | 218 +++ .../Sources/Transport/TCPTransport.swift | 159 ++ .../Sources/Transport/Transport.swift | 55 + .../Starscream/Starscream-Info.plist | 2 +- 35 files changed, 2866 insertions(+), 2113 deletions(-) create mode 100644 Pods/Starscream/Sources/Compression/Compression.swift rename Pods/Starscream/Sources/{Starscream/Compression.swift => Compression/WSCompression.swift} (61%) create mode 100644 Pods/Starscream/Sources/DataBytes/Data+Extensions.swift create mode 100644 Pods/Starscream/Sources/Engine/Engine.swift create mode 100644 Pods/Starscream/Sources/Engine/NativeEngine.swift create mode 100644 Pods/Starscream/Sources/Engine/WSEngine.swift create mode 100644 Pods/Starscream/Sources/Framer/FoundationHTTPHandler.swift create mode 100644 Pods/Starscream/Sources/Framer/FoundationHTTPServerHandler.swift create mode 100644 Pods/Starscream/Sources/Framer/FrameCollector.swift create mode 100644 Pods/Starscream/Sources/Framer/Framer.swift create mode 100644 Pods/Starscream/Sources/Framer/HTTPHandler.swift create mode 100644 Pods/Starscream/Sources/Framer/StringHTTPHandler.swift create mode 100644 Pods/Starscream/Sources/Security/FoundationSecurity.swift create mode 100644 Pods/Starscream/Sources/Security/Security.swift create mode 100644 Pods/Starscream/Sources/Server/Server.swift create mode 100644 Pods/Starscream/Sources/Server/WebSocketServer.swift delete mode 100644 Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift delete mode 100644 Pods/Starscream/Sources/Starscream/SSLSecurity.swift create mode 100644 Pods/Starscream/Sources/Transport/FoundationTransport.swift create mode 100644 Pods/Starscream/Sources/Transport/TCPTransport.swift create mode 100644 Pods/Starscream/Sources/Transport/Transport.swift diff --git a/.gitignore b/.gitignore index 9ca7b6c4..e4c327ac 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,7 @@ credentials-mc.json amplify build/ +.build/ dist/ node_modules/ aws-exports.js diff --git a/AppSyncRealTimeClient.podspec b/AppSyncRealTimeClient.podspec index 92d2cd4b..ac6d8c53 100644 --- a/AppSyncRealTimeClient.podspec +++ b/AppSyncRealTimeClient.podspec @@ -16,5 +16,5 @@ Pod::Spec.new do |s| s.requires_arc = true s.source_files = 'AppSyncRealTimeClient/**/*.swift' - s.dependency 'Starscream', '~> 3.1.1' + s.dependency 'Starscream', '~> 4.0.4' end \ No newline at end of file diff --git a/AppSyncRealTimeClient/Websocket/Starscream/StarscreamAdapter+Delegate.swift b/AppSyncRealTimeClient/Websocket/Starscream/StarscreamAdapter+Delegate.swift index f6f5f112..bddc44ee 100644 --- a/AppSyncRealTimeClient/Websocket/Starscream/StarscreamAdapter+Delegate.swift +++ b/AppSyncRealTimeClient/Websocket/Starscream/StarscreamAdapter+Delegate.swift @@ -10,24 +10,55 @@ import Starscream /// Extension to handle delegate callback from Starscream extension StarscreamAdapter: Starscream.WebSocketDelegate { + public func didReceive(event: WebSocketEvent, client: WebSocket) { + switch event { + case .connected: + websocketDidConnect(socket: client) + case .disconnected(let reason, let code): + AppSyncLogger.verbose("[StarscreamAdapter] disconnected: reason=\(reason); code=\(code)") + websocketDidDisconnect(socket: client, error: nil) + case .text(let string): + websocketDidReceiveMessage(socket: client, text: string) + case .binary(let data): + websocketDidReceiveData(socket: client, data: data) + case .ping: + AppSyncLogger.verbose("[StarscreamAdapter] ping") + case .pong: + AppSyncLogger.verbose("[StarscreamAdapter] pong") + case .viabilityChanged(let viability): + AppSyncLogger.verbose("[StarscreamAdapter] viabilityChanged: \(viability)") + case .reconnectSuggested(let suggestion): + AppSyncLogger.verbose("[StarscreamAdapter] reconnectSuggested: \(suggestion)") + case .cancelled: + websocketDidDisconnect(socket: client, error: nil) + case .error(let error): + websocketDidDisconnect(socket: client, error: error) + } + } - public func websocketDidConnect(socket: WebSocketClient) { + private func websocketDidConnect(socket: WebSocketClient) { AppSyncLogger.verbose("[StarscreamAdapter] websocketDidConnect: websocket has been connected.") - delegate?.websocketDidConnect(provider: self) + serialQueue.async { + self._isConnected = true + self.delegate?.websocketDidConnect(provider: self) + } } - public func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { + private func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { AppSyncLogger.verbose("[StarscreamAdapter] websocketDidDisconnect: \(error?.localizedDescription ?? "No error")") - delegate?.websocketDidDisconnect(provider: self, error: error) + serialQueue.async { + self._isConnected = false + self.delegate?.websocketDidDisconnect(provider: self, error: error) + } } - public func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { + private func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { AppSyncLogger.verbose("[StarscreamAdapter] websocketDidReceiveMessage: - \(text)") let data = text.data(using: .utf8) ?? Data() delegate?.websocketDidReceiveData(provider: self, data: data) } - public func websocketDidReceiveData(socket: WebSocketClient, data: Data) { + private func websocketDidReceiveData(socket: WebSocketClient, data: Data) { AppSyncLogger.verbose("[StarscreamAdapter] WebsocketDidReceiveData - \(data)") delegate?.websocketDidReceiveData(provider: self, data: data) } diff --git a/AppSyncRealTimeClient/Websocket/Starscream/StarscreamAdapter.swift b/AppSyncRealTimeClient/Websocket/Starscream/StarscreamAdapter.swift index 84263c6b..541c3b7b 100644 --- a/AppSyncRealTimeClient/Websocket/Starscream/StarscreamAdapter.swift +++ b/AppSyncRealTimeClient/Websocket/Starscream/StarscreamAdapter.swift @@ -9,22 +9,41 @@ import Foundation import Starscream public class StarscreamAdapter: AppSyncWebsocketProvider { - public init() { - // Do nothing - } - - private let serialQueue = DispatchQueue(label: "com.amazonaws.StarscreamAdapter.serialQueue") + let serialQueue: DispatchQueue + private let callbackQueue: DispatchQueue var socket: WebSocket? weak var delegate: AppSyncWebsocketDelegate? + // swiftlint:disable:next identifier_name + var _isConnected: Bool + public var isConnected: Bool { + serialQueue.sync { + _isConnected + } + } + + public init() { + let serialQueue = DispatchQueue(label: "com.amazonaws.StarscreamAdapter.serialQueue") + let callbackQueue = DispatchQueue( + label: "com.amazonaws.StarscreamAdapter.callBack", + target: serialQueue + ) + self._isConnected = false + self.serialQueue = serialQueue + self.callbackQueue = callbackQueue + } + public func connect(url: URL, protocols: [String], delegate: AppSyncWebsocketDelegate?) { serialQueue.async { AppSyncLogger.verbose("[StarscreamAdapter] connect. Connecting to url") - self.socket = WebSocket(url: url, protocols: protocols) + var urlRequest = URLRequest(url: url) + let protocolHeaderValue = protocols.joined(separator: ", ") + urlRequest.setValue(protocolHeaderValue, forHTTPHeaderField: "Sec-WebSocket-Protocol") + self.socket = WebSocket(request: urlRequest) self.delegate = delegate self.socket?.delegate = self - self.socket?.callbackQueue = DispatchQueue(label: "com.amazonaws.StarscreamAdapter.callBack") + self.socket?.callbackQueue = self.callbackQueue self.socket?.connect() } } @@ -43,10 +62,4 @@ public class StarscreamAdapter: AppSyncWebsocketProvider { self.socket?.write(string: message) } } - - public var isConnected: Bool { - serialQueue.sync { - return socket?.isConnected ?? false - } - } } diff --git a/Cartfile b/Cartfile index 2b4e2227..9c47c7a5 100644 --- a/Cartfile +++ b/Cartfile @@ -1 +1 @@ -github "daltoniam/starscream" ~> 3.1.1 +github "daltoniam/starscream" ~> 4.0.4 diff --git a/Package.resolved b/Package.resolved index eca5bc44..a9c6ce6d 100644 --- a/Package.resolved +++ b/Package.resolved @@ -6,17 +6,8 @@ "repositoryURL": "https://github.com/daltoniam/Starscream", "state": { "branch": null, - "revision": "e6b65c6d9077ea48b4a7bdda8994a1d3c6969c8d", - "version": "3.1.1" - } - }, - { - "package": "swift-nio-zlib-support", - "repositoryURL": "https://github.com/apple/swift-nio-zlib-support.git", - "state": { - "branch": null, - "revision": "37760e9a52030bb9011972c5213c3350fa9d41fd", - "version": "1.0.0" + "revision": "df8d82047f6654d8e4b655d1b1525c64e1059d21", + "version": "4.0.4" } } ] diff --git a/Package.swift b/Package.swift index 54bd6c49..24b81cf3 100644 --- a/Package.swift +++ b/Package.swift @@ -11,7 +11,7 @@ let package = Package( targets: ["AppSyncRealTimeClient"]), ], dependencies: [ - .package(url: "https://github.com/daltoniam/Starscream", .upToNextMinor(from: "3.1.1")) + .package(url: "https://github.com/daltoniam/Starscream", .upToNextMinor(from: "4.0.4")) ], targets: [ .target( diff --git a/Podfile b/Podfile index 9d004739..634c8dab 100644 --- a/Podfile +++ b/Podfile @@ -13,7 +13,7 @@ target 'AppSyncRealTimeClient' do # Pods for AppSyncRealTimeClient # If you update this dependency version, be sure to update the Cartfile also - pod "Starscream", "~> 3.1.0" + pod "Starscream", "~> 4.0.4" include_build_tools! diff --git a/Podfile.lock b/Podfile.lock index 6369ddf6..b1818f95 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -1,10 +1,10 @@ PODS: - - Starscream (3.1.1) + - Starscream (4.0.4) - SwiftFormat/CLI (0.48.17) - SwiftLint (0.45.0) DEPENDENCIES: - - Starscream (~> 3.1.0) + - Starscream (~> 4.0.4) - SwiftFormat/CLI - SwiftLint @@ -15,10 +15,10 @@ SPEC REPOS: - SwiftLint SPEC CHECKSUMS: - Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0 + Starscream: 5178aed56b316f13fa3bc55694e583d35dd414d9 SwiftFormat: 0a9044eb365d74d4a0a2cefa5fe44a4cbef382a7 SwiftLint: e5c7f1fba68eccfc51509d5b2ce1699f5502e0c7 -PODFILE CHECKSUM: 52bc6ec211be54e08e048379812e7a696613d5bf +PODFILE CHECKSUM: faccccbac411bb105d282d128939114db76875b9 COCOAPODS: 1.11.2 diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock index 6369ddf6..b1818f95 100644 --- a/Pods/Manifest.lock +++ b/Pods/Manifest.lock @@ -1,10 +1,10 @@ PODS: - - Starscream (3.1.1) + - Starscream (4.0.4) - SwiftFormat/CLI (0.48.17) - SwiftLint (0.45.0) DEPENDENCIES: - - Starscream (~> 3.1.0) + - Starscream (~> 4.0.4) - SwiftFormat/CLI - SwiftLint @@ -15,10 +15,10 @@ SPEC REPOS: - SwiftLint SPEC CHECKSUMS: - Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0 + Starscream: 5178aed56b316f13fa3bc55694e583d35dd414d9 SwiftFormat: 0a9044eb365d74d4a0a2cefa5fe44a4cbef382a7 SwiftLint: e5c7f1fba68eccfc51509d5b2ce1699f5502e0c7 -PODFILE CHECKSUM: 52bc6ec211be54e08e048379812e7a696613d5bf +PODFILE CHECKSUM: faccccbac411bb105d282d128939114db76875b9 COCOAPODS: 1.11.2 diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj index 50e250d1..1ceb155b 100644 --- a/Pods/Pods.xcodeproj/project.pbxproj +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -29,108 +29,124 @@ /* Begin PBXBuildFile section */ 00995668448B0482C6C3725DC3FB1E2D /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73010CC983E3809BECEE5348DA1BB8C6 /* Foundation.framework */; }; + 00C9C2E54995B3BEA1C999016833A58B /* Starscream-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8FBFA4F497BF24BAB2C3C2C46831CA0A /* Starscream-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; 02E351D61AED26EF2D1A51B014DEFA65 /* Pods-AppSyncRTCSample-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = A26BD722B33E83A41BD4A44DD2BDC4E3 /* Pods-AppSyncRTCSample-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 046AC7AA224C78A31C0A8FACB11D2D28 /* StringHTTPHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D2BCC3D81009251CF149E4E6A0C224E /* StringHTTPHandler.swift */; }; 2052554082DD68FC16C6F176C04D413C /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9783F8F2B1F7890527BA035E5948BCE2 /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 2318B70F6CB59888B879349F92DE450D /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1E3710DBCB77E7FD324B150464A090B /* WebSocket.swift */; }; 3156934B75D62B205598A5B9C8E2FF87 /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 632521D0E4C043F74AA5493B36ADF45A /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-dummy.m */; }; - 3744E502782192EA106AF498FEDB67B9 /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE599E071F98B60A2F95AEB05BFDB52F /* Compression.swift */; }; - 41CD4D248A99A2FC837BBC73988FF37E /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE42DB590EDA5163FCF669957D4095D2 /* SSLSecurity.swift */; }; + 33C71989B6C635864EC5E4862AFAAE8A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73010CC983E3809BECEE5348DA1BB8C6 /* Foundation.framework */; }; + 3A655D6817E99F062266BB601B0EEEDF /* Starscream-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3AF18D51FCC99A1CE4E23F9DAA637E43 /* Starscream-dummy.m */; }; + 3F3E9C6FF4BCB6F4FF18D9121CC3E42F /* WebSocketServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F5A03BCFF1BC81AACCA8C32725AD401 /* WebSocketServer.swift */; }; + 489EF4A7D4992C47CF590AEF9AA418FC /* FoundationTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C6D0498CE9448A64BAE886552FCCD6B /* FoundationTransport.swift */; }; 49C23C2D785C0C110AA02FC70CBA65DB /* Pods-AppSyncRealTimeClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = FA724FB4539BE70535E32D6B51B233CF /* Pods-AppSyncRealTimeClient-dummy.m */; }; - 56424C2C9CD0BC9AD2E7ACC7E94CC8B1 /* Starscream-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2AB2A2EACBA8232618B778F3D716F73B /* Starscream-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4A3B1BE129FDA231AC217E1C6DB2B8C8 /* Transport.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2CAEC3C9FC0A8AD7BE1DAB6A521D691 /* Transport.swift */; }; + 4AB6FCF35B998F60ED9EB100542EEA31 /* FoundationHTTPHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E6E2E9C7E9DC8FAA7C03E83452794FB /* FoundationHTTPHandler.swift */; }; + 5006DD4B60A05AF56EA0706A680BABF6 /* FoundationHTTPServerHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 180B214D60505BCE759982E83FF77C8E /* FoundationHTTPServerHandler.swift */; }; + 5281197FE8CC6E6954315F11B8F553D0 /* FoundationSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 03F7A3276C90DB9432B2403BBB9D2A53 /* FoundationSecurity.swift */; }; 5DA1BA241D8699925A6865F97C4A6891 /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 926BDB89A966BBC606CD53BA1871E433 /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests-dummy.m */; }; + 631654C419F62FE0270E1DF79CCF6F8B /* Data+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAFA07304E0D95CA475D728B2BA434B6 /* Data+Extensions.swift */; }; 68C5500DF1895E810A1B363D3BCB1110 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73010CC983E3809BECEE5348DA1BB8C6 /* Foundation.framework */; }; + 69A591F2BDE4941B391C102F4C26B115 /* Security.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EF5DA51A97FC4F9DAAED71CDF57C28F /* Security.swift */; }; 6AA6E85C39C4DDA0775DEE288B7D1B75 /* Pods-HostApp-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AAA4F28117B314B9CF3F58B0C87EBE67 /* Pods-HostApp-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6C0DACBE00A34619DEDB9A65CB959BA5 /* TCPTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 430F6AC58F7A56E9666194E84BA8C870 /* TCPTransport.swift */; }; + 7DDEA2F73F2A02D88D5164B46BA2C7E8 /* HTTPHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4928D4555D3EC334CA09A3D4B1BCBF1 /* HTTPHandler.swift */; }; 915ABE9F9D29D5D19F91A3BA1F272308 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73010CC983E3809BECEE5348DA1BB8C6 /* Foundation.framework */; }; - A34605EDA9C0B45A4E5008A271FD66BF /* Starscream-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = BBA7AD2E9ED46E28309E566D9FDC8248 /* Starscream-dummy.m */; }; A7F27212C7EB02BEB996BB85C98BE617 /* Pods-AppSyncRTCSample-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3373D970568188F6E29D4F8539662D39 /* Pods-AppSyncRTCSample-dummy.m */; }; A8EAF14B207AE4C294CA58685ABB6732 /* Pods-HostApp-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F2B4F08C3A443D450276C13458D68AB6 /* Pods-HostApp-dummy.m */; }; + B44349C69B2C0AF407B678B20DC9CB80 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = E52E884C35FE76A1139F42B05359CBC8 /* WebSocket.swift */; }; B9F1DD6721C5382B740DBF787B1C44D2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73010CC983E3809BECEE5348DA1BB8C6 /* Foundation.framework */; }; - DC3F116608C7363FA8F324825531DBAF /* SSLClientCertificate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A48FDDC89EBF8BAACA903343467D8E1F /* SSLClientCertificate.swift */; }; + BB056B9351B1BE41C2703393F69623DD /* WSEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = F07B207CD9F5DF97C2D649C58C619BB7 /* WSEngine.swift */; }; + C28A0006DD1C9AB062763C8FA2B3F93D /* NativeEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 410F41433B29C461DFD54BA9C49BF969 /* NativeEngine.swift */; }; + CC235941F0CF9FA8C0FA3323A0D18203 /* Framer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 69F2E8B7282AAD5139A14336728C9E95 /* Framer.swift */; }; DF66036EB14110A1888BD21CF6E5BE36 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73010CC983E3809BECEE5348DA1BB8C6 /* Foundation.framework */; }; + DF9BE4B3E95B007977780C9EFDA3EFBE /* Server.swift in Sources */ = {isa = PBXBuildFile; fileRef = C93067B8AD37A0C00AAF87778D10345F /* Server.swift */; }; + DFA2736CE4B16FD4D82450863EC58507 /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 737C74188FDC06A159452694C664B9EB /* Compression.swift */; }; E7074F52082307357FCAFDE840F3766B /* Pods-AppSyncRealTimeClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 5D60DBE52907CF3F1DF21E45E2C42E31 /* Pods-AppSyncRealTimeClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - EAE36B169874CBCA6F497D4A8B6B2E9D /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 73010CC983E3809BECEE5348DA1BB8C6 /* Foundation.framework */; }; + EB5C3537AD21658D3EC873A4A4AFDE30 /* FrameCollector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8637F2372A3F1500A725E0B3C2995DCA /* FrameCollector.swift */; }; F581C39CCBD6F9B56C65E6313E8D8FE8 /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = BE523AB6A5CF6415A6351FEC601ECA29 /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + FA2A3CCAE01CF0108D2FDB7C8108B988 /* WSCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = D95211B402A2EAC0FC7A03B6A757D124 /* WSCompression.swift */; }; + FAFD54F649DC5D69DD05D517A0131968 /* Engine.swift in Sources */ = {isa = PBXBuildFile; fileRef = A51034B0C6D96B4EACD015A210B238E5 /* Engine.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 2BFDD10FB6D0121AE6041BF9567A9B4E /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; - remoteInfo = Starscream; - }; - 4197106B2F2CDABDA89ACF8B4B02CFEA /* PBXContainerItemProxy */ = { + 06BB8ADDB6B27DD8A727DA13C2091908 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; remoteGlobalIDString = 52B60EC2A583F24ACBB69C113F5488B9; remoteInfo = SwiftLint; }; - 4CB6C670E838BF4EE4821CD9A0B10590 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 1CD0618C486973D5588EF20D2E8C0AEA; - remoteInfo = SwiftFormat; - }; - 4F167634D11F49E6A90F0FE70235B484 /* PBXContainerItemProxy */ = { + 09B2D7C1F2B55E4A125AF24657E2EFB1 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = 52B60EC2A583F24ACBB69C113F5488B9; - remoteInfo = SwiftLint; + remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; + remoteInfo = Starscream; }; - 52FEA08B206EF733CFB98D8BAB06C2DA /* PBXContainerItemProxy */ = { + 4E1BAB69CEE845D714318CA2A7066F4A /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; remoteInfo = Starscream; }; - 5A4BE8F66AA3773E4661141DF9A63ACF /* PBXContainerItemProxy */ = { + 56098D93FCA28F09DBFCC3DCFF662327 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; remoteGlobalIDString = 1CD0618C486973D5588EF20D2E8C0AEA; remoteInfo = SwiftFormat; }; - 6103614F981A63AE0D7B00AD467E2D2F /* PBXContainerItemProxy */ = { + 5CE5E0F974526340626EC7D75595E4E0 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; remoteInfo = Starscream; }; - 7021EDD89DBA954F6A2B37F86EF4E3F1 /* PBXContainerItemProxy */ = { + 5E72E41C284670928C742C9E29B2FDF5 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = 52B60EC2A583F24ACBB69C113F5488B9; - remoteInfo = SwiftLint; + remoteGlobalIDString = 1CD0618C486973D5588EF20D2E8C0AEA; + remoteInfo = SwiftFormat; }; - 76F576EC57EC3F3F4CC4D723ABBDBD1B /* PBXContainerItemProxy */ = { + 5EE800E8F6DEB44F2A75FED3E4E91F5B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; remoteGlobalIDString = 52B60EC2A583F24ACBB69C113F5488B9; remoteInfo = SwiftLint; }; - 7E6CB4560B5FA146A94778385149F9E8 /* PBXContainerItemProxy */ = { + 60EE22495C2A80B673CF4A59B1793E7D /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 1CD0618C486973D5588EF20D2E8C0AEA; + remoteInfo = SwiftFormat; + }; + 862B4B92298ED5F63A5C8737BF57D389 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; remoteGlobalIDString = 9B78EE4AF6AE03E79D88886319853FF7; remoteInfo = Starscream; }; - A06A0AB918732028CCDCE6D39BF146D0 /* PBXContainerItemProxy */ = { + B916E8066AE5CDA0E7549B206D4471B4 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; - remoteGlobalIDString = 1CD0618C486973D5588EF20D2E8C0AEA; - remoteInfo = SwiftFormat; + remoteGlobalIDString = 52B60EC2A583F24ACBB69C113F5488B9; + remoteInfo = SwiftLint; + }; + EE43AF49FAD18350DD69F4E4FCB87B0F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 52B60EC2A583F24ACBB69C113F5488B9; + remoteInfo = SwiftLint; }; - E547DBAB0736761F0A8DBED0F1AC60B2 /* PBXContainerItemProxy */ = { + F16074CA1F08041DB4A55FBAB3C22734 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; proxyType = 1; @@ -140,75 +156,99 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 03F7A3276C90DB9432B2403BBB9D2A53 /* FoundationSecurity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationSecurity.swift; path = Sources/Security/FoundationSecurity.swift; sourceTree = ""; }; + 06E916A4A690DF0DC02232C9ADED6449 /* Starscream-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-prefix.pch"; sourceTree = ""; }; 0C41223EE05E190DCA6549742F79399F /* Pods-AppSyncRTCSample.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AppSyncRTCSample.release.xcconfig"; sourceTree = ""; }; + 0EF5DA51A97FC4F9DAAED71CDF57C28F /* Security.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Security.swift; path = Sources/Security/Security.swift; sourceTree = ""; }; 1284AD0EE24AA15C7A4B36DE6C0D68DF /* Pods-AppSyncRTCSample-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AppSyncRTCSample-Info.plist"; sourceTree = ""; }; 134863EA1590459334B2B7F49710897A /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests.modulemap"; sourceTree = ""; }; 174519BFBCA8DC0E354AF1AB53B8650C /* Pods-HostApp.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-HostApp.debug.xcconfig"; sourceTree = ""; }; + 180B214D60505BCE759982E83FF77C8E /* FoundationHTTPServerHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationHTTPServerHandler.swift; path = Sources/Framer/FoundationHTTPServerHandler.swift; sourceTree = ""; }; + 1977BE05FF5EEAE30BE41581CE1CCFE0 /* Starscream.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Starscream.modulemap; sourceTree = ""; }; + 1E6FB18A133A55AEF2676257477E2BC6 /* SwiftFormat.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftFormat.release.xcconfig; sourceTree = ""; }; 221CD347554C6C8B635BA329F2FDF08C /* Pods-AppSyncRTCSample-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-AppSyncRTCSample-acknowledgements.markdown"; sourceTree = ""; }; 22A29C08E1F2879B5F40B9272E98D7BD /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests"; path = Pods_AppSyncRealTimeClient_AppSyncRealTimeClientTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 2A947351534CF9D7856A449AE01F152E /* SwiftFormat.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftFormat.debug.xcconfig; sourceTree = ""; }; - 2AB2A2EACBA8232618B778F3D716F73B /* Starscream-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-umbrella.h"; sourceTree = ""; }; - 2F28DAB03D13E2DB358720BF598A01B2 /* SwiftLint.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftLint.release.xcconfig; sourceTree = ""; }; 3373D970568188F6E29D4F8539662D39 /* Pods-AppSyncRTCSample-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-AppSyncRTCSample-dummy.m"; sourceTree = ""; }; 384E50D5E1B9FB176E1B375894858BB8 /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests-acknowledgements.plist"; sourceTree = ""; }; - 3A3A6CAF9CDDDDE7C829ABB4E8F31286 /* Starscream.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.debug.xcconfig; sourceTree = ""; }; - 3F57F11E3F0E636BB8BCCDE46C9A4B05 /* Starscream-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-prefix.pch"; sourceTree = ""; }; + 3AF18D51FCC99A1CE4E23F9DAA637E43 /* Starscream-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Starscream-dummy.m"; sourceTree = ""; }; 3FD3D578DE7FE4DE0500419C58D45EB7 /* Pods-HostApp.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-HostApp.release.xcconfig"; sourceTree = ""; }; 401F1B9DD1981C661B6D0C6BCAD21EBC /* Pods-AppSyncRealTimeClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-AppSyncRealTimeClient.modulemap"; sourceTree = ""; }; + 410F41433B29C461DFD54BA9C49BF969 /* NativeEngine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NativeEngine.swift; path = Sources/Engine/NativeEngine.swift; sourceTree = ""; }; 41141221B9F35AB6921FEC6590D21FCD /* Pods-AppSyncRTCSample-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AppSyncRTCSample-acknowledgements.plist"; sourceTree = ""; }; 422F3A44E627544820F8ABE6B3970EB8 /* Pods-AppSyncRealTimeClient.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AppSyncRealTimeClient.release.xcconfig"; sourceTree = ""; }; + 430F6AC58F7A56E9666194E84BA8C870 /* TCPTransport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TCPTransport.swift; path = Sources/Transport/TCPTransport.swift; sourceTree = ""; }; + 4F5A03BCFF1BC81AACCA8C32725AD401 /* WebSocketServer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocketServer.swift; path = Sources/Server/WebSocketServer.swift; sourceTree = ""; }; 53FD200EDC1B7F726E251F28FC00588D /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests"; path = Pods_HostApp_AppSyncRealTimeClientIntegrationTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 5D60DBE52907CF3F1DF21E45E2C42E31 /* Pods-AppSyncRealTimeClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-AppSyncRealTimeClient-umbrella.h"; sourceTree = ""; }; 5F0C8E5464C79B978332043AB7396F39 /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-Info.plist"; sourceTree = ""; }; 632521D0E4C043F74AA5493B36ADF45A /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-dummy.m"; sourceTree = ""; }; 6872C6E03EEA24905C6813A477B6C3B3 /* Pods-AppSyncRealTimeClient */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-AppSyncRealTimeClient"; path = Pods_AppSyncRealTimeClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 69F2E8B7282AAD5139A14336728C9E95 /* Framer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Framer.swift; path = Sources/Framer/Framer.swift; sourceTree = ""; }; 6BB605CE4D267DC8F407AF63D9AC8A95 /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests-Info.plist"; sourceTree = ""; }; 6ECF0AAE9F323948CD48B3C3A6738380 /* Pods-AppSyncRTCSample.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AppSyncRTCSample.debug.xcconfig"; sourceTree = ""; }; 73010CC983E3809BECEE5348DA1BB8C6 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 737C74188FDC06A159452694C664B9EB /* Compression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Compression.swift; path = Sources/Compression/Compression.swift; sourceTree = ""; }; + 7C6D0498CE9448A64BAE886552FCCD6B /* FoundationTransport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationTransport.swift; path = Sources/Transport/FoundationTransport.swift; sourceTree = ""; }; 82393BF234D31DE622FCE3F0A6D81DA8 /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests.modulemap"; sourceTree = ""; }; 856119884A110C4AE532855C4B44D973 /* Pods-HostApp-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-HostApp-acknowledgements.plist"; sourceTree = ""; }; + 8637F2372A3F1500A725E0B3C2995DCA /* FrameCollector.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FrameCollector.swift; path = Sources/Framer/FrameCollector.swift; sourceTree = ""; }; 891B2270823847ED23F2ECFC28F935EC /* Starscream */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Starscream; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 896A3130F1A9D03870F893C98B5FEE26 /* Starscream.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.release.xcconfig; sourceTree = ""; }; + 8E6E2E9C7E9DC8FAA7C03E83452794FB /* FoundationHTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FoundationHTTPHandler.swift; path = Sources/Framer/FoundationHTTPHandler.swift; sourceTree = ""; }; + 8FBFA4F497BF24BAB2C3C2C46831CA0A /* Starscream-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Starscream-umbrella.h"; sourceTree = ""; }; 926BDB89A966BBC606CD53BA1871E433 /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests-dummy.m"; sourceTree = ""; }; 93350F2DBE11F1A905B9BD37B2342670 /* Pods-AppSyncRTCSample.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-AppSyncRTCSample.modulemap"; sourceTree = ""; }; 9783F8F2B1F7890527BA035E5948BCE2 /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests-umbrella.h"; sourceTree = ""; }; 98EB4862848E26D52F6F6A7A071C1558 /* Pods-HostApp-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-HostApp-Info.plist"; sourceTree = ""; }; 990B73CD5CFE370366BE39253FBC1AC3 /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-acknowledgements.plist"; sourceTree = ""; }; 999D7A0732B0168D9EB631C456DEC8A3 /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests.release.xcconfig"; sourceTree = ""; }; + 9B273836AFE7E07EE713B29F94B54285 /* Starscream.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.release.xcconfig; sourceTree = ""; }; + 9D2BCC3D81009251CF149E4E6A0C224E /* StringHTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StringHTTPHandler.swift; path = Sources/Framer/StringHTTPHandler.swift; sourceTree = ""; }; 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; 9FF7D529C51D3F1B0D444B08C40EE3AD /* Pods-AppSyncRTCSample-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-AppSyncRTCSample-frameworks.sh"; sourceTree = ""; }; A26BD722B33E83A41BD4A44DD2BDC4E3 /* Pods-AppSyncRTCSample-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-AppSyncRTCSample-umbrella.h"; sourceTree = ""; }; A31447240FB4AA22B5D3E1287DAF4DCB /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests-acknowledgements.markdown"; sourceTree = ""; }; - A48FDDC89EBF8BAACA903343467D8E1F /* SSLClientCertificate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SSLClientCertificate.swift; path = Sources/Starscream/SSLClientCertificate.swift; sourceTree = ""; }; - A60B99DD561DFB67C1C8C906CAB2C062 /* SwiftLint.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftLint.debug.xcconfig; sourceTree = ""; }; + A51034B0C6D96B4EACD015A210B238E5 /* Engine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Engine.swift; path = Sources/Engine/Engine.swift; sourceTree = ""; }; + A7D3E7A9A95C8813B014F9E13BCC1168 /* Starscream-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Starscream-Info.plist"; sourceTree = ""; }; + A9735D953EBECD0EBC3C1D3EC8BCAFFC /* Starscream.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Starscream.debug.xcconfig; sourceTree = ""; }; AAA4F28117B314B9CF3F58B0C87EBE67 /* Pods-HostApp-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-HostApp-umbrella.h"; sourceTree = ""; }; AB0D09B888F2E45FB8F12D91368DEB24 /* Pods-AppSyncRealTimeClient-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-AppSyncRealTimeClient-acknowledgements.markdown"; sourceTree = ""; }; B0E3C9706DBD9CF2465CBA4F7DB2934A /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-frameworks.sh"; sourceTree = ""; }; B50EC21E064304AF394DE66ABDF70559 /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests.debug.xcconfig"; sourceTree = ""; }; - BBA7AD2E9ED46E28309E566D9FDC8248 /* Starscream-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Starscream-dummy.m"; sourceTree = ""; }; + BAFA07304E0D95CA475D728B2BA434B6 /* Data+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Data+Extensions.swift"; path = "Sources/DataBytes/Data+Extensions.swift"; sourceTree = ""; }; BDD999664B0D6248CA38728B4D9F5678 /* Pods-HostApp.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-HostApp.modulemap"; sourceTree = ""; }; - BE42DB590EDA5163FCF669957D4095D2 /* SSLSecurity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SSLSecurity.swift; path = Sources/Starscream/SSLSecurity.swift; sourceTree = ""; }; BE523AB6A5CF6415A6351FEC601ECA29 /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-umbrella.h"; sourceTree = ""; }; - BE599E071F98B60A2F95AEB05BFDB52F /* Compression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Compression.swift; path = Sources/Starscream/Compression.swift; sourceTree = ""; }; C2E044D620E53BF3DADA20B55291DB1E /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests-acknowledgements.markdown"; sourceTree = ""; }; + C4928D4555D3EC334CA09A3D4B1BCBF1 /* HTTPHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HTTPHandler.swift; path = Sources/Framer/HTTPHandler.swift; sourceTree = ""; }; + C56CA9A1C0E06E53913BBA31CEE13A31 /* SwiftLint.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftLint.debug.xcconfig; sourceTree = ""; }; C5D92A24D6DBC95BE97867525C82CA97 /* Pods-AppSyncRTCSample */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-AppSyncRTCSample"; path = Pods_AppSyncRTCSample.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - C7BD941BFE1AF5C140BFF017EFE3039E /* Starscream.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Starscream.modulemap; sourceTree = ""; }; + C93067B8AD37A0C00AAF87778D10345F /* Server.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Server.swift; path = Sources/Server/Server.swift; sourceTree = ""; }; CBD288DBC23116B89AEE85DE391FA5F1 /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests.release.xcconfig"; sourceTree = ""; }; CCC7535D1826737BD1D1A1C73494A875 /* Pods-AppSyncRealTimeClient-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AppSyncRealTimeClient-acknowledgements.plist"; sourceTree = ""; }; - D1E3710DBCB77E7FD324B150464A090B /* WebSocket.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Sources/Starscream/WebSocket.swift; sourceTree = ""; }; D511F2F371791B10D304FB282E85D15A /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests-frameworks.sh"; sourceTree = ""; }; D5297297949960DF1F2C453F5D4E7034 /* Pods-AppSyncRealTimeClient-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AppSyncRealTimeClient-Info.plist"; sourceTree = ""; }; D5E492CC0BF640273F329A4B0F8C322E /* Pods-HostApp-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-HostApp-acknowledgements.markdown"; sourceTree = ""; }; - E8910A0533C9BA321BE04437CEC1CB9F /* Starscream-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Starscream-Info.plist"; sourceTree = ""; }; + D95211B402A2EAC0FC7A03B6A757D124 /* WSCompression.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WSCompression.swift; path = Sources/Compression/WSCompression.swift; sourceTree = ""; }; + D999E258E54C8B9C1FD75659EC9F1DFA /* SwiftFormat.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftFormat.debug.xcconfig; sourceTree = ""; }; + DFAB773151BA1C1F2F4B68EBDE223BA5 /* SwiftLint.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftLint.release.xcconfig; sourceTree = ""; }; + E52E884C35FE76A1139F42B05359CBC8 /* WebSocket.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WebSocket.swift; path = Sources/Starscream/WebSocket.swift; sourceTree = ""; }; ED00F87B053026A542BE85D0CA39F88F /* Pods-HostApp */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-HostApp"; path = Pods_HostApp.framework; sourceTree = BUILT_PRODUCTS_DIR; }; EF215971A0AC1B1AFAF6E20BC75399E3 /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests.debug.xcconfig"; sourceTree = ""; }; - EFD4AB4803A3ECFFC0F0004E612F5A3F /* SwiftFormat.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftFormat.release.xcconfig; sourceTree = ""; }; + F07B207CD9F5DF97C2D649C58C619BB7 /* WSEngine.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WSEngine.swift; path = Sources/Engine/WSEngine.swift; sourceTree = ""; }; F2B4F08C3A443D450276C13458D68AB6 /* Pods-HostApp-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-HostApp-dummy.m"; sourceTree = ""; }; + F2CAEC3C9FC0A8AD7BE1DAB6A521D691 /* Transport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Transport.swift; path = Sources/Transport/Transport.swift; sourceTree = ""; }; FA2FBC1398CA557C7C4333EBDF94EB76 /* Pods-AppSyncRealTimeClient.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AppSyncRealTimeClient.debug.xcconfig"; sourceTree = ""; }; FA724FB4539BE70535E32D6B51B233CF /* Pods-AppSyncRealTimeClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-AppSyncRealTimeClient-dummy.m"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ + 22579CC44F871C4C542FC182B991B33C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 33C71989B6C635864EC5E4862AFAAE8A /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 37FAB413DB00C18A2E0311B4D786BF98 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -249,69 +289,56 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - E7E3F8390AB5C3382669377B65C5F561 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - EAE36B169874CBCA6F497D4A8B6B2E9D /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 04ADB7C9D15B5E9F6D776740EC22E056 /* Support Files */ = { - isa = PBXGroup; - children = ( - A60B99DD561DFB67C1C8C906CAB2C062 /* SwiftLint.debug.xcconfig */, - 2F28DAB03D13E2DB358720BF598A01B2 /* SwiftLint.release.xcconfig */, - ); - name = "Support Files"; - path = "../Target Support Files/SwiftLint"; - sourceTree = ""; - }; - 186EB39D03FC294015E85A5714AEEAE9 /* Support Files */ = { + 120316207F6661A29A01BB8F9BBEF8F1 /* Support Files */ = { isa = PBXGroup; children = ( - C7BD941BFE1AF5C140BFF017EFE3039E /* Starscream.modulemap */, - BBA7AD2E9ED46E28309E566D9FDC8248 /* Starscream-dummy.m */, - E8910A0533C9BA321BE04437CEC1CB9F /* Starscream-Info.plist */, - 3F57F11E3F0E636BB8BCCDE46C9A4B05 /* Starscream-prefix.pch */, - 2AB2A2EACBA8232618B778F3D716F73B /* Starscream-umbrella.h */, - 3A3A6CAF9CDDDDE7C829ABB4E8F31286 /* Starscream.debug.xcconfig */, - 896A3130F1A9D03870F893C98B5FEE26 /* Starscream.release.xcconfig */, + D999E258E54C8B9C1FD75659EC9F1DFA /* SwiftFormat.debug.xcconfig */, + 1E6FB18A133A55AEF2676257477E2BC6 /* SwiftFormat.release.xcconfig */, ); name = "Support Files"; - path = "../Target Support Files/Starscream"; - sourceTree = ""; - }; - 233CF0CD50DA3436E677DB0F4F73599B /* Pods */ = { - isa = PBXGroup; - children = ( - F39E8EF742FB51F1D709840B8AB241FE /* Starscream */, - 8D632796E9EAD04F4802326A1C59D701 /* SwiftFormat */, - 29972EF3796BE36BC11E508DAF94D5E3 /* SwiftLint */, - ); - name = Pods; + path = "../Target Support Files/SwiftFormat"; sourceTree = ""; }; - 29972EF3796BE36BC11E508DAF94D5E3 /* SwiftLint */ = { + 135C75D207DA61D8FCE4C40905592B0D /* Starscream */ = { isa = PBXGroup; children = ( - 04ADB7C9D15B5E9F6D776740EC22E056 /* Support Files */, + 737C74188FDC06A159452694C664B9EB /* Compression.swift */, + BAFA07304E0D95CA475D728B2BA434B6 /* Data+Extensions.swift */, + A51034B0C6D96B4EACD015A210B238E5 /* Engine.swift */, + 8E6E2E9C7E9DC8FAA7C03E83452794FB /* FoundationHTTPHandler.swift */, + 180B214D60505BCE759982E83FF77C8E /* FoundationHTTPServerHandler.swift */, + 03F7A3276C90DB9432B2403BBB9D2A53 /* FoundationSecurity.swift */, + 7C6D0498CE9448A64BAE886552FCCD6B /* FoundationTransport.swift */, + 8637F2372A3F1500A725E0B3C2995DCA /* FrameCollector.swift */, + 69F2E8B7282AAD5139A14336728C9E95 /* Framer.swift */, + C4928D4555D3EC334CA09A3D4B1BCBF1 /* HTTPHandler.swift */, + 410F41433B29C461DFD54BA9C49BF969 /* NativeEngine.swift */, + 0EF5DA51A97FC4F9DAAED71CDF57C28F /* Security.swift */, + C93067B8AD37A0C00AAF87778D10345F /* Server.swift */, + 9D2BCC3D81009251CF149E4E6A0C224E /* StringHTTPHandler.swift */, + 430F6AC58F7A56E9666194E84BA8C870 /* TCPTransport.swift */, + F2CAEC3C9FC0A8AD7BE1DAB6A521D691 /* Transport.swift */, + E52E884C35FE76A1139F42B05359CBC8 /* WebSocket.swift */, + 4F5A03BCFF1BC81AACCA8C32725AD401 /* WebSocketServer.swift */, + D95211B402A2EAC0FC7A03B6A757D124 /* WSCompression.swift */, + F07B207CD9F5DF97C2D649C58C619BB7 /* WSEngine.swift */, + 83681F15B53C4D30045511A41B8A97FD /* Support Files */, ); - name = SwiftLint; - path = SwiftLint; + name = Starscream; + path = Starscream; sourceTree = ""; }; - 41EFB1839E64D5AF588645193659C5EF /* Support Files */ = { + 37E4C763E3D1AD54AEBD3E13FA588594 /* Support Files */ = { isa = PBXGroup; children = ( - 2A947351534CF9D7856A449AE01F152E /* SwiftFormat.debug.xcconfig */, - EFD4AB4803A3ECFFC0F0004E612F5A3F /* SwiftFormat.release.xcconfig */, + C56CA9A1C0E06E53913BBA31CEE13A31 /* SwiftLint.debug.xcconfig */, + DFAB773151BA1C1F2F4B68EBDE223BA5 /* SwiftLint.release.xcconfig */, ); name = "Support Files"; - path = "../Target Support Files/SwiftFormat"; + path = "../Target Support Files/SwiftLint"; sourceTree = ""; }; 578452D2E740E91742655AC8F1636D1F /* iOS */ = { @@ -334,6 +361,21 @@ name = "Targets Support Files"; sourceTree = ""; }; + 83681F15B53C4D30045511A41B8A97FD /* Support Files */ = { + isa = PBXGroup; + children = ( + 1977BE05FF5EEAE30BE41581CE1CCFE0 /* Starscream.modulemap */, + 3AF18D51FCC99A1CE4E23F9DAA637E43 /* Starscream-dummy.m */, + A7D3E7A9A95C8813B014F9E13BCC1168 /* Starscream-Info.plist */, + 06E916A4A690DF0DC02232C9ADED6449 /* Starscream-prefix.pch */, + 8FBFA4F497BF24BAB2C3C2C46831CA0A /* Starscream-umbrella.h */, + A9735D953EBECD0EBC3C1D3EC8BCAFFC /* Starscream.debug.xcconfig */, + 9B273836AFE7E07EE713B29F94B54285 /* Starscream.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Starscream"; + sourceTree = ""; + }; 89A54FC8336E04DA8E84DCCA071461BB /* Pods-HostApp-AppSyncRealTimeClientIntegrationTests */ = { isa = PBXGroup; children = ( @@ -364,15 +406,6 @@ name = Products; sourceTree = ""; }; - 8D632796E9EAD04F4802326A1C59D701 /* SwiftFormat */ = { - isa = PBXGroup; - children = ( - 41EFB1839E64D5AF588645193659C5EF /* Support Files */, - ); - name = SwiftFormat; - path = SwiftFormat; - sourceTree = ""; - }; 93C6AFA96F7A396B4BC6BA11FAFA0E9C /* Pods-AppSyncRealTimeClient */ = { isa = PBXGroup; children = ( @@ -405,6 +438,15 @@ path = "Target Support Files/Pods-HostApp"; sourceTree = ""; }; + AAA1AE0C8BA120688EB23A3811F5E707 /* SwiftLint */ = { + isa = PBXGroup; + children = ( + 37E4C763E3D1AD54AEBD3E13FA588594 /* Support Files */, + ); + name = SwiftLint; + path = SwiftLint; + sourceTree = ""; + }; BA797455DAF286AA31DC0221F4F9071B /* Pods-AppSyncRTCSample */ = { isa = PBXGroup; children = ( @@ -422,12 +464,21 @@ path = "Target Support Files/Pods-AppSyncRTCSample"; sourceTree = ""; }; + CC045C9E62BD56A7F27C6D40B5E97D02 /* SwiftFormat */ = { + isa = PBXGroup; + children = ( + 120316207F6661A29A01BB8F9BBEF8F1 /* Support Files */, + ); + name = SwiftFormat; + path = SwiftFormat; + sourceTree = ""; + }; CF1408CF629C7361332E53B88F7BD30C = { isa = PBXGroup; children = ( 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, D210D550F4EA176C3123ED886F8F87F5 /* Frameworks */, - 233CF0CD50DA3436E677DB0F4F73599B /* Pods */, + D6B6D7C366E1E52F2D52D3CEACEB71E7 /* Pods */, 8A037C2DC441AE19C037C749BCBA7C8A /* Products */, 624D60885F96B9E644F9EF942F6722A5 /* Targets Support Files */, ); @@ -441,6 +492,16 @@ name = Frameworks; sourceTree = ""; }; + D6B6D7C366E1E52F2D52D3CEACEB71E7 /* Pods */ = { + isa = PBXGroup; + children = ( + 135C75D207DA61D8FCE4C40905592B0D /* Starscream */, + CC045C9E62BD56A7F27C6D40B5E97D02 /* SwiftFormat */, + AAA1AE0C8BA120688EB23A3811F5E707 /* SwiftLint */, + ); + name = Pods; + sourceTree = ""; + }; D88C2EDA1D194276526451EE816A0411 /* Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests */ = { isa = PBXGroup; children = ( @@ -458,19 +519,6 @@ path = "Target Support Files/Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests"; sourceTree = ""; }; - F39E8EF742FB51F1D709840B8AB241FE /* Starscream */ = { - isa = PBXGroup; - children = ( - BE599E071F98B60A2F95AEB05BFDB52F /* Compression.swift */, - A48FDDC89EBF8BAACA903343467D8E1F /* SSLClientCertificate.swift */, - BE42DB590EDA5163FCF669957D4095D2 /* SSLSecurity.swift */, - D1E3710DBCB77E7FD324B150464A090B /* WebSocket.swift */, - 186EB39D03FC294015E85A5714AEEAE9 /* Support Files */, - ); - name = Starscream; - path = Starscream; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXHeadersBuildPhase section */ @@ -482,11 +530,11 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - 0CABD434215470CF9FC65C8D206CE5C2 /* Headers */ = { + 3CBD0F9C48772E87C2F80436B70E099E /* Headers */ = { isa = PBXHeadersBuildPhase; buildActionMask = 2147483647; files = ( - 56424C2C9CD0BC9AD2E7ACC7E94CC8B1 /* Starscream-umbrella.h in Headers */, + 00C9C2E54995B3BEA1C999016833A58B /* Starscream-umbrella.h in Headers */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -537,9 +585,9 @@ buildRules = ( ); dependencies = ( - 2A470EAEAD34C67DAC9C1EB3F2269858 /* PBXTargetDependency */, - 6CEAE042D170863940F0389A91E52696 /* PBXTargetDependency */, - 1AE28277A80FC2CA6DDFD21C14215EE8 /* PBXTargetDependency */, + A39DAEEEF1AE8225597415A38BB5FF63 /* PBXTargetDependency */, + 18DE0F11690F08A3777547966BDC3039 /* PBXTargetDependency */, + AAAEC904946AC8ACBA6EC282B2C5526D /* PBXTargetDependency */, ); name = "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests"; productName = Pods_AppSyncRealTimeClient_AppSyncRealTimeClientTests; @@ -576,9 +624,9 @@ buildRules = ( ); dependencies = ( - D77A8BC0D5692CC056EBE2F57D26D31A /* PBXTargetDependency */, - 05912E3E7963C907B7CD086A46C760DB /* PBXTargetDependency */, - 795F862B2B2A056E260A646C327E4C65 /* PBXTargetDependency */, + 50FF195B0516037C88D626A9853D7713 /* PBXTargetDependency */, + 0B525E8757E6CA36B2703BEA3844655A /* PBXTargetDependency */, + 16B8FEF86C17F058C7F7AF2E13757CAC /* PBXTargetDependency */, ); name = "Pods-AppSyncRTCSample"; productName = Pods_AppSyncRTCSample; @@ -597,9 +645,9 @@ buildRules = ( ); dependencies = ( - 4F397B2E3566489F3320976A76E920AC /* PBXTargetDependency */, - 636C30E8A0DEE8833A0C8F1764A4F169 /* PBXTargetDependency */, - F3B4B256E762C1C30F99C9D1EB13BF82 /* PBXTargetDependency */, + F6395EE8939D653684CD10CEFF01DCAE /* PBXTargetDependency */, + FFA5650287A25891EF030A97F2EB28C9 /* PBXTargetDependency */, + DC319EC4A174CDC315D80378A5C28B30 /* PBXTargetDependency */, ); name = "Pods-HostApp-AppSyncRealTimeClientIntegrationTests"; productName = Pods_HostApp_AppSyncRealTimeClientIntegrationTests; @@ -618,9 +666,9 @@ buildRules = ( ); dependencies = ( - 36920C3DE2CCAFD7C71B9757180766D1 /* PBXTargetDependency */, - C221070588C0FEA0D18483C51A580442 /* PBXTargetDependency */, - 2DE486B9EE24D14B76E4451BF68C4824 /* PBXTargetDependency */, + 9D501468C8D35CAA9F50DDCD920DBFC1 /* PBXTargetDependency */, + 44AE4800F55BE63A267A21680DB9322D /* PBXTargetDependency */, + E7366048951920E7C08A15F36932050A /* PBXTargetDependency */, ); name = "Pods-AppSyncRealTimeClient"; productName = Pods_AppSyncRealTimeClient; @@ -629,12 +677,12 @@ }; 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */ = { isa = PBXNativeTarget; - buildConfigurationList = 14D7B821FD04F6513C0EFC8A1351C0C1 /* Build configuration list for PBXNativeTarget "Starscream" */; + buildConfigurationList = 5E342B11DDD91D2A8D5CEC382A58F29D /* Build configuration list for PBXNativeTarget "Starscream" */; buildPhases = ( - 0CABD434215470CF9FC65C8D206CE5C2 /* Headers */, - FA9B3B41849F26B72514ABEA7806A3B0 /* Sources */, - E7E3F8390AB5C3382669377B65C5F561 /* Frameworks */, - AEB48D90B0A78846E9B025489EF4C228 /* Resources */, + 3CBD0F9C48772E87C2F80436B70E099E /* Headers */, + 3CBD844312542615DF274F62D22D823A /* Sources */, + 22579CC44F871C4C542FC182B991B33C /* Frameworks */, + 6D93F8ECBEC0B1B601F31CAB9D03FAA2 /* Resources */, ); buildRules = ( ); @@ -687,14 +735,14 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - A8A642146702F3A9E14355D4ADFDA411 /* Resources */ = { + 6D93F8ECBEC0B1B601F31CAB9D03FAA2 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; - AEB48D90B0A78846E9B025489EF4C228 /* Resources */ = { + A8A642146702F3A9E14355D4ADFDA411 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( @@ -725,6 +773,34 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 3CBD844312542615DF274F62D22D823A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + DFA2736CE4B16FD4D82450863EC58507 /* Compression.swift in Sources */, + 631654C419F62FE0270E1DF79CCF6F8B /* Data+Extensions.swift in Sources */, + FAFD54F649DC5D69DD05D517A0131968 /* Engine.swift in Sources */, + 4AB6FCF35B998F60ED9EB100542EEA31 /* FoundationHTTPHandler.swift in Sources */, + 5006DD4B60A05AF56EA0706A680BABF6 /* FoundationHTTPServerHandler.swift in Sources */, + 5281197FE8CC6E6954315F11B8F553D0 /* FoundationSecurity.swift in Sources */, + 489EF4A7D4992C47CF590AEF9AA418FC /* FoundationTransport.swift in Sources */, + EB5C3537AD21658D3EC873A4A4AFDE30 /* FrameCollector.swift in Sources */, + CC235941F0CF9FA8C0FA3323A0D18203 /* Framer.swift in Sources */, + 7DDEA2F73F2A02D88D5164B46BA2C7E8 /* HTTPHandler.swift in Sources */, + C28A0006DD1C9AB062763C8FA2B3F93D /* NativeEngine.swift in Sources */, + 69A591F2BDE4941B391C102F4C26B115 /* Security.swift in Sources */, + DF9BE4B3E95B007977780C9EFDA3EFBE /* Server.swift in Sources */, + 3A655D6817E99F062266BB601B0EEEDF /* Starscream-dummy.m in Sources */, + 046AC7AA224C78A31C0A8FACB11D2D28 /* StringHTTPHandler.swift in Sources */, + 6C0DACBE00A34619DEDB9A65CB959BA5 /* TCPTransport.swift in Sources */, + 4A3B1BE129FDA231AC217E1C6DB2B8C8 /* Transport.swift in Sources */, + B44349C69B2C0AF407B678B20DC9CB80 /* WebSocket.swift in Sources */, + 3F3E9C6FF4BCB6F4FF18D9121CC3E42F /* WebSocketServer.swift in Sources */, + FA2A3CCAE01CF0108D2FDB7C8108B988 /* WSCompression.swift in Sources */, + BB056B9351B1BE41C2703393F69623DD /* WSEngine.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 477A612576590171AFD476321816B0D9 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -765,92 +841,80 @@ ); runOnlyForDeploymentPostprocessing = 0; }; - FA9B3B41849F26B72514ABEA7806A3B0 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 3744E502782192EA106AF498FEDB67B9 /* Compression.swift in Sources */, - DC3F116608C7363FA8F324825531DBAF /* SSLClientCertificate.swift in Sources */, - 41CD4D248A99A2FC837BBC73988FF37E /* SSLSecurity.swift in Sources */, - A34605EDA9C0B45A4E5008A271FD66BF /* Starscream-dummy.m in Sources */, - 2318B70F6CB59888B879349F92DE450D /* WebSocket.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 05912E3E7963C907B7CD086A46C760DB /* PBXTargetDependency */ = { + 0B525E8757E6CA36B2703BEA3844655A /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = SwiftFormat; target = 1CD0618C486973D5588EF20D2E8C0AEA /* SwiftFormat */; - targetProxy = E547DBAB0736761F0A8DBED0F1AC60B2 /* PBXContainerItemProxy */; + targetProxy = 60EE22495C2A80B673CF4A59B1793E7D /* PBXContainerItemProxy */; }; - 1AE28277A80FC2CA6DDFD21C14215EE8 /* PBXTargetDependency */ = { + 16B8FEF86C17F058C7F7AF2E13757CAC /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = SwiftLint; target = 52B60EC2A583F24ACBB69C113F5488B9 /* SwiftLint */; - targetProxy = 76F576EC57EC3F3F4CC4D723ABBDBD1B /* PBXContainerItemProxy */; + targetProxy = 5EE800E8F6DEB44F2A75FED3E4E91F5B /* PBXContainerItemProxy */; }; - 2A470EAEAD34C67DAC9C1EB3F2269858 /* PBXTargetDependency */ = { + 18DE0F11690F08A3777547966BDC3039 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = Starscream; - target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; - targetProxy = 6103614F981A63AE0D7B00AD467E2D2F /* PBXContainerItemProxy */; + name = SwiftFormat; + target = 1CD0618C486973D5588EF20D2E8C0AEA /* SwiftFormat */; + targetProxy = 5E72E41C284670928C742C9E29B2FDF5 /* PBXContainerItemProxy */; }; - 2DE486B9EE24D14B76E4451BF68C4824 /* PBXTargetDependency */ = { + 44AE4800F55BE63A267A21680DB9322D /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = SwiftLint; - target = 52B60EC2A583F24ACBB69C113F5488B9 /* SwiftLint */; - targetProxy = 7021EDD89DBA954F6A2B37F86EF4E3F1 /* PBXContainerItemProxy */; + name = SwiftFormat; + target = 1CD0618C486973D5588EF20D2E8C0AEA /* SwiftFormat */; + targetProxy = F16074CA1F08041DB4A55FBAB3C22734 /* PBXContainerItemProxy */; }; - 36920C3DE2CCAFD7C71B9757180766D1 /* PBXTargetDependency */ = { + 50FF195B0516037C88D626A9853D7713 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Starscream; target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; - targetProxy = 7E6CB4560B5FA146A94778385149F9E8 /* PBXContainerItemProxy */; + targetProxy = 5CE5E0F974526340626EC7D75595E4E0 /* PBXContainerItemProxy */; }; - 4F397B2E3566489F3320976A76E920AC /* PBXTargetDependency */ = { + 9D501468C8D35CAA9F50DDCD920DBFC1 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Starscream; target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; - targetProxy = 52FEA08B206EF733CFB98D8BAB06C2DA /* PBXContainerItemProxy */; + targetProxy = 09B2D7C1F2B55E4A125AF24657E2EFB1 /* PBXContainerItemProxy */; }; - 636C30E8A0DEE8833A0C8F1764A4F169 /* PBXTargetDependency */ = { + A39DAEEEF1AE8225597415A38BB5FF63 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = SwiftFormat; - target = 1CD0618C486973D5588EF20D2E8C0AEA /* SwiftFormat */; - targetProxy = 4CB6C670E838BF4EE4821CD9A0B10590 /* PBXContainerItemProxy */; + name = Starscream; + target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; + targetProxy = 4E1BAB69CEE845D714318CA2A7066F4A /* PBXContainerItemProxy */; }; - 6CEAE042D170863940F0389A91E52696 /* PBXTargetDependency */ = { + AAAEC904946AC8ACBA6EC282B2C5526D /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = SwiftFormat; - target = 1CD0618C486973D5588EF20D2E8C0AEA /* SwiftFormat */; - targetProxy = 5A4BE8F66AA3773E4661141DF9A63ACF /* PBXContainerItemProxy */; + name = SwiftLint; + target = 52B60EC2A583F24ACBB69C113F5488B9 /* SwiftLint */; + targetProxy = 06BB8ADDB6B27DD8A727DA13C2091908 /* PBXContainerItemProxy */; }; - 795F862B2B2A056E260A646C327E4C65 /* PBXTargetDependency */ = { + DC319EC4A174CDC315D80378A5C28B30 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = SwiftLint; target = 52B60EC2A583F24ACBB69C113F5488B9 /* SwiftLint */; - targetProxy = 4197106B2F2CDABDA89ACF8B4B02CFEA /* PBXContainerItemProxy */; + targetProxy = EE43AF49FAD18350DD69F4E4FCB87B0F /* PBXContainerItemProxy */; }; - C221070588C0FEA0D18483C51A580442 /* PBXTargetDependency */ = { + E7366048951920E7C08A15F36932050A /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = SwiftFormat; - target = 1CD0618C486973D5588EF20D2E8C0AEA /* SwiftFormat */; - targetProxy = A06A0AB918732028CCDCE6D39BF146D0 /* PBXContainerItemProxy */; + name = SwiftLint; + target = 52B60EC2A583F24ACBB69C113F5488B9 /* SwiftLint */; + targetProxy = B916E8066AE5CDA0E7549B206D4471B4 /* PBXContainerItemProxy */; }; - D77A8BC0D5692CC056EBE2F57D26D31A /* PBXTargetDependency */ = { + F6395EE8939D653684CD10CEFF01DCAE /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = Starscream; target = 9B78EE4AF6AE03E79D88886319853FF7 /* Starscream */; - targetProxy = 2BFDD10FB6D0121AE6041BF9567A9B4E /* PBXContainerItemProxy */; + targetProxy = 862B4B92298ED5F63A5C8737BF57D389 /* PBXContainerItemProxy */; }; - F3B4B256E762C1C30F99C9D1EB13BF82 /* PBXTargetDependency */ = { + FFA5650287A25891EF030A97F2EB28C9 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - name = SwiftLint; - target = 52B60EC2A583F24ACBB69C113F5488B9 /* SwiftLint */; - targetProxy = 4F167634D11F49E6A90F0FE70235B484 /* PBXContainerItemProxy */; + name = SwiftFormat; + target = 1CD0618C486973D5588EF20D2E8C0AEA /* SwiftFormat */; + targetProxy = 56098D93FCA28F09DBFCC3DCFF662327 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -1105,7 +1169,7 @@ }; 8021953E6393470ED3D7F8DD5FD2D6A5 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 2A947351534CF9D7856A449AE01F152E /* SwiftFormat.debug.xcconfig */; + baseConfigurationReference = D999E258E54C8B9C1FD75659EC9F1DFA /* SwiftFormat.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; @@ -1119,6 +1183,40 @@ }; name = Debug; }; + 89DDD25DB9130670FEDC5E0AD0F46AE7 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = A9735D953EBECD0EBC3C1D3EC8BCAFFC /* Starscream.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Starscream/Starscream-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Starscream/Starscream-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Starscream/Starscream.modulemap"; + PRODUCT_MODULE_NAME = Starscream; + PRODUCT_NAME = Starscream; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; 96A1F448F20C32FC078FF22CDFF73BDE /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 174519BFBCA8DC0E354AF1AB53B8650C /* Pods-HostApp.debug.xcconfig */; @@ -1194,7 +1292,7 @@ }; 9E65CF2031BEEA6B85B0C9F11AAAF3C6 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = EFD4AB4803A3ECFFC0F0004E612F5A3F /* SwiftFormat.release.xcconfig */; + baseConfigurationReference = 1E6FB18A133A55AEF2676257477E2BC6 /* SwiftFormat.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; @@ -1246,43 +1344,9 @@ }; name = Release; }; - A31B3E20A31FCEA384670AD38D1747FB /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 3A3A6CAF9CDDDDE7C829ABB4E8F31286 /* Starscream.debug.xcconfig */; - buildSettings = { - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/Starscream/Starscream-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Starscream/Starscream-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MODULEMAP_FILE = "Target Support Files/Starscream/Starscream.modulemap"; - PRODUCT_MODULE_NAME = Starscream; - PRODUCT_NAME = Starscream; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; AD81E62ACCB0B7A923FC8AA288F9921E /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 2F28DAB03D13E2DB358720BF598A01B2 /* SwiftLint.release.xcconfig */; + baseConfigurationReference = DFAB773151BA1C1F2F4B68EBDE223BA5 /* SwiftLint.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; @@ -1396,9 +1460,9 @@ }; name = Release; }; - D05DE4E89B9FCA5D999AA29D2F9E7A32 /* Release */ = { + CC66474D42F4DE32770AC3115C19B7CA /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 896A3130F1A9D03870F893C98B5FEE26 /* Starscream.release.xcconfig */; + baseConfigurationReference = 9B273836AFE7E07EE713B29F94B54285 /* Starscream.release.xcconfig */; buildSettings = { "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; @@ -1469,7 +1533,7 @@ }; EADD1F50ABC8096A0D6CB18822BB4EE4 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = A60B99DD561DFB67C1C8C906CAB2C062 /* SwiftLint.debug.xcconfig */; + baseConfigurationReference = C56CA9A1C0E06E53913BBA31CEE13A31 /* SwiftLint.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; @@ -1495,15 +1559,6 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 14D7B821FD04F6513C0EFC8A1351C0C1 /* Build configuration list for PBXNativeTarget "Starscream" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - A31B3E20A31FCEA384670AD38D1747FB /* Debug */, - D05DE4E89B9FCA5D999AA29D2F9E7A32 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; 446A753797FBF42F388F8ECE017D276B /* Build configuration list for PBXNativeTarget "Pods-AppSyncRealTimeClient-AppSyncRealTimeClientTests" */ = { isa = XCConfigurationList; buildConfigurations = ( @@ -1522,6 +1577,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + 5E342B11DDD91D2A8D5CEC382A58F29D /* Build configuration list for PBXNativeTarget "Starscream" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 89DDD25DB9130670FEDC5E0AD0F46AE7 /* Debug */, + CC66474D42F4DE32770AC3115C19B7CA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 6B2B7DF197DF6A7CA487150557230A41 /* Build configuration list for PBXAggregateTarget "SwiftFormat" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/Pods/Starscream/README.md b/Pods/Starscream/README.md index 90a7e0e6..634723aa 100644 --- a/Pods/Starscream/README.md +++ b/Pods/Starscream/README.md @@ -1,18 +1,15 @@ ![starscream](https://raw.githubusercontent.com/daltoniam/starscream/assets/starscream.jpg) -Starscream is a conforming WebSocket ([RFC 6455](http://tools.ietf.org/html/rfc6455)) client library in Swift. - -Its Objective-C counterpart can be found here: [Jetfire](https://github.com/acmacalister/jetfire) +Starscream is a conforming WebSocket ([RFC 6455](http://tools.ietf.org/html/rfc6455)) library in Swift. ## Features -- Conforms to all of the base [Autobahn test suite](http://autobahn.ws/testsuite/). +- Conforms to all of the base [Autobahn test suite](https://crossbar.io/autobahn/). - Nonblocking. Everything happens in the background, thanks to GCD. - TLS/WSS support. - Compression Extensions support ([RFC 7692](https://tools.ietf.org/html/rfc7692)) -- Simple concise codebase at just a few hundred LOC. -## Example +### Import the framework First thing is to import the framework. See the Installation instructions on how to add the framework to your project. @@ -20,94 +17,65 @@ First thing is to import the framework. See the Installation instructions on how import Starscream ``` +### Connect to the WebSocket Server + Once imported, you can open a connection to your WebSocket server. Note that `socket` is probably best as a property, so it doesn't get deallocated right after being setup. ```swift -socket = WebSocket(url: URL(string: "ws://localhost:8080/")!) +var request = URLRequest(url: URL(string: "http://localhost:8080")!) +request.timeoutInterval = 5 +socket = WebSocket(request: request) socket.delegate = self socket.connect() ``` -After you are connected, there are some delegate methods that we need to implement. - -### websocketDidConnect - -websocketDidConnect is called as soon as the client connects to the server. - -```swift -func websocketDidConnect(socket: WebSocketClient) { - print("websocket is connected") -} -``` - -### websocketDidDisconnect - -websocketDidDisconnect is called as soon as the client is disconnected from the server. - -```swift -func websocketDidDisconnect(socket: WebSocketClient, error: Error?) { - print("websocket is disconnected: \(error?.localizedDescription)") -} -``` - -### websocketDidReceiveMessage - -websocketDidReceiveMessage is called when the client gets a text frame from the connection. - -```swift -func websocketDidReceiveMessage(socket: WebSocketClient, text: String) { - print("got some text: \(text)") -} -``` - -### websocketDidReceiveData - -websocketDidReceiveData is called when the client gets a binary frame from the connection. - -```swift -func websocketDidReceiveData(socket: WebSocketClient, data: Data) { - print("got some data: \(data.count)") -} -``` - -### Optional: websocketDidReceivePong *(required protocol: WebSocketPongDelegate)* - -websocketDidReceivePong is called when the client gets a pong response from the connection. You need to implement the WebSocketPongDelegate protocol and set an additional delegate, eg: ` socket.pongDelegate = self` - -```swift -func websocketDidReceivePong(socket: WebSocketClient, data: Data?) { - print("Got pong! Maybe some data: \(data?.count)") +After you are connected, there is either a delegate or closure you can use for process WebSocket events. + +### Receiving data from a WebSocket + +`didReceive` receives all the WebSocket events in a single easy to handle enum. + +```swift +func didReceive(event: WebSocketEvent, client: WebSocket) { + switch event { + case .connected(let headers): + isConnected = true + print("websocket is connected: \(headers)") + case .disconnected(let reason, let code): + isConnected = false + print("websocket is disconnected: \(reason) with code: \(code)") + case .text(let string): + print("Received text: \(string)") + case .binary(let data): + print("Received data: \(data.count)") + case .ping(_): + break + case .pong(_): + break + case .viabilityChanged(_): + break + case .reconnectSuggested(_): + break + case .cancelled: + isConnected = false + case .error(let error): + isConnected = false + handleError(error) + } } ``` -Or you can use closures. +The closure of this would be: ```swift -socket = WebSocket(url: URL(string: "ws://localhost:8080/")!) -//websocketDidConnect -socket.onConnect = { - print("websocket is connected") -} -//websocketDidDisconnect -socket.onDisconnect = { (error: Error?) in - print("websocket is disconnected: \(error?.localizedDescription)") +socket.onEvent = { event in + switch event { + // handle events just like above... + } } -//websocketDidReceiveMessage -socket.onText = { (text: String) in - print("got some text: \(text)") -} -//websocketDidReceiveData -socket.onData = { (data: Data) in - print("got some data: \(data.count)") -} -//you could do onPong as well. -socket.connect() ``` -One more: you can listen to socket connection and disconnection via notifications. Starscream posts `WebsocketDidConnectNotification` and `WebsocketDidDisconnectNotification`. You can find an `Error` that caused the disconection by accessing `WebsocketDisconnectionErrorKeyName` on notification `userInfo`. - - -## The delegate methods give you a simple way to handle data from the server, but how do you send data? +### Writing to a WebSocket ### write a binary frame @@ -160,98 +128,49 @@ The disconnect method does what you would expect and closes the socket. socket.disconnect() ``` -The socket can be forcefully closed, by specifying a timeout (in milliseconds). A timeout of zero will also close the socket immediately without waiting on the server. +The disconnect method can also send a custom close code if desired. ```swift -socket.disconnect(forceTimeout: 10, closeCode: CloseCode.normal.rawValue) +socket.disconnect(closeCode: CloseCode.normal.rawValue) ``` -### isConnected +### Custom Headers, Protocols and Timeout -Returns if the socket is connected or not. - -```swift -if socket.isConnected { - // do cool stuff. -} -``` - -### Custom Headers - -You can also override the default websocket headers with your own custom ones like so: +You can override the default websocket headers, add your own custom ones and set a timeout: ```swift var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) -request.timeoutInterval = 5 +request.timeoutInterval = 5 // Sets the timeout for the connection request.setValue("someother protocols", forHTTPHeaderField: "Sec-WebSocket-Protocol") request.setValue("14", forHTTPHeaderField: "Sec-WebSocket-Version") +request.setValue("chat,superchat", forHTTPHeaderField: "Sec-WebSocket-Protocol") request.setValue("Everything is Awesome!", forHTTPHeaderField: "My-Awesome-Header") let socket = WebSocket(request: request) ``` -### Custom HTTP Method - -Your server may use a different HTTP method when connecting to the websocket: - -```swift -var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) -request.httpMethod = "POST" -request.timeoutInterval = 5 -let socket = WebSocket(request: request) -``` - -### Protocols - -If you need to specify a protocol, simple add it to the init: - -```swift -//chat and superchat are the example protocols here -socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"]) -socket.delegate = self -socket.connect() -``` - -### Self Signed SSL - -```swift -socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"]) - -//set this if you want to ignore SSL cert validation, so a self signed SSL certificate can be used. -socket.disableSSLCertValidation = true -``` - ### SSL Pinning SSL Pinning is also supported in Starscream. -```swift -socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"]) -let data = ... //load your certificate from disk -socket.security = SSLSecurity(certs: [SSLCert(data: data)], usePublicKeys: true) -//socket.security = SSLSecurity() //uses the .cer files in your app's bundle -``` -You load either a `Data` blob of your certificate or you can use a `SecKeyRef` if you have a public key you want to use. The `usePublicKeys` bool is whether to use the certificates for validation or the public keys. The public keys will be extracted from the certificates automatically if `usePublicKeys` is choosen. - -### SSL Cipher Suites -To use an SSL encrypted connection, you need to tell Starscream about the cipher suites your server supports. +Allow Self-signed certificates: ```swift -socket = WebSocket(url: URL(string: "wss://localhost:8080/")!, protocols: ["chat","superchat"]) - -// Set enabled cipher suites to AES 256 and AES 128 -socket.enabledSSLCipherSuites = [TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256] +var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) +let pinner = FoundationSecurity(allowSelfSigned: true) // don't validate SSL certificates +let socket = WebSocket(request: request, certPinner: pinner) ``` -If you don't know which cipher suites are supported by your server, you can try pointing [SSL Labs](https://www.ssllabs.com/ssltest/) at it and checking the results. +TODO: Update docs on how to load certificates and public keys into an app bundle, use the builtin pinner and TrustKit. ### Compression Extensions Compression Extensions ([RFC 7692](https://tools.ietf.org/html/rfc7692)) is supported in Starscream. Compression is enabled by default, however compression will only be used if it is supported by the server as well. You may enable or disable compression via the `.enableCompression` property: ```swift -socket = WebSocket(url: URL(string: "ws://localhost:8080/")!) -socket.enableCompression = false +var request = URLRequest(url: URL(string: "ws://localhost:8080/")!) +let compression = WSCompression() +let socket = WebSocket(request: request, compressionHandler: compression) ``` Compression should be disabled if your application is transmitting already-compressed, random, or other uncompressable data. @@ -272,7 +191,7 @@ Check out the SimpleTest project in the examples directory to see how to setup a ## Requirements -Starscream works with iOS 7/OSX 10.9 or above. It is recommended to use iOS 8/10.10 or above for CocoaPods/framework support. To use Starscream with a project targeting iOS 7, you must include all Swift files directly in your project. +Starscream works with iOS 8/10.10 or above for CocoaPods/framework support. To use Starscream with a project targeting iOS 7, you must include all Swift files directly in your project. ## Installation @@ -286,7 +205,7 @@ To use Starscream in your project add the following 'Podfile' to your project platform :ios, '9.0' use_frameworks! - pod 'Starscream', '~> 3.0.2' + pod 'Starscream', '~> 4.0.0' Then run: @@ -308,7 +227,7 @@ $ brew install carthage To integrate Starscream into your Xcode project using Carthage, specify it in your `Cartfile`: ``` -github "daltoniam/Starscream" >= 3.0.2 +github "daltoniam/Starscream" >= 4.0.0 ``` ### Accio @@ -318,7 +237,7 @@ Check out the [Accio](https://github.com/JamitLabs/Accio) docs on how to add a i Add the following to your Package.swift: ```swift -.package(url: "https://github.com/daltoniam/Starscream.git", .upToNextMajor(from: "3.1.0")), +.package(url: "https://github.com/daltoniam/Starscream.git", .upToNextMajor(from: "4.0.0")), ``` Next, add `Starscream` to your App targets dependencies like so: @@ -354,7 +273,7 @@ Once you have your Swift package set up, adding Starscream as a dependency is as ```swift dependencies: [ - .Package(url: "https://github.com/daltoniam/Starscream.git", majorVersion: 3) + .Package(url: "https://github.com/daltoniam/Starscream.git", majorVersion: 4) ] ``` @@ -368,58 +287,9 @@ Add the `Starscream.xcodeproj` to your Xcode project. Once that is complete, in If you are running this in an OSX app or on a physical iOS device you will need to make sure you add the `Starscream.framework` to be included in your app bundle. To do this, in Xcode, navigate to the target configuration window by clicking on the blue project icon, and selecting the application target under the "Targets" heading in the sidebar. In the tab bar at the top of that window, open the "Build Phases" panel. Expand the "Link Binary with Libraries" group, and add `Starscream.framework`. Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add `Starscream.framework` respectively. - -## WebSocketAdvancedDelegate -The advanced delegate acts just like the simpler delegate but provides some additional information on the connection and incoming frames. - -```swift -socket.advancedDelegate = self -``` - -In most cases you do not need the extra info and should use the normal delegate. - -#### websocketDidReceiveMessage -```swift -func websocketDidReceiveMessage(socket: WebSocketClient, text: String, response: WebSocket.WSResponse) { - print("got some text: \(text)") - print("First frame for this message arrived on \(response.firstFrame)") -} -``` - -#### websocketDidReceiveData -```swift -func websocketDidReceiveData(socket: WebSocketClient, data: Date, response: WebSocket.WSResponse) { - print("got some data it long: \(data.count)") - print("A total of \(response.frameCount) frames were used to send this data") -} -``` - -#### websocketHttpUpgrade -These methods are called when the HTTP upgrade request is sent and when the response returns. -```swift -func websocketHttpUpgrade(socket: WebSocketClient, request: CFHTTPMessage) { - print("the http request was sent we can check the raw http if we need to") -} -``` - -```swift -func websocketHttpUpgrade(socket: WebSocketClient, response: CFHTTPMessage) { - print("the http response has returned.") -} -``` - -## Swift versions - -* Swift 4.2 - 3.0.6 - -## KNOWN ISSUES -- WatchOS does not have the the CFNetwork String constants to modify the stream's SSL behavior. It will be the default Foundation SSL behavior. This means watchOS CANNOT use `SSLCiphers`, `disableSSLCertValidation`, or SSL pinning. All these values set on watchOS will do nothing. -- Linux does not have the security framework, so it CANNOT use SSL pinning or `SSLCiphers` either. - - ## TODOs -- [ ] Add Unit Tests - Local WebSocket server that runs against Autobahn +- [ ] Proxy support ## License diff --git a/Pods/Starscream/Sources/Compression/Compression.swift b/Pods/Starscream/Sources/Compression/Compression.swift new file mode 100644 index 00000000..0e7fae5a --- /dev/null +++ b/Pods/Starscream/Sources/Compression/Compression.swift @@ -0,0 +1,29 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Compression.swift +// Starscream +// +// Created by Dalton Cherry on 2/4/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public protocol CompressionHandler { + func load(headers: [String: String]) + func decompress(data: Data, isFinal: Bool) -> Data? + func compress(data: Data) -> Data? +} diff --git a/Pods/Starscream/Sources/Starscream/Compression.swift b/Pods/Starscream/Sources/Compression/WSCompression.swift similarity index 61% rename from Pods/Starscream/Sources/Starscream/Compression.swift rename to Pods/Starscream/Sources/Compression/WSCompression.swift index ab657902..21295841 100644 --- a/Pods/Starscream/Sources/Starscream/Compression.swift +++ b/Pods/Starscream/Sources/Compression/WSCompression.swift @@ -1,9 +1,9 @@ ////////////////////////////////////////////////////////////////////////////////////////////////// // -// Compression.swift +// WSCompression.swift // // Created by Joseph Ross on 7/16/14. -// Copyright © 2017 Joseph Ross. +// Copyright © 2017 Joseph Ross & Vluxe. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -29,13 +29,81 @@ import Foundation import zlib +public class WSCompression: CompressionHandler { + let headerWSExtensionName = "Sec-WebSocket-Extensions" + var decompressor: Decompressor? + var compressor: Compressor? + var decompressorTakeOver = false + var compressorTakeOver = false + + public init() { + + } + + public func load(headers: [String: String]) { + guard let extensionHeader = headers[headerWSExtensionName] else { return } + decompressorTakeOver = false + compressorTakeOver = false + + let parts = extensionHeader.components(separatedBy: ";") + for p in parts { + let part = p.trimmingCharacters(in: .whitespaces) + if part.hasPrefix("server_max_window_bits=") { + let valString = part.components(separatedBy: "=")[1] + if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { + decompressor = Decompressor(windowBits: val) + } + } else if part.hasPrefix("client_max_window_bits=") { + let valString = part.components(separatedBy: "=")[1] + if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { + compressor = Compressor(windowBits: val) + } + } else if part == "client_no_context_takeover" { + compressorTakeOver = true + } else if part == "server_no_context_takeover" { + decompressorTakeOver = true + } + } + } + + public func decompress(data: Data, isFinal: Bool) -> Data? { + guard let decompressor = decompressor else { return nil } + do { + let decompressedData = try decompressor.decompress(data, finish: isFinal) + if decompressorTakeOver { + try decompressor.reset() + } + return decompressedData + } catch { + //do nothing with the error for now + } + return nil + } + + public func compress(data: Data) -> Data? { + guard let compressor = compressor else { return nil } + do { + let compressedData = try compressor.compress(data) + if compressorTakeOver { + try compressor.reset() + } + return compressedData + } catch { + //do nothing with the error for now + } + return nil + } + + +} + class Decompressor { private var strm = z_stream() private var buffer = [UInt8](repeating: 0, count: 0x2000) private var inflateInitialized = false - private let windowBits:Int + private let windowBits: Int - init?(windowBits:Int) { + init?(windowBits: Int) { self.windowBits = windowBits guard initInflate() else { return nil } } @@ -56,7 +124,7 @@ class Decompressor { } func decompress(_ data: Data, finish: Bool) throws -> Data { - return try data.withUnsafeBytes { (bytes:UnsafePointer) -> Data in + return try data.withUnsafeBytes { (bytes: UnsafePointer) -> Data in return try decompress(bytes: bytes, count: data.count, finish: finish) } } @@ -71,19 +139,20 @@ class Decompressor { } return decompressed - } - private func decompress(bytes: UnsafePointer, count: Int, out:inout Data) throws { - var res:CInt = 0 + private func decompress(bytes: UnsafePointer, count: Int, out: inout Data) throws { + var res: CInt = 0 strm.next_in = UnsafeMutablePointer(mutating: bytes) strm.avail_in = CUnsignedInt(count) repeat { - strm.next_out = UnsafeMutablePointer(&buffer) - strm.avail_out = CUnsignedInt(buffer.count) + buffer.withUnsafeMutableBytes { (bufferPtr) in + strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress + strm.avail_out = CUnsignedInt(bufferPtr.count) - res = inflate(&strm, 0) + res = inflate(&strm, 0) + } let byteCount = buffer.count - Int(strm.avail_out) out.append(buffer, count: byteCount) @@ -111,7 +180,7 @@ class Compressor { private var strm = z_stream() private var buffer = [UInt8](repeating: 0, count: 0x2000) private var deflateInitialized = false - private let windowBits:Int + private let windowBits: Int init?(windowBits: Int) { self.windowBits = windowBits @@ -136,16 +205,18 @@ class Compressor { func compress(_ data: Data) throws -> Data { var compressed = Data() - var res:CInt = 0 + var res: CInt = 0 data.withUnsafeBytes { (ptr:UnsafePointer) -> Void in strm.next_in = UnsafeMutablePointer(mutating: ptr) strm.avail_in = CUnsignedInt(data.count) repeat { - strm.next_out = UnsafeMutablePointer(&buffer) - strm.avail_out = CUnsignedInt(buffer.count) + buffer.withUnsafeMutableBytes { (bufferPtr) in + strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress + strm.avail_out = CUnsignedInt(bufferPtr.count) - res = deflate(&strm, Z_SYNC_FLUSH) + res = deflate(&strm, Z_SYNC_FLUSH) + } let byteCount = buffer.count - Int(strm.avail_out) compressed.append(buffer, count: byteCount) @@ -174,4 +245,3 @@ class Compressor { teardownDeflate() } } - diff --git a/Pods/Starscream/Sources/DataBytes/Data+Extensions.swift b/Pods/Starscream/Sources/DataBytes/Data+Extensions.swift new file mode 100644 index 00000000..1d0852d7 --- /dev/null +++ b/Pods/Starscream/Sources/DataBytes/Data+Extensions.swift @@ -0,0 +1,53 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Data+Extensions.swift +// Starscream +// +// Created by Dalton Cherry on 3/27/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Fix for deprecation warnings +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +internal extension Data { + struct ByteError: Swift.Error {} + + #if swift(>=5.0) + func withUnsafeBytes(_ completion: (UnsafePointer) throws -> ResultType) rethrows -> ResultType { + return try withUnsafeBytes { + if let baseAddress = $0.baseAddress, $0.count > 0 { + return try completion(baseAddress.assumingMemoryBound(to: ContentType.self)) + } else { + throw ByteError() + } + } + } + #endif + + #if swift(>=5.0) + mutating func withUnsafeMutableBytes(_ completion: (UnsafeMutablePointer) throws -> ResultType) rethrows -> ResultType { + return try withUnsafeMutableBytes { + if let baseAddress = $0.baseAddress, $0.count > 0 { + return try completion(baseAddress.assumingMemoryBound(to: ContentType.self)) + } else { + throw ByteError() + } + } + } + #endif +} diff --git a/Pods/Starscream/Sources/Engine/Engine.swift b/Pods/Starscream/Sources/Engine/Engine.swift new file mode 100644 index 00000000..a60ef7e8 --- /dev/null +++ b/Pods/Starscream/Sources/Engine/Engine.swift @@ -0,0 +1,22 @@ +// +// Engine.swift +// Starscream +// +// Created by Dalton Cherry on 6/15/19. +// Copyright © 2019 Vluxe. All rights reserved. +// + +import Foundation + +public protocol EngineDelegate: class { + func didReceive(event: WebSocketEvent) +} + +public protocol Engine { + func register(delegate: EngineDelegate) + func start(request: URLRequest) + func stop(closeCode: UInt16) + func forceStop() + func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) + func write(string: String, completion: (() -> ())?) +} diff --git a/Pods/Starscream/Sources/Engine/NativeEngine.swift b/Pods/Starscream/Sources/Engine/NativeEngine.swift new file mode 100644 index 00000000..7294e364 --- /dev/null +++ b/Pods/Starscream/Sources/Engine/NativeEngine.swift @@ -0,0 +1,96 @@ +// +// NativeEngine.swift +// Starscream +// +// Created by Dalton Cherry on 6/15/19. +// Copyright © 2019 Vluxe. All rights reserved. +// + +import Foundation + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +public class NativeEngine: NSObject, Engine, URLSessionDataDelegate, URLSessionWebSocketDelegate { + private var task: URLSessionWebSocketTask? + weak var delegate: EngineDelegate? + + public func register(delegate: EngineDelegate) { + self.delegate = delegate + } + + public func start(request: URLRequest) { + let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil) + task = session.webSocketTask(with: request) + doRead() + task?.resume() + } + + public func stop(closeCode: UInt16) { + let closeCode = URLSessionWebSocketTask.CloseCode(rawValue: Int(closeCode)) ?? .normalClosure + task?.cancel(with: closeCode, reason: nil) + } + + public func forceStop() { + stop(closeCode: UInt16(URLSessionWebSocketTask.CloseCode.abnormalClosure.rawValue)) + } + + public func write(string: String, completion: (() -> ())?) { + task?.send(.string(string), completionHandler: { (error) in + completion?() + }) + } + + public func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) { + switch opcode { + case .binaryFrame: + task?.send(.data(data), completionHandler: { (error) in + completion?() + }) + case .textFrame: + let text = String(data: data, encoding: .utf8)! + write(string: text, completion: completion) + case .ping: + task?.sendPing(pongReceiveHandler: { (error) in + completion?() + }) + default: + break //unsupported + } + } + + private func doRead() { + task?.receive { [weak self] (result) in + switch result { + case .success(let message): + switch message { + case .string(let string): + self?.broadcast(event: .text(string)) + case .data(let data): + self?.broadcast(event: .binary(data)) + @unknown default: + break + } + break + case .failure(let error): + self?.broadcast(event: .error(error)) + } + self?.doRead() + } + } + + private func broadcast(event: WebSocketEvent) { + delegate?.didReceive(event: event) + } + + public func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) { + let p = `protocol` ?? "" + broadcast(event: .connected([HTTPWSHeader.protocolName: p])) + } + + public func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + var r = "" + if let d = reason { + r = String(data: d, encoding: .utf8) ?? "" + } + broadcast(event: .disconnected(r, UInt16(closeCode.rawValue))) + } +} diff --git a/Pods/Starscream/Sources/Engine/WSEngine.swift b/Pods/Starscream/Sources/Engine/WSEngine.swift new file mode 100644 index 00000000..decca641 --- /dev/null +++ b/Pods/Starscream/Sources/Engine/WSEngine.swift @@ -0,0 +1,234 @@ +// +// WSEngine.swift +// Starscream +// +// Created by Dalton Cherry on 6/15/19. +// Copyright © 2019 Vluxe. All rights reserved. +// + +import Foundation + +public class WSEngine: Engine, TransportEventClient, FramerEventClient, +FrameCollectorDelegate, HTTPHandlerDelegate { + private let transport: Transport + private let framer: Framer + private let httpHandler: HTTPHandler + private let compressionHandler: CompressionHandler? + private let certPinner: CertificatePinning? + private let headerChecker: HeaderValidator + private var request: URLRequest! + + private let frameHandler = FrameCollector() + private var didUpgrade = false + private var secKeyValue = "" + private let writeQueue = DispatchQueue(label: "com.vluxe.starscream.writequeue") + private let mutex = DispatchSemaphore(value: 1) + private var canSend = false + + weak var delegate: EngineDelegate? + public var respondToPingWithPong: Bool = true + + public init(transport: Transport, + certPinner: CertificatePinning? = nil, + headerValidator: HeaderValidator = FoundationSecurity(), + httpHandler: HTTPHandler = FoundationHTTPHandler(), + framer: Framer = WSFramer(), + compressionHandler: CompressionHandler? = nil) { + self.transport = transport + self.framer = framer + self.httpHandler = httpHandler + self.certPinner = certPinner + self.headerChecker = headerValidator + self.compressionHandler = compressionHandler + framer.updateCompression(supports: compressionHandler != nil) + frameHandler.delegate = self + } + + public func register(delegate: EngineDelegate) { + self.delegate = delegate + } + + public func start(request: URLRequest) { + mutex.wait() + let isConnected = canSend + mutex.signal() + if isConnected { + return + } + + self.request = request + transport.register(delegate: self) + framer.register(delegate: self) + httpHandler.register(delegate: self) + frameHandler.delegate = self + guard let url = request.url else { + return + } + transport.connect(url: url, timeout: request.timeoutInterval, certificatePinning: certPinner) + } + + public func stop(closeCode: UInt16 = CloseCode.normal.rawValue) { + let capacity = MemoryLayout.size + var pointer = [UInt8](repeating: 0, count: capacity) + writeUint16(&pointer, offset: 0, value: closeCode) + let payload = Data(bytes: pointer, count: MemoryLayout.size) + write(data: payload, opcode: .connectionClose, completion: { [weak self] in + self?.reset() + self?.forceStop() + }) + } + + public func forceStop() { + transport.disconnect() + } + + public func write(string: String, completion: (() -> ())?) { + let data = string.data(using: .utf8)! + write(data: data, opcode: .textFrame, completion: completion) + } + + public func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) { + writeQueue.async { [weak self] in + guard let s = self else { return } + s.mutex.wait() + let canWrite = s.canSend + s.mutex.signal() + if !canWrite { + return + } + + var isCompressed = false + var sendData = data + if let compressedData = s.compressionHandler?.compress(data: data) { + sendData = compressedData + isCompressed = true + } + + let frameData = s.framer.createWriteFrame(opcode: opcode, payload: sendData, isCompressed: isCompressed) + s.transport.write(data: frameData, completion: {_ in + completion?() + }) + } + } + + // MARK: - TransportEventClient + + public func connectionChanged(state: ConnectionState) { + switch state { + case .connected: + secKeyValue = HTTPWSHeader.generateWebSocketKey() + let wsReq = HTTPWSHeader.createUpgrade(request: request, supportsCompression: framer.supportsCompression(), secKeyValue: secKeyValue) + let data = httpHandler.convert(request: wsReq) + transport.write(data: data, completion: {_ in }) + case .waiting: + break + case .failed(let error): + handleError(error) + case .viability(let isViable): + broadcast(event: .viabilityChanged(isViable)) + case .shouldReconnect(let status): + broadcast(event: .reconnectSuggested(status)) + case .receive(let data): + if didUpgrade { + framer.add(data: data) + } else { + let offset = httpHandler.parse(data: data) + if offset > 0 { + let extraData = data.subdata(in: offset.. Data? { + return compressionHandler?.decompress(data: data, isFinal: isFinal) + } + + public func didForm(event: FrameCollector.Event) { + switch event { + case .text(let string): + broadcast(event: .text(string)) + case .binary(let data): + broadcast(event: .binary(data)) + case .pong(let data): + broadcast(event: .pong(data)) + case .ping(let data): + broadcast(event: .ping(data)) + if respondToPingWithPong { + write(data: data ?? Data(), opcode: .pong, completion: nil) + } + case .closed(let reason, let code): + broadcast(event: .disconnected(reason, code)) + stop(closeCode: code) + case .error(let error): + handleError(error) + } + } + + private func broadcast(event: WebSocketEvent) { + delegate?.didReceive(event: event) + } + + //This call can be coming from a lot of different queues/threads. + //be aware of that when modifying shared variables + private func handleError(_ error: Error?) { + if let wsError = error as? WSError { + stop(closeCode: wsError.code) + } else { + stop() + } + + delegate?.didReceive(event: .error(error)) + } + + private func reset() { + mutex.wait() + canSend = false + didUpgrade = false + mutex.signal() + } + + +} diff --git a/Pods/Starscream/Sources/Framer/FoundationHTTPHandler.swift b/Pods/Starscream/Sources/Framer/FoundationHTTPHandler.swift new file mode 100644 index 00000000..fb024aaa --- /dev/null +++ b/Pods/Starscream/Sources/Framer/FoundationHTTPHandler.swift @@ -0,0 +1,123 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// FoundationHTTPHandler.swift +// Starscream +// +// Created by Dalton Cherry on 1/25/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation +#if os(watchOS) +public typealias FoundationHTTPHandler = StringHTTPHandler +#else +public class FoundationHTTPHandler: HTTPHandler { + + var buffer = Data() + weak var delegate: HTTPHandlerDelegate? + + public init() { + + } + + public func convert(request: URLRequest) -> Data { + let msg = CFHTTPMessageCreateRequest(kCFAllocatorDefault, request.httpMethod! as CFString, + request.url! as CFURL, kCFHTTPVersion1_1).takeRetainedValue() + if let headers = request.allHTTPHeaderFields { + for (aKey, aValue) in headers { + CFHTTPMessageSetHeaderFieldValue(msg, aKey as CFString, aValue as CFString) + } + } + if let body = request.httpBody { + CFHTTPMessageSetBody(msg, body as CFData) + } + guard let data = CFHTTPMessageCopySerializedMessage(msg) else { + return Data() + } + return data.takeRetainedValue() as Data + } + + public func parse(data: Data) -> Int { + let offset = findEndOfHTTP(data: data) + if offset > 0 { + buffer.append(data.subdata(in: 0.. Bool { + var pointer = [UInt8]() + data.withUnsafeBytes { pointer.append(contentsOf: $0) } + + let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue() + if !CFHTTPMessageAppendBytes(response, pointer, data.count) { + return false //not enough data, wait for more + } + if !CFHTTPMessageIsHeaderComplete(response) { + return false //not enough data, wait for more + } + + let code = CFHTTPMessageGetResponseStatusCode(response) + if code != HTTPWSHeader.switchProtocolCode { + delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code))) + return true + } + + if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { + let nsHeaders = cfHeaders.takeRetainedValue() as NSDictionary + var headers = [String: String]() + for (key, value) in nsHeaders { + if let key = key as? String, let value = value as? String { + headers[key] = value + } + } + delegate?.didReceiveHTTP(event: .success(headers)) + return true + } + + delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData)) + return true + } + + public func register(delegate: HTTPHandlerDelegate) { + self.delegate = delegate + } + + private func findEndOfHTTP(data: Data) -> Int { + let endBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] + var pointer = [UInt8]() + data.withUnsafeBytes { pointer.append(contentsOf: $0) } + var k = 0 + for i in 0.. Data { + #if os(watchOS) + //TODO: build response header + return Data() + #else + let response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, HTTPWSHeader.switchProtocolCode, + nil, kCFHTTPVersion1_1).takeRetainedValue() + + //TODO: add other values to make a proper response here... + //TODO: also sec key thing (Sec-WebSocket-Key) + for (key, value) in headers { + CFHTTPMessageSetHeaderFieldValue(response, key as CFString, value as CFString) + } + guard let cfData = CFHTTPMessageCopySerializedMessage(response)?.takeRetainedValue() else { + return Data() + } + return cfData as Data + #endif + } + + public func parse(data: Data) { + buffer.append(data) + if parseContent(data: buffer) { + buffer = Data() + } + } + + //returns true when the buffer should be cleared + func parseContent(data: Data) -> Bool { + var pointer = [UInt8]() + data.withUnsafeBytes { pointer.append(contentsOf: $0) } + #if os(watchOS) + //TODO: parse data + return false + #else + let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true).takeRetainedValue() + if !CFHTTPMessageAppendBytes(response, pointer, data.count) { + return false //not enough data, wait for more + } + if !CFHTTPMessageIsHeaderComplete(response) { + return false //not enough data, wait for more + } + if let method = CFHTTPMessageCopyRequestMethod(response)?.takeRetainedValue() { + if (method as NSString) != getVerb { + delegate?.didReceive(event: .failure(HTTPUpgradeError.invalidData)) + return true + } + } + + if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) { + let nsHeaders = cfHeaders.takeRetainedValue() as NSDictionary + var headers = [String: String]() + for (key, value) in nsHeaders { + if let key = key as? String, let value = value as? String { + headers[key] = value + } + } + delegate?.didReceive(event: .success(headers)) + return true + } + + delegate?.didReceive(event: .failure(HTTPUpgradeError.invalidData)) + return true + #endif + } +} diff --git a/Pods/Starscream/Sources/Framer/FrameCollector.swift b/Pods/Starscream/Sources/Framer/FrameCollector.swift new file mode 100644 index 00000000..3ec1084c --- /dev/null +++ b/Pods/Starscream/Sources/Framer/FrameCollector.swift @@ -0,0 +1,107 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// FrameCollector.swift +// Starscream +// +// Created by Dalton Cherry on 1/24/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public protocol FrameCollectorDelegate: class { + func didForm(event: FrameCollector.Event) + func decompress(data: Data, isFinal: Bool) -> Data? +} + +public class FrameCollector { + public enum Event { + case text(String) + case binary(Data) + case pong(Data?) + case ping(Data?) + case error(Error) + case closed(String, UInt16) + } + weak var delegate: FrameCollectorDelegate? + var buffer = Data() + var frameCount = 0 + var isText = false //was the first frame a text frame or a binary frame? + var needsDecompression = false + + public func add(frame: Frame) { + //check single frame action and out of order frames + if frame.opcode == .connectionClose { + var code = frame.closeCode + var reason = "connection closed by server" + if let customCloseReason = String(data: frame.payload, encoding: .utf8) { + reason = customCloseReason + } else { + code = CloseCode.protocolError.rawValue + } + delegate?.didForm(event: .closed(reason, code)) + return + } else if frame.opcode == .pong { + delegate?.didForm(event: .pong(frame.payload)) + return + } else if frame.opcode == .ping { + delegate?.didForm(event: .ping(frame.payload)) + return + } else if frame.opcode == .continueFrame && frameCount == 0 { + let errCode = CloseCode.protocolError.rawValue + delegate?.didForm(event: .error(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: errCode))) + reset() + return + } else if frameCount > 0 && frame.opcode != .continueFrame { + let errCode = CloseCode.protocolError.rawValue + delegate?.didForm(event: .error(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: errCode))) + reset() + return + } + if frameCount == 0 { + isText = frame.opcode == .textFrame + needsDecompression = frame.needsDecompression + } + + let payload: Data + if needsDecompression { + payload = delegate?.decompress(data: frame.payload, isFinal: frame.isFin) ?? frame.payload + } else { + payload = frame.payload + } + buffer.append(payload) + frameCount += 1 + + if frame.isFin { + if isText { + if let string = String(data: buffer, encoding: .utf8) { + delegate?.didForm(event: .text(string)) + } else { + let errCode = CloseCode.protocolError.rawValue + delegate?.didForm(event: .error(WSError(type: .protocolError, message: "not valid UTF-8 data", code: errCode))) + } + } else { + delegate?.didForm(event: .binary(buffer)) + } + reset() + } + } + + func reset() { + buffer = Data() + frameCount = 0 + } +} diff --git a/Pods/Starscream/Sources/Framer/Framer.swift b/Pods/Starscream/Sources/Framer/Framer.swift new file mode 100644 index 00000000..f77d5b80 --- /dev/null +++ b/Pods/Starscream/Sources/Framer/Framer.swift @@ -0,0 +1,365 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Framer.swift +// Starscream +// +// Created by Dalton Cherry on 1/23/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +let FinMask: UInt8 = 0x80 +let OpCodeMask: UInt8 = 0x0F +let RSVMask: UInt8 = 0x70 +let RSV1Mask: UInt8 = 0x40 +let MaskMask: UInt8 = 0x80 +let PayloadLenMask: UInt8 = 0x7F +let MaxFrameSize: Int = 32 + +// Standard WebSocket close codes +public enum CloseCode: UInt16 { + case normal = 1000 + case goingAway = 1001 + case protocolError = 1002 + case protocolUnhandledType = 1003 + // 1004 reserved. + case noStatusReceived = 1005 + //1006 reserved. + case encoding = 1007 + case policyViolated = 1008 + case messageTooBig = 1009 +} + +public enum FrameOpCode: UInt8 { + case continueFrame = 0x0 + case textFrame = 0x1 + case binaryFrame = 0x2 + // 3-7 are reserved. + case connectionClose = 0x8 + case ping = 0x9 + case pong = 0xA + // B-F reserved. + case unknown = 100 +} + +public struct Frame { + let isFin: Bool + let needsDecompression: Bool + let isMasked: Bool + let opcode: FrameOpCode + let payloadLength: UInt64 + let payload: Data + let closeCode: UInt16 //only used by connectionClose opcode +} + +public enum FrameEvent { + case frame(Frame) + case error(Error) +} + +public protocol FramerEventClient: class { + func frameProcessed(event: FrameEvent) +} + +public protocol Framer { + func add(data: Data) + func register(delegate: FramerEventClient) + func createWriteFrame(opcode: FrameOpCode, payload: Data, isCompressed: Bool) -> Data + func updateCompression(supports: Bool) + func supportsCompression() -> Bool +} + +public class WSFramer: Framer { + private let queue = DispatchQueue(label: "com.vluxe.starscream.wsframer", attributes: []) + private weak var delegate: FramerEventClient? + private var buffer = Data() + public var compressionEnabled = false + private let isServer: Bool + + public init(isServer: Bool = false) { + self.isServer = isServer + } + + public func updateCompression(supports: Bool) { + compressionEnabled = supports + } + + public func supportsCompression() -> Bool { + return compressionEnabled + } + + enum ProcessEvent { + case needsMoreData + case processedFrame(Frame, Int) + case failed(Error) + } + + public func add(data: Data) { + queue.async { [weak self] in + self?.buffer.append(data) + while(true) { + let event = self?.process() ?? .needsMoreData + switch event { + case .needsMoreData: + return + case .processedFrame(let frame, let split): + guard let s = self else { return } + s.delegate?.frameProcessed(event: .frame(frame)) + if split >= s.buffer.count { + s.buffer = Data() + return + } + s.buffer = s.buffer.advanced(by: split) + case .failed(let error): + self?.delegate?.frameProcessed(event: .error(error)) + self?.buffer = Data() + return + } + } + } + } + + public func register(delegate: FramerEventClient) { + self.delegate = delegate + } + + private func process() -> ProcessEvent { + if buffer.count < 2 { + return .needsMoreData + } + var pointer = [UInt8]() + buffer.withUnsafeBytes { pointer.append(contentsOf: $0) } + + let isFin = (FinMask & pointer[0]) + let opcodeRawValue = (OpCodeMask & pointer[0]) + let opcode = FrameOpCode(rawValue: opcodeRawValue) ?? .unknown + let isMasked = (MaskMask & pointer[1]) + let payloadLen = (PayloadLenMask & pointer[1]) + let RSV1 = (RSVMask & pointer[0]) + var needsDecompression = false + + if compressionEnabled && opcode != .continueFrame { + needsDecompression = (RSV1Mask & pointer[0]) > 0 + } + if !isServer && (isMasked > 0 || RSV1 > 0) && opcode != .pong && !needsDecompression { + let errCode = CloseCode.protocolError.rawValue + return .failed(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: errCode)) + } + let isControlFrame = (opcode == .connectionClose || opcode == .ping) + if !isControlFrame && (opcode != .binaryFrame && opcode != .continueFrame && + opcode != .textFrame && opcode != .pong) { + let errCode = CloseCode.protocolError.rawValue + return .failed(WSError(type: .protocolError, message: "unknown opcode: \(opcodeRawValue)", code: errCode)) + } + if isControlFrame && isFin == 0 { + let errCode = CloseCode.protocolError.rawValue + return .failed(WSError(type: .protocolError, message: "control frames can't be fragmented", code: errCode)) + } + + var offset = 2 + + if isControlFrame && payloadLen > 125 { + return .failed(WSError(type: .protocolError, message: "payload length is longer than allowed for a control frame", code: CloseCode.protocolError.rawValue)) + } + + var dataLength = UInt64(payloadLen) + var closeCode = CloseCode.normal.rawValue + if opcode == .connectionClose { + if payloadLen == 1 { + closeCode = CloseCode.protocolError.rawValue + dataLength = 0 + } else if payloadLen > 1 { + if pointer.count < 4 { + return .needsMoreData + } + let size = MemoryLayout.size + closeCode = pointer.readUint16(offset: offset) + offset += size + dataLength -= UInt64(size) + if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) { + closeCode = CloseCode.protocolError.rawValue + } + } + } + + if payloadLen == 127 { + let size = MemoryLayout.size + if size + offset > pointer.count { + return .needsMoreData + } + dataLength = pointer.readUint64(offset: offset) + offset += size + } else if payloadLen == 126 { + let size = MemoryLayout.size + if size + offset > pointer.count { + return .needsMoreData + } + dataLength = UInt64(pointer.readUint16(offset: offset)) + offset += size + } + + let maskStart = offset + if isServer { + offset += MemoryLayout.size + } + + if dataLength > (pointer.count - offset) { + return .needsMoreData + } + + //I don't like this cast, but Data's count returns an Int. + //Might be a problem with huge payloads. Need to revisit. + let readDataLength = Int(dataLength) + + let payload: Data + if readDataLength == 0 { + payload = Data() + } else { + if isServer { + payload = pointer.unmaskData(maskStart: maskStart, offset: offset, length: readDataLength) + } else { + let end = offset + readDataLength + payload = Data(pointer[offset.. 0, needsDecompression: needsDecompression, isMasked: isMasked > 0, opcode: opcode, payloadLength: dataLength, payload: payload, closeCode: closeCode) + return .processedFrame(frame, offset) + } + + public func createWriteFrame(opcode: FrameOpCode, payload: Data, isCompressed: Bool) -> Data { + let payloadLength = payload.count + + let capacity = payloadLength + MaxFrameSize + var pointer = [UInt8](repeating: 0, count: capacity) + + //set the framing info + pointer[0] = FinMask | opcode.rawValue + if isCompressed { + pointer[0] |= RSV1Mask + } + + var offset = 2 //skip pass the framing info + if payloadLength < 126 { + pointer[1] = UInt8(payloadLength) + } else if payloadLength <= Int(UInt16.max) { + pointer[1] = 126 + writeUint16(&pointer, offset: offset, value: UInt16(payloadLength)) + offset += MemoryLayout.size + } else { + pointer[1] = 127 + writeUint64(&pointer, offset: offset, value: UInt64(payloadLength)) + offset += MemoryLayout.size + } + + //clients are required to mask the payload data, but server don't according to the RFC + if !isServer { + pointer[1] |= MaskMask + + //write the random mask key in + let maskKey: UInt32 = UInt32.random(in: 0...UInt32.max) + + writeUint32(&pointer, offset: offset, value: maskKey) + let maskStart = offset + offset += MemoryLayout.size + + //now write the payload data in + for i in 0...size)] + offset += 1 + } + } else { + for i in 0.. UInt16 { + return (UInt16(self[offset + 0]) << 8) | UInt16(self[offset + 1]) + } + + /** + Read a UInt64 from a buffer. + - parameter offset: is the offset index to start the read from (e.g. buffer[0], buffer[1], etc). + - returns: a UInt64 of the value from the buffer + */ + func readUint64(offset: Int) -> UInt64 { + var value = UInt64(0) + for i in 0...7 { + value = (value << 8) | UInt64(self[offset + i]) + } + return value + } + + func unmaskData(maskStart: Int, offset: Int, length: Int) -> Data { + var unmaskedBytes = [UInt8](repeating: 0, count: length) + let maskSize = MemoryLayout.size + for i in 0..> 8) + buffer[offset + 1] = UInt8(value & 0xff) +} + +/** + Write a UInt32 to the buffer. It fills the 4 array "slots" of the UInt8 array. + - parameter buffer: is the UInt8 array (pointer) to write the value too. + - parameter offset: is the offset index to start the write from (e.g. buffer[0], buffer[1], etc). + */ +public func writeUint32( _ buffer: inout [UInt8], offset: Int, value: UInt32) { + for i in 0...3 { + buffer[offset + i] = UInt8((value >> (8*UInt32(3 - i))) & 0xff) + } +} + +/** + Write a UInt64 to the buffer. It fills the 8 array "slots" of the UInt8 array. + - parameter buffer: is the UInt8 array (pointer) to write the value too. + - parameter offset: is the offset index to start the write from (e.g. buffer[0], buffer[1], etc). + */ +public func writeUint64( _ buffer: inout [UInt8], offset: Int, value: UInt64) { + for i in 0...7 { + buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) + } +} diff --git a/Pods/Starscream/Sources/Framer/HTTPHandler.swift b/Pods/Starscream/Sources/Framer/HTTPHandler.swift new file mode 100644 index 00000000..70941e75 --- /dev/null +++ b/Pods/Starscream/Sources/Framer/HTTPHandler.swift @@ -0,0 +1,148 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// HTTPHandler.swift +// Starscream +// +// Created by Dalton Cherry on 1/24/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum HTTPUpgradeError: Error { + case notAnUpgrade(Int) + case invalidData +} + +public struct HTTPWSHeader { + static let upgradeName = "Upgrade" + static let upgradeValue = "websocket" + static let hostName = "Host" + static let connectionName = "Connection" + static let connectionValue = "Upgrade" + static let protocolName = "Sec-WebSocket-Protocol" + static let versionName = "Sec-WebSocket-Version" + static let versionValue = "13" + static let extensionName = "Sec-WebSocket-Extensions" + static let keyName = "Sec-WebSocket-Key" + static let originName = "Origin" + static let acceptName = "Sec-WebSocket-Accept" + static let switchProtocolCode = 101 + static let defaultSSLSchemes = ["wss", "https"] + + /// Creates a new URLRequest based off the source URLRequest. + /// - Parameter request: the request to "upgrade" the WebSocket request by adding headers. + /// - Parameter supportsCompression: set if the client support text compression. + /// - Parameter secKeyName: the security key to use in the WebSocket request. https://tools.ietf.org/html/rfc6455#section-1.3 + /// - returns: A URLRequest request to be converted to data and sent to the server. + public static func createUpgrade(request: URLRequest, supportsCompression: Bool, secKeyValue: String) -> URLRequest { + guard let url = request.url, let parts = url.getParts() else { + return request + } + + var req = request + if request.value(forHTTPHeaderField: HTTPWSHeader.originName) == nil { + var origin = url.absoluteString + if let hostUrl = URL (string: "/", relativeTo: url) { + origin = hostUrl.absoluteString + origin.remove(at: origin.index(before: origin.endIndex)) + } + req.setValue(origin, forHTTPHeaderField: HTTPWSHeader.originName) + } + req.setValue(HTTPWSHeader.upgradeValue, forHTTPHeaderField: HTTPWSHeader.upgradeName) + req.setValue(HTTPWSHeader.connectionValue, forHTTPHeaderField: HTTPWSHeader.connectionName) + req.setValue(HTTPWSHeader.versionValue, forHTTPHeaderField: HTTPWSHeader.versionName) + req.setValue(secKeyValue, forHTTPHeaderField: HTTPWSHeader.keyName) + + if let cookies = HTTPCookieStorage.shared.cookies(for: url), !cookies.isEmpty { + let headers = HTTPCookie.requestHeaderFields(with: cookies) + for (key, val) in headers { + req.setValue(val, forHTTPHeaderField: key) + } + } + + if supportsCompression { + let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15" + req.setValue(val, forHTTPHeaderField: HTTPWSHeader.extensionName) + } + let hostValue = req.allHTTPHeaderFields?[HTTPWSHeader.hostName] ?? "\(parts.host):\(parts.port)" + req.setValue(hostValue, forHTTPHeaderField: HTTPWSHeader.hostName) + return req + } + + // generateWebSocketKey 16 random characters between a-z and return them as a base64 string + public static func generateWebSocketKey() -> String { + return Data((0..<16).map{ _ in UInt8.random(in: 97...122) }).base64EncodedString() + } +} + +public enum HTTPEvent { + case success([String: String]) + case failure(Error) +} + +public protocol HTTPHandlerDelegate: class { + func didReceiveHTTP(event: HTTPEvent) +} + +public protocol HTTPHandler { + func register(delegate: HTTPHandlerDelegate) + func convert(request: URLRequest) -> Data + func parse(data: Data) -> Int +} + +public protocol HTTPServerDelegate: class { + func didReceive(event: HTTPEvent) +} + +public protocol HTTPServerHandler { + func register(delegate: HTTPServerDelegate) + func parse(data: Data) + func createResponse(headers: [String: String]) -> Data +} + +public struct URLParts { + let port: Int + let host: String + let isTLS: Bool +} + +public extension URL { + /// isTLSScheme returns true if the scheme is https or wss + var isTLSScheme: Bool { + guard let scheme = self.scheme else { + return false + } + return HTTPWSHeader.defaultSSLSchemes.contains(scheme) + } + + /// getParts pulls host and port from the url. + func getParts() -> URLParts? { + guard let host = self.host else { + return nil // no host, this isn't a valid url + } + let isTLS = isTLSScheme + var port = self.port ?? 0 + if self.port == nil { + if isTLS { + port = 443 + } else { + port = 80 + } + } + return URLParts(port: port, host: host, isTLS: isTLS) + } +} diff --git a/Pods/Starscream/Sources/Framer/StringHTTPHandler.swift b/Pods/Starscream/Sources/Framer/StringHTTPHandler.swift new file mode 100644 index 00000000..33f5f9be --- /dev/null +++ b/Pods/Starscream/Sources/Framer/StringHTTPHandler.swift @@ -0,0 +1,143 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// StringHTTPHandler.swift +// Starscream +// +// Created by Dalton Cherry on 8/25/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public class StringHTTPHandler: HTTPHandler { + + var buffer = Data() + weak var delegate: HTTPHandlerDelegate? + + public init() { + + } + + public func convert(request: URLRequest) -> Data { + guard let url = request.url else { + return Data() + } + + var path = url.absoluteString + let offset = (url.scheme?.count ?? 2) + 3 + path = String(path[path.index(path.startIndex, offsetBy: offset).. Int { + let offset = findEndOfHTTP(data: data) + if offset > 0 { + buffer.append(data.subdata(in: 0.. Bool { + guard let str = String(data: data, encoding: .utf8) else { + delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData)) + return true + } + let splitArr = str.components(separatedBy: "\r\n") + var code = -1 + var i = 0 + var headers = [String: String]() + for str in splitArr { + if i == 0 { + let responseSplit = str.components(separatedBy: .whitespaces) + guard responseSplit.count > 1 else { + delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.invalidData)) + return true + } + if let c = Int(responseSplit[1]) { + code = c + } + } else { + guard let separatorIndex = str.firstIndex(of: ":") else { break } + let key = str.prefix(upTo: separatorIndex).trimmingCharacters(in: .whitespaces) + let val = str.suffix(from: str.index(after: separatorIndex)).trimmingCharacters(in: .whitespaces) + headers[key.lowercased()] = val + } + i += 1 + } + + if code != HTTPWSHeader.switchProtocolCode { + delegate?.didReceiveHTTP(event: .failure(HTTPUpgradeError.notAnUpgrade(code))) + return true + } + + delegate?.didReceiveHTTP(event: .success(headers)) + return true + } + + public func register(delegate: HTTPHandlerDelegate) { + self.delegate = delegate + } + + private func findEndOfHTTP(data: Data) -> Int { + let endBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] + var pointer = [UInt8]() + data.withUnsafeBytes { pointer.append(contentsOf: $0) } + var k = 0 + for i in 0.. ())) { + if allowSelfSigned { + completion(.success) + return + } + + if let validateDomain = domain { + SecTrustSetPolicies(trust, SecPolicyCreateSSL(true, validateDomain as NSString?)) + } + + handleSecurityTrust(trust: trust, completion: completion) + } + + private func handleSecurityTrust(trust: SecTrust, completion: ((PinningState) -> ())) { + if #available(iOS 12.0, OSX 10.14, watchOS 5.0, tvOS 12.0, *) { + var error: CFError? + if SecTrustEvaluateWithError(trust, &error) { + completion(.success) + } else { + completion(.failed(error)) + } + } else { + handleOldSecurityTrust(trust: trust, completion: completion) + } + } + + private func handleOldSecurityTrust(trust: SecTrust, completion: ((PinningState) -> ())) { + var result: SecTrustResultType = .unspecified + SecTrustEvaluate(trust, &result) + if result == .unspecified || result == .proceed { + completion(.success) + } else { + let e = CFErrorCreate(kCFAllocatorDefault, "FoundationSecurityError" as NSString?, Int(result.rawValue), nil) + completion(.failed(e)) + } + } +} + +extension FoundationSecurity: HeaderValidator { + public func validate(headers: [String: String], key: String) -> Error? { + if let acceptKey = headers[HTTPWSHeader.acceptName] { + let sha = "\(key)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64() + if sha != acceptKey { + return WSError(type: .securityError, message: "accept header doesn't match", code: SecurityErrorCode.acceptFailed.rawValue) + } + } + return nil + } +} + +private extension String { + func sha1Base64() -> String { + let data = self.data(using: .utf8)! + let pointer = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in + var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) + CC_SHA1(bytes.baseAddress, CC_LONG(data.count), &digest) + return digest + } + return Data(pointer).base64EncodedString() + } +} diff --git a/Pods/Starscream/Sources/Security/Security.swift b/Pods/Starscream/Sources/Security/Security.swift new file mode 100644 index 00000000..a64a7713 --- /dev/null +++ b/Pods/Starscream/Sources/Security/Security.swift @@ -0,0 +1,45 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Security.swift +// Starscream +// +// Created by Dalton Cherry on 3/16/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum SecurityErrorCode: UInt16 { + case acceptFailed = 1 + case pinningFailed = 2 +} + +public enum PinningState { + case success + case failed(CFError?) +} + +// CertificatePinning protocol provides an interface for Transports to handle Certificate +// or Public Key Pinning. +public protocol CertificatePinning: class { + func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) +} + +// validates the "Sec-WebSocket-Accept" header as defined 1.3 of the RFC 6455 +// https://tools.ietf.org/html/rfc6455#section-1.3 +public protocol HeaderValidator: class { + func validate(headers: [String: String], key: String) -> Error? +} diff --git a/Pods/Starscream/Sources/Server/Server.swift b/Pods/Starscream/Sources/Server/Server.swift new file mode 100644 index 00000000..527c851d --- /dev/null +++ b/Pods/Starscream/Sources/Server/Server.swift @@ -0,0 +1,56 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Server.swift +// Starscream +// +// Created by Dalton Cherry on 4/2/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum ConnectionEvent { + case connected([String: String]) + case disconnected(String, UInt16) + case text(String) + case binary(Data) + case pong(Data?) + case ping(Data?) + case error(Error) +} + +public protocol Connection { + func write(data: Data, opcode: FrameOpCode) +} + +public protocol ConnectionDelegate: class { + func didReceive(event: ServerEvent) +} + +public enum ServerEvent { + case connected(Connection, [String: String]) + case disconnected(Connection, String, UInt16) + case text(Connection, String) + case binary(Connection, Data) + case pong(Connection, Data?) + case ping(Connection, Data?) +} + +public protocol Server { + func start(address: String, port: UInt16) -> Error? +} + + diff --git a/Pods/Starscream/Sources/Server/WebSocketServer.swift b/Pods/Starscream/Sources/Server/WebSocketServer.swift new file mode 100644 index 00000000..4d3b9af5 --- /dev/null +++ b/Pods/Starscream/Sources/Server/WebSocketServer.swift @@ -0,0 +1,196 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// WebSocketServer.swift +// Starscream +// +// Created by Dalton Cherry on 4/5/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +#if canImport(Network) +import Foundation +import Network + +/// WebSocketServer is a Network.framework implementation of a WebSocket server +@available(watchOS, unavailable) +@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) +public class WebSocketServer: Server, ConnectionDelegate { + public var onEvent: ((ServerEvent) -> Void)? + private var connections = [String: ServerConnection]() + private var listener: NWListener? + private let queue = DispatchQueue(label: "com.vluxe.starscream.server.networkstream", attributes: []) + + public init() { + + } + + public func start(address: String, port: UInt16) -> Error? { + //TODO: support TLS cert adding/binding + let parameters = NWParameters(tls: nil, tcp: NWProtocolTCP.Options()) + let p = NWEndpoint.Port(rawValue: port)! + parameters.requiredLocalEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host.name(address, nil), port: p) + + guard let listener = try? NWListener(using: parameters, on: p) else { + return WSError(type: .serverError, message: "unable to start the listener at: \(address):\(port)", code: 0) + } + listener.newConnectionHandler = {[weak self] conn in + let transport = TCPTransport(connection: conn) + let c = ServerConnection(transport: transport) + c.delegate = self + self?.connections[c.uuid] = c + } +// listener.stateUpdateHandler = { state in +// switch state { +// case .ready: +// print("ready to get sockets!") +// case .setup: +// print("setup to get sockets!") +// case .cancelled: +// print("server cancelled!") +// case .waiting(let error): +// print("waiting error: \(error)") +// case .failed(let error): +// print("server failed: \(error)") +// @unknown default: +// print("wat?") +// } +// } + self.listener = listener + listener.start(queue: queue) + return nil + } + + public func didReceive(event: ServerEvent) { + onEvent?(event) + switch event { + case .disconnected(let conn, _, _): + guard let conn = conn as? ServerConnection else { + return + } + connections.removeValue(forKey: conn.uuid) + default: + break + } + } +} + +@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) +public class ServerConnection: Connection, HTTPServerDelegate, FramerEventClient, FrameCollectorDelegate, TransportEventClient { + let transport: TCPTransport + private let httpHandler = FoundationHTTPServerHandler() + private let framer = WSFramer(isServer: true) + private let frameHandler = FrameCollector() + private var didUpgrade = false + public var onEvent: ((ConnectionEvent) -> Void)? + public weak var delegate: ConnectionDelegate? + private let id: String + var uuid: String { + return id + } + + init(transport: TCPTransport) { + self.id = UUID().uuidString + self.transport = transport + transport.register(delegate: self) + httpHandler.register(delegate: self) + framer.register(delegate: self) + frameHandler.delegate = self + } + + public func write(data: Data, opcode: FrameOpCode) { + let wsData = framer.createWriteFrame(opcode: opcode, payload: data, isCompressed: false) + transport.write(data: wsData, completion: {_ in }) + } + + // MARK: - TransportEventClient + + public func connectionChanged(state: ConnectionState) { + switch state { + case .connected: + break + case .waiting: + break + case .failed(let error): + print("server connection error: \(error ?? WSError(type: .protocolError, message: "default error, no extra data", code: 0))") //handleError(error) + case .viability(_): + break + case .shouldReconnect(_): + break + case .receive(let data): + if didUpgrade { + framer.add(data: data) + } else { + httpHandler.parse(data: data) + } + case .cancelled: + print("server connection cancelled!") + //broadcast(event: .cancelled) + } + } + + /// MARK: - HTTPServerDelegate + + public func didReceive(event: HTTPEvent) { + switch event { + case .success(let headers): + didUpgrade = true + let response = httpHandler.createResponse(headers: [:]) + transport.write(data: response, completion: {_ in }) + delegate?.didReceive(event: .connected(self, headers)) + onEvent?(.connected(headers)) + case .failure(let error): + onEvent?(.error(error)) + } + } + + /// MARK: - FrameCollectorDelegate + + public func frameProcessed(event: FrameEvent) { + switch event { + case .frame(let frame): + frameHandler.add(frame: frame) + case .error(let error): + onEvent?(.error(error)) + } + } + + public func didForm(event: FrameCollector.Event) { + switch event { + case .text(let string): + delegate?.didReceive(event: .text(self, string)) + onEvent?(.text(string)) + case .binary(let data): + delegate?.didReceive(event: .binary(self, data)) + onEvent?(.binary(data)) + case .pong(let data): + delegate?.didReceive(event: .pong(self, data)) + onEvent?(.pong(data)) + case .ping(let data): + delegate?.didReceive(event: .ping(self, data)) + onEvent?(.ping(data)) + case .closed(let reason, let code): + delegate?.didReceive(event: .disconnected(self, reason, code)) + onEvent?(.disconnected(reason, code)) + case .error(let error): + onEvent?(.error(error)) + } + } + + public func decompress(data: Data, isFinal: Bool) -> Data? { + return nil + } +} +#endif diff --git a/Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift b/Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift deleted file mode 100644 index 34109122..00000000 --- a/Pods/Starscream/Sources/Starscream/SSLClientCertificate.swift +++ /dev/null @@ -1,92 +0,0 @@ -// -// SSLClientCertificate.swift -// Starscream -// -// Created by Tomasz Trela on 08/03/2018. -// Copyright © 2018 Vluxe. All rights reserved. -// - -import Foundation - -public struct SSLClientCertificateError: LocalizedError { - public var errorDescription: String? - - init(errorDescription: String) { - self.errorDescription = errorDescription - } -} - -public class SSLClientCertificate { - internal let streamSSLCertificates: NSArray - - /** - Convenience init. - - parameter pkcs12Path: Path to pkcs12 file containing private key and X.509 ceritifacte (.p12) - - parameter password: file password, see **kSecImportExportPassphrase** - */ - public convenience init(pkcs12Path: String, password: String) throws { - let pkcs12Url = URL(fileURLWithPath: pkcs12Path) - do { - try self.init(pkcs12Url: pkcs12Url, password: password) - } catch { - throw error - } - } - - /** - Designated init. For more information, see SSLSetCertificate() in Security/SecureTransport.h. - - parameter identity: SecIdentityRef, see **kCFStreamSSLCertificates** - - parameter identityCertificate: CFArray of SecCertificateRefs, see **kCFStreamSSLCertificates** - */ - public init(identity: SecIdentity, identityCertificate: SecCertificate) { - self.streamSSLCertificates = NSArray(objects: identity, identityCertificate) - } - - /** - Convenience init. - - parameter pkcs12Url: URL to pkcs12 file containing private key and X.509 ceritifacte (.p12) - - parameter password: file password, see **kSecImportExportPassphrase** - */ - public convenience init(pkcs12Url: URL, password: String) throws { - let importOptions = [kSecImportExportPassphrase as String : password] as CFDictionary - do { - try self.init(pkcs12Url: pkcs12Url, importOptions: importOptions) - } catch { - throw error - } - } - - /** - Designated init. - - parameter pkcs12Url: URL to pkcs12 file containing private key and X.509 ceritifacte (.p12) - - parameter importOptions: A dictionary containing import options. A - kSecImportExportPassphrase entry is required at minimum. Only password-based - PKCS12 blobs are currently supported. See **SecImportExport.h** - */ - public init(pkcs12Url: URL, importOptions: CFDictionary) throws { - do { - let pkcs12Data = try Data(contentsOf: pkcs12Url) - var rawIdentitiesAndCertificates: CFArray? - let pkcs12CFData: CFData = pkcs12Data as CFData - let importStatus = SecPKCS12Import(pkcs12CFData, importOptions, &rawIdentitiesAndCertificates) - - guard importStatus == errSecSuccess else { - throw SSLClientCertificateError(errorDescription: "(Starscream) Error during 'SecPKCS12Import', see 'SecBase.h' - OSStatus: \(importStatus)") - } - guard let identitiyAndCertificate = (rawIdentitiesAndCertificates as? Array>)?.first else { - throw SSLClientCertificateError(errorDescription: "(Starscream) Error - PKCS12 file is empty") - } - - let identity = identitiyAndCertificate[kSecImportItemIdentity as String] as! SecIdentity - var identityCertificate: SecCertificate? - let copyStatus = SecIdentityCopyCertificate(identity, &identityCertificate) - guard copyStatus == errSecSuccess else { - throw SSLClientCertificateError(errorDescription: "(Starscream) Error during 'SecIdentityCopyCertificate', see 'SecBase.h' - OSStatus: \(copyStatus)") - } - self.streamSSLCertificates = NSArray(objects: identity, identityCertificate!) - } catch { - throw error - } - } -} - diff --git a/Pods/Starscream/Sources/Starscream/SSLSecurity.swift b/Pods/Starscream/Sources/Starscream/SSLSecurity.swift deleted file mode 100644 index 6a14dd15..00000000 --- a/Pods/Starscream/Sources/Starscream/SSLSecurity.swift +++ /dev/null @@ -1,266 +0,0 @@ -////////////////////////////////////////////////////////////////////////////////////////////////// -// -// SSLSecurity.swift -// Starscream -// -// Created by Dalton Cherry on 5/16/15. -// Copyright (c) 2014-2016 Dalton Cherry. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -////////////////////////////////////////////////////////////////////////////////////////////////// -#if os(Linux) -#else -import Foundation -import Security - -public protocol SSLTrustValidator { - func isValid(_ trust: SecTrust, domain: String?) -> Bool -} - -open class SSLCert { - var certData: Data? - var key: SecKey? - - /** - Designated init for certificates - - - parameter data: is the binary data of the certificate - - - returns: a representation security object to be used with - */ - public init(data: Data) { - self.certData = data - } - - /** - Designated init for public keys - - - parameter key: is the public key to be used - - - returns: a representation security object to be used with - */ - public init(key: SecKey) { - self.key = key - } -} - -open class SSLSecurity : SSLTrustValidator { - public var validatedDN = true //should the domain name be validated? - public var validateEntireChain = true //should the entire cert chain be validated - - var isReady = false //is the key processing done? - var certificates: [Data]? //the certificates - var pubKeys: [SecKey]? //the public keys - var usePublicKeys = false //use public keys or certificate validation? - - /** - Use certs from main app bundle - - - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - - - returns: a representation security object to be used with - */ - public convenience init(usePublicKeys: Bool = false) { - let paths = Bundle.main.paths(forResourcesOfType: "cer", inDirectory: ".") - - let certs = paths.reduce([SSLCert]()) { (certs: [SSLCert], path: String) -> [SSLCert] in - var certs = certs - if let data = NSData(contentsOfFile: path) { - certs.append(SSLCert(data: data as Data)) - } - return certs - } - - self.init(certs: certs, usePublicKeys: usePublicKeys) - } - - /** - Designated init - - - parameter certs: is the certificates or public keys to use - - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - - - returns: a representation security object to be used with - */ - public init(certs: [SSLCert], usePublicKeys: Bool) { - self.usePublicKeys = usePublicKeys - - if self.usePublicKeys { - DispatchQueue.global(qos: .default).async { - let pubKeys = certs.reduce([SecKey]()) { (pubKeys: [SecKey], cert: SSLCert) -> [SecKey] in - var pubKeys = pubKeys - if let data = cert.certData, cert.key == nil { - cert.key = self.extractPublicKey(data) - } - if let key = cert.key { - pubKeys.append(key) - } - return pubKeys - } - - self.pubKeys = pubKeys - self.isReady = true - } - } else { - let certificates = certs.reduce([Data]()) { (certificates: [Data], cert: SSLCert) -> [Data] in - var certificates = certificates - if let data = cert.certData { - certificates.append(data) - } - return certificates - } - self.certificates = certificates - self.isReady = true - } - } - - /** - Valid the trust and domain name. - - - parameter trust: is the serverTrust to validate - - parameter domain: is the CN domain to validate - - - returns: if the key was successfully validated - */ - open func isValid(_ trust: SecTrust, domain: String?) -> Bool { - - var tries = 0 - while !self.isReady { - usleep(1000) - tries += 1 - if tries > 5 { - return false //doesn't appear it is going to ever be ready... - } - } - var policy: SecPolicy - if self.validatedDN { - policy = SecPolicyCreateSSL(true, domain as NSString?) - } else { - policy = SecPolicyCreateBasicX509() - } - SecTrustSetPolicies(trust,policy) - if self.usePublicKeys { - if let keys = self.pubKeys { - let serverPubKeys = publicKeyChain(trust) - for serverKey in serverPubKeys as [AnyObject] { - for key in keys as [AnyObject] { - if serverKey.isEqual(key) { - return true - } - } - } - } - } else if let certs = self.certificates { - let serverCerts = certificateChain(trust) - var collect = [SecCertificate]() - for cert in certs { - collect.append(SecCertificateCreateWithData(nil,cert as CFData)!) - } - SecTrustSetAnchorCertificates(trust,collect as NSArray) - var result: SecTrustResultType = .unspecified - SecTrustEvaluate(trust,&result) - if result == .unspecified || result == .proceed { - if !validateEntireChain { - return true - } - var trustedCount = 0 - for serverCert in serverCerts { - for cert in certs { - if cert == serverCert { - trustedCount += 1 - break - } - } - } - if trustedCount == serverCerts.count { - return true - } - } - } - return false - } - - /** - Get the public key from a certificate data - - - parameter data: is the certificate to pull the public key from - - - returns: a public key - */ - public func extractPublicKey(_ data: Data) -> SecKey? { - guard let cert = SecCertificateCreateWithData(nil, data as CFData) else { return nil } - - return extractPublicKey(cert, policy: SecPolicyCreateBasicX509()) - } - - /** - Get the public key from a certificate - - - parameter data: is the certificate to pull the public key from - - - returns: a public key - */ - public func extractPublicKey(_ cert: SecCertificate, policy: SecPolicy) -> SecKey? { - var possibleTrust: SecTrust? - SecTrustCreateWithCertificates(cert, policy, &possibleTrust) - - guard let trust = possibleTrust else { return nil } - var result: SecTrustResultType = .unspecified - SecTrustEvaluate(trust, &result) - return SecTrustCopyPublicKey(trust) - } - - /** - Get the certificate chain for the trust - - - parameter trust: is the trust to lookup the certificate chain for - - - returns: the certificate chain for the trust - */ - public func certificateChain(_ trust: SecTrust) -> [Data] { - let certificates = (0.. [Data] in - var certificates = certificates - let cert = SecTrustGetCertificateAtIndex(trust, index) - certificates.append(SecCertificateCopyData(cert!) as Data) - return certificates - } - - return certificates - } - - /** - Get the public key chain for the trust - - - parameter trust: is the trust to lookup the certificate chain and extract the public keys - - - returns: the public keys from the certifcate chain for the trust - */ - public func publicKeyChain(_ trust: SecTrust) -> [SecKey] { - let policy = SecPolicyCreateBasicX509() - let keys = (0.. [SecKey] in - var keys = keys - let cert = SecTrustGetCertificateAtIndex(trust, index) - if let key = extractPublicKey(cert!, policy: policy) { - keys.append(key) - } - - return keys - } - - return keys - } - - -} -#endif diff --git a/Pods/Starscream/Sources/Starscream/WebSocket.swift b/Pods/Starscream/Sources/Starscream/WebSocket.swift index 7d48a20d..1d3545c3 100644 --- a/Pods/Starscream/Sources/Starscream/WebSocket.swift +++ b/Pods/Starscream/Sources/Starscream/WebSocket.swift @@ -1,9 +1,10 @@ ////////////////////////////////////////////////////////////////////////////////////////////////// // // Websocket.swift +// Starscream // // Created by Dalton Cherry on 7/16/14. -// Copyright (c) 2014-2017 Dalton Cherry. +// Copyright (c) 2014-2019 Dalton Cherry. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -20,61 +21,31 @@ ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation -import CoreFoundation -import CommonCrypto - -public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification" -public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification" -public let WebsocketDisconnectionErrorKeyName = "WebsocketDisconnectionErrorKeyName" - -//Standard WebSocket close codes -public enum CloseCode : UInt16 { - case normal = 1000 - case goingAway = 1001 - case protocolError = 1002 - case protocolUnhandledType = 1003 - // 1004 reserved. - case noStatusReceived = 1005 - //1006 reserved. - case encoding = 1007 - case policyViolated = 1008 - case messageTooBig = 1009 -} public enum ErrorType: Error { - case outputStreamWriteError //output stream error during write case compressionError - case invalidSSLError //Invalid SSL certificate - case writeTimeoutError //The socket timed out waiting to be ready to write + case securityError case protocolError //There was an error parsing the WebSocket frames - case upgradeError //There was an error during the HTTP upgrade - case closeError //There was an error during the close (socket probably has been dereferenced) + case serverError } public struct WSError: Error { public let type: ErrorType public let message: String - public let code: Int + public let code: UInt16 + + public init(type: ErrorType, message: String, code: UInt16) { + self.type = type + self.message = message + self.code = code + } } -//WebSocketClient is setup to be dependency injection for testing public protocol WebSocketClient: class { - var delegate: WebSocketDelegate? {get set} - var pongDelegate: WebSocketPongDelegate? {get set} - var disableSSLCertValidation: Bool {get set} - var overrideTrustHostname: Bool {get set} - var desiredTrustHostname: String? {get set} - var sslClientCertificate: SSLClientCertificate? {get set} - #if os(Linux) - #else - var security: SSLTrustValidator? {get set} - var enabledSSLCipherSuites: [SSLCipherSuite]? {get set} - #endif - var isConnected: Bool {get} - func connect() - func disconnect(forceTimeout: TimeInterval?, closeCode: UInt16) + func disconnect(closeCode: UInt16) func write(string: String, completion: (() -> ())?) + func write(stringData: Data, completion: (() -> ())?) func write(data: Data, completion: (() -> ())?) func write(ping: Data, completion: (() -> ())?) func write(pong: Data, completion: (() -> ())?) @@ -93,1264 +64,115 @@ extension WebSocketClient { public func write(ping: Data) { write(ping: ping, completion: nil) } - + public func write(pong: Data) { write(pong: pong, completion: nil) } public func disconnect() { - disconnect(forceTimeout: nil, closeCode: CloseCode.normal.rawValue) + disconnect(closeCode: CloseCode.normal.rawValue) } } -//SSL settings for the stream -public struct SSLSettings { - public let useSSL: Bool - public let disableCertValidation: Bool - public var overrideTrustHostname: Bool - public var desiredTrustHostname: String? - public let sslClientCertificate: SSLClientCertificate? - #if os(Linux) - #else - public let cipherSuites: [SSLCipherSuite]? - #endif -} - -public protocol WSStreamDelegate: class { - func newBytesInStream() - func streamDidError(error: Error?) +public enum WebSocketEvent { + case connected([String: String]) + case disconnected(String, UInt16) + case text(String) + case binary(Data) + case pong(Data?) + case ping(Data?) + case error(Error?) + case viabilityChanged(Bool) + case reconnectSuggested(Bool) + case cancelled } -//This protocol is to allow custom implemention of the underlining stream. This way custom socket libraries (e.g. linux) can be used -public protocol WSStream { - var delegate: WSStreamDelegate? {get set} - func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) - func write(data: Data) -> Int - func read() -> Data? - func cleanup() - #if os(Linux) || os(watchOS) - #else - func sslTrust() -> (trust: SecTrust?, domain: String?) - #endif +public protocol WebSocketDelegate: class { + func didReceive(event: WebSocketEvent, client: WebSocket) } -open class FoundationStream : NSObject, WSStream, StreamDelegate { - private let workQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) - private var inputStream: InputStream? - private var outputStream: OutputStream? - public weak var delegate: WSStreamDelegate? - let BUFFER_MAX = 4096 - - public var enableSOCKSProxy = false +open class WebSocket: WebSocketClient, EngineDelegate { + private let engine: Engine + public weak var delegate: WebSocketDelegate? + public var onEvent: ((WebSocketEvent) -> Void)? - public func connect(url: URL, port: Int, timeout: TimeInterval, ssl: SSLSettings, completion: @escaping ((Error?) -> Void)) { - var readStream: Unmanaged? - var writeStream: Unmanaged? - let h = url.host! as NSString - CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream) - inputStream = readStream!.takeRetainedValue() - outputStream = writeStream!.takeRetainedValue() - - #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work - #else - if enableSOCKSProxy { - let proxyDict = CFNetworkCopySystemProxySettings() - let socksConfig = CFDictionaryCreateMutableCopy(nil, 0, proxyDict!.takeRetainedValue()) - let propertyKey = CFStreamPropertyKey(rawValue: kCFStreamPropertySOCKSProxy) - CFWriteStreamSetProperty(outputStream, propertyKey, socksConfig) - CFReadStreamSetProperty(inputStream, propertyKey, socksConfig) - } - #endif - - guard let inStream = inputStream, let outStream = outputStream else { return } - inStream.delegate = self - outStream.delegate = self - if ssl.useSSL { - inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) - outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey) - #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work - #else - var settings = [NSObject: NSObject]() - if ssl.disableCertValidation { - settings[kCFStreamSSLValidatesCertificateChain] = NSNumber(value: false) - } - if ssl.overrideTrustHostname { - if let hostname = ssl.desiredTrustHostname { - settings[kCFStreamSSLPeerName] = hostname as NSString - } else { - settings[kCFStreamSSLPeerName] = kCFNull - } - } - if let sslClientCertificate = ssl.sslClientCertificate { - settings[kCFStreamSSLCertificates] = sslClientCertificate.streamSSLCertificates - } - - inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) - outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey) - #endif - - #if os(Linux) - #else - if let cipherSuites = ssl.cipherSuites { - #if os(watchOS) //watchOS us unfortunately is missing the kCFStream properties to make this work - #else - if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?, - let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { - let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count) - let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count) - if resIn != errSecSuccess { - completion(WSError(type: .invalidSSLError, message: "Error setting ingoing cypher suites", code: Int(resIn))) - } - if resOut != errSecSuccess { - completion(WSError(type: .invalidSSLError, message: "Error setting outgoing cypher suites", code: Int(resOut))) - } - } - #endif - } - #endif + public var request: URLRequest + // Where the callback is executed. It defaults to the main UI thread queue. + public var callbackQueue = DispatchQueue.main + public var respondToPingWithPong: Bool { + set { + guard let e = engine as? WSEngine else { return } + e.respondToPingWithPong = newValue } - - CFReadStreamSetDispatchQueue(inStream, workQueue) - CFWriteStreamSetDispatchQueue(outStream, workQueue) - inStream.open() - outStream.open() - - var out = timeout// wait X seconds before giving up - workQueue.async { [weak self] in - while !outStream.hasSpaceAvailable { - usleep(100) // wait until the socket is ready - out -= 100 - if out < 0 { - completion(WSError(type: .writeTimeoutError, message: "Timed out waiting for the socket to be ready for a write", code: 0)) - return - } else if let error = outStream.streamError { - completion(error) - return // disconnectStream will be called. - } else if self == nil { - completion(WSError(type: .closeError, message: "socket object has been dereferenced", code: 0)) - return - } - } - completion(nil) //success! + get { + guard let e = engine as? WSEngine else { return true } + return e.respondToPingWithPong } } - public func write(data: Data) -> Int { - guard let outStream = outputStream else {return -1} - let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) - return outStream.write(buffer, maxLength: data.count) - } + // serial write queue to ensure writes happen in order + private let writeQueue = DispatchQueue(label: "com.vluxe.starscream.writequeue") + private var canSend = false + private let mutex = DispatchSemaphore(value: 1) - public func read() -> Data? { - guard let stream = inputStream else {return nil} - let buf = NSMutableData(capacity: BUFFER_MAX) - let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) - let length = stream.read(buffer, maxLength: BUFFER_MAX) - if length < 1 { - return nil - } - return Data(bytes: buffer, count: length) + public init(request: URLRequest, engine: Engine) { + self.request = request + self.engine = engine } - public func cleanup() { - if let stream = inputStream { - stream.delegate = nil - CFReadStreamSetDispatchQueue(stream, nil) - stream.close() - } - if let stream = outputStream { - stream.delegate = nil - CFWriteStreamSetDispatchQueue(stream, nil) - stream.close() + public convenience init(request: URLRequest, certPinner: CertificatePinning? = FoundationSecurity(), compressionHandler: CompressionHandler? = nil, useCustomEngine: Bool = true) { + if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *), !useCustomEngine { + self.init(request: request, engine: NativeEngine()) + } else if #available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) { + self.init(request: request, engine: WSEngine(transport: TCPTransport(), certPinner: certPinner, compressionHandler: compressionHandler)) + } else { + self.init(request: request, engine: WSEngine(transport: FoundationTransport(), certPinner: certPinner, compressionHandler: compressionHandler)) } - outputStream = nil - inputStream = nil } - #if os(Linux) || os(watchOS) - #else - public func sslTrust() -> (trust: SecTrust?, domain: String?) { - guard let outputStream = outputStream else { return (nil, nil) } - - let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust? - var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String? - if domain == nil, - let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { - var peerNameLen: Int = 0 - SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen) - var peerName = Data(count: peerNameLen) - let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer) in - SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen) - } - if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 { - domain = peerDomain - } - } - - return (trust, domain) + public func connect() { + engine.register(delegate: self) + engine.start(request: request) } - #endif - /** - Delegate for the stream methods. Processes incoming bytes - */ - open func stream(_ aStream: Stream, handle eventCode: Stream.Event) { - if eventCode == .hasBytesAvailable { - if aStream == inputStream { - delegate?.newBytesInStream() - } - } else if eventCode == .errorOccurred { - delegate?.streamDidError(error: aStream.streamError) - } else if eventCode == .endEncountered { - delegate?.streamDidError(error: nil) - } + public func disconnect(closeCode: UInt16 = CloseCode.normal.rawValue) { + engine.stop(closeCode: closeCode) } -} - -//WebSocket implementation - -//standard delegate you should use -public protocol WebSocketDelegate: class { - func websocketDidConnect(socket: WebSocketClient) - func websocketDidDisconnect(socket: WebSocketClient, error: Error?) - func websocketDidReceiveMessage(socket: WebSocketClient, text: String) - func websocketDidReceiveData(socket: WebSocketClient, data: Data) -} - -//got pongs -public protocol WebSocketPongDelegate: class { - func websocketDidReceivePong(socket: WebSocketClient, data: Data?) -} - -// A Delegate with more advanced info on messages and connection etc. -public protocol WebSocketAdvancedDelegate: class { - func websocketDidConnect(socket: WebSocket) - func websocketDidDisconnect(socket: WebSocket, error: Error?) - func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse) - func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse) - func websocketHttpUpgrade(socket: WebSocket, request: String) - func websocketHttpUpgrade(socket: WebSocket, response: String) -} - - -open class WebSocket : NSObject, StreamDelegate, WebSocketClient, WSStreamDelegate { - - public enum OpCode : UInt8 { - case continueFrame = 0x0 - case textFrame = 0x1 - case binaryFrame = 0x2 - // 3-7 are reserved. - case connectionClose = 0x8 - case ping = 0x9 - case pong = 0xA - // B-F reserved. - } - - public static let ErrorDomain = "WebSocket" - - // Where the callback is executed. It defaults to the main UI thread queue. - public var callbackQueue = DispatchQueue.main - - // MARK: - Constants - - let headerWSUpgradeName = "Upgrade" - let headerWSUpgradeValue = "websocket" - let headerWSHostName = "Host" - let headerWSConnectionName = "Connection" - let headerWSConnectionValue = "Upgrade" - let headerWSProtocolName = "Sec-WebSocket-Protocol" - let headerWSVersionName = "Sec-WebSocket-Version" - let headerWSVersionValue = "13" - let headerWSExtensionName = "Sec-WebSocket-Extensions" - let headerWSKeyName = "Sec-WebSocket-Key" - let headerOriginName = "Origin" - let headerWSAcceptName = "Sec-WebSocket-Accept" - let BUFFER_MAX = 4096 - let FinMask: UInt8 = 0x80 - let OpCodeMask: UInt8 = 0x0F - let RSVMask: UInt8 = 0x70 - let RSV1Mask: UInt8 = 0x40 - let MaskMask: UInt8 = 0x80 - let PayloadLenMask: UInt8 = 0x7F - let MaxFrameSize: Int = 32 - let httpSwitchProtocolCode = 101 - let supportedSSLSchemes = ["wss", "https"] - - public class WSResponse { - var isFin = false - public var code: OpCode = .continueFrame - var bytesLeft = 0 - public var frameCount = 0 - public var buffer: NSMutableData? - public let firstFrame = { - return Date() - }() - } - - // MARK: - Delegates - - /// Responds to callback about new messages coming in over the WebSocket - /// and also connection/disconnect messages. - public weak var delegate: WebSocketDelegate? - - /// The optional advanced delegate can be used instead of of the delegate - public weak var advancedDelegate: WebSocketAdvancedDelegate? - - /// Receives a callback for each pong message recived. - public weak var pongDelegate: WebSocketPongDelegate? - - public var onConnect: (() -> Void)? - public var onDisconnect: ((Error?) -> Void)? - public var onText: ((String) -> Void)? - public var onData: ((Data) -> Void)? - public var onPong: ((Data?) -> Void)? - public var onHttpResponseHeaders: (([String: String]) -> Void)? - - public var disableSSLCertValidation = false - public var overrideTrustHostname = false - public var desiredTrustHostname: String? = nil - public var sslClientCertificate: SSLClientCertificate? = nil - - public var enableCompression = true - #if os(Linux) - #else - public var security: SSLTrustValidator? - public var enabledSSLCipherSuites: [SSLCipherSuite]? - #endif - public var isConnected: Bool { - mutex.lock() - let isConnected = connected - mutex.unlock() - return isConnected - } - public var request: URLRequest //this is only public to allow headers, timeout, etc to be modified on reconnect - public var currentURL: URL { return request.url! } - - public var respondToPingWithPong: Bool = true - - // MARK: - Private - - private struct CompressionState { - var supportsCompression = false - var messageNeedsDecompression = false - var serverMaxWindowBits = 15 - var clientMaxWindowBits = 15 - var clientNoContextTakeover = false - var serverNoContextTakeover = false - var decompressor:Decompressor? = nil - var compressor:Compressor? = nil + public func forceDisconnect() { + engine.forceStop() } - private var stream: WSStream - private var connected = false - private var isConnecting = false - private let mutex = NSLock() - private var compressionState = CompressionState() - private var writeQueue = OperationQueue() - private var readStack = [WSResponse]() - private var inputQueue = [Data]() - private var fragBuffer: Data? - private var certValidated = false - private var didDisconnect = false - private var readyToWrite = false - private var headerSecKey = "" - private var canDispatch: Bool { - mutex.lock() - let canWork = readyToWrite - mutex.unlock() - return canWork + public func write(data: Data, completion: (() -> ())?) { + write(data: data, opcode: .binaryFrame, completion: completion) } - /// Used for setting protocols. - public init(request: URLRequest, protocols: [String]? = nil, stream: WSStream = FoundationStream()) { - self.request = request - self.stream = stream - if request.value(forHTTPHeaderField: headerOriginName) == nil { - guard let url = request.url else {return} - var origin = url.absoluteString - if let hostUrl = URL (string: "/", relativeTo: url) { - origin = hostUrl.absoluteString - origin.remove(at: origin.index(before: origin.endIndex)) - } - self.request.setValue(origin, forHTTPHeaderField: headerOriginName) - } - if let protocols = protocols, !protocols.isEmpty { - self.request.setValue(protocols.joined(separator: ","), forHTTPHeaderField: headerWSProtocolName) - } - writeQueue.maxConcurrentOperationCount = 1 + public func write(string: String, completion: (() -> ())?) { + engine.write(string: string, completion: completion) } - public convenience init(url: URL, protocols: [String]? = nil) { - var request = URLRequest(url: url) - request.timeoutInterval = 5 - self.init(request: request, protocols: protocols) - } - - // Used for specifically setting the QOS for the write queue. - public convenience init(url: URL, writeQueueQOS: QualityOfService, protocols: [String]? = nil) { - self.init(url: url, protocols: protocols) - writeQueue.qualityOfService = writeQueueQOS - } - - /** - Connect to the WebSocket server on a background thread. - */ - open func connect() { - guard !isConnecting else { return } - didDisconnect = false - isConnecting = true - createHTTPRequest() - } - - /** - Disconnect from the server. I send a Close control frame to the server, then expect the server to respond with a Close control frame and close the socket from its end. I notify my delegate once the socket has been closed. - - If you supply a non-nil `forceTimeout`, I wait at most that long (in seconds) for the server to close the socket. After the timeout expires, I close the socket and notify my delegate. - - If you supply a zero (or negative) `forceTimeout`, I immediately close the socket (without sending a Close control frame) and notify my delegate. - - - Parameter forceTimeout: Maximum time to wait for the server to close the socket. - - Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket. - */ - open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) { - guard isConnected else { return } - switch forceTimeout { - case .some(let seconds) where seconds > 0: - let milliseconds = Int(seconds * 1_000) - callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in - self?.disconnectStream(nil) - } - fallthrough - case .none: - writeError(closeCode) - default: - disconnectStream(nil) - break - } - } - - /** - Write a string to the websocket. This sends it as a text frame. - - If you supply a non-nil completion block, I will perform it when the write completes. - - - parameter string: The string to write. - - parameter completion: The (optional) completion handler. - */ - open func write(string: String, completion: (() -> ())? = nil) { - guard isConnected else { return } - dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion) - } - - /** - Write binary data to the websocket. This sends it as a binary frame. - - If you supply a non-nil completion block, I will perform it when the write completes. - - - parameter data: The data to write. - - parameter completion: The (optional) completion handler. - */ - open func write(data: Data, completion: (() -> ())? = nil) { - guard isConnected else { return } - dequeueWrite(data, code: .binaryFrame, writeCompletion: completion) - } - - /** - Write a ping to the websocket. This sends it as a control frame. - Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s - */ - open func write(ping: Data, completion: (() -> ())? = nil) { - guard isConnected else { return } - dequeueWrite(ping, code: .ping, writeCompletion: completion) - } - - /** - Write a pong to the websocket. This sends it as a control frame. - Respond to a Yodel. - */ - open func write(pong: Data, completion: (() -> ())? = nil) { - guard isConnected else { return } - dequeueWrite(pong, code: .pong, writeCompletion: completion) - } - - /** - Private method that starts the connection. - */ - private func createHTTPRequest() { - guard let url = request.url else {return} - var port = url.port - if port == nil { - if supportedSSLSchemes.contains(url.scheme!) { - port = 443 - } else { - port = 80 - } - } - request.setValue(headerWSUpgradeValue, forHTTPHeaderField: headerWSUpgradeName) - request.setValue(headerWSConnectionValue, forHTTPHeaderField: headerWSConnectionName) - headerSecKey = generateWebSocketKey() - request.setValue(headerWSVersionValue, forHTTPHeaderField: headerWSVersionName) - request.setValue(headerSecKey, forHTTPHeaderField: headerWSKeyName) - - if enableCompression { - let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15" - request.setValue(val, forHTTPHeaderField: headerWSExtensionName) - } - let hostValue = request.allHTTPHeaderFields?[headerWSHostName] ?? "\(url.host!):\(port!)" - request.setValue(hostValue, forHTTPHeaderField: headerWSHostName) - - var path = url.absoluteString - let offset = (url.scheme?.count ?? 2) + 3 - path = String(path[path.index(path.startIndex, offsetBy: offset).. String { - var key = "" - let seed = 16 - for _ in 0.. ())?) { + write(data: stringData, opcode: .textFrame, completion: completion) } - - /** - Delegate for the stream methods. Processes incoming bytes - */ - public func newBytesInStream() { - processInputStream() + public func write(ping: Data, completion: (() -> ())?) { + write(data: ping, opcode: .ping, completion: completion) } - public func streamDidError(error: Error?) { - disconnectStream(error) - } - - /** - Disconnect the stream object and notifies the delegate. - */ - private func disconnectStream(_ error: Error?, runDelegate: Bool = true) { - if error == nil { - writeQueue.waitUntilAllOperationsAreFinished() - } else { - writeQueue.cancelAllOperations() - } - - mutex.lock() - cleanupStream() - connected = false - mutex.unlock() - if runDelegate { - doDisconnect(error) - } - } - - /** - cleanup the streams. - */ - private func cleanupStream() { - stream.cleanup() - fragBuffer = nil - } - - /** - Handles the incoming bytes and sending them to the proper processing method. - */ - private func processInputStream() { - let data = stream.read() - guard let d = data else { return } - var process = false - if inputQueue.count == 0 { - process = true - } - inputQueue.append(d) - if process { - dequeueInput() - } - } - - /** - Dequeue the incoming input so it is processed in order. - */ - private func dequeueInput() { - while !inputQueue.isEmpty { - autoreleasepool { - let data = inputQueue[0] - var work = data - if let buffer = fragBuffer { - var combine = NSData(data: buffer) as Data - combine.append(data) - work = combine - fragBuffer = nil - } - let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self) - let length = work.count - if !connected { - processTCPHandshake(buffer, bufferLen: length) - } else { - processRawMessagesInBuffer(buffer, bufferLen: length) - } - inputQueue = inputQueue.filter{ $0 != data } - } - } - } - - /** - Handle checking the inital connection status - */ - private func processTCPHandshake(_ buffer: UnsafePointer, bufferLen: Int) { - let code = processHTTP(buffer, bufferLen: bufferLen) - switch code { - case 0: - break - case -1: - fragBuffer = Data(bytes: buffer, count: bufferLen) - break // do nothing, we are going to collect more data - default: - doDisconnect(WSError(type: .upgradeError, message: "Invalid HTTP upgrade", code: code)) - } - } - - /** - Finds the HTTP Packet in the TCP stream, by looking for the CRLF. - */ - private func processHTTP(_ buffer: UnsafePointer, bufferLen: Int) -> Int { - let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")] - var k = 0 - var totalSize = 0 - for i in 0.. 0 { - let code = validateResponse(buffer, bufferLen: totalSize) - if code != 0 { - return code - } - isConnecting = false - mutex.lock() - connected = true - mutex.unlock() - didDisconnect = false - if canDispatch { - callbackQueue.async { [weak self] in - guard let self = self else { return } - self.onConnect?() - self.delegate?.websocketDidConnect(socket: self) - self.advancedDelegate?.websocketDidConnect(socket: self) - NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self) - } - } - //totalSize += 1 //skip the last \n - let restSize = bufferLen - totalSize - if restSize > 0 { - processRawMessagesInBuffer(buffer + totalSize, bufferLen: restSize) - } - return 0 //success - } - return -1 // Was unable to find the full TCP header. - } - - /** - Validates the HTTP is a 101 as per the RFC spec. - */ - private func validateResponse(_ buffer: UnsafePointer, bufferLen: Int) -> Int { - guard let str = String(data: Data(bytes: buffer, count: bufferLen), encoding: .utf8) else { return -1 } - let splitArr = str.components(separatedBy: "\r\n") - var code = -1 - var i = 0 - var headers = [String: String]() - for str in splitArr { - if i == 0 { - let responseSplit = str.components(separatedBy: .whitespaces) - guard responseSplit.count > 1 else { return -1 } - if let c = Int(responseSplit[1]) { - code = c - } - } else { - let responseSplit = str.components(separatedBy: ":") - guard responseSplit.count > 1 else { break } - let key = responseSplit[0].trimmingCharacters(in: .whitespaces) - let val = responseSplit[1].trimmingCharacters(in: .whitespaces) - headers[key.lowercased()] = val - } - i += 1 - } - advancedDelegate?.websocketHttpUpgrade(socket: self, response: str) - onHttpResponseHeaders?(headers) - if code != httpSwitchProtocolCode { - return code - } - - if let extensionHeader = headers[headerWSExtensionName.lowercased()] { - processExtensionHeader(extensionHeader) - } - - if let acceptKey = headers[headerWSAcceptName.lowercased()] { - if acceptKey.count > 0 { - if headerSecKey.count > 0 { - let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64() - if sha != acceptKey as String { - return -1 - } - } - return 0 - } - } - return -1 - } - - /** - Parses the extension header, setting up the compression parameters. - */ - func processExtensionHeader(_ extensionHeader: String) { - let parts = extensionHeader.components(separatedBy: ";") - for p in parts { - let part = p.trimmingCharacters(in: .whitespaces) - if part == "permessage-deflate" { - compressionState.supportsCompression = true - } else if part.hasPrefix("server_max_window_bits=") { - let valString = part.components(separatedBy: "=")[1] - if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { - compressionState.serverMaxWindowBits = val - } - } else if part.hasPrefix("client_max_window_bits=") { - let valString = part.components(separatedBy: "=")[1] - if let val = Int(valString.trimmingCharacters(in: .whitespaces)) { - compressionState.clientMaxWindowBits = val - } - } else if part == "client_no_context_takeover" { - compressionState.clientNoContextTakeover = true - } else if part == "server_no_context_takeover" { - compressionState.serverNoContextTakeover = true - } - } - if compressionState.supportsCompression { - compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits) - compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits) - } - } - - /** - Read a 16 bit big endian value from a buffer - */ - private static func readUint16(_ buffer: UnsafePointer, offset: Int) -> UInt16 { - return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1]) - } - - /** - Read a 64 bit big endian value from a buffer - */ - private static func readUint64(_ buffer: UnsafePointer, offset: Int) -> UInt64 { - var value = UInt64(0) - for i in 0...7 { - value = (value << 8) | UInt64(buffer[offset + i]) - } - return value - } - - /** - Write a 16-bit big endian value to a buffer. - */ - private static func writeUint16(_ buffer: UnsafeMutablePointer, offset: Int, value: UInt16) { - buffer[offset + 0] = UInt8(value >> 8) - buffer[offset + 1] = UInt8(value & 0xff) + public func write(pong: Data, completion: (() -> ())?) { + write(data: pong, opcode: .pong, completion: completion) } - - /** - Write a 64-bit big endian value to a buffer. - */ - private static func writeUint64(_ buffer: UnsafeMutablePointer, offset: Int, value: UInt64) { - for i in 0...7 { - buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff) - } - } - - /** - Process one message at the start of `buffer`. Return another buffer (sharing storage) that contains the leftover contents of `buffer` that I didn't process. - */ - private func processOneRawMessage(inBuffer buffer: UnsafeBufferPointer) -> UnsafeBufferPointer { - let response = readStack.last - guard let baseAddress = buffer.baseAddress else {return emptyBuffer} - let bufferLen = buffer.count - if response != nil && bufferLen < 2 { - fragBuffer = Data(buffer: buffer) - return emptyBuffer - } - if let response = response, response.bytesLeft > 0 { - var len = response.bytesLeft - var extra = bufferLen - response.bytesLeft - if response.bytesLeft > bufferLen { - len = bufferLen - extra = 0 - } - response.bytesLeft -= len - response.buffer?.append(Data(bytes: baseAddress, count: len)) - _ = processResponse(response) - return buffer.fromOffset(bufferLen - extra) - } else { - let isFin = (FinMask & baseAddress[0]) - let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0]) - let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue) - let isMasked = (MaskMask & baseAddress[1]) - let payloadLen = (PayloadLenMask & baseAddress[1]) - var offset = 2 - if compressionState.supportsCompression && receivedOpcode != .continueFrame { - compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0 - } - if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression { - let errCode = CloseCode.protocolError.rawValue - doDisconnect(WSError(type: .protocolError, message: "masked and rsv data is not currently supported", code: Int(errCode))) - writeError(errCode) - return emptyBuffer - } - let isControlFrame = (receivedOpcode == .connectionClose || receivedOpcode == .ping) - if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame && - receivedOpcode != .textFrame && receivedOpcode != .pong) { - let errCode = CloseCode.protocolError.rawValue - doDisconnect(WSError(type: .protocolError, message: "unknown opcode: \(receivedOpcodeRawValue)", code: Int(errCode))) - writeError(errCode) - return emptyBuffer - } - if isControlFrame && isFin == 0 { - let errCode = CloseCode.protocolError.rawValue - doDisconnect(WSError(type: .protocolError, message: "control frames can't be fragmented", code: Int(errCode))) - writeError(errCode) - return emptyBuffer - } - var closeCode = CloseCode.normal.rawValue - if receivedOpcode == .connectionClose { - if payloadLen == 1 { - closeCode = CloseCode.protocolError.rawValue - } else if payloadLen > 1 { - closeCode = WebSocket.readUint16(baseAddress, offset: offset) - if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1013 && closeCode < 3000) { - closeCode = CloseCode.protocolError.rawValue - } - } - if payloadLen < 2 { - doDisconnect(WSError(type: .protocolError, message: "connection closed by server", code: Int(closeCode))) - writeError(closeCode) - return emptyBuffer - } - } else if isControlFrame && payloadLen > 125 { - writeError(CloseCode.protocolError.rawValue) - return emptyBuffer - } - var dataLength = UInt64(payloadLen) - if dataLength == 127 { - dataLength = WebSocket.readUint64(baseAddress, offset: offset) - offset += MemoryLayout.size - } else if dataLength == 126 { - dataLength = UInt64(WebSocket.readUint16(baseAddress, offset: offset)) - offset += MemoryLayout.size - } - if bufferLen < offset || UInt64(bufferLen - offset) < dataLength { - fragBuffer = Data(bytes: baseAddress, count: bufferLen) - return emptyBuffer - } - var len = dataLength - if dataLength > UInt64(bufferLen) { - len = UInt64(bufferLen-offset) - } - if receivedOpcode == .connectionClose && len > 0 { - let size = MemoryLayout.size - offset += size - len -= UInt64(size) - } - let data: Data - if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor { - do { - data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0) - if isFin > 0 && compressionState.serverNoContextTakeover { - try decompressor.reset() - } - } catch { - let closeReason = "Decompression failed: \(error)" - let closeCode = CloseCode.encoding.rawValue - doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode))) - writeError(closeCode) - return emptyBuffer - } - } else { - data = Data(bytes: baseAddress+offset, count: Int(len)) - } - - if receivedOpcode == .connectionClose { - var closeReason = "connection closed by server" - if let customCloseReason = String(data: data, encoding: .utf8) { - closeReason = customCloseReason - } else { - closeCode = CloseCode.protocolError.rawValue - } - doDisconnect(WSError(type: .protocolError, message: closeReason, code: Int(closeCode))) - writeError(closeCode) - return emptyBuffer - } - if receivedOpcode == .pong { - if canDispatch { - callbackQueue.async { [weak self] in - guard let self = self else { return } - let pongData: Data? = data.count > 0 ? data : nil - self.onPong?(pongData) - self.pongDelegate?.websocketDidReceivePong(socket: self, data: pongData) - } - } - return buffer.fromOffset(offset + Int(len)) - } - var response = readStack.last - if isControlFrame { - response = nil // Don't append pings. - } - if isFin == 0 && receivedOpcode == .continueFrame && response == nil { - let errCode = CloseCode.protocolError.rawValue - doDisconnect(WSError(type: .protocolError, message: "continue frame before a binary or text frame", code: Int(errCode))) - writeError(errCode) - return emptyBuffer - } - var isNew = false - if response == nil { - if receivedOpcode == .continueFrame { - let errCode = CloseCode.protocolError.rawValue - doDisconnect(WSError(type: .protocolError, message: "first frame can't be a continue frame", code: Int(errCode))) - writeError(errCode) - return emptyBuffer - } - isNew = true - response = WSResponse() - response!.code = receivedOpcode! - response!.bytesLeft = Int(dataLength) - response!.buffer = NSMutableData(data: data) - } else { - if receivedOpcode == .continueFrame { - response!.bytesLeft = Int(dataLength) - } else { - let errCode = CloseCode.protocolError.rawValue - doDisconnect(WSError(type: .protocolError, message: "second and beyond of fragment message must be a continue frame", code: Int(errCode))) - writeError(errCode) - return emptyBuffer - } - response!.buffer!.append(data) - } - if let response = response { - response.bytesLeft -= Int(len) - response.frameCount += 1 - response.isFin = isFin > 0 ? true : false - if isNew { - readStack.append(response) - } - _ = processResponse(response) - } - - let step = Int(offset + numericCast(len)) - return buffer.fromOffset(step) - } - } - - /** - Process all messages in the buffer if possible. - */ - private func processRawMessagesInBuffer(_ pointer: UnsafePointer, bufferLen: Int) { - var buffer = UnsafeBufferPointer(start: pointer, count: bufferLen) - repeat { - buffer = processOneRawMessage(inBuffer: buffer) - } while buffer.count >= 2 - if buffer.count > 0 { - fragBuffer = Data(buffer: buffer) - } - } - - /** - Process the finished response of a buffer. - */ - private func processResponse(_ response: WSResponse) -> Bool { - if response.isFin && response.bytesLeft <= 0 { - if response.code == .ping { - if respondToPingWithPong { - let data = response.buffer! // local copy so it is perverse for writing - dequeueWrite(data as Data, code: .pong) - } - } else if response.code == .textFrame { - guard let str = String(data: response.buffer! as Data, encoding: .utf8) else { - writeError(CloseCode.encoding.rawValue) - return false - } - if canDispatch { - callbackQueue.async { [weak self] in - guard let self = self else { return } - self.onText?(str) - self.delegate?.websocketDidReceiveMessage(socket: self, text: str) - self.advancedDelegate?.websocketDidReceiveMessage(socket: self, text: str, response: response) - } - } - } else if response.code == .binaryFrame { - if canDispatch { - let data = response.buffer! // local copy so it is perverse for writing - callbackQueue.async { [weak self] in - guard let self = self else { return } - self.onData?(data as Data) - self.delegate?.websocketDidReceiveData(socket: self, data: data as Data) - self.advancedDelegate?.websocketDidReceiveData(socket: self, data: data as Data, response: response) - } - } - } - readStack.removeLast() - return true - } - return false - } - - /** - Write an error to the socket - */ - private func writeError(_ code: UInt16) { - let buf = NSMutableData(capacity: MemoryLayout.size) - let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) - WebSocket.writeUint16(buffer, offset: 0, value: code) - dequeueWrite(Data(bytes: buffer, count: MemoryLayout.size), code: .connectionClose) - } - - /** - Used to write things to the stream - */ - private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) { - let operation = BlockOperation() - operation.addExecutionBlock { [weak self, weak operation] in - //stream isn't ready, let's wait - guard let self = self else { return } - guard let sOperation = operation else { return } - var offset = 2 - var firstByte:UInt8 = self.FinMask | code.rawValue - var data = data - if [.textFrame, .binaryFrame].contains(code), let compressor = self.compressionState.compressor { - do { - data = try compressor.compress(data) - if self.compressionState.clientNoContextTakeover { - try compressor.reset() - } - firstByte |= self.RSV1Mask - } catch { - // TODO: report error? We can just send the uncompressed frame. - } - } - let dataLength = data.count - let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize) - let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self) - buffer[0] = firstByte - if dataLength < 126 { - buffer[1] = CUnsignedChar(dataLength) - } else if dataLength <= Int(UInt16.max) { - buffer[1] = 126 - WebSocket.writeUint16(buffer, offset: offset, value: UInt16(dataLength)) - offset += MemoryLayout.size - } else { - buffer[1] = 127 - WebSocket.writeUint64(buffer, offset: offset, value: UInt64(dataLength)) - offset += MemoryLayout.size - } - buffer[1] |= self.MaskMask - let maskKey = UnsafeMutablePointer(buffer + offset) - _ = SecRandomCopyBytes(kSecRandomDefault, Int(MemoryLayout.size), maskKey) - offset += MemoryLayout.size - - for i in 0...size] - offset += 1 - } - var total = 0 - while !sOperation.isCancelled { - if !self.readyToWrite { - self.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0)) - break - } - let stream = self.stream - let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self) - let len = stream.write(data: Data(bytes: writeBuffer, count: offset-total)) - if len <= 0 { - self.doDisconnect(WSError(type: .outputStreamWriteError, message: "output stream had an error during write", code: 0)) - break - } else { - total += len - } - if total >= offset { - if let callback = writeCompletion { - self.callbackQueue.async { - callback() - } - } - - break - } - } - } - writeQueue.addOperation(operation) + + private func write(data: Data, opcode: FrameOpCode, completion: (() -> ())?) { + engine.write(data: data, opcode: opcode, completion: completion) } - - /** - Used to preform the disconnect delegate - */ - private func doDisconnect(_ error: Error?) { - guard !didDisconnect else { return } - didDisconnect = true - isConnecting = false - mutex.lock() - connected = false - mutex.unlock() - guard canDispatch else {return} + + // MARK: - EngineDelegate + public func didReceive(event: WebSocketEvent) { callbackQueue.async { [weak self] in - guard let self = self else { return } - self.onDisconnect?(error) - self.delegate?.websocketDidDisconnect(socket: self, error: error) - self.advancedDelegate?.websocketDidDisconnect(socket: self, error: error) - let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] } - NotificationCenter.default.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo) + guard let s = self else { return } + s.delegate?.didReceive(event: event, client: s) + s.onEvent?(event) } } - - // MARK: - Deinit - - deinit { - mutex.lock() - readyToWrite = false - cleanupStream() - mutex.unlock() - writeQueue.cancelAllOperations() - } - -} - -private extension String { - func sha1Base64() -> String { - let data = self.data(using: String.Encoding.utf8)! - var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) - data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) } - return Data(bytes: digest).base64EncodedString() - } -} - -private extension Data { - - init(buffer: UnsafeBufferPointer) { - self.init(bytes: buffer.baseAddress!, count: buffer.count) - } - -} - -private extension UnsafeBufferPointer { - - func fromOffset(_ offset: Int) -> UnsafeBufferPointer { - return UnsafeBufferPointer(start: baseAddress?.advanced(by: offset), count: count - offset) - } - -} - -private let emptyBuffer = UnsafeBufferPointer(start: nil, count: 0) - -#if swift(>=4) -#else -fileprivate extension String { - var count: Int { - return self.characters.count - } } -#endif diff --git a/Pods/Starscream/Sources/Transport/FoundationTransport.swift b/Pods/Starscream/Sources/Transport/FoundationTransport.swift new file mode 100644 index 00000000..8d304f88 --- /dev/null +++ b/Pods/Starscream/Sources/Transport/FoundationTransport.swift @@ -0,0 +1,218 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// FoundationTransport.swift +// Starscream +// +// Created by Dalton Cherry on 1/23/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum FoundationTransportError: Error { + case invalidRequest + case invalidOutputStream + case timeout +} + +public class FoundationTransport: NSObject, Transport, StreamDelegate { + private weak var delegate: TransportEventClient? + private let workQueue = DispatchQueue(label: "com.vluxe.starscream.websocket", attributes: []) + private var inputStream: InputStream? + private var outputStream: OutputStream? + private var isOpen = false + private var onConnect: ((InputStream, OutputStream) -> Void)? + private var isTLS = false + private var certPinner: CertificatePinning? + + public var usingTLS: Bool { + return self.isTLS + } + + public init(streamConfiguration: ((InputStream, OutputStream) -> Void)? = nil) { + super.init() + onConnect = streamConfiguration + } + + deinit { + inputStream?.delegate = nil + outputStream?.delegate = nil + } + + public func connect(url: URL, timeout: Double = 10, certificatePinning: CertificatePinning? = nil) { + guard let parts = url.getParts() else { + delegate?.connectionChanged(state: .failed(FoundationTransportError.invalidRequest)) + return + } + self.certPinner = certificatePinning + self.isTLS = parts.isTLS + var readStream: Unmanaged? + var writeStream: Unmanaged? + let h = parts.host as NSString + CFStreamCreatePairWithSocketToHost(nil, h, UInt32(parts.port), &readStream, &writeStream) + inputStream = readStream!.takeRetainedValue() + outputStream = writeStream!.takeRetainedValue() + guard let inStream = inputStream, let outStream = outputStream else { + return + } + inStream.delegate = self + outStream.delegate = self + + if isTLS { + let key = CFStreamPropertyKey(rawValue: kCFStreamPropertySocketSecurityLevel) + CFReadStreamSetProperty(inStream, key, kCFStreamSocketSecurityLevelNegotiatedSSL) + CFWriteStreamSetProperty(outStream, key, kCFStreamSocketSecurityLevelNegotiatedSSL) + } + + onConnect?(inStream, outStream) + + isOpen = false + CFReadStreamSetDispatchQueue(inStream, workQueue) + CFWriteStreamSetDispatchQueue(outStream, workQueue) + inStream.open() + outStream.open() + + + workQueue.asyncAfter(deadline: .now() + timeout, execute: { [weak self] in + guard let s = self else { return } + if !s.isOpen { + s.delegate?.connectionChanged(state: .failed(FoundationTransportError.timeout)) + } + }) + } + + public func disconnect() { + if let stream = inputStream { + stream.delegate = nil + CFReadStreamSetDispatchQueue(stream, nil) + stream.close() + } + if let stream = outputStream { + stream.delegate = nil + CFWriteStreamSetDispatchQueue(stream, nil) + stream.close() + } + isOpen = false + outputStream = nil + inputStream = nil + } + + public func register(delegate: TransportEventClient) { + self.delegate = delegate + } + + public func write(data: Data, completion: @escaping ((Error?) -> ())) { + guard let outStream = outputStream else { + completion(FoundationTransportError.invalidOutputStream) + return + } + var total = 0 + let buffer = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self) + //NOTE: this might need to be dispatched to the work queue instead of being written inline. TBD. + while total < data.count { + let written = outStream.write(buffer, maxLength: data.count) + if written < 0 { + completion(FoundationTransportError.invalidOutputStream) + return + } + total += written + } + completion(nil) + } + + private func getSecurityData() -> (SecTrust?, String?) { + #if os(watchOS) + return (nil, nil) + #else + guard let outputStream = outputStream else { + return (nil, nil) + } + let trust = outputStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as! SecTrust? + var domain = outputStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as! String? + + if domain == nil, + let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? { + var peerNameLen: Int = 0 + SSLGetPeerDomainNameLength(sslContextOut, &peerNameLen) + var peerName = Data(count: peerNameLen) + let _ = peerName.withUnsafeMutableBytes { (peerNamePtr: UnsafeMutablePointer) in + SSLGetPeerDomainName(sslContextOut, peerNamePtr, &peerNameLen) + } + if let peerDomain = String(bytes: peerName, encoding: .utf8), peerDomain.count > 0 { + domain = peerDomain + } + } + return (trust, domain) + #endif + } + + private func read() { + guard let stream = inputStream else { + return + } + let maxBuffer = 4096 + let buf = NSMutableData(capacity: maxBuffer) + let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self) + let length = stream.read(buffer, maxLength: maxBuffer) + if length < 1 { + return + } + let data = Data(bytes: buffer, count: length) + delegate?.connectionChanged(state: .receive(data)) + } + + // MARK: - StreamDelegate + + open func stream(_ aStream: Stream, handle eventCode: Stream.Event) { + switch eventCode { + case .hasBytesAvailable: + if aStream == inputStream { + read() + } + case .errorOccurred: + delegate?.connectionChanged(state: .failed(aStream.streamError)) + case .endEncountered: + if aStream == inputStream { + delegate?.connectionChanged(state: .cancelled) + } + case .openCompleted: + if aStream == inputStream { + let (trust, domain) = getSecurityData() + if let pinner = certPinner, let trust = trust { + pinner.evaluateTrust(trust: trust, domain: domain, completion: { [weak self] (state) in + switch state { + case .success: + self?.isOpen = true + self?.delegate?.connectionChanged(state: .connected) + case .failed(let error): + self?.delegate?.connectionChanged(state: .failed(error)) + } + + }) + } else { + isOpen = true + delegate?.connectionChanged(state: .connected) + } + } + case .endEncountered: + if aStream == inputStream { + delegate?.connectionChanged(state: .cancelled) + } + default: + break + } + } +} diff --git a/Pods/Starscream/Sources/Transport/TCPTransport.swift b/Pods/Starscream/Sources/Transport/TCPTransport.swift new file mode 100644 index 00000000..459cb2ed --- /dev/null +++ b/Pods/Starscream/Sources/Transport/TCPTransport.swift @@ -0,0 +1,159 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// HTTPTransport.swift +// Starscream +// +// Created by Dalton Cherry on 1/23/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +#if canImport(Network) +import Foundation +import Network + +public enum TCPTransportError: Error { + case invalidRequest +} + +@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) +public class TCPTransport: Transport { + private var connection: NWConnection? + private let queue = DispatchQueue(label: "com.vluxe.starscream.networkstream", attributes: []) + private weak var delegate: TransportEventClient? + private var isRunning = false + private var isTLS = false + + public var usingTLS: Bool { + return self.isTLS + } + + public init(connection: NWConnection) { + self.connection = connection + start() + } + + public init() { + //normal connection, will use the "connect" method below + } + + public func connect(url: URL, timeout: Double = 10, certificatePinning: CertificatePinning? = nil) { + guard let parts = url.getParts() else { + delegate?.connectionChanged(state: .failed(TCPTransportError.invalidRequest)) + return + } + self.isTLS = parts.isTLS + let options = NWProtocolTCP.Options() + options.connectionTimeout = Int(timeout.rounded(.up)) + + let tlsOptions = isTLS ? NWProtocolTLS.Options() : nil + if let tlsOpts = tlsOptions { + sec_protocol_options_set_verify_block(tlsOpts.securityProtocolOptions, { (sec_protocol_metadata, sec_trust, sec_protocol_verify_complete) in + let trust = sec_trust_copy_ref(sec_trust).takeRetainedValue() + guard let pinner = certificatePinning else { + sec_protocol_verify_complete(true) + return + } + pinner.evaluateTrust(trust: trust, domain: parts.host, completion: { (state) in + switch state { + case .success: + sec_protocol_verify_complete(true) + case .failed(_): + sec_protocol_verify_complete(false) + } + }) + }, queue) + } + let parameters = NWParameters(tls: tlsOptions, tcp: options) + let conn = NWConnection(host: NWEndpoint.Host.name(parts.host, nil), port: NWEndpoint.Port(rawValue: UInt16(parts.port))!, using: parameters) + connection = conn + start() + } + + public func disconnect() { + isRunning = false + connection?.cancel() + } + + public func register(delegate: TransportEventClient) { + self.delegate = delegate + } + + public func write(data: Data, completion: @escaping ((Error?) -> ())) { + connection?.send(content: data, completion: .contentProcessed { (error) in + completion(error) + }) + } + + private func start() { + guard let conn = connection else { + return + } + conn.stateUpdateHandler = { [weak self] (newState) in + switch newState { + case .ready: + self?.delegate?.connectionChanged(state: .connected) + case .waiting: + self?.delegate?.connectionChanged(state: .waiting) + case .cancelled: + self?.delegate?.connectionChanged(state: .cancelled) + case .failed(let error): + self?.delegate?.connectionChanged(state: .failed(error)) + case .setup, .preparing: + break + @unknown default: + break + } + } + + conn.viabilityUpdateHandler = { [weak self] (isViable) in + self?.delegate?.connectionChanged(state: .viability(isViable)) + } + + conn.betterPathUpdateHandler = { [weak self] (isBetter) in + self?.delegate?.connectionChanged(state: .shouldReconnect(isBetter)) + } + + conn.start(queue: queue) + isRunning = true + readLoop() + } + + //readLoop keeps reading from the connection to get the latest content + private func readLoop() { + if !isRunning { + return + } + connection?.receive(minimumIncompleteLength: 2, maximumLength: 4096, completion: {[weak self] (data, context, isComplete, error) in + guard let s = self else {return} + if let data = data { + s.delegate?.connectionChanged(state: .receive(data)) + } + + // Refer to https://developer.apple.com/documentation/network/implementing_netcat_with_network_framework + if let context = context, context.isFinal, isComplete { + return + } + + if error == nil { + s.readLoop() + } + + }) + } +} +#else +typealias TCPTransport = FoundationTransport +#endif diff --git a/Pods/Starscream/Sources/Transport/Transport.swift b/Pods/Starscream/Sources/Transport/Transport.swift new file mode 100644 index 00000000..e645651f --- /dev/null +++ b/Pods/Starscream/Sources/Transport/Transport.swift @@ -0,0 +1,55 @@ +////////////////////////////////////////////////////////////////////////////////////////////////// +// +////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Transport.swift +// Starscream +// +// Created by Dalton Cherry on 1/23/19. +// Copyright © 2019 Vluxe. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +////////////////////////////////////////////////////////////////////////////////////////////////// + +import Foundation + +public enum ConnectionState { + case connected + case waiting + case cancelled + case failed(Error?) + + //the viability (connection status) of the connection has updated + //e.g. connection is down, connection came back up, etc + case viability(Bool) + + //the connection has upgrade to wifi from cellular. + //you should consider reconnecting to take advantage of this + case shouldReconnect(Bool) + + //the connection receive data + case receive(Data) +} + +public protocol TransportEventClient: class { + func connectionChanged(state: ConnectionState) +} + +public protocol Transport: class { + func register(delegate: TransportEventClient) + func connect(url: URL, timeout: Double, certificatePinning: CertificatePinning?) + func disconnect() + func write(data: Data, completion: @escaping ((Error?) -> ())) + var usingTLS: Bool { get } +} diff --git a/Pods/Target Support Files/Starscream/Starscream-Info.plist b/Pods/Target Support Files/Starscream/Starscream-Info.plist index 793d31a9..f78cea60 100644 --- a/Pods/Target Support Files/Starscream/Starscream-Info.plist +++ b/Pods/Target Support Files/Starscream/Starscream-Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 3.1.1 + 4.0.4 CFBundleSignature ???? CFBundleVersion