0001    // Socket.swift
0002    //
0003    // The MIT License (MIT)
0004    //
0005    // Copyright (c) 2015 Zewo
0006    //
0007    // Permission is hereby granted, free of charge, to any person obtaining a copy
0008    // of this software and associated documentation files (the "Software"), to deal
0009    // in the Software without restriction, including without limitation the rights
0010    // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
0011    // copies of the Software, and to permit persons to whom the Software is
0012    // furnished to do so, subject to the following conditions:
0013    //
0014    // The above copyright notice and this permission notice shall be included in all
0015    // copies or substantial portions of the Software.
0016    //
0017    // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
0018    // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
0019    // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
0020    // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
0021    // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
0022    // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
0023    // SOFTWARE.
0024    
0025    @_exported import Event
0026    @_exported import Base64
0027    @_exported import OpenSSL
0028    
0029    internal extension Data {
0030    	init<T>(number: T) {
0031    		var totalBytes = sizeof(T)
0032    		let valuePointer = UnsafeMutablePointer<T>.alloc(1)
0033    		valuePointer.memory = number
0034    		let bytesPointer = UnsafeMutablePointer<Byte>(valuePointer)
0035    		var bytes = [UInt8](count: totalBytes, repeatedValue: 0)
0036    		let size = sizeof(UInt16)
0037    		if totalBytes > size { totalBytes = size }
0038    		for j in 0 ..< totalBytes {
0039    			bytes[totalBytes - 1 - j] = (bytesPointer + j).memory
0040    		}
0041    		valuePointer.destroy()
0042    		valuePointer.dealloc(1)
0043    		self.init(bytes: bytes)
0044    	}
0045    	
0046    	func toInt(size size: Int, offset: Int = 0) -> UIntMax {
0047    		guard size > 0 && size <= 8 && count >= offset+size else { return 0 }
0048    		let slice = self[startIndex.advancedBy(offset) ..< startIndex.advancedBy(offset+size)]
0049    		var result: UIntMax = 0
0050    		for (idx, byte) in slice.enumerate() {
0051    			let shiftAmount = UIntMax(size.toIntMax() - idx - 1) * 8
0052    			result += UIntMax(byte) << shiftAmount
0053    		}
0054    		return result
0055    	}
0056    }
0057    
0058    public class Socket
Client__.swift:38
    private let onConnect: Socket throws -> Void
