Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1648a51b6f | ||
|
|
ad7043c918 | ||
|
|
48672d8df3 | ||
|
|
c101a04845 | ||
|
|
f57786ad5b | ||
|
|
7ff1d327de | ||
|
|
18a227e591 | ||
|
|
6d49c37fb8 | ||
|
|
a0c213364d | ||
|
|
3c79bd0a75 | ||
|
|
a11533b61f | ||
|
|
8acd32324e | ||
|
|
de20099c07 | ||
|
|
877db516c2 | ||
|
|
4dd882b8ad | ||
|
|
ccc3745bb8 | ||
|
|
718dc27089 | ||
|
|
798d8a62ae | ||
|
|
9241bf869f | ||
|
|
166d59341c | ||
|
|
c757ede90e | ||
|
|
a005646054 |
No files matched your search
@@ -60,20 +60,20 @@ If you need Swift 1.2/Xcode 6.3/4 use v2.4.5 (Pre-Swift 2 support is no longer m
|
||||
|
||||
If you need Swift 1.1/Xcode 6.2 use v1.5.2. (Pre-Swift 1.2 support is no longer maintained)
|
||||
|
||||
Carthage
|
||||
-----------------
|
||||
Add this line to your `Cartfile`:
|
||||
```
|
||||
github "socketio/socket.io-client-swift" ~> 3.1.2 # Or latest version
|
||||
```
|
||||
|
||||
Run `carthage update --platform ios,macosx`.
|
||||
|
||||
Manually (iOS 7+)
|
||||
-----------------
|
||||
1. Copy the SocketIOClientSwift folder into your Xcode project. (Make sure you add the files to your target(s))
|
||||
2. If you plan on using this from Objective-C, read [this](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html) on exposing Swift code to Objective-C.
|
||||
|
||||
Carthage
|
||||
-----------------
|
||||
Add this line to your `Cartfile`:
|
||||
```
|
||||
github "socketio/socket.io-client-swift" ~> 3.1.6 # Or latest version
|
||||
```
|
||||
|
||||
Run `carthage update --platform ios,macosx`.
|
||||
|
||||
CocoaPods 0.36.0 or later (iOS 8+)
|
||||
------------------
|
||||
Create `Podfile` and add `pod 'Socket.IO-Client-Swift'`:
|
||||
@@ -83,7 +83,7 @@ source 'https://github.com/CocoaPods/Specs.git'
|
||||
platform :ios, '8.0'
|
||||
use_frameworks!
|
||||
|
||||
pod 'Socket.IO-Client-Swift', '~> 3.1.2' # Or latest version
|
||||
pod 'Socket.IO-Client-Swift', '~> 3.1.6' # Or latest version
|
||||
```
|
||||
|
||||
Install pods:
|
||||
@@ -100,10 +100,23 @@ import Socket_IO_Client_Swift
|
||||
```
|
||||
|
||||
Objective-C:
|
||||
|
||||
```Objective-C
|
||||
#import <Socket_IO_Client_Swift/Socket_IO_Client_Swift-Swift.h>
|
||||
```
|
||||
|
||||
CocoaSeeds
|
||||
-----------------
|
||||
|
||||
Add this line to your `Seedfile`:
|
||||
|
||||
```
|
||||
github "socketio/socket.io-client-swift", "v3.1.6", :files => "SocketIOClientSwift/*.swift" # Or latest version
|
||||
```
|
||||
|
||||
Run `seed install`.
|
||||
|
||||
|
||||
##API
|
||||
Constructors
|
||||
-----------
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = "Socket.IO-Client-Swift"
|
||||
s.version = "3.1.2"
|
||||
s.version = "3.1.6"
|
||||
s.summary = "Socket.IO-client for iOS and OS X"
|
||||
s.description = <<-DESC
|
||||
Socket.IO-client for iOS and OS X.
|
||||
@@ -12,7 +12,7 @@ Pod::Spec.new do |s|
|
||||
s.author = { "Erik" => "nuclear.ace@gmail.com" }
|
||||
s.ios.deployment_target = '8.0'
|
||||
s.osx.deployment_target = '10.10'
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v3.1.2' }
|
||||
s.source = { :git => "https://github.com/socketio/socket.io-client-swift.git", :tag => 'v3.1.6' }
|
||||
s.source_files = "SocketIOClientSwift/**/*.swift"
|
||||
s.requires_arc = true
|
||||
# s.dependency 'Starscream', '~> 0.9' # currently this repo includes Starscream swift files
|
||||
|
||||
@@ -561,7 +561,9 @@
|
||||
572EF2121B51F12F00EEBB58 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
BITCODE_GENERATION_MODE = bitcode;
|
||||
CODE_SIGN_IDENTITY = "Developer ID Application";
|
||||
ENABLE_BITCODE = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
PRODUCT_NAME = SocketIO;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
@@ -571,7 +573,9 @@
|
||||
572EF2131B51F12F00EEBB58 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
BITCODE_GENERATION_MODE = bitcode;
|
||||
CODE_SIGN_IDENTITY = "Developer ID Application";
|
||||
ENABLE_BITCODE = YES;
|
||||
PRODUCT_NAME = SocketIO;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
|
||||
};
|
||||
@@ -594,6 +598,7 @@
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
CODE_SIGN_IDENTITY = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
COPY_PHASE_STRIP = NO;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
@@ -648,7 +653,8 @@
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
CODE_SIGN_IDENTITY = "iPhone Distribution";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution";
|
||||
COPY_PHASE_STRIP = NO;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
|
||||
@@ -19,7 +19,9 @@ class SocketParserTest: XCTestCase {
|
||||
"61-/swift,19[[1,2],{\"test\":\"bob\"},25,\"polo\",{\"_placeholder\":true,\"num\":0}]": ("/swift", [ [1, 2], ["test": "bob"], 25, "polo", "~~0"], [], 19),
|
||||
"4/swift,": ("/swift", [], [], -1),
|
||||
"0/swift": ("/swift", [], [], -1),
|
||||
"1/swift": ("/swift", [], [], -1)]
|
||||
"1/swift": ("/swift", [], [], -1),
|
||||
"4\"ERROR\"": ("/", ["ERROR"], [], -1),
|
||||
"41": ("/", [1], [], -1)]
|
||||
|
||||
func testDisconnect() {
|
||||
let message = "1"
|
||||
@@ -66,6 +68,16 @@ class SocketParserTest: XCTestCase {
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testErrorTypeString() {
|
||||
let message = "4\"ERROR\""
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testErrorTypeInt() {
|
||||
let message = "41"
|
||||
validateParseResult(message)
|
||||
}
|
||||
|
||||
func testInvalidInput() {
|
||||
let message = "8"
|
||||
switch SocketParser.parseString(message) {
|
||||
|
||||
@@ -29,10 +29,10 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
private typealias ProbeWaitQueue = [Probe]
|
||||
|
||||
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
|
||||
private let emitQueue = dispatch_queue_create("engineEmitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let handleQueue = dispatch_queue_create("engineHandleQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let logType = "SocketEngine"
|
||||
private let parseQueue = dispatch_queue_create("engineParseQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let session: NSURLSession!
|
||||
private let workQueue = NSOperationQueue()
|
||||
|
||||
@@ -41,6 +41,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
private var fastUpgrade = false
|
||||
private var forcePolling = false
|
||||
private var forceWebsockets = false
|
||||
private var invalidated = false
|
||||
private var pingInterval: Double?
|
||||
private var pingTimer: NSTimer?
|
||||
private var pingTimeout = 0.0 {
|
||||
@@ -99,6 +100,8 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
|
||||
deinit {
|
||||
Logger.log("Engine is being deinit", type: logType)
|
||||
closed = true
|
||||
stopPolling()
|
||||
}
|
||||
|
||||
private func checkIfMessageIsBase64Binary(var message: String) {
|
||||
@@ -191,8 +194,14 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
private func createWebsocketAndConnect(connect: Bool) {
|
||||
let wsUrl = urlWebSocket + (sid == "" ? "" : "&sid=\(sid)")
|
||||
|
||||
ws = WebSocket(url: NSURL(string: wsUrl)!,
|
||||
cookies: cookies)
|
||||
ws = WebSocket(url: NSURL(string: wsUrl)!)
|
||||
|
||||
if cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
|
||||
for (key, value) in headers {
|
||||
ws?.headers[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
if extraHeaders != nil {
|
||||
for (headerName, value) in extraHeaders! {
|
||||
@@ -223,7 +232,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
|
||||
private func doPoll() {
|
||||
if websocket || waitingForPoll || !connected {
|
||||
if websocket || waitingForPoll || !connected || closed {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -241,19 +250,23 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
doRequest(req)
|
||||
doLongPoll(req)
|
||||
}
|
||||
|
||||
private func doRequest(req: NSMutableURLRequest,
|
||||
withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) {
|
||||
if !polling || closed || invalidated {
|
||||
return
|
||||
}
|
||||
|
||||
Logger.log("Doing polling request", type: logType)
|
||||
|
||||
req.cachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
|
||||
session.dataTaskWithRequest(req, completionHandler: callback).resume()
|
||||
}
|
||||
|
||||
private func doRequest(req: NSMutableURLRequest) {
|
||||
if !polling {
|
||||
return
|
||||
}
|
||||
|
||||
req.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
|
||||
|
||||
Logger.log("Doing polling request", type: logType)
|
||||
|
||||
session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||
private func doLongPoll(req: NSMutableURLRequest) {
|
||||
doRequest(req) {[weak self] data, res, err in
|
||||
if let this = self {
|
||||
if err != nil || data == nil {
|
||||
if this.polling {
|
||||
@@ -263,23 +276,24 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Logger.log("Got polling response", type: this.logType)
|
||||
|
||||
|
||||
if let str = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String {
|
||||
dispatch_async(this.parseQueue) {[weak this] in
|
||||
this?.parsePollingMessage(str)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
this.waitingForPoll = false
|
||||
|
||||
|
||||
if this.fastUpgrade {
|
||||
this.doFastUpgrade()
|
||||
} else if !this.closed && this.polling {
|
||||
this.doPoll()
|
||||
}
|
||||
}}.resume()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func flushProbeWait() {
|
||||
@@ -338,13 +352,13 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
|
||||
Logger.log("POSTing: %@", type: logType, args: postStr)
|
||||
|
||||
session.dataTaskWithRequest(req) {[weak self] data, res, err in
|
||||
doRequest(req) {[weak self] data, res, err in
|
||||
if let this = self {
|
||||
if err != nil && this.polling {
|
||||
this.handlePollingFailed(err?.localizedDescription ?? "Error")
|
||||
return
|
||||
} else if err != nil {
|
||||
NSLog(err?.localizedDescription ?? "Error")
|
||||
Logger.error(err?.localizedDescription ?? "Error", type: this.logType)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -356,7 +370,8 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
this?.doPoll()
|
||||
}
|
||||
}
|
||||
}}.resume()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We had packets waiting for send when we upgraded
|
||||
@@ -481,7 +496,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
}
|
||||
|
||||
doRequest(reqPolling)
|
||||
doLongPoll(reqPolling)
|
||||
}
|
||||
|
||||
private func parsePollingMessage(str: String) {
|
||||
@@ -515,14 +530,15 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
private func parseEngineMessage(var message: String, fromPolling: Bool) {
|
||||
Logger.log("Got message: %@", type: logType, args: message)
|
||||
|
||||
if fromPolling {
|
||||
fixDoubleUTF8(&message)
|
||||
}
|
||||
|
||||
let type = PacketType(str: (message["^(\\d)"].groups()?[1]) ?? "") ?? {
|
||||
self.checkIfMessageIsBase64Binary(message)
|
||||
return .Noop
|
||||
}()
|
||||
|
||||
|
||||
if fromPolling && type != .Noop {
|
||||
fixDoubleUTF8(&message)
|
||||
}
|
||||
|
||||
switch type {
|
||||
case PacketType.Message:
|
||||
@@ -620,6 +636,7 @@ public final class SocketEngine: NSObject, WebSocketDelegate {
|
||||
}
|
||||
|
||||
func stopPolling() {
|
||||
invalidated = true
|
||||
session.finishTasksAndInvalidate()
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
import Foundation
|
||||
|
||||
public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
private let emitQueue = dispatch_queue_create("emitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let emitQueue = dispatch_queue_create("com.socketio.emitQueue", DISPATCH_QUEUE_SERIAL)
|
||||
private let handleQueue: dispatch_queue_t!
|
||||
|
||||
public let socketURL: String
|
||||
@@ -111,7 +111,6 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
|
||||
deinit {
|
||||
Logger.log("Client is being deinit", type: logType)
|
||||
engine?.close(fast: true)
|
||||
}
|
||||
|
||||
private func addEngine() -> SocketEngine {
|
||||
@@ -172,10 +171,10 @@ public final class SocketIOClient: NSObject, SocketEngineClient {
|
||||
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(timeoutAfter) * Int64(NSEC_PER_SEC))
|
||||
|
||||
dispatch_after(time, dispatch_get_main_queue()) {
|
||||
if self.status != .Connected {
|
||||
self.status = .Closed
|
||||
self.engine?.close(fast: true)
|
||||
dispatch_after(time, handleQueue) {[weak self] in
|
||||
if let this = self where this.status != .Connected {
|
||||
this.status = .Closed
|
||||
this.engine?.close(fast: true)
|
||||
|
||||
handler?()
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ struct SocketPacket {
|
||||
|
||||
message += jsonString! as String + ","
|
||||
} catch {
|
||||
Logger.error("Error creating JSON object in SocketPacket.completeMessage", type: SocketPacket.logType)
|
||||
Logger.error("Error creating JSON object in SocketPacket.completeMessage", type: SocketPacket.logType)
|
||||
}
|
||||
} else if var str = arg as? String {
|
||||
str = str["\n"] ~= "\\\\n"
|
||||
|
||||
@@ -54,7 +54,7 @@ class SocketParser {
|
||||
case .Disconnect:
|
||||
socket.didDisconnect("Got Disconnect")
|
||||
case .Error:
|
||||
socket.didError("Error: \(pack.data)")
|
||||
socket.didError(pack.data)
|
||||
default:
|
||||
Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description)
|
||||
}
|
||||
@@ -93,7 +93,11 @@ class SocketParser {
|
||||
|
||||
var idString = ""
|
||||
|
||||
while parser.hasNext {
|
||||
if type == .Error {
|
||||
parser.advanceIndexBy(-1)
|
||||
}
|
||||
|
||||
while parser.hasNext && type != .Error {
|
||||
if let int = Int(parser.read(1)) {
|
||||
idString += String(int)
|
||||
} else {
|
||||
@@ -107,7 +111,13 @@ class SocketParser {
|
||||
|
||||
switch parseData(noPlaceholders) {
|
||||
case .Left(let err):
|
||||
return .Left(err)
|
||||
// If first you don't succeed, try again
|
||||
if case let .Right(data) = parseData("\([noPlaceholders as AnyObject])") {
|
||||
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
|
||||
nsp: namespace ?? "/", placeholders: placeholders))
|
||||
} else {
|
||||
return .Left(err)
|
||||
}
|
||||
case .Right(let data):
|
||||
return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1,
|
||||
nsp: namespace ?? "/", placeholders: placeholders))
|
||||
|
||||
+165
-192
@@ -8,6 +8,7 @@
|
||||
|
||||
import Foundation
|
||||
import CoreFoundation
|
||||
import Security
|
||||
|
||||
public protocol WebSocketDelegate: class {
|
||||
func websocketDidConnect(socket: WebSocket)
|
||||
@@ -93,19 +94,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
public var headers = Dictionary<String,String>()
|
||||
public var voipEnabled = false
|
||||
public var selfSignedSSL = false
|
||||
private var security: Security?
|
||||
private var security: SSLSecurity?
|
||||
public var enabledSSLCipherSuites: [SSLCipherSuite]?
|
||||
public var isConnected :Bool {
|
||||
return connected
|
||||
}
|
||||
|
||||
private var cookies:[NSHTTPCookie]?
|
||||
private var url: NSURL
|
||||
private var inputStream: NSInputStream?
|
||||
private var outputStream: NSOutputStream?
|
||||
private var isRunLoop = false
|
||||
private var connected = false
|
||||
private var isCreated = false
|
||||
private var writeQueue: NSOperationQueue?
|
||||
private var writeQueue = NSOperationQueue()
|
||||
private var readStack = Array<WSResponse>()
|
||||
private var inputQueue = Array<NSData>()
|
||||
private var fragBuffer: NSData?
|
||||
@@ -115,13 +115,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
//init the websocket with a url
|
||||
public init(url: NSURL) {
|
||||
self.url = url
|
||||
writeQueue.maxConcurrentOperationCount = 1
|
||||
}
|
||||
|
||||
public convenience init(url: NSURL, cookies:[NSHTTPCookie]?) {
|
||||
self.init(url: url)
|
||||
self.cookies = cookies
|
||||
}
|
||||
|
||||
//used for setting protocols.
|
||||
public convenience init(url: NSURL, protocols: Array<String>) {
|
||||
self.init(url: url)
|
||||
@@ -133,23 +128,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if isCreated {
|
||||
return
|
||||
}
|
||||
|
||||
dispatch_async(queue, { [weak self] in
|
||||
guard let weakSelf = self else {
|
||||
return
|
||||
}
|
||||
|
||||
weakSelf.didDisconnect = false
|
||||
})
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
self?.didDisconnect = false
|
||||
})
|
||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), { [weak self] in
|
||||
guard let weakSelf = self else {
|
||||
return
|
||||
}
|
||||
|
||||
weakSelf.isCreated = true
|
||||
weakSelf.createHTTPRequest()
|
||||
weakSelf.isCreated = false
|
||||
})
|
||||
self?.isCreated = true
|
||||
self?.createHTTPRequest()
|
||||
self?.isCreated = false
|
||||
})
|
||||
}
|
||||
|
||||
///disconnect from the websocket server
|
||||
@@ -188,30 +174,22 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
port = 80
|
||||
}
|
||||
}
|
||||
|
||||
if self.cookies != nil {
|
||||
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(self.cookies!)
|
||||
for (key, value) in headers {
|
||||
self.addHeader(urlRequest, key: key as String, val: value as String)
|
||||
}
|
||||
}
|
||||
|
||||
self.addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
|
||||
self.addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
|
||||
addHeader(urlRequest, key: headerWSUpgradeName, val: headerWSUpgradeValue)
|
||||
addHeader(urlRequest, key: headerWSConnectionName, val: headerWSConnectionValue)
|
||||
if let protocols = optionalProtocols {
|
||||
self.addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joinWithSeparator(","))
|
||||
addHeader(urlRequest, key: headerWSProtocolName, val: protocols.joinWithSeparator(","))
|
||||
}
|
||||
self.addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
|
||||
self.addHeader(urlRequest, key: headerWSKeyName, val: self.generateWebSocketKey())
|
||||
self.addHeader(urlRequest, key: headerOriginName, val: url.absoluteString)
|
||||
self.addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
|
||||
addHeader(urlRequest, key: headerWSVersionName, val: headerWSVersionValue)
|
||||
addHeader(urlRequest, key: headerWSKeyName, val: generateWebSocketKey())
|
||||
addHeader(urlRequest, key: headerOriginName, val: url.absoluteString)
|
||||
addHeader(urlRequest, key: headerWSHostName, val: "\(url.host!):\(port!)")
|
||||
for (key,value) in headers {
|
||||
self.addHeader(urlRequest, key: key, val: value)
|
||||
addHeader(urlRequest, key: key, val: value)
|
||||
}
|
||||
if let cfHTTPMessage = CFHTTPMessageCopySerializedMessage(urlRequest) {
|
||||
let serializedRequest = cfHTTPMessage.takeRetainedValue()
|
||||
initStreamsWithData(serializedRequest, Int(port!))
|
||||
}
|
||||
|
||||
|
||||
let serializedRequest: NSData = CFHTTPMessageCopySerializedMessage(urlRequest)!.takeRetainedValue()
|
||||
self.initStreamsWithData(serializedRequest, Int(port!))
|
||||
}
|
||||
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
|
||||
private func addHeader(urlRequest: CFHTTPMessage,key: String, val: String) {
|
||||
@@ -244,31 +222,48 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
CFStreamCreatePairWithSocketToHost(nil, h, UInt32(port), &readStream, &writeStream)
|
||||
inputStream = readStream!.takeRetainedValue()
|
||||
outputStream = writeStream!.takeRetainedValue()
|
||||
|
||||
inputStream!.delegate = self
|
||||
outputStream!.delegate = self
|
||||
guard let inStream = inputStream, let outStream = outputStream else { return }
|
||||
inStream.delegate = self
|
||||
outStream.delegate = self
|
||||
if url.scheme == "wss" || url.scheme == "https" {
|
||||
inputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||
outputStream!.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||
inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||
outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||
} else {
|
||||
certValidated = true //not a https session, so no need to check SSL pinning
|
||||
}
|
||||
if self.voipEnabled {
|
||||
inputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
||||
outputStream!.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
||||
if voipEnabled {
|
||||
inStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
||||
outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
||||
}
|
||||
if self.selfSignedSSL {
|
||||
if selfSignedSSL {
|
||||
let settings: Dictionary<NSObject, NSObject> = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
|
||||
inputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
outputStream!.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||
}
|
||||
if let cipherSuites = self.enabledSSLCipherSuites {
|
||||
if let sslContextIn = CFReadStreamCopyProperty(inputStream, kCFStreamPropertySSLContext) as! SSLContextRef?,
|
||||
sslContextOut = CFWriteStreamCopyProperty(outputStream, kCFStreamPropertySSLContext) as! SSLContextRef? {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
isRunLoop = true
|
||||
inputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
outputStream!.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inputStream!.open()
|
||||
outputStream!.open()
|
||||
inStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
outStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
inStream.open()
|
||||
outStream.open()
|
||||
let bytes = UnsafePointer<UInt8>(data.bytes)
|
||||
outputStream!.write(bytes, maxLength: data.length)
|
||||
outStream.write(bytes, maxLength: data.length)
|
||||
while(isRunLoop) {
|
||||
NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture() as NSDate)
|
||||
}
|
||||
@@ -283,8 +278,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if sec.isValid(trust as! SecTrustRef, domain: domain as! String?) {
|
||||
certValidated = true
|
||||
} else {
|
||||
let error = self.errorWithDetail("Invalid SSL certificate", code: 1)
|
||||
doDisconnect(error)
|
||||
let error = errorWithDetail("Invalid SSL certificate", code: 1)
|
||||
disconnectStream(error)
|
||||
return
|
||||
}
|
||||
@@ -302,9 +296,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
//disconnect the stream object
|
||||
private func disconnectStream(error: NSError?) {
|
||||
if writeQueue != nil {
|
||||
writeQueue!.waitUntilAllOperationsAreFinished()
|
||||
}
|
||||
writeQueue.waitUntilAllOperationsAreFinished()
|
||||
if let stream = inputStream {
|
||||
stream.removeFromRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
|
||||
stream.close()
|
||||
@@ -316,7 +308,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
outputStream = nil
|
||||
isRunLoop = false
|
||||
certValidated = false
|
||||
self.doDisconnect(error)
|
||||
doDisconnect(error)
|
||||
connected = false
|
||||
}
|
||||
|
||||
@@ -327,9 +319,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
let length = inputStream!.read(buffer, maxLength: BUFFER_MAX)
|
||||
if length > 0 {
|
||||
if !connected {
|
||||
let status = processHTTP(buffer, bufferLen: length)
|
||||
if !status {
|
||||
self.doDisconnect(self.errorWithDetail("Invalid HTTP upgrade", code: 1))
|
||||
connected = processHTTP(buffer, bufferLen: length)
|
||||
if !connected {
|
||||
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
|
||||
CFHTTPMessageAppendBytes(response, buffer, length)
|
||||
let code = CFHTTPMessageGetResponseStatusCode(response)
|
||||
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
|
||||
}
|
||||
} else {
|
||||
var process = false
|
||||
@@ -348,7 +343,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if inputQueue.count > 0 {
|
||||
let data = inputQueue[0]
|
||||
var work = data
|
||||
if (fragBuffer != nil) {
|
||||
if fragBuffer != nil {
|
||||
let combine = NSMutableData(data: fragBuffer!)
|
||||
combine.appendData(data)
|
||||
work = combine
|
||||
@@ -378,17 +373,17 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
if totalSize > 0 {
|
||||
if validateResponse(buffer, bufferLen: totalSize) {
|
||||
dispatch_async(queue, {
|
||||
self.connected = true
|
||||
if let connectBlock = self.onConnect {
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let connectBlock = s.onConnect {
|
||||
connectBlock()
|
||||
}
|
||||
self.delegate?.websocketDidConnect(self)
|
||||
})
|
||||
s.delegate?.websocketDidConnect(s)
|
||||
})
|
||||
totalSize += 1 //skip the last \n
|
||||
let restSize = bufferLen - totalSize
|
||||
if restSize > 0 {
|
||||
processRawMessage((buffer+totalSize), bufferLen: restSize)
|
||||
processRawMessage((buffer+totalSize),bufferLen: restSize)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -403,11 +398,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if CFHTTPMessageGetResponseStatusCode(response) != 101 {
|
||||
return false
|
||||
}
|
||||
let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response)
|
||||
let headers:NSDictionary? = cfHeaders?.takeRetainedValue()
|
||||
let acceptKey = headers?[headerWSAcceptName] as! NSString
|
||||
if acceptKey.length > 0 {
|
||||
return true
|
||||
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
|
||||
let headers = cfHeaders.takeRetainedValue() as NSDictionary
|
||||
let acceptKey = headers[headerWSAcceptName] as! NSString
|
||||
if acceptKey.length > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -443,8 +439,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
var offset = 2
|
||||
if((isMasked > 0 || (RSVMask & buffer[0]) > 0) && receivedOpcode != OpCode.Pong.rawValue) {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("masked and rsv data is not currently supported", code: errCode)
|
||||
self.doDisconnect(error)
|
||||
doDisconnect(errorWithDetail("masked and rsv data is not currently supported", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
@@ -452,15 +447,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if !isControlFrame && (receivedOpcode != OpCode.BinaryFrame.rawValue && receivedOpcode != OpCode.ContinueFrame.rawValue &&
|
||||
receivedOpcode != OpCode.TextFrame.rawValue && receivedOpcode != OpCode.Pong.rawValue) {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode)
|
||||
self.doDisconnect(error)
|
||||
doDisconnect(errorWithDetail("unknown opcode: \(receivedOpcode)", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
if isControlFrame && isFin == 0 {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("control frames can't be fragmented", code: errCode)
|
||||
self.doDisconnect(error)
|
||||
doDisconnect(errorWithDetail("control frames can't be fragmented", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
@@ -486,8 +479,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
}
|
||||
}
|
||||
let error = self.errorWithDetail("connection closed by server", code: code)
|
||||
self.doDisconnect(error)
|
||||
doDisconnect(errorWithDetail("connection closed by server", code: code))
|
||||
writeError(code)
|
||||
return
|
||||
}
|
||||
@@ -521,10 +513,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
data = NSData(bytes: UnsafePointer<UInt8>((buffer+offset)), length: Int(len))
|
||||
}
|
||||
if receivedOpcode == OpCode.Pong.rawValue {
|
||||
dispatch_async(queue, {
|
||||
self.onPong?()
|
||||
self.pongDelegate?.websocketDidReceivePong(self)
|
||||
})
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let pongBlock = s.onPong {
|
||||
pongBlock()
|
||||
}
|
||||
s.pongDelegate?.websocketDidReceivePong(s)
|
||||
})
|
||||
|
||||
let step = Int(offset+numericCast(len))
|
||||
let extra = bufferLen-step
|
||||
@@ -539,8 +534,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
if isFin == 0 && receivedOpcode == OpCode.ContinueFrame.rawValue && response == nil {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("continue frame before a binary or text frame", code: errCode)
|
||||
self.doDisconnect(error)
|
||||
doDisconnect(errorWithDetail("continue frame before a binary or text frame", code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
@@ -548,9 +542,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
if(response == nil) {
|
||||
if receivedOpcode == OpCode.ContinueFrame.rawValue {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("first frame can't be a continue frame",
|
||||
code: errCode)
|
||||
self.doDisconnect(error)
|
||||
doDisconnect(errorWithDetail("first frame can't be a continue frame",
|
||||
code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
@@ -564,9 +557,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
response!.bytesLeft = Int(dataLength)
|
||||
} else {
|
||||
let errCode = CloseCode.ProtocolError.rawValue
|
||||
let error = self.errorWithDetail("second and beyond of fragment message must be a continue frame",
|
||||
code: errCode)
|
||||
self.doDisconnect(error)
|
||||
doDisconnect(errorWithDetail("second and beyond of fragment message must be a continue frame",
|
||||
code: errCode))
|
||||
writeError(errCode)
|
||||
return
|
||||
}
|
||||
@@ -608,24 +600,28 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
dequeueWrite(data, code: OpCode.Pong)
|
||||
} else if response.code == .TextFrame {
|
||||
let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
|
||||
|
||||
if let str = str as String? {
|
||||
dispatch_async(queue, {
|
||||
self.onText?(str)
|
||||
self.delegate?.websocketDidReceiveMessage(self, text: str)
|
||||
})
|
||||
} else {
|
||||
if str == nil {
|
||||
writeError(CloseCode.Encoding.rawValue)
|
||||
return false
|
||||
}
|
||||
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let textBlock = s.onText {
|
||||
textBlock(str! as String)
|
||||
}
|
||||
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
|
||||
})
|
||||
} else if response.code == .BinaryFrame {
|
||||
let data = response.buffer! //local copy so it is perverse for writing
|
||||
dispatch_async(queue) {
|
||||
self.onData?(data)
|
||||
self.delegate?.websocketDidReceiveData(self, data: data)
|
||||
}
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
if let dataBlock = s.onData {
|
||||
dataBlock(data)
|
||||
}
|
||||
s.delegate?.websocketDidReceiveData(s, data: data)
|
||||
})
|
||||
}
|
||||
|
||||
readStack.removeLast()
|
||||
return true
|
||||
}
|
||||
@@ -648,31 +644,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
///used to write things to the stream
|
||||
private func dequeueWrite(data: NSData, code: OpCode) {
|
||||
if writeQueue == nil {
|
||||
writeQueue = NSOperationQueue()
|
||||
writeQueue!.maxConcurrentOperationCount = 1
|
||||
if !isConnected {
|
||||
return
|
||||
}
|
||||
writeQueue!.addOperationWithBlock {
|
||||
writeQueue.addOperationWithBlock { [weak self] in
|
||||
//stream isn't ready, let's wait
|
||||
var tries = 0;
|
||||
while self.outputStream == nil || !self.connected {
|
||||
if(tries < 5) {
|
||||
sleep(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
tries++;
|
||||
}
|
||||
if !self.connected {
|
||||
return
|
||||
}
|
||||
guard let s = self else { return }
|
||||
var offset = 2
|
||||
UINT16_MAX
|
||||
let bytes = UnsafeMutablePointer<UInt8>(data.bytes)
|
||||
let dataLength = data.length
|
||||
let frame = NSMutableData(capacity: dataLength + self.MaxFrameSize)
|
||||
let frame = NSMutableData(capacity: dataLength + s.MaxFrameSize)
|
||||
let buffer = UnsafeMutablePointer<UInt8>(frame!.mutableBytes)
|
||||
buffer[0] = self.FinMask | code.rawValue
|
||||
buffer[0] = s.FinMask | code.rawValue
|
||||
if dataLength < 126 {
|
||||
buffer[1] = CUnsignedChar(dataLength)
|
||||
} else if dataLength <= Int(UInt16.max) {
|
||||
@@ -686,7 +669,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
sizeBuffer[0] = UInt64(dataLength).bigEndian
|
||||
offset += sizeof(UInt64)
|
||||
}
|
||||
buffer[1] |= self.MaskMask
|
||||
buffer[1] |= s.MaskMask
|
||||
let maskKey = UnsafeMutablePointer<UInt8>(buffer + offset)
|
||||
SecRandomCopyBytes(kSecRandomDefault, Int(sizeof(UInt32)), maskKey)
|
||||
offset += sizeof(UInt32)
|
||||
@@ -697,23 +680,24 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
}
|
||||
var total = 0
|
||||
while true {
|
||||
if self.outputStream == nil {
|
||||
if !s.isConnected {
|
||||
break
|
||||
}
|
||||
guard let outStream = s.outputStream else { break }
|
||||
let writeBuffer = UnsafePointer<UInt8>(frame!.bytes+total)
|
||||
let len = self.outputStream?.write(writeBuffer, maxLength: offset-total)
|
||||
if len == nil || len! < 0 {
|
||||
let len = outStream.write(writeBuffer, maxLength: offset-total)
|
||||
if len < 0 {
|
||||
var error: NSError?
|
||||
if let streamError = self.outputStream?.streamError {
|
||||
if let streamError = outStream.streamError {
|
||||
error = streamError
|
||||
} else {
|
||||
let errCode = InternalErrorCode.OutputStreamWriteError.rawValue
|
||||
error = self.errorWithDetail("output stream error during write", code: errCode)
|
||||
error = s.errorWithDetail("output stream error during write", code: errCode)
|
||||
}
|
||||
self.doDisconnect(error)
|
||||
s.doDisconnect(error)
|
||||
break
|
||||
} else {
|
||||
total += len!
|
||||
total += len
|
||||
}
|
||||
if total >= offset {
|
||||
break
|
||||
@@ -725,31 +709,20 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
||||
|
||||
///used to preform the disconnect delegate
|
||||
private func doDisconnect(error: NSError?) {
|
||||
if !self.didDisconnect {
|
||||
dispatch_async(queue) {
|
||||
self.didDisconnect = true
|
||||
|
||||
self.onDisconnect?(error)
|
||||
self.delegate?.websocketDidDisconnect(self, error: error)
|
||||
}
|
||||
if !didDisconnect {
|
||||
dispatch_async(queue,{ [weak self] in
|
||||
guard let s = self else { return }
|
||||
s.didDisconnect = true
|
||||
if let disconnect = s.onDisconnect {
|
||||
disconnect(error)
|
||||
}
|
||||
s.delegate?.websocketDidDisconnect(s, error: error)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Security.swift
|
||||
// Starscream
|
||||
//
|
||||
// Created by Dalton Cherry on 5/16/15.
|
||||
// Copyright (c) 2015 Vluxe. All rights reserved.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
private class SSLCert {
|
||||
var certData: NSData?
|
||||
var key: SecKeyRef?
|
||||
@@ -757,9 +730,9 @@ private class SSLCert {
|
||||
/**
|
||||
Designated init for certificates
|
||||
|
||||
:param: data is the binary data of the certificate
|
||||
- parameter data: is the binary data of the certificate
|
||||
|
||||
:returns: a representation security object to be used with
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
init(data: NSData) {
|
||||
self.certData = data
|
||||
@@ -768,17 +741,17 @@ private class SSLCert {
|
||||
/**
|
||||
Designated init for public keys
|
||||
|
||||
:param: key is the public key to be used
|
||||
- parameter key: is the public key to be used
|
||||
|
||||
:returns: a representation security object to be used with
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
init(key: SecKeyRef) {
|
||||
self.key = key
|
||||
}
|
||||
}
|
||||
|
||||
private class Security {
|
||||
private var validatedDN = true //should the domain name be validated?
|
||||
private class SSLSecurity {
|
||||
var validatedDN = true //should the domain name be validated?
|
||||
|
||||
var isReady = false //is the key processing done?
|
||||
var certificates: [NSData]? //the certificates
|
||||
@@ -788,11 +761,11 @@ private class Security {
|
||||
/**
|
||||
Use certs from main app bundle
|
||||
|
||||
:param: usePublicKeys is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
- 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
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
private convenience init(usePublicKeys: Bool = false) {
|
||||
convenience init(usePublicKeys: Bool = false) {
|
||||
let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".")
|
||||
var collect = Array<SSLCert>()
|
||||
for path in paths {
|
||||
@@ -806,12 +779,12 @@ private class Security {
|
||||
/**
|
||||
Designated init
|
||||
|
||||
:param: keys is the certificates or public keys to use
|
||||
:param: usePublicKeys is to specific if the publicKeys or certificates should be used for SSL pinning validation
|
||||
- parameter keys: 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
|
||||
- returns: a representation security object to be used with
|
||||
*/
|
||||
private init(certs: [SSLCert], usePublicKeys: Bool) {
|
||||
init(certs: [SSLCert], usePublicKeys: Bool) {
|
||||
self.usePublicKeys = usePublicKeys
|
||||
|
||||
if self.usePublicKeys {
|
||||
@@ -843,12 +816,12 @@ private class Security {
|
||||
/**
|
||||
Valid the trust and domain name.
|
||||
|
||||
:param: trust is the serverTrust to validate
|
||||
:param: domain is the CN domain to validate
|
||||
- parameter trust: is the serverTrust to validate
|
||||
- parameter domain: is the CN domain to validate
|
||||
|
||||
:returns: if the key was successfully validated
|
||||
- returns: if the key was successfully validated
|
||||
*/
|
||||
private func isValid(trust: SecTrustRef, domain: String?) -> Bool {
|
||||
func isValid(trust: SecTrustRef, domain: String?) -> Bool {
|
||||
|
||||
var tries = 0
|
||||
while(!self.isReady) {
|
||||
@@ -912,14 +885,14 @@ private class Security {
|
||||
/**
|
||||
Get the public key from a certificate data
|
||||
|
||||
:param: data is the certificate to pull the public key from
|
||||
- parameter data: is the certificate to pull the public key from
|
||||
|
||||
:returns: a public key
|
||||
- returns: a public key
|
||||
*/
|
||||
func extractPublicKey(data: NSData) -> SecKeyRef? {
|
||||
let possibleCert = SecCertificateCreateWithData(nil,data)
|
||||
if let cert = possibleCert {
|
||||
return extractPublicKeyFromCert(cert,policy: SecPolicyCreateBasicX509())
|
||||
return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -927,16 +900,16 @@ private class Security {
|
||||
/**
|
||||
Get the public key from a certificate
|
||||
|
||||
:param: data is the certificate to pull the public key from
|
||||
- parameter data: is the certificate to pull the public key from
|
||||
|
||||
:returns: a public key
|
||||
- returns: a public key
|
||||
*/
|
||||
func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? {
|
||||
let possibleTrust = UnsafeMutablePointer<SecTrust?>.alloc(1)
|
||||
SecTrustCreateWithCertificates( cert, policy, possibleTrust)
|
||||
if let trust = possibleTrust.memory {
|
||||
var possibleTrust: SecTrust?
|
||||
SecTrustCreateWithCertificates(cert, policy, &possibleTrust)
|
||||
if let trust = possibleTrust {
|
||||
var result: SecTrustResultType = 0
|
||||
SecTrustEvaluate(trust,&result)
|
||||
SecTrustEvaluate(trust, &result)
|
||||
return SecTrustCopyPublicKey(trust)
|
||||
}
|
||||
return nil
|
||||
@@ -945,9 +918,9 @@ private class Security {
|
||||
/**
|
||||
Get the certificate chain for the trust
|
||||
|
||||
:param: trust is the trust to lookup the certificate chain for
|
||||
- parameter trust: is the trust to lookup the certificate chain for
|
||||
|
||||
:returns: the certificate chain for the trust
|
||||
- returns: the certificate chain for the trust
|
||||
*/
|
||||
func certificateChainForTrust(trust: SecTrustRef) -> Array<NSData> {
|
||||
var collect = Array<NSData>()
|
||||
@@ -961,9 +934,9 @@ private class Security {
|
||||
/**
|
||||
Get the public key chain for the trust
|
||||
|
||||
:param: trust is the trust to lookup the certificate chain and extract the public keys
|
||||
- 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
|
||||
- returns: the public keys from the certifcate chain for the trust
|
||||
*/
|
||||
func publicKeyChainForTrust(trust: SecTrustRef) -> Array<SecKeyRef> {
|
||||
var collect = Array<SecKeyRef>()
|
||||
|
||||
Reference in new issue
Block a user