Fix Pods, add Welcome screen

This commit is contained in:
Ivan Grachyov 2021-06-17 20:45:27 +03:00
parent d97e87042c
commit a8925c5da0
31 changed files with 3891 additions and 4545 deletions

View File

@ -27,6 +27,7 @@
2C1995472674C4BA00A8E370 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2C1995452674C4BA00A8E370 /* Main.storyboard */; };
2C1995562674D0F300A8E370 /* Ethereum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C1995552674D0F300A8E370 /* Ethereum.swift */; };
2C6706A5267A6BFE006AAEF2 /* Bundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C6706A4267A6BFE006AAEF2 /* Bundle.swift */; };
2C797E7E267BB88800F2CE2D /* WelcomeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C797E7D267BB88800F2CE2D /* WelcomeViewController.swift */; };
2C8A09B52675101300993638 /* AccountsService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C8A09B42675101300993638 /* AccountsService.swift */; };
2C8A09C6267513FC00993638 /* Agent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C8A09C5267513FC00993638 /* Agent.swift */; };
2C8A09D42675184700993638 /* Window.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C8A09D32675184700993638 /* Window.swift */; };
@ -66,6 +67,7 @@
2C1995492674C4BA00A8E370 /* Encrypted_Ink.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Encrypted_Ink.entitlements; sourceTree = "<group>"; };
2C1995552674D0F300A8E370 /* Ethereum.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Ethereum.swift; sourceTree = "<group>"; };
2C6706A4267A6BFE006AAEF2 /* Bundle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Bundle.swift; sourceTree = "<group>"; };
2C797E7D267BB88800F2CE2D /* WelcomeViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WelcomeViewController.swift; sourceTree = "<group>"; };
2C8A09B42675101300993638 /* AccountsService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountsService.swift; sourceTree = "<group>"; };
2C8A09C5267513FC00993638 /* Agent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Agent.swift; sourceTree = "<group>"; };
2C8A09D32675184700993638 /* Window.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Window.swift; sourceTree = "<group>"; };
@ -186,6 +188,7 @@
isa = PBXGroup;
children = (
2C1995412674C4B900A8E370 /* ImportViewController.swift */,
2C797E7D267BB88800F2CE2D /* WelcomeViewController.swift */,
2CDAB3712675B3F0009F8B97 /* PinViewController.swift */,
2C8A09E72675960D00993638 /* ErrorViewController.swift */,
2C8A09EA2675964700993638 /* ApproveViewController.swift */,
@ -361,6 +364,7 @@
0DB729202674E2DB0011F7A1 /* EIP712Domain.swift in Sources */,
0DB729182674E2DB0011F7A1 /* EIP712Signer.swift in Sources */,
2C8A09EE2675965F00993638 /* WaitingViewController.swift in Sources */,
2C797E7E267BB88800F2CE2D /* WelcomeViewController.swift in Sources */,
0DB729192674E2DB0011F7A1 /* EIP712TypedData.swift in Sources */,
2C8A09E82675960D00993638 /* ErrorViewController.swift in Sources */,
2C1995422674C4B900A8E370 /* ImportViewController.swift in Sources */,

View File