Client__.swift:40
	public init(ssl: Bool, host: String, port: Int, onConnect: Socket throws -> Void) throws {
Server.swift:33
	private let onConnect: Socket throws -> Void
Server.swift:35
	public init(onConnect: Socket throws -> Void) {
Server.swift:46
		guard let accept = Socket.accept(key) else {
{ 0059 0060 public enum Error
Socket.swift:234
                throw try fail(Error.SmallData)
Socket.swift:243
                throw try fail(Error.InvalidOpCode)
Socket.swift:249
                throw try fail(Error.MaskedFrameFromServer)
Socket.swift:253
                throw try fail(Error.UnaskedFrameFromClient)
Socket.swift:267
                    throw try fail(Error.ControlFrameNotFinal)
Socket.swift:271
                    throw try fail(Error.ControlFrameWithReservedBits)
Socket.swift:275
                    throw try fail(Error.ControlFrameInvalidLength)
Socket.swift:279
                    throw try fail(Error.ContinuationOutOfOrder)
Socket.swift:283
                    throw try fail(Error.ContinuationOutOfOrder)
Socket.swift:289
                    throw try fail(Error.DataFrameWithInvalidBits)
Socket.swift:346
                    throw try fail(Error.MaskKeyInvalidLength)
Socket.swift:372
                    throw try fail(Error.NoMaskKey)
Socket.swift:403
            throw Error.NoFrame
: ErrorType { 0061 case NoFrame
Socket.swift:403
            throw Error.NoFrame
0062 case SmallData
Socket.swift:234
                throw try fail(Error.SmallData)
0063 case InvalidOpCode
Socket.swift:243
                throw try fail(Error.InvalidOpCode)
0064 case MaskedFrameFromServer
Socket.swift:249
                throw try fail(Error.MaskedFrameFromServer)
0065 case UnaskedFrameFromClient
Socket.swift:253
                throw try fail(Error.UnaskedFrameFromClient)
0066 case ControlFrameNotFinal
Socket.swift:267
                    throw try fail(Error.ControlFrameNotFinal)
0067 case ControlFrameWithReservedBits
Socket.swift:271
                    throw try fail(Error.ControlFrameWithReservedBits)
0068 case ControlFrameInvalidLength
Socket.swift:275
                    throw try fail(Error.ControlFrameInvalidLength)
0069 case ContinuationOutOfOrder
Socket.swift:279
                    throw try fail(Error.ContinuationOutOfOrder)
Socket.swift:283
                    throw try fail(Error.ContinuationOutOfOrder)
0070 case DataFrameWithInvalidBits
Socket.swift:289
                    throw try fail(Error.DataFrameWithInvalidBits)
0071 case MaskKeyInvalidLength
Socket.swift:346
                    throw try fail(Error.MaskKeyInvalidLength)
0072 case NoMaskKey
Socket.swift:372
                    throw try fail(Error.NoMaskKey)
0073 } 0074 0075 private static let GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" 0076 0077 public enum Mode
Socket.swift:94
	public let mode: Mode
Socket.swift:111
	init(stream: StreamType, mode: Mode, request: Request, response: Response) {
{ 0078 case Server
Socket.swift:370
			if self.mode == .Server {
0079 case Client
Socket.swift:461
		if mode == .Client {
0080 } 0081 0082 private enum State
Socket.swift:98
	private var state: State = .Header
{ 0083 case Header
Socket.swift:98
	private var state: State = .Header
Socket.swift:232
		case .Header:
Socket.swift:320
				state = .Header
Socket.swift:355
				state = .Header
Socket.swift:391
				state = .Header
0084 case HeaderExtra
Socket.swift:316
				state = .HeaderExtra
Socket.swift:325
		case .HeaderExtra:
0085 case Payload
Socket.swift:318
				state = .Payload
Socket.swift:353
				state = .Payload
Socket.swift:362
		case .Payload:
0086 } 0087 0088 private enum CloseState
Socket.swift:99
	private var closeState: CloseState = .Open
{ 0089 case Open
Socket.swift:99
	private var closeState: CloseState = .Open
Socket.swift:155
        if closeState == .Open {
Socket.swift:197
		if closeState == .Open {
Socket.swift:426
			if self.closeState == .Open {
0090 case ServerClose
Socket.swift:151
        if closeState == .ServerClose {
Socket.swift:156
            closeState = .ServerClose
Socket.swift:451
			} else if self.closeState == .ServerClose {
0091 case ClientClose
Socket.swift:167
        if closeState == .ClientClose {
Socket.swift:440
				closeState = .ClientClose
0092 } 0093 0094 public let mode
Socket.swift:370
			if self.mode == .Server {
Socket.swift:461
		if mode == .Client {
: Mode 0095 public let request: Request 0096 public let response: Response 0097 private let stream: StreamType 0098 private var state
Socket.swift:231
		switch state {
Socket.swift:316
				state = .HeaderExtra
Socket.swift:318
				state = .Payload
Socket.swift:320
				state = .Header
Socket.swift:353
				state = .Payload
Socket.swift:355
				state = .Header
Socket.swift:391
				state = .Header
: State = .Header 0099 private var closeState
Socket.swift:151
        if closeState == .ServerClose {
Socket.swift:155
        if closeState == .Open {
Socket.swift:156
            closeState = .ServerClose
Socket.swift:167
        if closeState == .ClientClose {
Socket.swift:197
		if closeState == .Open {
Socket.swift:426
			if self.closeState == .Open {
Socket.swift:440
				closeState = .ClientClose
Socket.swift:451
			} else if self.closeState == .ServerClose {
: CloseState = .Open 0100 0101 private var initialFrame
Socket.swift:296
				initialFrame = frames.last
Socket.swift:414
		self.initialFrame = nil
: Frame? 0102 private var frames
Socket.swift:296
				initialFrame = frames.last
Socket.swift:326
			guard var frame = frames.last where data.count >= frame.headerExtraLength else {
Socket.swift:359
			frames[frames.endIndex.predecessor()] = frame
Socket.swift:359
			frames[frames.endIndex.predecessor()] = frame
Socket.swift:363
			guard var frame = frames.last where data.count > 0 else {
Socket.swift:395
			frames[frames.endIndex.predecessor()] = frame
Socket.swift:395
			frames[frames.endIndex.predecessor()] = frame
Socket.swift:402
		guard let frame = frames.last else {
Socket.swift:412
		self.frames.removeAll()
: [Frame] = [] 0103 private var buffer: Data = [] 0104 0105 private let binaryEventEmitter = EventEmitter<Data>() 0106 private let textEventEmitter = EventEmitter<String>() 0107 private let pingEventEmitter = EventEmitter<Data>() 0108 private let pongEventEmitter = EventEmitter<Data>() 0109 private let closeEventEmitter = EventEmitter<(code: CloseCode?, reason: String?)>() 0110 0111 init(stream: StreamType, mode: Mode, request: Request, response: Response) { 0112 self.stream = stream 0113 self.mode = mode 0114 self.request = request 0115 self.response = response 0116 } 0117 0118 public func onBinary(listen: EventListener<Data>.Listen) -> EventListener<Data> { 0119 return binaryEventEmitter.addListener(listen: listen) 0120 } 0121 0122 public func onText(listen: EventListener<String>.Listen) -> EventListener<String> { 0123 return textEventEmitter.addListener(listen: listen) 0124 } 0125 0126 public func onPing(listen: EventListener<Data>.Listen) -> EventListener<Data> { 0127 return pingEventEmitter.addListener(listen: listen) 0128 } 0129 0130 public func onPong(listen: EventListener<Data>.Listen) -> EventListener<Data> { 0131 return pongEventEmitter.addListener(listen: listen) 0132 } 0133 0134 public func onClose(listen: EventListener<(code: CloseCode?, reason: String?)>.Listen) -> EventListener<(code: CloseCode?, reason: String?)> { 0135 return closeEventEmitter.addListener(listen: listen) 0136 } 0137 0138 public func send(string: String) throws { 0139 try send(.Text, data: string.data) 0140 } 0141 0142 public func send
Socket.swift:146
    public func send(convertible: DataConvertible) throws {
(data: Data) throws { 0143 try send(.Binary, data: data) 0144 } 0145 0146 public func send(convertible: DataConvertible) throws { 0147 try send(.Binary, data: convertible.data) 0148 } 0149 0150 public func close
Socket.swift:227
			try close(.ProtocolError)
Socket.swift:449
				try close(closeCode ?? .Normal, reason: closeReason)
(code: CloseCode = .Normal, reason: String? = nil) throws { 0151 if closeState == .ServerClose { 0152 return 0153 } 0154 0155 if closeState == .Open { 0156 closeState = .ServerClose 0157 } 0158 0159 var data = Data(number: code.code) 0160 0161 if let reason = reason { 0162 data += reason 0163 } 0164 0165 try send(.Close, data: data) 0166 0167 if closeState == .ClientClose { 0168 stream.close() 0169 } 0170 } 0171 0172 public func ping
Socket.swift:176
    public func ping(convertible: DataConvertible) throws {
(data: Data = []) throws { 0173 try send(.Ping, data: data) 0174 } 0175 0176 public func ping(convertible: DataConvertible) throws { 0177 try send(.Ping, data: convertible.data) 0178 } 0179 0180 public func pong
Socket.swift:184
    public func pong(convertible: DataConvertible) throws {
(data: Data = []) throws { 0181 try send(.Pong, data: data) 0182 } 0183 0184 public func pong(convertible: DataConvertible) throws { 0185 try send(.Pong, data: convertible.data) 0186 } 0187 0188 func loop() throws { 0189 while !stream.closed { 0190 do { 0191 let data = try stream.receive() 0192 try processData(data) 0193 } catch StreamError.ClosedStream { 0194 break 0195 } 0196 } 0197 if closeState == .Open { 0198 try closeEventEmitter.emit((code: .Abnormal, reason: nil)) 0199 } 0200 } 0201 0202 private func processData(data: Data) throws { 0203 guard data.count > 0 else { 0204 return 0205 } 0206 0207 var totalBytesRead = 0 0208 0209 while totalBytesRead < data.count { 0210 let bytesRead = try readBytes(data[totalBytesRead ..< data.count]) 0211 0212 if bytesRead == 0 { 0213 break 0214 } 0215 0216 totalBytesRead += bytesRead 0217 } 0218 } 0219 0220 private func readBytes(data: Data) throws -> Int { 0221 0222 if data.count == 0 { 0223 return 0 0224 } 0225 0226 func fail(error: ErrorType) throws -> ErrorType { 0227 try close(.ProtocolError) 0228 return error 0229 } 0230 0231 switch state { 0232 case .Header: 0233 guard data.count >= 2 else { 0234 throw try fail(Error.SmallData) 0235 } 0236 0237 let fin = data[0] & Frame.FinMask != 0 0238 let rsv1 = data[0] & Frame.Rsv1Mask != 0 0239 let rsv2 = data[0] & Frame.Rsv2Mask != 0 0240 let rsv3 = data[0] & Frame.Rsv3Mask != 0 0241 0242 guard let opCode = Frame.OpCode(rawValue: data[0] & Frame.OpCodeMask) else { 0243 throw try fail(Error.InvalidOpCode) 0244 } 0245 0246 let masked = data[1] & Frame.MaskMask != 0 0247 0248 guard !masked || self.mode == .Server else { 0249 throw try fail(Error.MaskedFrameFromServer) 0250 } 0251 0252 guard masked || self.mode == .Client else { 0253 throw try fail(Error.UnaskedFrameFromClient) 0254 } 0255 0256 let payloadLength = data[1] & Frame.PayloadLenMask 0257 var headerExtraLength = masked ? sizeof(UInt32) : 0 0258 0259 if payloadLength == 126 { 0260 headerExtraLength += sizeof(UInt16) 0261 } else if payloadLength == 127 { 0262 headerExtraLength += sizeof(UInt64) 0263 } 0264 0265 if opCode.isControl { 0266 guard fin else { 0267 throw try fail(Error.ControlFrameNotFinal) 0268 } 0269 0270 guard !rsv1 && !rsv2 && !rsv3 else { 0271 throw try fail(Error.ControlFrameWithReservedBits) 0272 } 0273 0274 guard payloadLength < 126 else { 0275 throw try fail(Error.ControlFrameInvalidLength) 0276 } 0277 } else { 0278 guard opCode != .Continuation || frames.count != 0 else { 0279 throw try fail(Error.ContinuationOutOfOrder) 0280 } 0281 0282 guard opCode == .Continuation || frames.count == 0 else { 0283 throw try fail(Error.ContinuationOutOfOrder) 0284 } 0285 0286 // guard !rsv1 || pmdEnabled else { return fail("Data frames must only use rsv1 bit if permessage-deflate extension is on") } 0287 0288 guard !rsv2 && !rsv3 else { 0289 throw try fail(Error.DataFrameWithInvalidBits) 0290 } 0291 } 0292 0293 var _opCode = opCode 0294 0295 if !opCode.isControl && frames.count > 0 { 0296 initialFrame = frames.last 0297 _opCode = initialFrame!.opCode 0298 } else { 0299 buffer = [] 0300 } 0301 0302 let frame = Frame( 0303 fin: fin, 0304 rsv1: rsv1, 0305 rsv2: rsv2, 0306 rsv3: rsv3, 0307 opCode: _opCode, 0308 masked: masked, 0309 payloadLength: UInt64(payloadLength), 0310 headerExtraLength: headerExtraLength 0311 ) 0312 0313 frames.append(frame) 0314 0315 if headerExtraLength > 0 { 0316 state = .HeaderExtra 0317 } else if payloadLength > 0 { 0318 state = .Payload 0319 } else { 0320 state = .Header 0321 try processFrames() 0322 } 0323 0324 return 2 0325 case .HeaderExtra: 0326 guard var frame = frames.last where data.count >= frame.headerExtraLength else { 0327 return 0 0328 } 0329 0330 var payloadLength = UIntMax(frame.payloadLength) 0331 0332 if payloadLength == 126 { 0333 payloadLength = data.toInt(size: 2) 0334 } else if payloadLength == 127 { 0335 payloadLength = data.toInt(size: 8) 0336 } 0337 0338 frame.payloadLength = payloadLength 0339 frame.payloadRemainingLength = payloadLength 0340 0341 if frame.masked { 0342 let maskOffset = max(Int(frame.headerExtraLength) - 4, 0) 0343 let maskKey = Data(data[maskOffset ..< maskOffset+4]) 0344 0345 guard maskKey.count == 4 else { 0346 throw try fail(Error.MaskKeyInvalidLength) 0347 } 0348 0349 frame.maskKey = maskKey 0350 } 0351 0352 if frame.payloadLength > 0 { 0353 state = .Payload 0354 } else { 0355 state = .Header 0356 try processFrames() 0357 } 0358 0359 frames[frames.endIndex.predecessor()] = frame 0360 0361 return frame.headerExtraLength 0362 case .Payload: 0363 guard var frame = frames.last where data.count > 0 else { 0364 return 0 0365 } 0366 0367 let consumeLength = min(frame.payloadRemainingLength, UInt64(data.count)) 0368 var _data: Data 0369 0370 if self.mode == .Server { 0371 guard frame.maskKey != nil else { 0372 throw try fail(Error.NoMaskKey) 0373 } 0374 0375 _data = [] 0376 0377 for byte in data[0..<Int(consumeLength)] { 0378 _data.appendByte(byte ^ frame.maskKey[frame.maskOffset % 4]) 0379 frame.maskOffset += 1 0380 } 0381 } else { 0382 _data = data[0..<Int(consumeLength)] 0383 } 0384 0385 buffer += _data 0386 0387 let newPayloadRemainingLength = frame.payloadRemainingLength - consumeLength 0388 frame.payloadRemainingLength = newPayloadRemainingLength 0389 0390 if newPayloadRemainingLength == 0 { 0391 state = .Header 0392 try processFrames() 0393 } 0394 0395 frames[frames.endIndex.predecessor()] = frame 0396 0397 return Int(consumeLength) 0398 } 0399 } 0400 0401 private func processFrames
Socket.swift:321
				try processFrames()
Socket.swift:356
				try processFrames()
Socket.swift:392
				try processFrames()
() throws { 0402 guard let frame = frames.last else { 0403 throw Error.NoFrame 0404 } 0405 0406 guard frame.fin else { 0407 return 0408 } 0409 0410 let buffer = self.buffer 0411 0412 self.frames.removeAll() 0413 self.buffer.removeAllBytes() 0414 self.initialFrame = nil 0415 0416 switch frame.opCode { 0417 case .Binary: 0418 try binaryEventEmitter.emit(buffer) 0419 case .Text: 0420 try textEventEmitter.emit(try String(data: buffer)) 0421 case .Ping: 0422 try pingEventEmitter.emit(buffer) 0423 case .Pong: 0424 try pongEventEmitter.emit(buffer) 0425 case .Close: 0426 if self.closeState == .Open { 0427 var rawCloseCode: Int? 0428 var closeReason: String? 0429 var data = buffer 0430 0431 if data.count >= 2 { 0432 rawCloseCode = Int(UInt16(data.prefix(2).toInt(size: 2))) 0433 data.removeFirst(2) 0434 0435 if data.count > 0 { 0436 closeReason = try String(data: data) 0437 } 0438 } 0439 0440 closeState = .ClientClose 0441 0442 let closeCode: CloseCode? 0443 if let rawCloseCode = rawCloseCode { 0444 closeCode = CloseCode(code: rawCloseCode) 0445 } else { 0446 closeCode = nil 0447 } 0448 0449 try close(closeCode ?? .Normal, reason: closeReason) 0450 try closeEventEmitter.emit((closeCode, closeReason)) 0451 } else if self.closeState == .ServerClose { 0452 stream.close() 0453 } 0454 case .Continuation: 0455 return 0456 } 0457 } 0458 0459 private func send(opCode: Frame.OpCode, data: Data) throws { 0460 let maskKey: Data 0461 if mode == .Client { 0462 maskKey = try Random.getBytes(4) 0463 } else { 0464 maskKey = nil 0465 } 0466 let frame = Frame(opCode: opCode, data: data, maskKey: maskKey) 0467 let data = frame.getData() 0468 try stream.send(data) 0469 try stream.flush() 0470 } 0471 0472 static func accept(key: String) -> String? { 0473 return try? Base64.encode(Hash.hash(.SHA1, message: (key + GUID).data)) 0474 } 0475 0476 } 0477