|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the SwiftNIO open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | + |
| 16 | +import NIO |
| 17 | +import NIOHTTP1 |
| 18 | +import NIOWebSocket |
| 19 | +import NIOTransportServices |
| 20 | +import Network |
| 21 | +import Foundation |
| 22 | + |
| 23 | +final class WebSocketTimeHandler: ChannelInboundHandler { |
| 24 | + |
| 25 | + private var ws: SwiftWS.WebSocket |
| 26 | + |
| 27 | + init(_ ws: SwiftWS.WebSocket){ |
| 28 | + self.ws = ws |
| 29 | + } |
| 30 | + |
| 31 | + typealias InboundIn = WebSocketFrame |
| 32 | + typealias OutboundOut = WebSocketFrame |
| 33 | + |
| 34 | + private var awaitingClose: Bool = false |
| 35 | + |
| 36 | + public func handlerAdded(context: ChannelHandlerContext) { |
| 37 | + self.checkForMessage(context: context) |
| 38 | + } |
| 39 | + |
| 40 | + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { |
| 41 | + let frame = self.unwrapInboundIn(data) |
| 42 | + |
| 43 | + switch frame.opcode { |
| 44 | + case .connectionClose: |
| 45 | + ws.onCloseAction?(.init(wasClean: true, code: 0, reason: "Close event received", target: ws)) |
| 46 | + self.receivedClose(context: context, frame: frame) |
| 47 | + case .ping: |
| 48 | + self.pong(context: context, frame: frame) |
| 49 | + case .text: |
| 50 | + var data = frame.unmaskedData |
| 51 | + let text = data.readString(length: data.readableBytes) ?? "" |
| 52 | + ws.onMessageAction?(.init(data: text, type: "", target: ws)) |
| 53 | + case .binary, .continuation, .pong: |
| 54 | + // We ignore these frames. |
| 55 | + break |
| 56 | + default: |
| 57 | + // Unknown frames are errors. |
| 58 | + ws.onCloseAction?(.init(wasClean: false, code: 0, reason: "Unknown frames errors", target: ws)) |
| 59 | + self.closeOnError(context: context) |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + public func channelReadComplete(context: ChannelHandlerContext) { |
| 64 | + context.flush() |
| 65 | + } |
| 66 | + |
| 67 | + private func checkForMessage(context: ChannelHandlerContext) { |
| 68 | + guard context.channel.isActive else { return } |
| 69 | + |
| 70 | + // We can't send if we sent a close message. |
| 71 | + guard !self.awaitingClose else { return } |
| 72 | + |
| 73 | + if ws.isClosing { |
| 74 | + var buffer = context.channel.allocator.buffer(capacity: 2) |
| 75 | + buffer.writeInteger(UInt16(ws.closeCode)) |
| 76 | + buffer.writeString(ws.closeReason) |
| 77 | + let closeFrame = WebSocketFrame(fin: true, opcode: .connectionClose, data: buffer) |
| 78 | + _ = context.writeAndFlush(self.wrapOutboundOut(closeFrame)) |
| 79 | + awaitingClose = true |
| 80 | + return |
| 81 | + } |
| 82 | + // We can't really check for error here, but it's also not the purpose of the |
| 83 | + // example so let's not worry about it. |
| 84 | + if !ws.messageStack.isEmpty{ |
| 85 | + for message in ws.messageStack { |
| 86 | + let buffer = context.channel.allocator.buffer(string: message) |
| 87 | + let frame = WebSocketFrame(fin: true, opcode: .text, data: buffer) |
| 88 | + context.write(self.wrapOutboundOut(frame)) |
| 89 | + .whenFailure { (_: Error) in |
| 90 | + context.close(promise: nil) |
| 91 | + } |
| 92 | + } |
| 93 | + ws.messageStack.removeAll() |
| 94 | + context.flush() |
| 95 | + } |
| 96 | + |
| 97 | + context.eventLoop.scheduleTask(in: .milliseconds(100), { self.checkForMessage(context: context) }) |
| 98 | + } |
| 99 | + |
| 100 | + private func receivedClose(context: ChannelHandlerContext, frame: WebSocketFrame) { |
| 101 | + // Handle a received close frame. In websockets, we're just going to send the close |
| 102 | + // frame and then close, unless we already sent our own close frame. |
| 103 | + if awaitingClose { |
| 104 | + // Cool, we started the close and were waiting for the user. We're done. |
| 105 | + context.close(promise: nil) |
| 106 | + } else { |
| 107 | + // This is an unsolicited close. We're going to send a response frame and |
| 108 | + // then, when we've sent it, close up shop. We should send back the close code the remote |
| 109 | + // peer sent us, unless they didn't send one at all. |
| 110 | + var data = frame.unmaskedData |
| 111 | + let closeDataCode = data.readSlice(length: 2) ?? ByteBuffer() |
| 112 | + let closeFrame = WebSocketFrame(fin: true, opcode: .connectionClose, data: closeDataCode) |
| 113 | + _ = context.write(self.wrapOutboundOut(closeFrame)).map { () in |
| 114 | + context.close(promise: nil) |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + private func pong(context: ChannelHandlerContext, frame: WebSocketFrame) { |
| 120 | + var frameData = frame.data |
| 121 | + let maskingKey = frame.maskKey |
| 122 | + |
| 123 | + if let maskingKey = maskingKey { |
| 124 | + frameData.webSocketUnmask(maskingKey) |
| 125 | + } |
| 126 | + |
| 127 | + let responseFrame = WebSocketFrame(fin: true, opcode: .pong, data: frameData) |
| 128 | + context.write(self.wrapOutboundOut(responseFrame), promise: nil) |
| 129 | + } |
| 130 | + |
| 131 | + private func closeOnError(context: ChannelHandlerContext) { |
| 132 | + // We have hit an error, we want to close. We do that by sending a close frame and then |
| 133 | + // shutting down the write side of the connection. |
| 134 | + var data = context.channel.allocator.buffer(capacity: 2) |
| 135 | + data.write(webSocketErrorCode: .protocolError) |
| 136 | + let frame = WebSocketFrame(fin: true, opcode: .connectionClose, data: data) |
| 137 | + context.write(self.wrapOutboundOut(frame)).whenComplete { (_: Result<Void, Error>) in |
| 138 | + context.close(mode: .output, promise: nil) |
| 139 | + } |
| 140 | + awaitingClose = true |
| 141 | + } |
| 142 | +} |
0 commit comments