@ -1261,6 +1261,75 @@ DQ
</objects>
<point key="canvasLocation" x="677" y="1177"/>
</scene>
<!--Welcome View Controller-->
<scene sceneID="xdv-om-uKF">
<objects>
<viewController storyboardIdentifier="WelcomeViewController" id="42G-F4-o1P" customClass="WelcomeViewController" customModule="Encrypted_Ink" customModuleProvider="target" sceneMemberID="viewController">
<view key="view" id="n8I-Pv-qZV">
<rect key="frame" x="0.0" y="0.0" width="250" height="350"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" translatesAutoresizingMaskIntoConstraints="NO" id="vxh-AZ-Ll4">
<rect key="frame" x="14" y="292" width="222" height="34"/>
<textFieldCell key="cell" controlSize="large" selectable="YES" alignment="center" title="Encrypted Ink" id="dja-pE-CfV">
<font key="font" metaFont="systemHeavy" size="29"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<stackView distribution="fill" orientation="horizontal" alignment="top" spacing="12" horizontalStackHuggingPriority="249.99998474121094" verticalStackHuggingPriority="249.99998474121094" detachesHiddenViews="YES" translatesAutoresizingMaskIntoConstraints="NO" id="zQX-EK-b8k">
<rect key="frame" x="80" y="50" width="91" height="28"/>
<subviews>
<button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="ADG-H0-CZa">
<rect key="frame" x="-6" y="-6" width="103" height="40"/>
<buttonCell key="cell" type="push" title="Get Started" bezelStyle="rounded" alignment="center" controlSize="large" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="jgC-3I-6bj">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
<string key="keyEquivalent" base64-UTF8="YES">
DQ
</string>
<connections>
<action selector="actionButtonTapped:" target="42G-F4-o1P" id="bQ4-aL-OKd"/>
</connections>
</buttonCell>
</button>
</subviews>
<visibilityPriorities>
<integer value="1000"/>
</visibilityPriorities>
<customSpacing>
<real value="3.4028234663852886e+38"/>
</customSpacing>
</stackView>
<textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" translatesAutoresizingMaskIntoConstraints="NO" id="BvK-xX-gxC">
<rect key="frame" x="26" y="162" width="198" height="50"/>
<textFieldCell key="cell" controlSize="large" selectable="YES" alignment="center" title="Sign crypto transactions." id="4kF-cy-CbK">
<font key="font" metaFont="systemBold" size="21"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
</subviews>
<constraints>
<constraint firstItem="vxh-AZ-Ll4" firstAttribute="leading" secondItem="n8I-Pv-qZV" secondAttribute="leading" constant="16" id="2GM-cf-uH4"/>
<constraint firstItem="BvK-xX-gxC" firstAttribute="trailing" secondItem="vxh-AZ-Ll4" secondAttribute="trailing" constant="-12" id="Abm-DF-vuk"/>
<constraint firstAttribute="trailing" secondItem="vxh-AZ-Ll4" secondAttribute="trailing" constant="16" id="QMd-6k-AoX"/>
<constraint firstItem="zQX-EK-b8k" firstAttribute="centerX" secondItem="n8I-Pv-qZV" secondAttribute="centerX" id="hP0-do-VO9"/>
<constraint firstAttribute="bottom" secondItem="zQX-EK-b8k" secondAttribute="bottom" constant="50" id="hnV-5a-0gu"/>
<constraint firstItem="BvK-xX-gxC" firstAttribute="centerY" secondItem="n8I-Pv-qZV" secondAttribute="centerY" constant="-12" id="iwn-Nu-KVg"/>
<constraint firstItem="BvK-xX-gxC" firstAttribute="leading" secondItem="vxh-AZ-Ll4" secondAttribute="leading" constant="12" id="ntl-wz-qp6"/>
<constraint firstItem="vxh-AZ-Ll4" firstAttribute="top" secondItem="n8I-Pv-qZV" secondAttribute="top" constant="24" id="wzk-IR-5rG"/>
</constraints>
</view>
<connections>
<outlet property="messageLabel" destination="BvK-xX-gxC" id="1F3-ae-gz2"/>
<outlet property="titleLabel" destination="vxh-AZ-Ll4" id="JEh-av-Oj4"/>
</connections>
</viewController>
<customObject id="Anv-AQ-Eke" userLabel="First Responder" customClass="NSResponder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="677" y="315"/>
</scene>
</scenes>
<resources>
<image name="NSApplicationIcon" width="32" height="32"/>

View File

@ -0,0 +1,19 @@
// Copyright © 2021 Encrypted Ink. All rights reserved.
import Cocoa
class WelcomeViewController: NSViewController {
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var messageLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
messageLabel.stringValue = "Sign crypto transactions.\n\nIn any browser.\n\nOn any website."
}
@IBAction func actionButtonTapped(_ sender: Any) {
// TODO: go to password creation
}
}

View File

