Compare commits

...

67 Commits

Author SHA1 Message Date
daltoniam 86310e7bbc updated podspec 2017-07-07 15:18:08 -05:00
daltoniam 7edfb2ad85 the joys of getting all the package manager to play nice 2017-07-07 14:38:47 -05:00
daltoniam 09b9136ef0 updated changelog 2017-06-29 17:48:36 -05:00
daltoniam 5434be279c updated pod spec for compression changes 2017-06-29 17:46:31 -05:00
Dalton 08edd54a40 Merge pull request #349 from giullo/Fix-SSL-Pinning-Crash
SecTrust object now is conditionally unwrapped
2017-06-29 17:44:18 -05:00
Giuliano Galea 8623fe8b9e SecTrust object now is conditionally unwrapped 2017-06-27 10:29:29 +02:00
daltoniam fa85b9c61c spm fix 2017-06-24 19:09:03 -05:00
daltoniam 6e9a33a854 spm fix 2017-06-24 18:55:53 -05:00
daltoniam b5e68fceae package manager update 2017-06-24 18:13:24 -05:00
daltoniam 601ef74ca4 fixes #309, #319, #334 2017-06-24 18:09:48 -05:00
Dalton 7e517c246b Merge pull request #337 from hishnash/AdvancedDelegate
Add Advanced Delegate and Custom HTTP methods
2017-06-24 14:54:36 -05:00
Dalton bb11123729 Merge pull request #344 from wittedhaddock/patch-1
Update README with (trite) grammar changes
2017-06-24 14:46:35 -05:00
Dalton 7bf478ce94 Merge pull request #339 from junelife/compression
Support websocket compression
2017-06-24 14:45:25 -05:00
Matthaus Woolard bce64dabfa make WSResponse values public 2017-06-18 14:02:12 +03:00
Matthaus Woolard 3104c289e9 Add Advanced Delegate and Custom HTTP methods
Added the `WebSocketAdvancedDelegate` protocol that optionaly replaces the `WebSocketDelegate` adding support for:

* More detail when getting data (exposes the WSFrame object to the delegate)
* More detail about the HTTP request and response so that the user can extract needed information.

Also added support for custom HTTP methods for the http request.
2017-06-18 12:08:07 +03:00
James Graham f35266534a Update README with (trite) grammar changes 2017-06-06 10:46:07 -04:00
Joseph Ross 44fdfa3791 Include zlib as a module, rather than using @_silgen_name and redefinition. This is less verbose and less error-prone. 2017-05-25 14:23:07 -07:00
Joseph Ross 35fc161193 Add information about compression support to README. Other changes based on PR feedback. 2017-05-25 10:24:51 -07:00
Joseph Ross 45546818fb Avoid unnecessary copying. Confirm Autobahn fuzzing test results are comparable with the autobahn library itself. 2017-05-24 17:17:12 -07:00
Joseph Ross 19793796bb Fix capture memory leaks in Autobahn tester. 2017-05-24 13:39:06 -07:00
Joseph Ross 4ba077ee4b Fixes to handle different windowsBits and noContextTakeover. 2017-05-24 13:06:37 -07:00
Joseph Ross ca85642c21 Integrate compression classes. 2017-05-24 12:01:43 -07:00
Joseph Ross ccc9c4ea43 Add compression classes and unit tests. 2017-05-24 07:38:03 -07:00
Dalton 02718e7a45 Merge pull request #333 from nuclearace/master
Remove void parameter from onConnect, Swift4 would require passi…
2017-05-23 13:39:55 -05:00
Erik 961fd34f3d Remove void parameter from onConnect, Swift4 would require passing () into it 2017-05-20 21:40:38 -04:00
Dalton ee993322c1 Merge pull request #320 from RaghavMangrola/master
Swift Package Manager Installation Instructions
2017-03-28 20:15:52 -05:00
daltoniam 85070aab91 few warning fixes 2017-03-28 20:09:07 -05:00
Raghav Mangrola 07351dcb77 Swift Package Manager Installation Instructions 2017-03-19 16:11:13 -07:00
daltoniam dbeb1190b8 some cleanup and SSL pinning fix 2017-03-14 13:12:39 -05:00
daltoniam 13859364e3 updated changelog 2017-02-03 14:25:31 -06:00
daltoniam 41c0c5e08b version bump 2017-02-03 14:20:21 -06:00
daltoniam 60b27a4388 possible fix for #301 2017-01-11 22:55:39 -06:00
daltoniam a68bf7c35b connect delegate before firing message delegates. Fixed disconnect getting called before connect 2017-01-11 12:10:33 -06:00
Dalton 33a4551f3b Merge pull request #302 from Elethier/operation-cancellation
Fixed issues with not cancelling block operations properly
2017-01-10 22:25:12 -06:00
Dalton b22fae407e Merge pull request #300 from Elethier/multiple-disconnects
Added guard against multiple disconnects
2017-01-10 21:41:02 -06:00
Dalton e9160df255 Merge pull request #296 from nuclearace/fix-disconnect
Fix #295
2017-01-06 21:32:13 -06:00
Praneet Sahgal c63e173021 Fixed issues with not cancelling block operations properly 2017-01-04 09:15:56 -06:00
Praneet Sahgal ddcc30d200 Added guard against multiple disconnects 2017-01-04 09:03:42 -06:00
Erik 6bacb6f972 Fix #295
This sets didDisconnect to false if we receive a connect.
2016-12-31 18:05:11 -05:00
Dalton aca2ad5332 Merge pull request #292 from euskadi31/master
Change public to open
2016-12-30 16:32:51 -06:00
Dalton 3ba1963c65 Merge pull request #294 from wordpress-mobile/prevent-reconnection-crash
Prevent reconnection crash
2016-12-30 15:56:12 -06:00
Dalton 3cc4a60e05 Merge pull request #289 from robinmj/master
Fix for excessive memory use caused by the receipt of an unusually large message
2016-12-30 15:54:37 -06:00
Jorge Bernal 14313df360 Disconnect and clean up streams before connecting.
Since `disconnect` without a timeout only sends a close message to the server,
if we tried to `connect` the socket again before the connection was closed it
would not clean up the streams properly, which could result in a crash.

