bump websocket version
This commit is contained in:
parent
3ec1b93f8e
commit
b6cb0b2c7b
@ -88,10 +88,10 @@ public class SSLSecurity : NSObject {
|
|||||||
- returns: a representation security object to be used with
|
- returns: a representation security object to be used with
|
||||||
*/
|
*/
|
||||||
public init(certs: [SSLCert], usePublicKeys: Bool) {
|
public init(certs: [SSLCert], usePublicKeys: Bool) {
|
||||||
super.init()
|
|
||||||
|
|
||||||
self.usePublicKeys = usePublicKeys
|
self.usePublicKeys = usePublicKeys
|
||||||
|
|
||||||
|
super.init()
|
||||||
|
|
||||||
if self.usePublicKeys {
|
if self.usePublicKeys {
|
||||||
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
|
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) {
|
||||||
let pubKeys = certs.reduce([SecKeyRef]()) { (pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
|
let pubKeys = certs.reduce([SecKeyRef]()) { (pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in
|
||||||
|
|||||||
@ -259,7 +259,7 @@ public final class SocketEngine : NSObject, NSURLSessionDelegate, SocketEnginePo
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ws?.queue = handleQueue
|
ws?.callbackQueue = handleQueue
|
||||||
ws?.voipEnabled = voipEnabled
|
ws?.voipEnabled = voipEnabled
|
||||||
ws?.delegate = self
|
ws?.delegate = self
|
||||||
ws?.selfSignedSSL = selfSigned
|
ws?.selfSignedSSL = selfSigned
|
||||||
|
|||||||
@ -38,44 +38,46 @@ public protocol WebSocketPongDelegate: class {
|
|||||||
func websocketDidReceivePong(socket: WebSocket)
|
func websocketDidReceivePong(socket: WebSocket)
|
||||||
}
|
}
|
||||||
|
|
||||||
public class WebSocket : NSObject, NSStreamDelegate {
|
public class WebSocket: NSObject, NSStreamDelegate {
|
||||||
|
|
||||||
enum OpCode : UInt8 {
|
enum OpCode: UInt8 {
|
||||||
case ContinueFrame = 0x0
|
case ContinueFrame = 0x0
|
||||||
case TextFrame = 0x1
|
case TextFrame = 0x1
|
||||||
case BinaryFrame = 0x2
|
case BinaryFrame = 0x2
|
||||||
//3-7 are reserved.
|
// 3-7 are reserved.
|
||||||
case ConnectionClose = 0x8
|
case ConnectionClose = 0x8
|
||||||
case Ping = 0x9
|
case Ping = 0x9
|
||||||
case Pong = 0xA
|
case Pong = 0xA
|
||||||
//B-F reserved.
|
// B-F reserved.
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum CloseCode : UInt16 {
|
public enum CloseCode: UInt16 {
|
||||||
case Normal = 1000
|
case Normal = 1000
|
||||||
case GoingAway = 1001
|
case GoingAway = 1001
|
||||||
case ProtocolError = 1002
|
case ProtocolError = 1002
|
||||||
case ProtocolUnhandledType = 1003
|
case ProtocolUnhandledType = 1003
|
||||||
// 1004 reserved.
|
// 1004 reserved.
|
||||||
case NoStatusReceived = 1005
|
case NoStatusReceived = 1005
|
||||||
//1006 reserved.
|
// 1006 reserved.
|
||||||
case Encoding = 1007
|
case Encoding = 1007
|
||||||
case PolicyViolated = 1008
|
case PolicyViolated = 1008
|
||||||
case MessageTooBig = 1009
|
case MessageTooBig = 1009
|
||||||
}
|
}
|
||||||
|
|
||||||
public static let ErrorDomain = "WebSocket"
|
public static let ErrorDomain = "WebSocket"
|
||||||
|
|
||||||
enum InternalErrorCode : UInt16 {
|
enum InternalErrorCode: UInt16 {
|
||||||
// 0-999 WebSocket status codes not used
|
// 0-999 WebSocket status codes not used
|
||||||
case OutputStreamWriteError = 1
|
case OutputStreamWriteError = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
//Where the callback is executed. It defaults to the main UI thread queue.
|
/// Where the callback is executed. It defaults to the main UI thread queue.
|
||||||
public var queue = dispatch_get_main_queue()
|
public var callbackQueue = dispatch_get_main_queue()
|
||||||
|
|
||||||
var optionalProtocols : [String]?
|
var optionalProtocols : [String]?
|
||||||
//Constant Values.
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
let headerWSUpgradeName = "Upgrade"
|
let headerWSUpgradeName = "Upgrade"
|
||||||
let headerWSUpgradeValue = "websocket"
|
let headerWSUpgradeValue = "websocket"
|
||||||
let headerWSHostName = "Host"
|
let headerWSHostName = "Host"
|
||||||
@ -94,6 +96,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
let MaskMask: UInt8 = 0x80
|
let MaskMask: UInt8 = 0x80
|
||||||
let PayloadLenMask: UInt8 = 0x7F
|
let PayloadLenMask: UInt8 = 0x7F
|
||||||
let MaxFrameSize: Int = 32
|
let MaxFrameSize: Int = 32
|
||||||
|
let httpSwitchProtocolCode = 101
|
||||||
|
let supportedSSLSchemes = ["wss", "https"]
|
||||||
|
|
||||||
class WSResponse {
|
class WSResponse {
|
||||||
var isFin = false
|
var isFin = false
|
||||||
@ -103,13 +107,24 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
var buffer: NSMutableData?
|
var buffer: NSMutableData?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Delegates
|
||||||
|
|
||||||
|
/// Responds to callback about new messages coming in over the WebSocket
|
||||||
|
/// and also connection/disconnect messages.
|
||||||
public weak var delegate: WebSocketDelegate?
|
public weak var delegate: WebSocketDelegate?
|
||||||
|
|
||||||
|
/// Recives a callback for each pong message recived.
|
||||||
public weak var pongDelegate: WebSocketPongDelegate?
|
public weak var pongDelegate: WebSocketPongDelegate?
|
||||||
|
|
||||||
|
|
||||||
|
// MARK: - Block based API.
|
||||||
|
|
||||||
public var onConnect: ((Void) -> Void)?
|
public var onConnect: ((Void) -> Void)?
|
||||||
public var onDisconnect: ((NSError?) -> Void)?
|
public var onDisconnect: ((NSError?) -> Void)?
|
||||||
public var onText: ((String) -> Void)?
|
public var onText: ((String) -> Void)?
|
||||||
public var onData: ((NSData) -> Void)?
|
public var onData: ((NSData) -> Void)?
|
||||||
public var onPong: ((Void) -> Void)?
|
public var onPong: ((Void) -> Void)?
|
||||||
|
|
||||||
public var headers = [String: String]()
|
public var headers = [String: String]()
|
||||||
public var voipEnabled = false
|
public var voipEnabled = false
|
||||||
public var selfSignedSSL = false
|
public var selfSignedSSL = false
|
||||||
@ -120,12 +135,15 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
public var isConnected :Bool {
|
public var isConnected :Bool {
|
||||||
return connected
|
return connected
|
||||||
}
|
}
|
||||||
public var currentURL: NSURL {return url}
|
public var currentURL: NSURL { return url }
|
||||||
|
|
||||||
|
// MARK: - Private
|
||||||
|
|
||||||
private var url: NSURL
|
private var url: NSURL
|
||||||
private var inputStream: NSInputStream?
|
private var inputStream: NSInputStream?
|
||||||
private var outputStream: NSOutputStream?
|
private var outputStream: NSOutputStream?
|
||||||
private var connected = false
|
private var connected = false
|
||||||
private var isCreated = false
|
private var isConnecting = false
|
||||||
private var writeQueue = NSOperationQueue()
|
private var writeQueue = NSOperationQueue()
|
||||||
private var readStack = [WSResponse]()
|
private var readStack = [WSResponse]()
|
||||||
private var inputQueue = [NSData]()
|
private var inputQueue = [NSData]()
|
||||||
@ -141,10 +159,11 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
mutex.unlock()
|
mutex.unlock()
|
||||||
return canWork
|
return canWork
|
||||||
}
|
}
|
||||||
//the shared processing queue used for all websocket
|
|
||||||
|
/// The shared processing queue used for all WebSocket.
|
||||||
private static let sharedWorkQueue = dispatch_queue_create("com.vluxe.starscream.websocket", DISPATCH_QUEUE_SERIAL)
|
private static let sharedWorkQueue = dispatch_queue_create("com.vluxe.starscream.websocket", DISPATCH_QUEUE_SERIAL)
|
||||||
|
|
||||||
//used for setting protocols.
|
/// Used for setting protocols.
|
||||||
public init(url: NSURL, protocols: [String]? = nil) {
|
public init(url: NSURL, protocols: [String]? = nil) {
|
||||||
self.url = url
|
self.url = url
|
||||||
self.origin = url.absoluteString
|
self.origin = url.absoluteString
|
||||||
@ -152,13 +171,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
optionalProtocols = protocols
|
optionalProtocols = protocols
|
||||||
}
|
}
|
||||||
|
|
||||||
///Connect to the websocket server on a background thread
|
/// Connect to the WebSocket server on a background thread.
|
||||||
public func connect() {
|
public func connect() {
|
||||||
guard !isCreated else { return }
|
guard !isConnecting else { return }
|
||||||
didDisconnect = false
|
didDisconnect = false
|
||||||
isCreated = true
|
isConnecting = true
|
||||||
createHTTPRequest()
|
createHTTPRequest()
|
||||||
isCreated = false
|
isConnecting = false
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -173,7 +192,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
public func disconnect(forceTimeout forceTimeout: NSTimeInterval? = nil) {
|
public func disconnect(forceTimeout forceTimeout: NSTimeInterval? = nil) {
|
||||||
switch forceTimeout {
|
switch forceTimeout {
|
||||||
case .Some(let seconds) where seconds > 0:
|
case .Some(let seconds) where seconds > 0:
|
||||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), queue) { [weak self] in
|
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), callbackQueue) { [weak self] in
|
||||||
self?.disconnectStream(nil)
|
self?.disconnectStream(nil)
|
||||||
}
|
}
|
||||||
fallthrough
|
fallthrough
|
||||||
@ -181,7 +200,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
writeError(CloseCode.Normal.rawValue)
|
writeError(CloseCode.Normal.rawValue)
|
||||||
|
|
||||||
default:
|
default:
|
||||||
self.disconnectStream(nil)
|
disconnectStream(nil)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -212,14 +231,14 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
dequeueWrite(data, code: .BinaryFrame, writeCompletion: completion)
|
dequeueWrite(data, code: .BinaryFrame, writeCompletion: completion)
|
||||||
}
|
}
|
||||||
|
|
||||||
//write a ping to the websocket. This sends it as a control frame.
|
// 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
|
// Yodel a sound to the planet. This sends it as an astroid. http://youtu.be/Eu5ZJELRiJ8?t=42s
|
||||||
public func writePing(data: NSData, completion: (() -> ())? = nil) {
|
public func writePing(data: NSData, completion: (() -> ())? = nil) {
|
||||||
guard isConnected else { return }
|
guard isConnected else { return }
|
||||||
dequeueWrite(data, code: .Ping, writeCompletion: completion)
|
dequeueWrite(data, code: .Ping, writeCompletion: completion)
|
||||||
}
|
}
|
||||||
|
|
||||||
//private method that starts the connection
|
/// Private method that starts the connection.
|
||||||
private func createHTTPRequest() {
|
private func createHTTPRequest() {
|
||||||
|
|
||||||
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
|
let urlRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, "GET",
|
||||||
@ -227,7 +246,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
|
|
||||||
var port = url.port
|
var port = url.port
|
||||||
if port == nil {
|
if port == nil {
|
||||||
if ["wss", "https"].contains(url.scheme) {
|
if supportedSSLSchemes.contains(url.scheme) {
|
||||||
port = 443
|
port = 443
|
||||||
} else {
|
} else {
|
||||||
port = 80
|
port = 80
|
||||||
@ -253,12 +272,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//Add a header to the CFHTTPMessage by using the NSString bridges to CFString
|
/// Add a header to the CFHTTPMessage by using the NSString bridges to CFString.
|
||||||
private func addHeader(urlRequest: CFHTTPMessage, key: NSString, val: NSString) {
|
private func addHeader(urlRequest: CFHTTPMessage, key: NSString, val: NSString) {
|
||||||
CFHTTPMessageSetHeaderFieldValue(urlRequest, key, val)
|
CFHTTPMessageSetHeaderFieldValue(urlRequest, key, val)
|
||||||
}
|
}
|
||||||
|
|
||||||
//generate a websocket key as needed in rfc
|
/// Generate a WebSocket key as needed in RFC.
|
||||||
private func generateWebSocketKey() -> String {
|
private func generateWebSocketKey() -> String {
|
||||||
var key = ""
|
var key = ""
|
||||||
let seed = 16
|
let seed = 16
|
||||||
@ -271,7 +290,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
return baseKey!
|
return baseKey!
|
||||||
}
|
}
|
||||||
|
|
||||||
//Start the stream connection and write the data to the output stream
|
/// Start the stream connection and write the data to the output stream.
|
||||||
private func initStreamsWithData(data: NSData, _ port: Int) {
|
private func initStreamsWithData(data: NSData, _ port: Int) {
|
||||||
//higher level API we will cut over to at some point
|
//higher level API we will cut over to at some point
|
||||||
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
|
//NSStream.getStreamsToHostWithName(url.host, port: url.port.integerValue, inputStream: &inputStream, outputStream: &outputStream)
|
||||||
@ -285,7 +304,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
guard let inStream = inputStream, let outStream = outputStream else { return }
|
guard let inStream = inputStream, let outStream = outputStream else { return }
|
||||||
inStream.delegate = self
|
inStream.delegate = self
|
||||||
outStream.delegate = self
|
outStream.delegate = self
|
||||||
if ["wss", "https"].contains(url.scheme) {
|
if supportedSSLSchemes.contains(url.scheme) {
|
||||||
inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
inStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||||
outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
outStream.setProperty(NSStreamSocketSecurityLevelNegotiatedSSL, forKey: NSStreamSocketSecurityLevelKey)
|
||||||
} else {
|
} else {
|
||||||
@ -296,7 +315,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
outStream.setProperty(NSStreamNetworkServiceTypeVoIP, forKey: NSStreamNetworkServiceType)
|
||||||
}
|
}
|
||||||
if selfSignedSSL {
|
if selfSignedSSL {
|
||||||
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool:false), kCFStreamSSLPeerName: kCFNull]
|
let settings: [NSObject: NSObject] = [kCFStreamSSLValidatesCertificateChain: NSNumber(bool: false), kCFStreamSSLPeerName: kCFNull]
|
||||||
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
inStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||||
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
outStream.setProperty(settings, forKey: kCFStreamPropertySSLSettings as String)
|
||||||
}
|
}
|
||||||
@ -327,23 +346,24 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
self.mutex.unlock()
|
self.mutex.unlock()
|
||||||
|
|
||||||
let bytes = UnsafePointer<UInt8>(data.bytes)
|
let bytes = UnsafePointer<UInt8>(data.bytes)
|
||||||
var out = timeout * 1000000 //wait 5 seconds before giving up
|
var out = timeout * 1000000 // wait 5 seconds before giving up
|
||||||
writeQueue.addOperationWithBlock { [weak self] in
|
writeQueue.addOperationWithBlock { [weak self] in
|
||||||
while !outStream.hasSpaceAvailable {
|
while !outStream.hasSpaceAvailable {
|
||||||
usleep(100) //wait until the socket is ready
|
usleep(100) // wait until the socket is ready
|
||||||
out -= 100
|
out -= 100
|
||||||
if out < 0 {
|
if out < 0 {
|
||||||
self?.cleanupStream()
|
self?.cleanupStream()
|
||||||
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
|
self?.doDisconnect(self?.errorWithDetail("write wait timed out", code: 2))
|
||||||
return
|
return
|
||||||
} else if outStream.streamError != nil {
|
} else if outStream.streamError != nil {
|
||||||
return //disconnectStream will be called.
|
return // disconnectStream will be called.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
outStream.write(bytes, maxLength: data.length)
|
outStream.write(bytes, maxLength: data.length)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//delegate for the stream methods. Processes incoming bytes
|
|
||||||
|
// Delegate for the stream methods. Processes incoming bytes.
|
||||||
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
|
public func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
|
||||||
|
|
||||||
if let sec = security where !certValidated && [.HasBytesAvailable, .HasSpaceAvailable].contains(eventCode) {
|
if let sec = security where !certValidated && [.HasBytesAvailable, .HasSpaceAvailable].contains(eventCode) {
|
||||||
@ -369,7 +389,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
disconnectStream(nil)
|
disconnectStream(nil)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//disconnect the stream object
|
|
||||||
|
/// Disconnect the stream object and notifies the delegate.
|
||||||
private func disconnectStream(error: NSError?) {
|
private func disconnectStream(error: NSError?) {
|
||||||
if error == nil {
|
if error == nil {
|
||||||
writeQueue.waitUntilAllOperationsAreFinished()
|
writeQueue.waitUntilAllOperationsAreFinished()
|
||||||
@ -395,7 +416,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
inputStream = nil
|
inputStream = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
///handles the incoming bytes and sending them to the proper processing method
|
/// Handles the incoming bytes and sending them to the proper processing method.
|
||||||
private func processInputStream() {
|
private func processInputStream() {
|
||||||
let buf = NSMutableData(capacity: BUFFER_MAX)
|
let buf = NSMutableData(capacity: BUFFER_MAX)
|
||||||
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
||||||
@ -411,7 +432,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
dequeueInput()
|
dequeueInput()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
///dequeue the incoming input so it is processed in order
|
|
||||||
|
/// Dequeue the incoming input so it is processed in order.
|
||||||
private func dequeueInput() {
|
private func dequeueInput() {
|
||||||
while !inputQueue.isEmpty {
|
while !inputQueue.isEmpty {
|
||||||
let data = inputQueue[0]
|
let data = inputQueue[0]
|
||||||
@ -429,18 +451,18 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
} else {
|
} else {
|
||||||
processRawMessagesInBuffer(buffer, bufferLen: length)
|
processRawMessagesInBuffer(buffer, bufferLen: length)
|
||||||
}
|
}
|
||||||
inputQueue = inputQueue.filter{$0 != data}
|
inputQueue = inputQueue.filter{ $0 != data }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//handle checking the inital connection status
|
// Handle checking the initial connection status.
|
||||||
private func processTCPHandshake(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
private func processTCPHandshake(buffer: UnsafePointer<UInt8>, bufferLen: Int) {
|
||||||
let code = processHTTP(buffer, bufferLen: bufferLen)
|
let code = processHTTP(buffer, bufferLen: bufferLen)
|
||||||
switch code {
|
switch code {
|
||||||
case 0:
|
case 0:
|
||||||
connected = true
|
connected = true
|
||||||
guard canDispatch else {return}
|
guard canDispatch else {return}
|
||||||
dispatch_async(queue) { [weak self] in
|
dispatch_async(callbackQueue) { [weak self] in
|
||||||
guard let s = self else { return }
|
guard let s = self else { return }
|
||||||
s.onConnect?()
|
s.onConnect?()
|
||||||
s.delegate?.websocketDidConnect(s)
|
s.delegate?.websocketDidConnect(s)
|
||||||
@ -448,12 +470,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
case -1:
|
case -1:
|
||||||
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
fragBuffer = NSData(bytes: buffer, length: bufferLen)
|
||||||
break //do nothing, we are going to collect more data
|
break // do nothing, we are going to collect more data
|
||||||
default:
|
default:
|
||||||
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
|
doDisconnect(errorWithDetail("Invalid HTTP upgrade", code: UInt16(code)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
///Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
|
|
||||||
|
/// Finds the HTTP Packet in the TCP stream, by looking for the CRLF.
|
||||||
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
|
private func processHTTP(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
|
||||||
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
|
let CRLFBytes = [UInt8(ascii: "\r"), UInt8(ascii: "\n"), UInt8(ascii: "\r"), UInt8(ascii: "\n")]
|
||||||
var k = 0
|
var k = 0
|
||||||
@ -481,15 +504,15 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
return 0 //success
|
return 0 //success
|
||||||
}
|
}
|
||||||
return -1 //was unable to find the full TCP header
|
return -1 // Was unable to find the full TCP header.
|
||||||
}
|
}
|
||||||
|
|
||||||
///validates the HTTP is a 101 as per the RFC spec
|
/// Validates the HTTP is a 101 as per the RFC spec.
|
||||||
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
|
private func validateResponse(buffer: UnsafePointer<UInt8>, bufferLen: Int) -> Int {
|
||||||
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
|
let response = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, false).takeRetainedValue()
|
||||||
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
|
CFHTTPMessageAppendBytes(response, buffer, bufferLen)
|
||||||
let code = CFHTTPMessageGetResponseStatusCode(response)
|
let code = CFHTTPMessageGetResponseStatusCode(response)
|
||||||
if code != 101 {
|
if code != httpSwitchProtocolCode {
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
|
if let cfHeaders = CFHTTPMessageCopyAllHeaderFields(response) {
|
||||||
@ -503,12 +526,12 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
return -1
|
return -1
|
||||||
}
|
}
|
||||||
|
|
||||||
///read a 16 bit big endian value from a buffer
|
///read a 16-bit big endian value from a buffer
|
||||||
private static func readUint16(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
|
private static func readUint16(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt16 {
|
||||||
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
|
return (UInt16(buffer[offset + 0]) << 8) | UInt16(buffer[offset + 1])
|
||||||
}
|
}
|
||||||
|
|
||||||
///read a 64 bit big endian value from a buffer
|
///read a 64-bit big endian value from a buffer
|
||||||
private static func readUint64(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
|
private static func readUint64(buffer: UnsafePointer<UInt8>, offset: Int) -> UInt64 {
|
||||||
var value = UInt64(0)
|
var value = UInt64(0)
|
||||||
for i in 0...7 {
|
for i in 0...7 {
|
||||||
@ -517,13 +540,13 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
///write a 16 bit big endian value to a buffer
|
/// Write a 16-bit big endian value to a buffer.
|
||||||
private static func writeUint16(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
|
private static func writeUint16(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt16) {
|
||||||
buffer[offset + 0] = UInt8(value >> 8)
|
buffer[offset + 0] = UInt8(value >> 8)
|
||||||
buffer[offset + 1] = UInt8(value & 0xff)
|
buffer[offset + 1] = UInt8(value & 0xff)
|
||||||
}
|
}
|
||||||
|
|
||||||
///write a 64 bit big endian value to a buffer
|
/// Write a 64-bit big endian value to a buffer.
|
||||||
private static func writeUint64(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
|
private static func writeUint64(buffer: UnsafeMutablePointer<UInt8>, offset: Int, value: UInt64) {
|
||||||
for i in 0...7 {
|
for i in 0...7 {
|
||||||
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
|
buffer[offset + i] = UInt8((value >> (8*UInt64(7 - i))) & 0xff)
|
||||||
@ -588,17 +611,19 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
offset += 2
|
offset += 2
|
||||||
}
|
}
|
||||||
|
var closeReason = "connection closed by server"
|
||||||
if payloadLen > 2 {
|
if payloadLen > 2 {
|
||||||
let len = Int(payloadLen-2)
|
let len = Int(payloadLen - 2)
|
||||||
if len > 0 {
|
if len > 0 {
|
||||||
let bytes = baseAddress + offset
|
let bytes = baseAddress + offset
|
||||||
let str: NSString? = NSString(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding)
|
if let customCloseReason = String(data: NSData(bytes: bytes, length: len), encoding: NSUTF8StringEncoding) {
|
||||||
if str == nil {
|
closeReason = customCloseReason
|
||||||
|
} else {
|
||||||
code = CloseCode.ProtocolError.rawValue
|
code = CloseCode.ProtocolError.rawValue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
doDisconnect(errorWithDetail("connection closed by server", code: code))
|
doDisconnect(errorWithDetail(closeReason, code: code))
|
||||||
writeError(code)
|
writeError(code)
|
||||||
return emptyBuffer
|
return emptyBuffer
|
||||||
}
|
}
|
||||||
@ -631,7 +656,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
if receivedOpcode == .Pong {
|
if receivedOpcode == .Pong {
|
||||||
if canDispatch {
|
if canDispatch {
|
||||||
dispatch_async(queue) { [weak self] in
|
dispatch_async(callbackQueue) { [weak self] in
|
||||||
guard let s = self else { return }
|
guard let s = self else { return }
|
||||||
s.onPong?()
|
s.onPong?()
|
||||||
s.pongDelegate?.websocketDidReceivePong(s)
|
s.pongDelegate?.websocketDidReceivePong(s)
|
||||||
@ -641,7 +666,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
var response = readStack.last
|
var response = readStack.last
|
||||||
if isControlFrame {
|
if isControlFrame {
|
||||||
response = nil //don't append pings
|
response = nil // Don't append pings.
|
||||||
}
|
}
|
||||||
if isFin == 0 && receivedOpcode == .ContinueFrame && response == nil {
|
if isFin == 0 && receivedOpcode == .ContinueFrame && response == nil {
|
||||||
let errCode = CloseCode.ProtocolError.rawValue
|
let errCode = CloseCode.ProtocolError.rawValue
|
||||||
@ -685,7 +710,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
processResponse(response)
|
processResponse(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
let step = Int(offset+numericCast(len))
|
let step = Int(offset + numericCast(len))
|
||||||
return buffer.fromOffset(step)
|
return buffer.fromOffset(step)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -701,11 +726,11 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
///process the finished response of a buffer
|
/// Process the finished response of a buffer.
|
||||||
private func processResponse(response: WSResponse) -> Bool {
|
private func processResponse(response: WSResponse) -> Bool {
|
||||||
if response.isFin && response.bytesLeft <= 0 {
|
if response.isFin && response.bytesLeft <= 0 {
|
||||||
if response.code == .Ping {
|
if response.code == .Ping {
|
||||||
let data = response.buffer! //local copy so it is perverse for writing
|
let data = response.buffer! // local copy so it's not perverse for writing
|
||||||
dequeueWrite(data, code: OpCode.Pong)
|
dequeueWrite(data, code: OpCode.Pong)
|
||||||
} else if response.code == .TextFrame {
|
} else if response.code == .TextFrame {
|
||||||
let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
|
let str: NSString? = NSString(data: response.buffer!, encoding: NSUTF8StringEncoding)
|
||||||
@ -714,7 +739,7 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if canDispatch {
|
if canDispatch {
|
||||||
dispatch_async(queue) { [weak self] in
|
dispatch_async(callbackQueue) { [weak self] in
|
||||||
guard let s = self else { return }
|
guard let s = self else { return }
|
||||||
s.onText?(str! as String)
|
s.onText?(str! as String)
|
||||||
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
|
s.delegate?.websocketDidReceiveMessage(s, text: str! as String)
|
||||||
@ -722,8 +747,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
} else if response.code == .BinaryFrame {
|
} else if response.code == .BinaryFrame {
|
||||||
if canDispatch {
|
if canDispatch {
|
||||||
let data = response.buffer! //local copy so it is perverse for writing
|
let data = response.buffer! //local copy so it's not perverse for writing
|
||||||
dispatch_async(queue) { [weak self] in
|
dispatch_async(callbackQueue) { [weak self] in
|
||||||
guard let s = self else { return }
|
guard let s = self else { return }
|
||||||
s.onData?(data)
|
s.onData?(data)
|
||||||
s.delegate?.websocketDidReceiveData(s, data: data)
|
s.delegate?.websocketDidReceiveData(s, data: data)
|
||||||
@ -736,21 +761,22 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
///Create an error
|
/// Create an error.
|
||||||
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
|
private func errorWithDetail(detail: String, code: UInt16) -> NSError {
|
||||||
var details = [String: String]()
|
var details = [String: String]()
|
||||||
details[NSLocalizedDescriptionKey] = detail
|
details[NSLocalizedDescriptionKey] = detail
|
||||||
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details)
|
return NSError(domain: WebSocket.ErrorDomain, code: Int(code), userInfo: details)
|
||||||
}
|
}
|
||||||
|
|
||||||
///write a an error to the socket
|
/// Write a an error to the socket.
|
||||||
private func writeError(code: UInt16) {
|
private func writeError(code: UInt16) {
|
||||||
let buf = NSMutableData(capacity: sizeof(UInt16))
|
let buf = NSMutableData(capacity: sizeof(UInt16))
|
||||||
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
let buffer = UnsafeMutablePointer<UInt8>(buf!.bytes)
|
||||||
WebSocket.writeUint16(buffer, offset: 0, value: code)
|
WebSocket.writeUint16(buffer, offset: 0, value: code)
|
||||||
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
|
dequeueWrite(NSData(bytes: buffer, length: sizeof(UInt16)), code: .ConnectionClose)
|
||||||
}
|
}
|
||||||
///used to write things to the stream
|
|
||||||
|
/// Used to write things to the stream.
|
||||||
private func dequeueWrite(data: NSData, code: OpCode, writeCompletion: (() -> ())? = nil) {
|
private func dequeueWrite(data: NSData, code: OpCode, writeCompletion: (() -> ())? = nil) {
|
||||||
writeQueue.addOperationWithBlock { [weak self] in
|
writeQueue.addOperationWithBlock { [weak self] in
|
||||||
//stream isn't ready, let's wait
|
//stream isn't ready, let's wait
|
||||||
@ -800,8 +826,8 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
total += len
|
total += len
|
||||||
}
|
}
|
||||||
if total >= offset {
|
if total >= offset {
|
||||||
if let queue = self?.queue, callback = writeCompletion {
|
if let callbackQueue = self?.callbackQueue, callback = writeCompletion {
|
||||||
dispatch_async(queue) {
|
dispatch_async(callbackQueue) {
|
||||||
callback()
|
callback()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -813,21 +839,23 @@ public class WebSocket : NSObject, NSStreamDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
///used to preform the disconnect delegate
|
/// Used to preform the disconnect delegate.
|
||||||
private func doDisconnect(error: NSError?) {
|
private func doDisconnect(error: NSError?) {
|
||||||
guard !didDisconnect else { return }
|
guard !didDisconnect else { return }
|
||||||
didDisconnect = true
|
didDisconnect = true
|
||||||
connected = false
|
connected = false
|
||||||
guard canDispatch else {return}
|
guard canDispatch else {return}
|
||||||
dispatch_async(queue) { [weak self] in
|
dispatch_async(callbackQueue) { [weak self] in
|
||||||
guard let s = self else { return }
|
guard let s = self else { return }
|
||||||
s.onDisconnect?(error)
|
s.onDisconnect?(error)
|
||||||
s.delegate?.websocketDidDisconnect(s, error: error)
|
s.delegate?.websocketDidDisconnect(s, error: error)
|
||||||
let userInfo = error.map({ [WebsocketDisconnectionErrorKeyName: $0] })
|
let userInfo = error.map{ [WebsocketDisconnectionErrorKeyName: $0] }
|
||||||
s.notificationCenter.postNotificationName(WebsocketDidDisconnectNotification, object: self, userInfo: userInfo)
|
s.notificationCenter.postNotificationName(WebsocketDidDisconnectNotification, object: self, userInfo: userInfo)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Deinit
|
||||||
|
|
||||||
deinit {
|
deinit {
|
||||||
mutex.lock()
|
mutex.lock()
|
||||||
readyToWrite = false
|
readyToWrite = false
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user