@ -10,12 +10,12 @@ PODS:
- PromiseKit/Foundation (6.15.3):
- PromiseKit/CorePromise
- secp256k1.swift (0.1.4)
- Starscream (4.0.4)
- Starscream (3.1.1)
- SwiftyJSON (4.3.0)
- WalletConnect (0.1.0):
- CryptoSwift
- PromiseKit
- Starscream
- Starscream (~> 3.1.1)
- Web3Swift.io (0.0.4):
- BigInt (~> 5.0)
- CryptoSwift (~> 1.0)
@ -47,7 +47,7 @@ EXTERNAL SOURCES:
CHECKOUT OPTIONS:
WalletConnect:
:commit: 689c28f519a615310d493a7e638974bfff6d0ce9
:commit: 30040bab47c26002648eec96ed6c19403cc38d71
:git: https://github.com/grachyov/wallet-connect-swift
Web3Swift.io:
:commit: 4e04054ac06a9875137ebbfac5a4b8c9f94d49f6
@ -59,9 +59,9 @@ SPEC CHECKSUMS:
CryptoSwift: 7cc902df1784de3b389a387756c7d710f197730c
PromiseKit: 3b2b6995e51a954c46dbc550ce3da44fbfb563c5
secp256k1.swift: a7e7a214f6db6ce5db32cc6b2b45e5c4dd633634
Starscream: 5178aed56b316f13fa3bc55694e583d35dd414d9
Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0
SwiftyJSON: 6faa0040f8b59dead0ee07436cbf76b73c08fd08
WalletConnect: 366f1790394831a768dfc77c8c4f35f8fbdaae31
WalletConnect: 1df75d4355b1cacfc27d7ef2416fae43862d0eb4
Web3Swift.io: 18fd06aed9d56df9c704f9c6f87b06675bb05b53
PODFILE CHECKSUM: ade248ecc3a8a618186e3d3d754de44149e11bd9

View File