See #272
2016-12-27 16:23:39 +01:00
Jorge Bernal 162c1d53b8 Keep isConnecting true while connecting.
The existing code only prevented a second connection to be created while
createHTTPRequest was being called (setting up the HTTP request and the
streams). However, between the time when the socket opens the streams until the
TCP handshake ends, it would be both `!conneted` and `!isConnecting`, which
wouldn't prevent a second `connect`.
2016-12-27 15:56:01 +01:00
Axel Etcheverry b404f98244 Change public to open 2016-12-19 15:31:10 +01:00
daltoniam 8d0c0c1afa simple test update 2016-12-12 13:26:41 -06:00
Dalton 816fe413a4 Merge pull request #288 from dancasimiro/host-only-origin
Remove the path components from the URL sent as origin
2016-12-12 13:22:27 -06:00
Daniel C. Casimiro 5cc0d860ba Add path components to the test server URL
This demonstrates the path stripping from the origin URL.
2016-11-22 08:53:45 -05:00
Daniel C. Casimiro 4d2f8dbfee Remove the path components from the URL sent as origin
This fixes issue #287. The origin is a URI indicating the server from
which the request initiated. It does not include any path information,
but only the server name.
2016-11-22 08:53:45 -05:00
Robin Johnson 126c021e61 fixed malloc failure by draining autorelease pool with every dequeuing operation 2016-11-21 19:14:20 -07:00
daltoniam c13584b99c bumped spec 2016-11-14 22:29:34 -06:00
Dalton 178c3e8a49 Merge pull request #277 from nuclearace/master
Fix Swift package manager
2016-11-01 18:57:49 -05:00
Erik ccc1b703dd Fix Swift package manager 2016-10-30 19:47:58 -04:00
daltoniam 1b64f78542 version bump 2016-10-26 20:41:30 -05:00
Dalton 549500a503 Merge pull request #253 from noremac/master
Only disable SSL cert validation if we are using a secure scheme.
2016-10-26 20:26:58 -05:00
Dalton 22d57dca07 Merge pull request #276 from profer/master
Enable custom trust validation
2016-10-26 20:26:30 -05:00
daltoniam dd5119cfce fix for #261 2016-10-26 20:25:39 -05:00
Wolfgang Profer a6b2e4329b Enable custom trust validation
Change WebSocket to use a protocol for trust validation instead of SSLSecurity directly. This allows users of Starscream to supply their own validation logic.
2016-10-24 13:43:44 +02:00
Dalton 931e3ba8ae Merge pull request #266 from fjcaetano/master
'Open'ing classes
2016-10-11 23:23:09 -05:00
Dalton 7476f5196e Merge pull request #267 from Dipak99041012/2.0.0HotFixes
[Fixup] crash for SSL Pinning Strange crash
2016-10-11 23:20:28 -05:00
Dipak Kasabwala 20285cce97 [Fixup] crash for SSL Pinning Strange crash 2016-10-10 18:14:01 -04:00
Flávio Caetano 8e1de1d475 'Open'ing classes 2016-10-10 17:47:13 -03:00
Cameron Pulsford acf64adc24 Only disable SSL cert validation if we are using a secure scheme. 2016-09-30 14:49:26 -04:00
Dalton b0fa08cde4 Merge pull request #259 from robinkunde/master
Improve clarity of asyncAfter code and other timeout
2016-09-30 13:34:49 -05:00
Dalton 9d32864ab4 Merge pull request #260 from ujell/master
Fixed parameter names in documentation
2016-09-30 13:02:28 -05:00
Yücel Uzun 7ef2bc41e0 Fixed parameter names in documentation 2016-09-29 18:50:22 +02:00
Robin Kunde 24e32a78e3 improve clarity of asyncAfter code and other timeout 2016-09-28 12:27:48 -04:00
22 changed files with 849 additions and 183 deletions
+48
View File
@@ -2,6 +2,54 @@
All notable changes to this project will be documented in this file.
`Starscream` adheres to [Semantic Versioning](http://semver.org/).
#### [2.1.0](https://github.com/daltoniam/Starscream/tree/2.1.0)
Adds WebSocket compression. Also adds advance WebSocket delegate for extra control. Bug Fixes.
[#349](https://github.com/daltoniam/Starscream/pull/349)
[#344](https://github.com/daltoniam/Starscream/pull/344)
[#339](https://github.com/daltoniam/Starscream/pull/339)
[#337](https://github.com/daltoniam/Starscream/pull/337)
[#334](https://github.com/daltoniam/Starscream/issues/334)
[#333](https://github.com/daltoniam/Starscream/pull/333)
[#319](https://github.com/daltoniam/Starscream/issues/319)
[#309](https://github.com/daltoniam/Starscream/issues/309)
[#329](https://github.com/daltoniam/Starscream/issues/329)
#### [2.0.4](https://github.com/daltoniam/Starscream/tree/2.0.4)
SSL Pinning fix by Giuliano Galea as reported by Lukas Futera of [Centralway](https://www.centralway.com/de/).
Warning fixes for Swift 3.1
#### [2.0.3](https://github.com/daltoniam/Starscream/tree/2.0.3)
[#302](https://github.com/daltoniam/Starscream/issues/302)
[#301](https://github.com/daltoniam/Starscream/issues/301)
[#300](https://github.com/daltoniam/Starscream/issues/300)
[#296](https://github.com/daltoniam/Starscream/issues/296)
[#294](https://github.com/daltoniam/Starscream/issues/294)
[#292](https://github.com/daltoniam/Starscream/issues/292)
[#289](https://github.com/daltoniam/Starscream/issues/289)
[#288](https://github.com/daltoniam/Starscream/issues/288)
#### [2.0.2](https://github.com/daltoniam/Starscream/tree/2.0.2)
Fix for the Swift Package Manager.
Fixed:
[#277](https://github.com/daltoniam/Starscream/issues/277)
#### [2.0.1](https://github.com/daltoniam/Starscream/tree/2.0.1)
Bug fixes.
Fixed:
[#261](https://github.com/daltoniam/Starscream/issues/261)
[#276](https://github.com/daltoniam/Starscream/issues/276)
[#267](https://github.com/daltoniam/Starscream/issues/267)
[#266](https://github.com/daltoniam/Starscream/issues/266)
[#259](https://github.com/daltoniam/Starscream/issues/259)
#### [2.0.0](https://github.com/daltoniam/Starscream/tree/2.0.0)
Added Swift 3 support.
+8 -1
View File
@@ -21,5 +21,12 @@
import PackageDescription
let package = Package(
name: "Starscream"
name: "Starscream",
dependencies: [
.Package(url: "https://github.com/daltoniam/zlib-spm.git",
majorVersion: 1),
.Package(url: "https://github.com/IBM-Swift/CommonCrypto.git",
majorVersion: 0),
],
exclude: ["Tests", "examples"]
)
+84 -14
View File
@@ -2,19 +2,16 @@
Starscream is a conforming WebSocket ([RFC 6455](http://tools.ietf.org/html/rfc6455)) client library in Swift for iOS and OSX.
It's Objective-C counter part can be found here: [Jetfire](https://github.com/acmacalister/jetfire)
Its Objective-C counterpart can be found here: [Jetfire](https://github.com/acmacalister/jetfire)
## Features
- 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.
## Swift 2.3
See release/tag 1.1.4 for Swift 2.3 support.
## Example
First thing is to import the framework. See the Installation instructions on how to add the framework to your project.
@@ -164,6 +161,21 @@ socket.headers["Sec-WebSocket-Version"] = "14"
socket.headers["My-Awesome-Header"] = "Everything is Awesome!"
```
### Custom HTTP Method
Your server may use a different HTTP method when connecting to the websocket:
```swift
socket.httpMethod = .post
```
you can use a custom string:
```swift
socket.httpMethod = .custom(value: "mycustomhttpmethod")
```
### Protocols
If you need to specify a protocol, simple add it to the init:
@@ -175,23 +187,18 @@ socket.delegate = self
socket.connect()
```
### Self Signed SSL and VOIP
There are a couple of other properties that modify the stream:
### Self Signed SSL
```swift
socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"])
//set this if you are planning on using the socket in a VOIP background setting (using the background VOIP service).
socket.voipEnabled = true
//set this 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.
SSL Pinning is also supported in Starscream.
```swift
socket = WebSocket(url: URL(string: "ws://localhost:8080/")!, protocols: ["chat","superchat"])
@@ -201,6 +208,17 @@ socket.security = SSLSecurity(certs: [SSLCert(data: data)], usePublicKeys: true)
```
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.
### Compression Extensions
Compression Extensions ([RFC 7692](https://tools.ietf.org/html/rfc7692)) is supported in Starscream. Compression is enabled by default, however compression will only be used if it is supported by the server as well. You may enable or disable compression via the `.enableCompression` property:
```swift
socket = WebSocket(url: URL(string: "ws://localhost:8080/")!)
socket.enableCompression = false
```
Compression should be disabled if your application is transmitting already-compressed, random, or other uncompressable data.
### Custom Queue
A custom queue can be specified when delegate methods are called. By default `DispatchQueue.main` is used, thus making all delegate methods calls run on the main thread. It is important to note that all WebSocket processing is done on a background thread, only the delegate method calls are changed when modifying the queue. The actual processing is always on a background thread and will not pause your app.
@@ -231,7 +249,7 @@ To use Starscream in your project add the following 'Podfile' to your project
platform :ios, '9.0'
use_frameworks!
pod 'Starscream', '~> 2.0.0'
pod 'Starscream', '~> 2.0.3'
Then run:
@@ -253,7 +271,7 @@ $ brew install carthage
To integrate Starscream into your Xcode project using Carthage, specify it in your `Cartfile`:
```
github "daltoniam/Starscream" >= 2.0.0
github "daltoniam/Starscream" >= 2.0.3
```
### Rogue
@@ -268,6 +286,18 @@ rogue add https://github.com/daltoniam/starscream
Next open the `libs` folder and add the `Starscream.xcodeproj` to your Xcode project. Once that is complete, in your "Build Phases" add the `Starscream.framework` to your "Link Binary with Libraries" phase. Make sure to add the `libs` folder to your `.gitignore` file.
### Swift Package Manager
The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler.
Once you have your Swift package set up, adding Starscream as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.
```swift
dependencies: [
.Package(url: "https://github.com/daltoniam/Starscream.git", majorVersion: 2)
]
```
### Other
Simply grab the framework (either via git submodule or another package manager).
@@ -278,6 +308,46 @@ 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: WebSocket, 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: WebSocket, 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: WebSocket, request: CFHTTPMessage) {
print("the http request was sent we can check the raw http if we need to")
}
```
```swift
func websocketHttpUpgrade(socket: WebSocket, response: CFHTTPMessage) {
print("the http response has returned.")
}
```
## TODOs
- [ ] WatchOS?
+177
View File
@@ -0,0 +1,177 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Compression.swift
//
// Created by Joseph Ross on 7/16/14.
// 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.
// 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.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Compression implementation is implemented in conformance with RFC 7692 Compression Extensions
// for WebSocket: https://tools.ietf.org/html/rfc7692
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
import CZLib
class Decompressor {
private var strm = z_stream()
private var buffer = [UInt8](repeating: 0, count: 0x2000)
private var inflateInitialized = false
private let windowBits:Int
init?(windowBits:Int) {
self.windowBits = windowBits
guard initInflate() else { return nil }
}
private func initInflate() -> Bool {
if Z_OK == inflateInit2_(&strm, -CInt(windowBits),
ZLIB_VERSION, CInt(MemoryLayout<z_stream>.size))
{
inflateInitialized = true
return true
}
return false
}
func reset() throws {
teardownInflate()
guard initInflate() else { throw NSError() }
}
func decompress(_ data: Data, finish: Bool) throws -> Data {
return try data.withUnsafeBytes { (bytes:UnsafePointer<UInt8>) -> Data in
return try decompress(bytes: bytes, count: data.count, finish: finish)
}
}
func decompress(bytes: UnsafePointer<UInt8>, count: Int, finish: Bool) throws -> Data {
var decompressed = Data()
try decompress(bytes: bytes, count: count, out: &decompressed)
if finish {
let tail:[UInt8] = [0x00, 0x00, 0xFF, 0xFF]
try decompress(bytes: tail, count: tail.count, out: &decompressed)
}
return decompressed
}
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 {
strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
strm.avail_out = CUnsignedInt(buffer.count)
res = inflate(&strm, 0)
let byteCount = buffer.count - Int(strm.avail_out)
out.append(buffer, count: byteCount)
} while res == Z_OK && strm.avail_out == 0
guard (res == Z_OK && strm.avail_out > 0)
|| (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count)
else {
throw NSError(domain: WebSocket.ErrorDomain, code: Int(WebSocket.InternalErrorCode.compressionError.rawValue), userInfo: nil)
}
}
private func teardownInflate() {
if inflateInitialized, Z_OK == inflateEnd(&strm) {
inflateInitialized = false
}
}
deinit {
teardownInflate()
}
}
class Compressor {
private var strm = z_stream()
private var buffer = [UInt8](repeating: 0, count: 0x2000)
private var deflateInitialized = false
private let windowBits:Int
init?(windowBits: Int) {
self.windowBits = windowBits
guard initDeflate() else { return nil }
}
private func initDeflate() -> Bool {
if Z_OK == deflateInit2_(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
-CInt(windowBits), 8, Z_DEFAULT_STRATEGY,
ZLIB_VERSION, CInt(MemoryLayout<z_stream>.size))
{
deflateInitialized = true
return true
}
return false
}
func reset() throws {
teardownDeflate()
guard initDeflate() else { throw NSError() }
}
func compress(_ data: Data) throws -> Data {
var compressed = Data()
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 {
strm.next_out = UnsafeMutablePointer<UInt8>(&buffer)
strm.avail_out = CUnsignedInt(buffer.count)
res = deflate(&strm, Z_SYNC_FLUSH)
let byteCount = buffer.count - Int(strm.avail_out)
compressed.append(buffer, count: byteCount)
}
while res == Z_OK && strm.avail_out == 0
}
guard res == Z_OK && strm.avail_out > 0
|| (res == Z_BUF_ERROR && Int(strm.avail_out) == buffer.count)
else {
throw NSError(domain: WebSocket.ErrorDomain, code: Int(WebSocket.InternalErrorCode.compressionError.rawValue), userInfo: nil)
}
compressed.removeLast(4)
return compressed
}
private func teardownDeflate() {
if deflateInitialized, Z_OK == deflateEnd(&strm) {
deflateInitialized = false
}
}
deinit {
teardownDeflate()
}
}
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.0</string>
<string>2.1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.0</string>
<string>2.1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+7 -3
View File
@@ -23,7 +23,11 @@
import Foundation
import Security
public class SSLCert {
public protocol SSLTrustValidator {
func isValid(_ trust: SecTrust, domain: String?) -> Bool
}
open class SSLCert {
var certData: Data?
var key: SecKey?
@@ -50,7 +54,7 @@ public class SSLCert {
}
}
public class SSLSecurity {
open class SSLSecurity : SSLTrustValidator {
public var validatedDN = true //should the domain name be validated?
var isReady = false //is the key processing done?
@@ -82,7 +86,7 @@ public class SSLSecurity {
/**
Designated init
- parameter keys: is the certificates or public keys to use
- 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
+306 -124
View File
@@ -21,7 +21,7 @@
import Foundation
import CoreFoundation
import Security
import CommonCrypto
public let WebsocketDidConnectNotification = "WebsocketDidConnectNotification"
public let WebsocketDidDisconnectNotification = "WebsocketDidDisconnectNotification"
@@ -38,9 +38,19 @@ public protocol WebSocketPongDelegate: class {
func websocketDidReceivePong(socket: WebSocket, data: Data?)
}
public class WebSocket : NSObject, StreamDelegate {
// A Delegate with more advanced info on messages and connection etc.
public protocol WebSocketAdvancedDelegate: class {
func websocketDidConnect(socket: WebSocket)
func websocketDidDisconnect(socket: WebSocket, error: NSError?)
func websocketDidReceiveMessage(socket: WebSocket, text: String, response: WebSocket.WSResponse)
func websocketDidReceiveData(socket: WebSocket, data: Data, response: WebSocket.WSResponse)
func websocketHttpUpgrade(socket: WebSocket, request: CFHTTPMessage)
func websocketHttpUpgrade(socket: WebSocket, response: CFHTTPMessage)
}
open class WebSocket : NSObject, StreamDelegate {
enum OpCode : UInt8 {
public enum OpCode : UInt8 {
case continueFrame = 0x0
case textFrame = 0x1
case binaryFrame = 0x2
@@ -69,6 +79,9 @@ public class WebSocket : NSObject, StreamDelegate {
enum InternalErrorCode: UInt16 {
// 0-999 WebSocket status codes not used
case outputStreamWriteError = 1
case compressionError = 2
case invalidSSLError = 3
case writeTimeoutError = 4
}
// Where the callback is executed. It defaults to the main UI thread queue.
@@ -86,6 +99,7 @@ public class WebSocket : NSObject, StreamDelegate {
let headerWSProtocolName = "Sec-WebSocket-Protocol"
let headerWSVersionName = "Sec-WebSocket-Version"
let headerWSVersionValue = "13"
let headerWSExtensionName = "Sec-WebSocket-Extensions"
let headerWSKeyName = "Sec-WebSocket-Key"
let headerOriginName = "Origin"
let headerWSAcceptName = "Sec-WebSocket-Accept"
@@ -93,18 +107,22 @@ public class WebSocket : NSObject, StreamDelegate {
let FinMask: UInt8 = 0x80
let OpCodeMask: UInt8 = 0x0F
let RSVMask: UInt8 = 0x70
let RSV1Mask: UInt8 = 0x40
let MaskMask: UInt8 = 0x80
let PayloadLenMask: UInt8 = 0x7F
let MaxFrameSize: Int = 32
let httpSwitchProtocolCode = 101
let supportedSSLSchemes = ["wss", "https"]
class WSResponse {
public class WSResponse {
var isFin = false
var code: OpCode = .continueFrame
public var code: OpCode = .continueFrame
var bytesLeft = 0
var frameCount = 0
var buffer: NSMutableData?
public var frameCount = 0
public var buffer: NSMutableData?
public let firstFrame = {
return Date()
}()
}
// MARK: - Delegates
@@ -113,22 +131,48 @@ public class WebSocket : NSObject, StreamDelegate {
/// and also connection/disconnect messages.
public weak var delegate: WebSocketDelegate?
/// The optional advanced delegate can be used insteadof of the delegate
public weak var advancedDelegate: WebSocketAdvancedDelegate?
/// Receives a callback for each pong message recived.
public weak var pongDelegate: WebSocketPongDelegate?
// MARK: - Block based API.
public var onConnect: ((Void) -> Void)?
public enum HTTPMethod {
case get
case post
case put
case connect
case custom(value: String)
var representation: String {
switch self {
case .get:
return "GET"
case .post:
return "POST"
case .put:
return "PUT"
case .connect:
return "CONNECT"
case .custom(let value):
return value.capitalized
}
}
}
public var onConnect: (() -> Void)?
public var onDisconnect: ((NSError?) -> Void)?
public var onText: ((String) -> Void)?
public var onData: ((Data) -> Void)?
public var onPong: ((Data?) -> Void)?
public var httpMethod: HTTPMethod = .get
public var headers = [String: String]()
public var voipEnabled = false
public var disableSSLCertValidation = false
public var security: SSLSecurity?
public var enableCompression = true
public var security: SSLTrustValidator?
public var enabledSSLCipherSuites: [SSLCipherSuite]?
public var origin: String?
public var timeout = 5
@@ -139,12 +183,24 @@ public class WebSocket : NSObject, StreamDelegate {
public var currentURL: URL { return url }
// MARK: - Private
private struct CompressionState {
var supportsCompression = false
var messageNeedsDecompression = false
var serverMaxWindowBits = 15
var clientMaxWindowBits = 15
var clientNoContextTakeover = false
var serverNoContextTakeover = false
var decompressor:Decompressor? = nil
var compressor:Compressor? = nil
}
private var url: URL
private var inputStream: InputStream?
private var outputStream: OutputStream?
private var connected = false
private var isConnecting = false
private var compressionState = CompressionState()
private var writeQueue = OperationQueue()
private var readStack = [WSResponse]()
private var inputQueue = [Data]()
@@ -152,6 +208,7 @@ public class WebSocket : NSObject, StreamDelegate {
private var certValidated = false
private var didDisconnect = false
private var readyToWrite = false
private var headerSecKey = ""
private let mutex = NSLock()
private let notificationCenter = NotificationCenter.default
private var canDispatch: Bool {
@@ -167,6 +224,11 @@ public class WebSocket : NSObject, StreamDelegate {
public init(url: URL, protocols: [String]? = nil) {
self.url = url
self.origin = url.absoluteString
if let hostUrl = URL (string: "/", relativeTo: url) {
var origin = hostUrl.absoluteString
origin.remove(at: origin.index(before: origin.endIndex))
self.origin = origin
}
writeQueue.maxConcurrentOperationCount = 1
optionalProtocols = protocols
}
@@ -180,12 +242,11 @@ public class WebSocket : NSObject, StreamDelegate {
/**
Connect to the WebSocket server on a background thread.
*/
public func connect() {
open func connect() {
guard !isConnecting else { return }
didDisconnect = false
isConnecting = true
createHTTPRequest()
isConnecting = false
}
/**
@@ -198,10 +259,12 @@ public class WebSocket : NSObject, StreamDelegate {
- Parameter forceTimeout: Maximum time to wait for the server to close the socket.
- Parameter closeCode: The code to send on disconnect. The default is the normal close code for cleanly disconnecting a webSocket.
*/
public func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
open func disconnect(forceTimeout: TimeInterval? = nil, closeCode: UInt16 = CloseCode.normal.rawValue) {
guard isConnected else { return }
switch forceTimeout {
case .some(let seconds) where seconds > 0:
callbackQueue.asyncAfter(deadline: DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { [weak self] in
let milliseconds = Int(seconds * 1_000)
callbackQueue.asyncAfter(deadline: .now() + .milliseconds(milliseconds)) { [weak self] in
self?.disconnectStream(nil)
}
fallthrough
@@ -218,10 +281,10 @@ public class WebSocket : NSObject, StreamDelegate {
If you supply a non-nil completion block, I will perform it when the write completes.
- parameter str: The string to write.
- parameter string: The string to write.
- parameter completion: The (optional) completion handler.
*/
public func write(string: String, completion: (() -> ())? = nil) {
open func write(string: String, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(string.data(using: String.Encoding.utf8)!, code: .textFrame, writeCompletion: completion)
}
@@ -234,7 +297,7 @@ public class WebSocket : NSObject, StreamDelegate {
- parameter data: The data to write.
- parameter completion: The (optional) completion handler.
*/
public func write(data: Data, completion: (() -> ())? = nil) {
open func write(data: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(data, code: .binaryFrame, writeCompletion: completion)
}
@@ -243,7 +306,7 @@ public class WebSocket : NSObject, StreamDelegate {
Write a ping to the websocket. This sends it as a control frame.
Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
*/
public func write(ping: Data, completion: (() -> ())? = nil) {
open func write(ping: Data, completion: (() -> ())? = nil) {
guard isConnected else { return }
dequeueWrite(ping, code: .ping, writeCompletion: completion)
}
@@ -252,8 +315,7 @@ public class WebSocket : NSObject, StreamDelegate {
Private method that starts the connection.
*/
private func createHTTPRequest() {
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET" as CFString,
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, httpMethod.representation as CFString,
url as CFURL, kCFHTTPVersion1_1).takeRetainedValue()
var port = url.port
@@ -269,11 +331,16 @@ public class WebSocket : NSObject, StreamDelegate {
if let protocols = optionalProtocols {
addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joined(separator: ","))
}
headerSecKey = generateWebSocketKey()
addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey())
addHeader(urlRequest, key: headerWSKeyName, val: headerSecKey)
if let origin = origin {
addHeader(urlRequest, key: headerOriginName, val: origin)
}
if enableCompression {
let val = "permessage-deflate; client_max_window_bits; server_max_window_bits=15"
addHeader(urlRequest, key: headerWSExtensionName, val: val)
}
addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
for (key, value) in headers {
addHeader(urlRequest, key: key, val: value)
@@ -281,6 +348,7 @@ public class WebSocket : NSObject, StreamDelegate {
if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) {
let serializedRequest = cfHTTPMessage.takeRetainedValue()
initStreamsWithData(serializedRequest as Data, Int(port!))
self.advancedDelegate?.websocketHttpUpgrade(socket: self, request: urlRequest)
}
}
@@ -313,6 +381,9 @@ public class WebSocket : NSObject, StreamDelegate {
//higher level API we will cut over to at some point
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
// Disconnect and clean up any existing streams before setting up a new pair
disconnectStream(nil, runDelegate: false)
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
let h = url.host! as NSString
@@ -323,36 +394,33 @@ public class WebSocket : NSObject, StreamDelegate {
inStream.delegate = self
outStream.delegate = self
if supportedSSLSchemes.contains(url.scheme!) {
certValidated = false
inStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
outStream.setProperty(StreamSocketSecurityLevel.negotiatedSSL as AnyObject, forKey: Stream.PropertyKey.socketSecurityLevelKey)
} else {
certValidated = true //not a https session, so no need to check SSL pinning
}
if voipEnabled {
inStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType)
outStream.setProperty(StreamNetworkServiceTypeValue.voIP as AnyObject, forKey: Stream.PropertyKey.networkServiceType)
}
if disableSSLCertValidation {
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(value: false), kCFStreamSSLPeerName: kCFNull]
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
}
if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
if disableSSLCertValidation {
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(value: false), kCFStreamSSLPeerName: kCFNull]
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as Stream.PropertyKey)
}
if let cipherSuites = self.enabledSSLCipherSuites {
if let sslContextIn = CFReadStreamCopyProperty(inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext?,
let sslContextOut = CFWriteStreamCopyProperty(outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLContext)) as! SSLContext? {
let resIn = SSLSetEnabledCiphers(sslContextIn, cipherSuites, cipherSuites.count)
let resOut = SSLSetEnabledCiphers(sslContextOut, cipherSuites, cipherSuites.count)
if resIn != errSecSuccess {
let error = self.errorWithDetail("Error setting ingoing cypher suites", code: UInt16(resIn))
disconnectStream(error)
return
}
if resOut != errSecSuccess {
let error = self.errorWithDetail("Error setting outgoing cypher suites", code: UInt16(resOut))
disconnectStream(error)
return
}
}
}
} else {
certValidated = true //not a https session, so no need to check SSL pinning
}
CFReadStreamSetDispatchQueue(inStream, WebSocket.sharedWorkQueue)
@@ -365,38 +433,52 @@ public class WebSocket : NSObject, StreamDelegate {
self.mutex.unlock()
let bytes = UnsafeRawPointer((data as NSData).bytes).assumingMemoryBound(to: UInt8.self)
var out = timeout * 1000000 // wait 5 seconds before giving up
writeQueue.addOperation { [weak self] in
while !outStream.hasSpaceAvailable {
var out = timeout * 1_000_000 // wait 5 seconds before giving up
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
guard let sOperation = operation else { return }
while !outStream.hasSpaceAvailable && !sOperation.isCancelled {
usleep(100) // wait until the socket is ready
guard !sOperation.isCancelled else { return }
out -= 100
if out < 0 {
self?.cleanupStream()
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
WebSocket.sharedWorkQueue.async {
self?.cleanupStream()
}
let errCode = InternalErrorCode.writeTimeoutError.rawValue
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: errCode))
return
} else if outStream.streamError != nil {
return // disconnectStream will be called.
}
}
guard !sOperation.isCancelled, let s = self else { return }
// Do the pinning now if needed
if let sec = s.security, !s.certValidated {
if let possibleTrust = outStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) {
let domain = outStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String
s.certValidated = sec.isValid(possibleTrust as! SecTrust, domain: domain)
} else {
s.certValidated = false
}
if !s.certValidated {
WebSocket.sharedWorkQueue.async {
let errCode = InternalErrorCode.invalidSSLError.rawValue
let error = s.errorWithDetail("Invalid SSL certificate", code: errCode)
s.disconnectStream(error)
}
return
}
}
outStream.write(bytes, maxLength: data.count)
}
writeQueue.addOperation(operation)
}
/**
Delegate for the stream methods. Processes incoming bytes
*/
public func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if let sec = security, !certValidated && [.hasBytesAvailable, .hasSpaceAvailable].contains(eventCode) {
let trust = aStream.property(forKey: kCFStreamPropertySSLPeerTrust as Stream.PropertyKey) as AnyObject
let domain = aStream.property(forKey: kCFStreamSSLPeerName as Stream.PropertyKey) as? String
if sec.isValid(trust as! SecTrust, domain: domain) {
certValidated = true
} else {
let error = errorWithDetail("Invalid SSL certificate", code: 1)
disconnectStream(error)
return
}
}
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
if eventCode == .hasBytesAvailable {
if aStream == inputStream {
processInputStream()
@@ -411,14 +493,17 @@ public class WebSocket : NSObject, StreamDelegate {
/**
Disconnect the stream object and notifies the delegate.
*/
private func disconnectStream(_ error: NSError?) {
private func disconnectStream(_ error: NSError?, runDelegate: Bool = true) {
if error == nil {
writeQueue.waitUntilAllOperationsAreFinished()
} else {
writeQueue.cancelAllOperations()
}
cleanupStream()
doDisconnect(error)
connected = false
if runDelegate {
doDisconnect(error)
}
}
/**
@@ -437,6 +522,7 @@ public class WebSocket : NSObject, StreamDelegate {
}
outputStream = nil
inputStream = nil
fragBuffer = nil
}
/**
@@ -446,7 +532,6 @@ public class WebSocket : NSObject, StreamDelegate {
let buf = NSMutableData(capacity: BUFFER_MAX)
let buffer = UnsafeMutableRawPointer(mutating: buf!.bytes).assumingMemoryBound(to: UInt8.self)
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
guard length > 0 else { return }
var process = false
if inputQueue.count == 0 {
@@ -463,22 +548,24 @@ public class WebSocket : NSObject, StreamDelegate {
*/
private func dequeueInput() {
while !inputQueue.isEmpty {
let data = inputQueue[0]
var work = data
if let fragBuffer = fragBuffer {
var combine = NSData(data: fragBuffer) as Data
combine.append(data)
work = combine
self.fragBuffer = nil
autoreleasepool {
let data = inputQueue[0]
var work = data
if let buffer = fragBuffer {
var combine = NSData(data: buffer) as Data
combine.append(data)
work = combine
fragBuffer = nil
}
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
let length = work.count
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{ $0 != data }
}
let buffer = UnsafeRawPointer((work as NSData).bytes).assumingMemoryBound(to: UInt8.self)
let length = work.count
if !connected {
processTCPHandshake(buffer, bufferLen: length)
} else {
processRawMessagesInBuffer(buffer, bufferLen: length)
}
inputQueue = inputQueue.filter{ $0 != data }
}
}
@@ -489,17 +576,10 @@ public class WebSocket : NSObject, StreamDelegate {
let code = processHTTP(buffer, bufferLen: bufferLen)
switch code {
case 0:
connected = true
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(socket: s)
s.notificationCenter.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
}
break
case -1:
fragBuffer = Data(bytes: buffer, count: bufferLen)
break // do nothing, we are going to collect more data
break // do nothing, we are going to collect more data
default:
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
}
@@ -528,6 +608,18 @@ public class WebSocket : NSObject, StreamDelegate {
if code != 0 {
return code
}
isConnecting = false
connected = true
didDisconnect = false
if canDispatch {
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onConnect?()
s.delegate?.websocketDidConnect(socket: s)
s.advancedDelegate?.websocketDidConnect(socket: s)
s.notificationCenter.post(name: NSNotification.Name(WebsocketDidConnectNotification), object: self)
}
}
totalSize += 1 //skip the last \n
let restSize = bufferLen - totalSize
if restSize > 0 {
@@ -545,13 +637,24 @@ public class WebSocket : NSObject, StreamDelegate {
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
let code = CFHTTPMessageGetResponseStatusCode(response)
self.advancedDelegate?.websocketHttpUpgrade(socket: self, response: response)
if code != httpSwitchProtocolCode {
return code
}
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
let headers = cfHeaders.takeRetainedValue() as NSDictionary
if let extensionHeader = headers[headerWSExtensionName as NSString] as? String {
processExtensionHeader(extensionHeader)
}
if let acceptKey = headers[headerWSAcceptName as NSString] as? NSString {
if acceptKey.length > 0 {
if headerSecKey.characters.count > 0 {
let sha = "\(headerSecKey)258EAFA5-E914-47DA-95CA-C5AB0DC85B11".sha1Base64()
if sha != acceptKey as String {
return -1
}
}
return 0
}
}
@@ -559,6 +662,37 @@ public class WebSocket : NSObject, StreamDelegate {
return -1
}
/**
Parses the extension header, setting up the compression parameters.
*/
func processExtensionHeader(_ extensionHeader: String) {
let parts = extensionHeader.components(separatedBy: ";")
for p in parts {
let part = p.trimmingCharacters(in: .whitespaces)
if part == "permessage-deflate" {
compressionState.supportsCompression = true
} else if part.hasPrefix("server_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.serverMaxWindowBits = val
}
} else if part.hasPrefix("client_max_window_bits=") {
let valString = part.components(separatedBy: "=")[1]
if let val = Int(valString.trimmingCharacters(in: .whitespaces)) {
compressionState.clientMaxWindowBits = val
}
} else if part == "client_no_context_takeover" {
compressionState.clientNoContextTakeover = true
} else if part == "server_no_context_takeover" {
compressionState.serverNoContextTakeover = true
}
}
if compressionState.supportsCompression {
compressionState.decompressor = Decompressor(windowBits: compressionState.serverMaxWindowBits)
compressionState.compressor = Compressor(windowBits: compressionState.clientMaxWindowBits)
}
}
/**
Read a 16 bit big endian value from a buffer
*/
@@ -618,11 +752,15 @@ public class WebSocket : NSObject, StreamDelegate {
return buffer.fromOffset(bufferLen - extra)
} else {
let isFin = (FinMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: (OpCodeMask & baseAddress[0]))
let receivedOpcodeRawValue = (OpCodeMask & baseAddress[0])
let receivedOpcode = OpCode(rawValue: receivedOpcodeRawValue)
let isMasked = (MaskMask & baseAddress[1])
let payloadLen = (PayloadLenMask & baseAddress[1])
var offset = 2
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong {
if compressionState.supportsCompression && receivedOpcode != .continueFrame {
compressionState.messageNeedsDecompression = (RSV1Mask & baseAddress[0]) > 0
}
if (isMasked > 0 || (RSVMask & baseAddress[0]) > 0) && receivedOpcode != .pong && !compressionState.messageNeedsDecompression {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
writeError(errCode)
@@ -632,7 +770,7 @@ public class WebSocket : NSObject, StreamDelegate {
if !isControlFrame && (receivedOpcode != .binaryFrame && receivedOpcode != .continueFrame &&
receivedOpcode != .textFrame && receivedOpcode != .pong) {
let errCode = CloseCode.protocolError.rawValue
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcodeRawValue)", code: errCode))
writeError(errCode)
return emptyBuffer
}
@@ -642,34 +780,22 @@ public class WebSocket : NSObject, StreamDelegate {
writeError(errCode)
return emptyBuffer
}
var closeCode = CloseCode.normal.rawValue
if receivedOpcode == .connectionClose {
var code = CloseCode.normal.rawValue
if payloadLen == 1 {
code = CloseCode.protocolError.rawValue
closeCode = CloseCode.protocolError.rawValue
} else if payloadLen > 1 {
code = WebSocket.readUint16(baseAddress, offset: offset)
if code < 1000 || (code > 1003 && code < 1007) || (code > 1011 && code < 3000) {
code = CloseCode.protocolError.rawValue
}
offset += 2
}
var closeReason = "connection closed by server"
if payloadLen > 2 {
let len = Int(payloadLen - 2)
if len > 0 {
let bytes = baseAddress + offset
if let customCloseReason = String(data: Data(bytes: bytes, count: len), encoding: .utf8) {
closeReason = customCloseReason
} else {
code = CloseCode.protocolError.rawValue
}
closeCode = WebSocket.readUint16(baseAddress, offset: offset)
if closeCode < 1000 || (closeCode > 1003 && closeCode < 1007) || (closeCode > 1011 && closeCode < 3000) {
closeCode = CloseCode.protocolError.rawValue
}
}
doDisconnect(errorWithDetail(closeReason, code: code))
writeError(code)
return emptyBuffer
}
if isControlFrame && payloadLen > 125 {
if payloadLen < 2 {
doDisconnect(errorWithDetail("connection closed by server", code: closeCode))
writeError(closeCode)
return emptyBuffer
}
} else if isControlFrame && payloadLen > 125 {
writeError(CloseCode.protocolError.rawValue)
return emptyBuffer
}
@@ -689,13 +815,40 @@ public class WebSocket : NSObject, StreamDelegate {
if dataLength > UInt64(bufferLen) {
len = UInt64(bufferLen-offset)
}
if receivedOpcode == .connectionClose && len > 0 {
let size = MemoryLayout<UInt16>.size
offset += size
len -= UInt64(size)
}
let data: Data
if len < 0 {
len = 0
data = Data()
if compressionState.messageNeedsDecompression, let decompressor = compressionState.decompressor {
do {
data = try decompressor.decompress(bytes: baseAddress+offset, count: Int(len), finish: isFin > 0)
if isFin > 0 && compressionState.serverNoContextTakeover{
try decompressor.reset()
}
} catch {
let closeReason = "Decompression failed: \(error)"
let closeCode = CloseCode.encoding.rawValue
doDisconnect(errorWithDetail(closeReason, code: closeCode))
writeError(closeCode)
return emptyBuffer
}
} else {
data = Data(bytes: baseAddress+offset, count: Int(len))
}
if receivedOpcode == .connectionClose {
var closeReason = "connection closed by server"
if let customCloseReason = String(data: data, encoding: .utf8) {
closeReason = customCloseReason
} else {
closeCode = CloseCode.protocolError.rawValue
}
doDisconnect(errorWithDetail(closeReason, code: closeCode))
writeError(closeCode)
return emptyBuffer
}
if receivedOpcode == .pong {
if canDispatch {
callbackQueue.async { [weak self] in
@@ -790,6 +943,7 @@ public class WebSocket : NSObject, StreamDelegate {
guard let s = self else { return }
s.onText?(str! as String)
s.delegate?.websocketDidReceiveMessage(socket: s, text: str! as String)
s.advancedDelegate?.websocketDidReceiveMessage(socket: s, text: str! as String, response: response)
}
}
} else if response.code == .binaryFrame {
@@ -799,6 +953,7 @@ public class WebSocket : NSObject, StreamDelegate {
guard let s = self else { return }
s.onData?(data as Data)
s.delegate?.websocketDidReceiveData(socket: s, data: data as Data)
s.advancedDelegate?.websocketDidReceiveData(socket: s, data: data as Data, response: response)
}
}
}
@@ -831,14 +986,29 @@ public class WebSocket : NSObject, StreamDelegate {
Used to write things to the stream
*/
private func dequeueWrite(_ data: Data, code: OpCode, writeCompletion: (() -> ())? = nil) {
writeQueue.addOperation { [weak self] in
let operation = BlockOperation()
operation.addExecutionBlock { [weak self, weak operation] in
//stream isn't ready, let's wait
guard let s = self else { return }
guard let sOperation = operation else { return }
var offset = 2
var firstByte:UInt8 = s.FinMask | code.rawValue
var data = data
if [.textFrame, .binaryFrame].contains(code), let compressor = s.compressionState.compressor {
do {
data = try compressor.compress(data)
if s.compressionState.clientNoContextTakeover {
try compressor.reset()
}
firstByte |= s.RSV1Mask
} catch {
// TODO: report error? We can just send the uncompressed frame.
}
}
let dataLength = data.count
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
let buffer = UnsafeMutableRawPointer(frame!.mutableBytes).assumingMemoryBound(to: UInt8.self)
buffer[0] = s.FinMask | code.rawValue
buffer[0] = firstByte
if dataLength < 126 {
buffer[1] = CUnsignedChar(dataLength)
} else if dataLength <= Int(UInt16.max) {
@@ -860,7 +1030,7 @@ public class WebSocket : NSObject, StreamDelegate {
offset += 1
}
var total = 0
while true {
while !sOperation.isCancelled {
guard let outStream = s.outputStream else { break }
let writeBuffer = UnsafeRawPointer(frame!.bytes+total).assumingMemoryBound(to: UInt8.self)
let len = outStream.write(writeBuffer, maxLength: offset-total)
@@ -887,8 +1057,8 @@ public class WebSocket : NSObject, StreamDelegate {
break
}
}
}
writeQueue.addOperation(operation)
}
/**
@@ -897,12 +1067,14 @@ public class WebSocket : NSObject, StreamDelegate {
private func doDisconnect(_ error: NSError?) {
guard !didDisconnect else { return }
didDisconnect = true
isConnecting = false
connected = false
guard canDispatch else {return}
callbackQueue.async { [weak self] in
guard let s = self else { return }
s.onDisconnect?(error)
s.delegate?.websocketDidDisconnect(socket: s, error: error)
s.advancedDelegate?.websocketDidDisconnect(socket: s, error: error)
let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] }
s.notificationCenter.post(name: NSNotification.Name(WebsocketDidDisconnectNotification), object: self, userInfo: userInfo)
}
@@ -915,10 +1087,20 @@ public class WebSocket : NSObject, StreamDelegate {
readyToWrite = false
mutex.unlock()
cleanupStream()
writeQueue.cancelAllOperations()
}
}
private extension String {
func sha1Base64() -> String {
let data = self.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(data.count), &digest) }
return Data(bytes: digest).base64EncodedString()
}
}
private extension Data {
init(buffer: UnsafeBufferPointer<UInt8>) {
+6 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = "Starscream"
s.version = "2.0.0"
s.version = "2.1.0"
s.summary = "A conforming WebSocket RFC 6455 client library in Swift for iOS and OSX."
s.homepage = "https://github.com/daltoniam/Starscream"
s.license = 'Apache License, Version 2.0'
@@ -12,4 +12,9 @@ Pod::Spec.new do |s|
s.tvos.deployment_target = '9.0'
s.source_files = 'Source/*.swift'
s.requires_arc = 'true'
s.libraries = 'z'
s.pod_target_xcconfig = {
'SWIFT_INCLUDE_PATHS' => '$(PODS_ROOT)/Starscream/zlib'
}
s.preserve_paths = 'zlib/*'
end
+98 -8
View File
@@ -17,10 +17,33 @@
5C1360081C473BEF00AA3A01 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C1360011C473BEF00AA3A01 /* WebSocket.swift */; };
5C1360091C473BEF00AA3A01 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C1360011C473BEF00AA3A01 /* WebSocket.swift */; };
5C13600A1C473BEF00AA3A01 /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C1360011C473BEF00AA3A01 /* WebSocket.swift */; };
5CADAB511BEBD068005DE2F0 /* StarscreamTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B3E7A0119D48C2F006071F7 /* StarscreamTests.swift */; };
6B3E7A0319D48C2F006071F7 /* StarscreamTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B3E7A0119D48C2F006071F7 /* StarscreamTests.swift */; };
742419BC1DC6BDBA003ACE43 /* StarscreamTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 742419BB1DC6BDBA003ACE43 /* StarscreamTests.swift */; };
742419BD1DC6BDBA003ACE43 /* StarscreamTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 742419BB1DC6BDBA003ACE43 /* StarscreamTests.swift */; };
742419BE1DC6BDBA003ACE43 /* StarscreamTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 742419BB1DC6BDBA003ACE43 /* StarscreamTests.swift */; };
D85927D01ED65933003460CB /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C1360011C473BEF00AA3A01 /* WebSocket.swift */; };
D85927D11ED65963003460CB /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C135FFF1C473BEF00AA3A01 /* SSLSecurity.swift */; };
D85927D81ED76F25003460CB /* include.h in Headers */ = {isa = PBXBuildFile; fileRef = D85927D71ED76F25003460CB /* include.h */; };
D85927D91ED76F25003460CB /* include.h in Headers */ = {isa = PBXBuildFile; fileRef = D85927D71ED76F25003460CB /* include.h */; };
D85927DA1ED76F25003460CB /* include.h in Headers */ = {isa = PBXBuildFile; fileRef = D85927D71ED76F25003460CB /* include.h */; };
D85927DB1ED7737C003460CB /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C1360011C473BEF00AA3A01 /* WebSocket.swift */; };
D85927DC1ED7737C003460CB /* WebSocket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C1360011C473BEF00AA3A01 /* WebSocket.swift */; };
D85927DD1ED773AC003460CB /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C135FFF1C473BEF00AA3A01 /* SSLSecurity.swift */; };
D85927DE1ED773AD003460CB /* SSLSecurity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C135FFF1C473BEF00AA3A01 /* SSLSecurity.swift */; };
D88EAF7F1ED4DFB5004FE2C3 /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = D88EAF7E1ED4DFB5004FE2C3 /* Compression.swift */; };
D88EAF821ED4DFD3004FE2C3 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = D88EAF811ED4DFD3004FE2C3 /* libz.tbd */; };
D88EAF841ED4E7D8004FE2C3 /* CompressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D88EAF831ED4E7D8004FE2C3 /* CompressionTests.swift */; };
D88EAF851ED4E7D8004FE2C3 /* CompressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D88EAF831ED4E7D8004FE2C3 /* CompressionTests.swift */; };
D88EAF861ED4E7D8004FE2C3 /* CompressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D88EAF831ED4E7D8004FE2C3 /* CompressionTests.swift */; };
D88EAF871ED4E88C004FE2C3 /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = D88EAF7E1ED4DFB5004FE2C3 /* Compression.swift */; };
D88EAF881ED4E88C004FE2C3 /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = D88EAF7E1ED4DFB5004FE2C3 /* Compression.swift */; };
D88EAF891ED4E88D004FE2C3 /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = D88EAF7E1ED4DFB5004FE2C3 /* Compression.swift */; };
D88EAF8A1ED4E88D004FE2C3 /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = D88EAF7E1ED4DFB5004FE2C3 /* Compression.swift */; };
D88EAF8B1ED4E88D004FE2C3 /* Compression.swift in Sources */ = {isa = PBXBuildFile; fileRef = D88EAF7E1ED4DFB5004FE2C3 /* Compression.swift */; };
D88EAF8E1ED4E92E004FE2C3 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = D88EAF8D1ED4E92E004FE2C3 /* libz.tbd */; };
D88EAF911ED4E949004FE2C3 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = D88EAF901ED4E949004FE2C3 /* libz.tbd */; };
D88EAF921ED4E95D004FE2C3 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6B3E79E619D48B7F006071F7 /* Starscream.framework */; };
D88EAF931ED4E975004FE2C3 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = D88EAF811ED4DFD3004FE2C3 /* libz.tbd */; };
D9C3E36A19E48FF1009FC285 /* Starscream.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D9C3E35F19E48FF1009FC285 /* Starscream.framework */; };
D9C3E37819E4903F009FC285 /* StarscreamTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B3E7A0119D48C2F006071F7 /* StarscreamTests.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -51,7 +74,14 @@
6B3E79E619D48B7F006071F7 /* Starscream.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; };
6B3E79F119D48B7F006071F7 /* Starscream iOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Starscream iOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
6B3E7A0019D48C2F006071F7 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
6B3E7A0119D48C2F006071F7 /* StarscreamTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StarscreamTests.swift; sourceTree = "<group>"; };
742419BB1DC6BDBA003ACE43 /* StarscreamTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = StarscreamTests.swift; path = StarscreamTests/StarscreamTests.swift; sourceTree = "<group>"; };
D85927D61ED761A0003460CB /* module.modulemap */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
D85927D71ED76F25003460CB /* include.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = include.h; sourceTree = "<group>"; };
D88EAF7E1ED4DFB5004FE2C3 /* Compression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Compression.swift; path = Source/Compression.swift; sourceTree = SOURCE_ROOT; };
D88EAF811ED4DFD3004FE2C3 /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = usr/lib/libz.tbd; sourceTree = SDKROOT; };
D88EAF831ED4E7D8004FE2C3 /* CompressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompressionTests.swift; sourceTree = "<group>"; };
D88EAF8D1ED4E92E004FE2C3 /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/lib/libz.tbd; sourceTree = DEVELOPER_DIR; };
D88EAF901ED4E949004FE2C3 /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS10.2.sdk/usr/lib/libz.tbd; sourceTree = DEVELOPER_DIR; };
D9C3E35F19E48FF1009FC285 /* Starscream.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Starscream.framework; sourceTree = BUILT_PRODUCTS_DIR; };
D9C3E36919E48FF1009FC285 /* Starscream OSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "Starscream OSXTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
@@ -61,6 +91,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D88EAF911ED4E949004FE2C3 /* libz.tbd in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -76,6 +107,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D88EAF821ED4DFD3004FE2C3 /* libz.tbd in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -83,6 +115,8 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D88EAF931ED4E975004FE2C3 /* libz.tbd in Frameworks */,
D88EAF921ED4E95D004FE2C3 /* Starscream.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -90,6 +124,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
D88EAF8E1ED4E92E004FE2C3 /* libz.tbd in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -107,9 +142,11 @@
6B3E79DC19D48B7F006071F7 = {
isa = PBXGroup;
children = (
D85927D51ED761A0003460CB /* zlib */,
6B3E79E819D48B7F006071F7 /* Starscream */,
6B3E79FF19D48C2F006071F7 /* Tests */,
6B3E79E719D48B7F006071F7 /* Products */,
D88EAF801ED4DFD3004FE2C3 /* Frameworks */,
);
sourceTree = "<group>";
};
@@ -132,6 +169,7 @@
5C1360001C473BEF00AA3A01 /* Starscream.h */,
5C135FFF1C473BEF00AA3A01 /* SSLSecurity.swift */,
5C1360011C473BEF00AA3A01 /* WebSocket.swift */,
D88EAF7E1ED4DFB5004FE2C3 /* Compression.swift */,
6B3E79E919D48B7F006071F7 /* Supporting Files */,
);
path = Starscream;
@@ -150,11 +188,31 @@
isa = PBXGroup;
children = (
6B3E7A0019D48C2F006071F7 /* Info.plist */,
6B3E7A0119D48C2F006071F7 /* StarscreamTests.swift */,
742419BB1DC6BDBA003ACE43 /* StarscreamTests.swift */,
D88EAF831ED4E7D8004FE2C3 /* CompressionTests.swift */,
);
path = Tests;
sourceTree = "<group>";
};
D85927D51ED761A0003460CB /* zlib */ = {
isa = PBXGroup;
children = (
D85927D61ED761A0003460CB /* module.modulemap */,
D85927D71ED76F25003460CB /* include.h */,
);
path = zlib;
sourceTree = "<group>";
};
D88EAF801ED4DFD3004FE2C3 /* Frameworks */ = {
isa = PBXGroup;
children = (
D88EAF901ED4E949004FE2C3 /* libz.tbd */,
D88EAF8D1ED4E92E004FE2C3 /* libz.tbd */,
D88EAF811ED4DFD3004FE2C3 /* libz.tbd */,
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
@@ -163,6 +221,7 @@
buildActionMask = 2147483647;
files = (
5C1360071C473BEF00AA3A01 /* Starscream.h in Headers */,
D85927DA1ED76F25003460CB /* include.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -171,6 +230,7 @@
buildActionMask = 2147483647;
files = (
5C1360051C473BEF00AA3A01 /* Starscream.h in Headers */,
D85927D81ED76F25003460CB /* include.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -179,6 +239,7 @@
buildActionMask = 2147483647;
files = (
5C1360061C473BEF00AA3A01 /* Starscream.h in Headers */,
D85927D91ED76F25003460CB /* include.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -308,6 +369,7 @@
};
0912779F1BD673A70003036D = {
CreatedOnToolsVersion = 7.1;
LastSwiftMigration = 0810;
};
6B3E79E519D48B7F006071F7 = {
CreatedOnToolsVersion = 6.0.1;
@@ -315,12 +377,14 @@
};
6B3E79F019D48B7F006071F7 = {
CreatedOnToolsVersion = 6.0.1;
LastSwiftMigration = 0810;
};
D9C3E35E19E48FF1009FC285 = {
CreatedOnToolsVersion = 6.1;
};
D9C3E36819E48FF1009FC285 = {
CreatedOnToolsVersion = 6.1;
LastSwiftMigration = 0810;
};
};
};
@@ -396,6 +460,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D88EAF8A1ED4E88D004FE2C3 /* Compression.swift in Sources */,
5C13600A1C473BEF00AA3A01 /* WebSocket.swift in Sources */,
5C1360041C473BEF00AA3A01 /* SSLSecurity.swift in Sources */,
);
@@ -405,7 +470,11 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
5CADAB511BEBD068005DE2F0 /* StarscreamTests.swift in Sources */,
D88EAF8B1ED4E88D004FE2C3 /* Compression.swift in Sources */,
D85927DE1ED773AD003460CB /* SSLSecurity.swift in Sources */,
D85927DB1ED7737C003460CB /* WebSocket.swift in Sources */,
D88EAF861ED4E7D8004FE2C3 /* CompressionTests.swift in Sources */,
742419BE1DC6BDBA003ACE43 /* StarscreamTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -413,6 +482,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D88EAF7F1ED4DFB5004FE2C3 /* Compression.swift in Sources */,
5C1360081C473BEF00AA3A01 /* WebSocket.swift in Sources */,
5C1360021C473BEF00AA3A01 /* SSLSecurity.swift in Sources */,
);
@@ -422,7 +492,11 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
6B3E7A0319D48C2F006071F7 /* StarscreamTests.swift in Sources */,
D88EAF871ED4E88C004FE2C3 /* Compression.swift in Sources */,
D85927D11ED65963003460CB /* SSLSecurity.swift in Sources */,
D85927D01ED65933003460CB /* WebSocket.swift in Sources */,
D88EAF841ED4E7D8004FE2C3 /* CompressionTests.swift in Sources */,
742419BC1DC6BDBA003ACE43 /* StarscreamTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -430,6 +504,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D88EAF881ED4E88C004FE2C3 /* Compression.swift in Sources */,
5C1360091C473BEF00AA3A01 /* WebSocket.swift in Sources */,
5C1360031C473BEF00AA3A01 /* SSLSecurity.swift in Sources */,
);
@@ -439,7 +514,11 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
D9C3E37819E4903F009FC285 /* StarscreamTests.swift in Sources */,
D88EAF891ED4E88D004FE2C3 /* Compression.swift in Sources */,
D85927DD1ED773AC003460CB /* SSLSecurity.swift in Sources */,
D85927DC1ED7737C003460CB /* WebSocket.swift in Sources */,
D88EAF851ED4E7D8004FE2C3 /* CompressionTests.swift in Sources */,
742419BD1DC6BDBA003ACE43 /* StarscreamTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -515,6 +594,7 @@
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = NO;
CLANG_ENABLE_MODULES = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
@@ -522,6 +602,7 @@
PRODUCT_BUNDLE_IDENTIFIER = com.vluxe.StarscreamTvTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = appletvos;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
TVOS_DEPLOYMENT_TARGET = 9.0;
};
@@ -531,6 +612,7 @@
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = NO;
CLANG_ENABLE_MODULES = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_NO_COMMON_BLOCKS = YES;
@@ -589,6 +671,7 @@
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
SWIFT_INCLUDE_PATHS = $SRCROOT/zlib;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
@@ -632,6 +715,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_INCLUDE_PATHS = $SRCROOT/zlib;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
@@ -693,6 +777,7 @@
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = NO;
CLANG_ENABLE_MODULES = YES;
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
@@ -705,6 +790,7 @@
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.vluxe.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
};
name = Debug;
@@ -713,6 +799,7 @@
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = NO;
CLANG_ENABLE_MODULES = YES;
FRAMEWORK_SEARCH_PATHS = (
"$(SDKROOT)/Developer/Library/Frameworks",
"$(inherited)",
@@ -780,6 +867,7 @@
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = NO;
CLANG_ENABLE_MODULES = YES;
COMBINE_HIDPI_IMAGES = YES;
FRAMEWORK_SEARCH_PATHS = (
"$(DEVELOPER_FRAMEWORKS_DIR)",
@@ -795,6 +883,7 @@
PRODUCT_BUNDLE_IDENTIFIER = "com.vluxe.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = macosx;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
};
name = Debug;
@@ -803,6 +892,7 @@
isa = XCBuildConfiguration;
buildSettings = {
APPLICATION_EXTENSION_API_ONLY = NO;
CLANG_ENABLE_MODULES = YES;
COMBINE_HIDPI_IMAGES = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
FRAMEWORK_SEARCH_PATHS = (
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
LastUpgradeVersion = "0810"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
LastUpgradeVersion = "0810"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
LastUpgradeVersion = "0810"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0800"
LastUpgradeVersion = "0810"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+65
View File
@@ -0,0 +1,65 @@
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// CompressionTests.swift
//
// Created by Joseph Ross on 7/16/14.
// 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.
// 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 XCTest
class CompressionTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testBasic() {
let compressor = Compressor(windowBits: 15)!
let decompressor = Decompressor(windowBits: 15)!
let rawData = "Hello, World! Hello, World! Hello, World! Hello, World! Hello, World!".data(using: .utf8)!
let compressed = try! compressor.compress(rawData)
let uncompressed = try! decompressor.decompress(compressed, finish: true)
XCTAssert(rawData == uncompressed)
}
func testHugeData() {
let compressor = Compressor(windowBits: 15)!
let decompressor = Decompressor(windowBits: 15)!
// 2 Gigs!
// var rawData = Data(repeating: 0, count: 0x80000000)
var rawData = Data(repeating: 0, count: 0x80000)
rawData.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> Void in
arc4random_buf(ptr, rawData.count)
}
let compressed = try! compressor.compress(rawData)
let uncompressed = try! decompressor.decompress(compressed, finish: true)
XCTAssert(rawData == uncompressed)
}
}
@@ -20,7 +20,7 @@ class ViewController: UIViewController {
//getTestInfo(1)
}
func removeSocket(_ s: WebSocket) {
func removeSocket(_ s: WebSocket?) {
socketArray = socketArray.filter{$0 != s}
}
@@ -28,15 +28,15 @@ class ViewController: UIViewController {
let s = WebSocket(url: URL(string: "ws://\(host)/getCaseCount")!, protocols: [])
socketArray.append(s)
s.onText = {[unowned self] (text: String) in
s.onText = { [weak self] (text: String) in
if let c = Int(text) {
print("number of cases is: \(c)")
self.caseCount = c
self?.caseCount = c
}
}
s.onDisconnect = {[unowned self] (error: NSError?) in
self.getTestInfo(1)
self.removeSocket(s)
s.onDisconnect = { [weak self, weak s] (error: NSError?) in
self?.getTestInfo(1)
self?.removeSocket(s)
}
s.connect()
}
@@ -44,7 +44,7 @@ class ViewController: UIViewController {
func getTestInfo(_ caseNum: Int) {
let s = createSocket("getCaseInfo",caseNum)
socketArray.append(s)
s.onText = {(text: String) in
s.onText = { (text: String) in
// let data = text.dataUsingEncoding(NSUTF8StringEncoding)
// do {
// let resp: AnyObject? = try NSJSONSerialization.JSONObjectWithData(data!,
@@ -62,12 +62,12 @@ class ViewController: UIViewController {
}
var once = false
s.onDisconnect = {[unowned self] (error: NSError?) in
s.onDisconnect = { [weak self, weak s] (error: NSError?) in
if !once {
once = true
self.runTest(caseNum)
self?.runTest(caseNum)
}
self.removeSocket(s)
self?.removeSocket(s)
}
s.connect()
}
@@ -75,19 +75,19 @@ class ViewController: UIViewController {
func runTest(_ caseNum: Int) {
let s = createSocket("runCase",caseNum)
self.socketArray.append(s)
s.onText = {(text: String) in
s.write(string: text)
s.onText = { [weak s] (text: String) in
s?.write(string: text)
}
s.onData = {(data: Data) in
s.write(data: data)
s.onData = { [weak s] (data: Data) in
s?.write(data: data)
}
var once = false
s.onDisconnect = {[unowned self] (error: NSError?) in
s.onDisconnect = {[weak self, weak s] (error: NSError?) in
if !once {
once = true
print("case:\(caseNum) finished")
self.verifyTest(caseNum)
self.removeSocket(s)
self?.verifyTest(caseNum)
self?.removeSocket(s)
}
}
s.connect()
@@ -96,7 +96,7 @@ class ViewController: UIViewController {
func verifyTest(_ caseNum: Int) {
let s = createSocket("getCaseStatus",caseNum)
self.socketArray.append(s)
s.onText = {(text: String) in
s.onText = { (text: String) in
let data = text.data(using: String.Encoding.utf8)
do {
let resp: Any? = try JSONSerialization.jsonObject(with: data!,
@@ -115,17 +115,17 @@ class ViewController: UIViewController {
}
}
var once = false
s.onDisconnect = {[unowned self] (error: NSError?) in
s.onDisconnect = { [weak self, weak s] (error: NSError?) in
if !once {
once = true
let nextCase = caseNum+1
if nextCase <= self.caseCount {
self.getTestInfo(nextCase)
if nextCase <= (self?.caseCount)! {
self?.getTestInfo(nextCase)
} else {
self.finishReports()
self?.finishReports()
}
}
self.removeSocket(s)
self?.removeSocket(s)
}
s.connect()
}
@@ -133,9 +133,9 @@ class ViewController: UIViewController {
func finishReports() {
let s = createSocket("updateReports",0)
self.socketArray.append(s)
s.onDisconnect = {[unowned self] (error: NSError?) in
s.onDisconnect = { [weak self, weak s] (error: NSError?) in
print("finished all the tests!")
self.removeSocket(s)
self?.removeSocket(s)
}
s.connect()
}
@@ -85,6 +85,13 @@
ReferencedContainer = "container:SimpleTest.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "OS_ACTIVITY_MODE"
value = "disable"
isEnabled = "YES">
</EnvironmentVariable>
</EnvironmentVariables>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
+1 -1
View File
@@ -22,4 +22,4 @@ EM.run {
ws.send Faker::Hacker.say_something_smart
}
end
}
}
+2
View File
@@ -0,0 +1,2 @@
#include <zlib.h>
#include <CommonCrypto/CommonCrypto.h>
+9
View File
@@ -0,0 +1,9 @@
module CZLib [system] {
header "include.h"
link "z"
export *
}
module CommonCrypto [system] {
header "include.h"
export *
}