-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebsocket_server.rb
More file actions
313 lines (284 loc) · 10.8 KB
/
websocket_server.rb
File metadata and controls
313 lines (284 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# MIT License
#
# Copyright (c) 2023 Kenneth Kinion
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# This is a stand-alone WebSocket implementation that uses only Ruby sockets.
# The emphasis on this implementation is on understanding what is happening
# in the underlying requests, with a secondary goal of this being as concise
# as possible and being contained within a single source file.
#
# References used to build this server include:
# "Building a simple websockets server from scratch in Ruby"
# http://blog.honeybadger.io/building-a-simple-websockets-server-from-scratch-in-ruby/
#
# "RFC 6455 - The WebSocket Protocol"
# https://tools.ietf.org/html/rfc6455
#
# WebSocket Ruby Gem - "Universal Ruby library to handle WebSocket protocol"
# https://github.com/imanel/websocket-ruby
module WebSocket
class Server
require 'socket'
require 'openssl'
require 'logger'
require 'digest'
require_relative 'websocket_client'
SERVER_ACTIONS = [
:client_connect, :client_disconnect,
]
# Configures the WebSocketServer, but does not start the server
# @params [Hash] opts - options hash supporting:
# host: hostname from which to serve WebSockets
# port: port from which to serve WebSockets
# logger: logger override to use for log messages (defaults to STDOUT)
def initialize(opts = {}, host: nil, port: nil, logger: nil, ssl: nil,
ssl_key: nil, ssl_cert: nil)
@host = host || opts[:host]
@port = port || opts[:port]
@logger = logger || opts[:logger]
@ssl = ssl || opts[:ssl]
@ssl_key = ssl_key || opts[:ssl_key]
@ssl_cert = ssl_cert || opts[:ssl_cert]
@client_handlers = Hash.new{|h, v| h[v] = []}
@server_handlers = Hash.new{|h, v| h[v] = []}
@clients = {}
@client_mutex = Mutex.new
@server = nil
@socket = nil
@ctx = nil
unless @logger
@logger = Logger.new(STDOUT)
@logger.level = Logger::WARN
end
end
# Registers a custom action handler for client events
# Executes the given code when the specified action occurs
#
# @param [Symbol] action - the name of the action
# @param [Proc or lambda] func - a callable object
# @param [Block] block - code block
def on(action, func = nil, &block)
func ||= block
if SERVER_ACTIONS.include?(action)
@server_handlers[action] << func
else
@client_handlers[action] << func
end
end
# shortcuts
def on_text(func = nil, &block); on(:text, func, &block) end
def on_binary(func = nil, &block); on(:binary, func, &block) end
def on_close(func = nil, &block); on(:close, func, &block) end
def on_ping(func = nil, &block); on(:ping, func, &block) end
def on_pong(func = nil, &block); on(:pong, func, &block) end
def on_client_connect(func = nil, &block); on(:client_connect, func, &block) end
def on_client_disconnect(func = nil, &block); on(:client_disconnect, func, &block) end
# Starts the WebSocket server, spawns a new thread for every request
def run!
start_server!
@server_thread = Thread.new do
loop do
# TODO handle OpenSSL::SSL::SSLError on SSL client accept from non-SSL client
Thread.start(@server.accept) do |socket|
begin
socket.accept if @ssl
handle_request(socket)
rescue => e
@logger.error "#{e.class}: #{e.message}"
@logger.debug e.backtrace
ensure
closing_client = @client_mutex.synchronize do
@clients.delete(socket)
end
# invoke callbacks for disconnect if there is a client to
# disconnect
emit(:client_disconnect, closing_client) if closing_client
socket.close
end
end
end
end
end
# Stops the main WebSocket server thread
def stop!
return unless running?
@logger.info 'Stopping WebSocket server'
@client_mutex.synchronize do
@clients.each do |socket, client|
client.stop!
end
end
@server_thread.kill if @server_thread
@server.close
@socket.close unless @socket.nil?
end
# Returns true only when the server is running
def running?
!(@server.nil? || @server.closed?)
end
# Returns an array of all connected clients
#
# @return [Array] all currently-connected clients
def connected_clients
@client_mutex.synchronize do
@clients.values.dup
end
end
private
# Invoke any provided custom handlers for the given event type
#
# @param [Symbol] type - the event type
# @param [Array] *args - arguments to provide to the block handler
def emit(type, *args)
@server_handlers[type].dup.each { |handler| handler.call(*args) }
end
# This handles reading the WebSocket request from a client, validating the
# request, and then serving content if the request appears to be valid
# TODO: server should respond to bad requests with "400 Bad Request"
#
# @param [TCPSocket] socket - the incoming socket from a WebSocket client
def handle_request(socket)
request = ''
http_request = path = host = origin = nil
# read the raw HTTP request, line by line, until through the headers
while (line = socket.gets)
# the HTTP request (verb, path, version) is the first line
http_request ||= line
request += line
# end of the HTTP request
break if line.strip.empty?
end
# get the requested path from the HTTP request
if http_request =~ /^GET (\S+) HTTP\/1\.1\s*$/
path = $1
else
respond_400 socket, 'Received unsupported request type'
return
end
# requred headers
unless request =~ /^Connection: Upgrade\s*$/i
respond_400 socket, 'Received request without "Connection: Upgrade" header'
return
end
unless request =~ /^Upgrade: websocket\s*$/i
respond_400 socket, 'Received request without "Upgrade: websocket" header'
return
end
if request =~ /^Host: (\S+)\s*$/i
host = $1
else
respond_400 socket, 'Did not receive valid "Host" header'
return
end
websocket_key = websocket_version = nil
other_headers = []
# inspect the WebSocket headers
request.scan(/^(Sec-WebSocket-[^: ]+: [^\r]*)\r?$/i).flatten.each do |head|
case head
when /^Sec-WebSocket-Version: 13$/i
websocket_version = 13
when /^Sec-WebSocket-Key: (\S+)$/i
websocket_key = $1
else
other_headers << head
end
end
unless websocket_version
respond_400 socket, 'Did not receive websocket version header value of 13'
return
end
unless websocket_key
respond_400 socket, 'Received invalid websocket request (missing key)'
return
end
unless other_headers.empty?
@logger.info "Additional WebSocket headers: #{other_headers.join('#')}"
end
# Optional header
# See notes about "Origin Considerations" in the RFC:
# https://tools.ietf.org/html/rfc6455#section-10.2
origin = $1 if request =~ /^Origin: (\S+)\s*$/i
@logger.info 'Received websocket key, establishing connection'
response_to_hash = "#{websocket_key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
websocket_accept = Digest::SHA1.base64digest(response_to_hash)
response = <<-HEADER
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: #{websocket_accept}
HEADER
response = response.split("\n", -1).map {|l| l.strip}
response = response.join("\r\n")
socket.write response
client = WebSocket::Client.new(socket,
path: path, host: host, origin: origin,
handlers: @client_handlers,
logger: @logger,
)
# start handling frames for the connection
client_serve_thread = client.serve!
@client_mutex.synchronize do
# add to our awareness of connected clients
@clients[socket] = client
end
# emit the corresponding handler
emit(:client_connect, client)
# serves until the underlying thread ends
client_serve_thread.join
end
# Sends a valid 400 error to the connecting client
#
# @param [TCPSocket] socket - the TCP socket to the client
# @param [String] message - the error message to send
def respond_400(socket, message)
@logger.warn message
message = message.force_encoding('BINARY')
response = <<-HEADER
HTTP/1.1 400 Bad Request
Content-Type: text/html
Content-Length: #{message.length}
Connection: close
HEADER
response = response.split("\n", -1).map {|l| l.strip}
response = response.join("\r\n")
socket.write response
socket.write message
end
# Starts the listening TCPServer. Note that this is abstracted to allow
# for overriding default behavior, like adding support for accepting
# connections over SSL/TLS
def start_server!
@logger.info "Listening on #{@host}:#{@port}"
@server = TCPServer.new(@host, @port)
if @ssl
@logger.info "Initializing SSL context"
raise "Must provide SSL key" if @ssl_key.nil?
raise "Must provide SSL certificate" if @ssl_cert.nil?
@socket = @server
@ctx = OpenSSL::SSL::SSLContext.new
@ctx.cert = OpenSSL::X509::Certificate.new(File.open(@ssl_cert))
@ctx.key = OpenSSL::PKey::RSA.new(File.open(@ssl_key))
@server = OpenSSL::SSL::SSLServer.new(@socket, @ctx)
@server.start_immediately = false
end
loop { break unless @server.closed? }
end
end
end