@ -29,7 +29,7 @@
],
"Starscream": [
"~> 3.1.1"
],
"PromiseKit": [

10
Pods/Manifest.lock generated
View File

@ -10,12 +10,12 @@ PODS:
- PromiseKit/Foundation (6.15.3):
- PromiseKit/CorePromise
- secp256k1.swift (0.1.4)
- Starscream (4.0.4)
- Starscream (3.1.1)
- SwiftyJSON (4.3.0)
- WalletConnect (0.1.0):
- CryptoSwift
- PromiseKit
- Starscream
- Starscream (~> 3.1.1)
- Web3Swift.io (0.0.4):
- BigInt (~> 5.0)
- CryptoSwift (~> 1.0)
@ -47,7 +47,7 @@ EXTERNAL SOURCES:
CHECKOUT OPTIONS:
WalletConnect:
:commit: 689c28f519a615310d493a7e638974bfff6d0ce9
:commit: 30040bab47c26002648eec96ed6c19403cc38d71
:git: https://github.com/grachyov/wallet-connect-swift
Web3Swift.io:
:commit: 4e04054ac06a9875137ebbfac5a4b8c9f94d49f6
@ -59,9 +59,9 @@ SPEC CHECKSUMS:
CryptoSwift: 7cc902df1784de3b389a387756c7d710f197730c
PromiseKit: 3b2b6995e51a954c46dbc550ce3da44fbfb563c5
secp256k1.swift: a7e7a214f6db6ce5db32cc6b2b45e5c4dd633634
Starscream: 5178aed56b316f13fa3bc55694e583d35dd414d9
Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0
SwiftyJSON: 6faa0040f8b59dead0ee07436cbf76b73c08fd08
WalletConnect: 366f1790394831a768dfc77c8c4f35f8fbdaae31
WalletConnect: 1df75d4355b1cacfc27d7ef2416fae43862d0eb4
Web3Swift.io: 18fd06aed9d56df9c704f9c6f87b06675bb05b53
PODFILE CHECKSUM: ade248ecc3a8a618186e3d3d754de44149e11bd9

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,18 @@
![starscream](https://raw.githubusercontent.com/daltoniam/starscream/assets/starscream.jpg)
Starscream is a conforming WebSocket ([RFC 6455](http://tools.ietf.org/html/rfc6455)) library in Swift.
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)
## Features
- Conforms to all of the base [Autobahn test suite](https://crossbar.io/autobahn/).
- Conforms to all of the base [Autobahn test suite](http://autobahn.ws/testsuite/).
- 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.
### Import the framework
## Example
First thing is to import the framework. See the Installation instructions on how to add the framework to your project.
@ -17,65 +20,94 @@ 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
var request = URLRequest(url: URL(string: "http://localhost:8080")!)
request.timeoutInterval = 5
socket = WebSocket(request: request)
socket = WebSocket(url: URL(string: "ws://localhost:8080/")!)
socket.delegate = self
socket.connect()
```
After you are connected, there is either a delegate or closure you can use for process WebSocket events.
After you are connected, there are some delegate methods that we need to implement.
### Receiving data from a WebSocket
### websocketDidConnect
`didReceive` receives all the WebSocket events in a single easy to handle enum.
websocketDidConnect is called as soon as the client connects to the server.
```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)
}
func websocketDidConnect(socket: WebSocketClient) {
print("websocket is connected")
}
```
The closure of this would be:
### websocketDidDisconnect
websocketDidDisconnect is called as soon as the client is disconnected from the server.
```swift
socket.onEvent = { event in
switch event {
// handle events just like above...
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
print("websocket is disconnected: \(error?.localizedDescription)")
}
```
### Writing to a WebSocket
### 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)")
}
```
Or you can use closures.
```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)")
}
//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?
### write a binary frame
@ -128,49 +160,98 @@ The disconnect method does what you would expect and closes the socket.
socket.disconnect()
```
The disconnect method can also send a custom close code if desired.
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.
```swift
socket.disconnect(closeCode: CloseCode.normal.rawValue)
socket.disconnect(forceTimeout: 10, closeCode: CloseCode.normal.rawValue)
```
### Custom Headers, Protocols and Timeout
### isConnected
You can override the default websocket headers, add your own custom ones and set a 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:
```swift
var request = URLRequest(url: URL(string: "ws://localhost:8080/")!)
request.timeoutInterval = 5 // Sets the timeout for the connection
request.timeoutInterval = 5
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.
Allow Self-signed certificates:
### SSL Cipher Suites
To use an SSL encrypted connection, you need to tell Starscream about the cipher suites your server supports.
```swift
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)
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]
```
TODO: Update docs on how to load certificates and public keys into an app bundle, use the builtin pinner and TrustKit.
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.
### 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
var request = URLRequest(url: URL(string: "ws://localhost:8080/")!)
let compression = WSCompression()
let socket = WebSocket(request: request, compressionHandler: compression)
socket = WebSocket(url: URL(string: "ws://localhost:8080/")!)
socket.enableCompression = false
```
Compression should be disabled if your application is transmitting already-compressed, random, or other uncompressable data.
@ -191,7 +272,7 @@ Check out the SimpleTest project in the examples directory to see how to setup a
## Requirements
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.
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.
## Installation
@ -205,7 +286,7 @@ To use Starscream in your project add the following 'Podfile' to your project
platform :ios, '9.0'
use_frameworks!
pod 'Starscream', '~> 4.0.0'
pod 'Starscream', '~> 3.0.2'
Then run:
@ -227,7 +308,7 @@ $ brew install carthage
To integrate Starscream into your Xcode project using Carthage, specify it in your `Cartfile`:
```
github "daltoniam/Starscream" >= 4.0.0
github "daltoniam/Starscream" >= 3.0.2
```
### Accio
@ -237,7 +318,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: "4.0.0")),
.package(url: "https://github.com/daltoniam/Starscream.git", .upToNextMajor(from: "3.1.0")),
```
Next, add `Starscream` to your App targets dependencies like so:
@ -273,7 +354,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: 4)
.Package(url: "https://github.com/daltoniam/Starscream.git", majorVersion: 3)
]
```
@ -287,9 +368,58 @@ 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
- [ ] Proxy support
- [ ] Add Unit Tests - Local WebSocket server that runs against Autobahn
## License

View File

@ -1,29 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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?
}

View File

@ -1,53 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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<ResultType, ContentType>(_ completion: (UnsafePointer<ContentType>) 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<ResultType, ContentType>(_ completion: (UnsafeMutablePointer<ContentType>) 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
}

View File

@ -1,22 +0,0 @@
//
// 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: (() -> ())?)
}

View File

@ -1,96 +0,0 @@
//
// 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)))
}
}

View File

@ -1,234 +0,0 @@
//
// 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<UInt16>.size
var pointer = [UInt8](repeating: 0, count: capacity)
writeUint16(&pointer, offset: 0, value: closeCode)
let payload = Data(bytes: pointer, count: MemoryLayout<UInt16>.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.endIndex)
framer.add(data: extraData)
}
}
case .cancelled:
broadcast(event: .cancelled)
}
}
// MARK: - HTTPHandlerDelegate
public func didReceiveHTTP(event: HTTPEvent) {
switch event {
case .success(let headers):
if let error = headerChecker.validate(headers: headers, key: secKeyValue) {
handleError(error)
return
}
mutex.wait()
didUpgrade = true
canSend = true
mutex.signal()
compressionHandler?.load(headers: headers)
if let url = request.url {
HTTPCookie.cookies(withResponseHeaderFields: headers, for: url).forEach {
HTTPCookieStorage.shared.setCookie($0)
}
}
broadcast(event: .connected(headers))
case .failure(let error):
handleError(error)
}
}
// MARK: - FramerEventClient
public func frameProcessed(event: FrameEvent) {
switch event {
case .frame(let frame):
frameHandler.add(frame: frame)
case .error(let error):
handleError(error)
}
}
// MARK: - FrameCollectorDelegate
public func decompress(data: Data, isFinal: Bool) -> 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()
}
}

View File

@ -1,123 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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..<offset))
} else {
buffer.append(data)
}
if parseContent(data: buffer) {
buffer = Data()
}
return offset
}
//returns true when the buffer should be cleared
func parseContent(data: Data) -> 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.count {
if pointer[i] == endBytes[k] {
k += 1
if k == 4 {
return i + 1
}
} else {
k = 0
}
}
return -1
}
}
#endif

View File

@ -1,99 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// FoundationHTTPHandler.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 class FoundationHTTPServerHandler: HTTPServerHandler {
var buffer = Data()
weak var delegate: HTTPServerDelegate?
let getVerb: NSString = "GET"
public func register(delegate: HTTPServerDelegate) {
self.delegate = delegate
}
public func createResponse(headers: [String: String]) -> 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
}
}

View File

@ -1,107 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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
}
}

View File

@ -1,365 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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<UInt16>.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<UInt64>.size
if size + offset > pointer.count {
return .needsMoreData
}
dataLength = pointer.readUint64(offset: offset)
offset += size
} else if payloadLen == 126 {
let size = MemoryLayout<UInt16>.size
if size + offset > pointer.count {
return .needsMoreData
}
dataLength = UInt64(pointer.readUint16(offset: offset))
offset += size
}
let maskStart = offset
if isServer {
offset += MemoryLayout<UInt32>.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..<end])
}
}
offset += readDataLength
let frame = Frame(isFin: isFin > 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<UInt16>.size
} else {
pointer[1] = 127
writeUint64(&pointer, offset: offset, value: UInt64(payloadLength))
offset += MemoryLayout<UInt64>.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<UInt32>.size
//now write the payload data in
for i in 0..<payloadLength {
pointer[offset] = payload[i] ^ pointer[maskStart + (i % MemoryLayout<UInt32>.size)]
offset += 1
}
} else {
for i in 0..<payloadLength {
pointer[offset] = payload[i]
offset += 1
}
}
return Data(pointer[0..<offset])
}
}
/// MARK: - functions for simpler array buffer reading and writing
public protocol MyWSArrayType {}
extension UInt8: MyWSArrayType {}
public extension Array where Element: MyWSArrayType & UnsignedInteger {
/**
Read a UInt16 from a buffer.
- parameter offset: is the offset index to start the read from (e.g. buffer[0], buffer[1], etc).
- returns: a UInt16 of the value from the buffer
*/
func readUint16(offset: Int) -> 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<UInt32>.size
for i in 0..<length {
unmaskedBytes[i] = UInt8(self[offset + i] ^ self[maskStart + (i % maskSize)])
}
return Data(unmaskedBytes)
}
}
/**
Write a UInt16 to the buffer. It fills the 2 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 writeUint16( _ buffer: inout [UInt8], offset: Int, value: UInt16) {
buffer[offset + 0] = UInt8(value >> 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)
}
}

View File

@ -1,148 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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)
}
}

View File

@ -1,143 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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)..<path.endIndex])
if let range = path.range(of: "/") {
path = String(path[range.lowerBound..<path.endIndex])
} else {
path = "/"
if let query = url.query {
path += "?" + query
}
}
var httpBody = "\(request.httpMethod ?? "GET") \(path) HTTP/1.1\r\n"
if let headers = request.allHTTPHeaderFields {
for (key, val) in headers {
httpBody += "\(key): \(val)\r\n"
}
}
httpBody += "\r\n"
guard var data = httpBody.data(using: .utf8) else {
return Data()
}
if let body = request.httpBody {
data.append(body)
}
return data
}
public func parse(data: Data) -> Int {
let offset = findEndOfHTTP(data: data)
if offset > 0 {
buffer.append(data.subdata(in: 0..<offset))
if parseContent(data: buffer) {
buffer = Data()
}
} else {
buffer.append(data)
}
return offset
}
//returns true when the buffer should be cleared
func parseContent(data: Data) -> 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..<data.count {
if pointer[i] == endBytes[k] {
k += 1
if k == 4 {
return i + 1
}
} else {
k = 0
}
}
return -1
}
}

View File

@ -1,101 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// FoundationSecurity.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
import CommonCrypto
public enum FoundationSecurityError: Error {
case invalidRequest
}
public class FoundationSecurity {
var allowSelfSigned = false
public init(allowSelfSigned: Bool = false) {
self.allowSelfSigned = allowSelfSigned
}
}
extension FoundationSecurity: CertificatePinning {
public func evaluateTrust(trust: SecTrust, domain: String?, completion: ((PinningState) -> ())) {
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()
}
}

View File

@ -1,45 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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?
}

View File

@ -1,56 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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?
}

View File

@ -1,196 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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

View File

@ -1,9 +1,9 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// WSCompression.swift
// Compression.swift
//
// Created by Joseph Ross on 7/16/14.
// Copyright © 2017 Joseph Ross & Vluxe. All rights reserved.
// Copyright © 2017 Joseph Ross.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@ -29,81 +29,13 @@
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 }
}
@ -124,7 +56,7 @@ class Decompressor {
}
func decompress(_ data: Data, finish: Bool) throws -> Data {
return try data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Data in
return try data.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) -> Data in
return try decompress(bytes: bytes, count: data.count, finish: finish)
}
}
@ -139,20 +71,19 @@ class Decompressor {
}
return decompressed
}
private func decompress(bytes: UnsafePointer<UInt8>, count: Int, out: inout Data) throws {
var res: CInt = 0
private func decompress(bytes: UnsafePointer<UInt8>, count: Int, out:inout Data) throws {
var res:CInt = 0
strm.next_in = UnsafeMutablePointer<UInt8>(mutating: bytes)
strm.avail_in = CUnsignedInt(count)
repeat {
buffer.withUnsafeMutableBytes { (bufferPtr) in
strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress
strm.avail_out = CUnsignedInt(bufferPtr.count)
strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
strm.avail_out = CUnsignedInt(buffer.count)
res = inflate(&strm, 0)
}
res = inflate(&strm, 0)
let byteCount = buffer.count - Int(strm.avail_out)
out.append(buffer, count: byteCount)
@ -180,7 +111,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
@ -205,18 +136,16 @@ class Compressor {
func compress(_ data: Data) throws -> Data {
var compressed = Data()
var res: CInt = 0
var res:CInt = 0
data.withUnsafeBytes { (ptr:UnsafePointer<UInt8>) -> Void in
strm.next_in = UnsafeMutablePointer<UInt8>(mutating: ptr)
strm.avail_in = CUnsignedInt(data.count)
repeat {
buffer.withUnsafeMutableBytes { (bufferPtr) in
strm.next_out = bufferPtr.bindMemory(to: UInt8.self).baseAddress
strm.avail_out = CUnsignedInt(bufferPtr.count)
strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
strm.avail_out = CUnsignedInt(buffer.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)
@ -245,3 +174,4 @@ class Compressor {
teardownDeflate()
}
}

View File

@ -0,0 +1,92 @@
//
// 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<Dictionary<String, Any>>)?.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
}
}
}

View File

@ -0,0 +1,266 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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..<SecTrustGetCertificateCount(trust)).reduce([Data]()) { (certificates: [Data], index: Int) -> [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..<SecTrustGetCertificateCount(trust)).reduce([SecKey]()) { (keys: [SecKey], index: Int) -> [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

File diff suppressed because it is too large Load Diff

View File

@ -1,218 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
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<Int8>) 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
}
}
}

View File

@ -1,159 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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

View File

@ -1,55 +0,0 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// 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 }
}

View File

@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>4.0.4</string>
<string>3.1.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>