ipcd/src/websocketd.cr

524 lines
15 KiB
Crystal
Raw Normal View History

2019-08-01 00:44:38 +02:00
require "option_parser"
require "ipc"
require "socket"
require "./colors"
require "json"
2019-08-01 00:44:38 +02:00
require "socket"
require "http/server"
require "base64"
require "digest"
require "./utils"
2020-08-28 02:02:19 +02:00
require "baguette-crystal-base"
2020-08-24 16:55:35 +02:00
require "colorize"
2020-02-04 02:06:13 +01:00
# All modifications to standard libraries go there.
require "./lib_modifications.cr"
2019-08-01 00:44:38 +02:00
2020-08-23 17:30:54 +02:00
class Context
# service instance parameters
# they can be changed via the cli
class_property service_name = "websocket"
class_property host = "0.0.0.0"
class_property port_to_listen : UInt16 = 1234
class_property timer_delay : Int32 = 30_000.to_i32
2020-09-01 00:44:12 +02:00
2020-08-28 18:08:20 +02:00
class_property print_messages = false
2020-09-01 00:44:12 +02:00
class_property print_timer = false
2020-08-23 17:30:54 +02:00
end
2019-08-01 00:44:38 +02:00
2019-11-04 15:35:01 +01:00
OptionParser.parse do |parser|
2019-11-04 09:15:42 +01:00
parser.on "-l host", "--l host", "IP address to listen on." do |h|
2020-08-23 17:30:54 +02:00
Context.host = h
2019-11-04 09:15:42 +01:00
end
2020-02-04 02:06:13 +01:00
2019-08-01 00:44:38 +02:00
parser.on "-p port", "--port port", "Port to listen on." do |port|
2020-08-23 17:30:54 +02:00
Context.port_to_listen = port.to_u16
2019-08-01 00:44:38 +02:00
end
parser.on "-s service-name", "--service-name service-name", "Service name." do |name|
2020-08-23 17:30:54 +02:00
Context.service_name = name
2019-08-01 00:44:38 +02:00
end
parser.on "-t timer-delay", "--timer-delay timer-delay", "Timer delay (in seconds)" do |t|
2020-08-23 17:30:54 +02:00
Context.timer_delay = t.to_i32 * 1000
end
2020-02-04 02:06:13 +01:00
parser.on "-v verbosity-level", "--verbosity level", "Verbosity." do |opt|
2020-08-28 02:02:19 +02:00
Baguette::Context.verbosity = opt.to_i
2020-02-04 02:06:13 +01:00
end
2020-09-01 00:44:12 +02:00
parser.on "-T", "--print-timer", "Print timer." do
Context.print_timer = true
end
2020-08-28 18:08:20 +02:00
parser.on "-M", "--print-messages", "Print messages received and sent." do
Context.print_messages = true
end
2019-08-01 00:44:38 +02:00
parser.on "-h", "--help", "Show this help" do
puts parser
exit 0
end
end
2020-02-04 02:06:13 +01:00
2020-08-23 17:30:54 +02:00
# Link between fd and TCPSocket, WebSocket and IPC::Client instances.
2019-08-01 00:44:38 +02:00
class InstanceStorage
property service : IPC::SwitchingService
property switchtable : Hash(Int32, Int32)
property is_client : Hash(Int32,Bool)
property is_json : Hash(Int32, Bool)
property fd_to_tcpsocket : Hash(Int32, TCPSocket)
property fd_to_websocket : Hash(Int32, WebSocket)
2020-08-23 17:30:54 +02:00
property fd_to_ipcclient : Hash(Int32, IPC::Client)
2019-08-01 00:44:38 +02:00
def initialize (@service : IPC::SwitchingService)
# fdlist_client = [] of TCPSocket
@switchtable = Hash(Int32, Int32).new
@is_client = Hash(Int32,Bool).new
@is_json = Hash(Int32,Bool).new
@fd_to_tcpsocket = Hash(Int32, TCPSocket).new
@fd_to_websocket = Hash(Int32, WebSocket).new
2020-08-23 17:30:54 +02:00
@fd_to_ipcclient = Hash(Int32, IPC::Client).new
2019-08-01 00:44:38 +02:00
end
def remove_fd (fdclient : Int32)
2020-08-28 02:02:19 +02:00
Baguette::Log.info "closing the client:#{CRESET} #{fdclient}"
if fdclient == -1
raise "fdclient is -1, nothing to do with it"
end
2020-08-28 18:08:20 +02:00
begin
# 1. closing both the client and the service
tcpfdc = @fd_to_tcpsocket[fdclient]
2019-08-01 00:44:38 +02:00
# 2. closing the TCP connections
tcpfdc.close unless tcpfdc.closed?
2020-08-28 18:08:20 +02:00
rescue e
Baguette::Log.error "remove_fd: 1 #{e}"
2020-08-28 18:08:20 +02:00
end
2019-08-01 00:44:38 +02:00
# 3. removing the client and the service fds from the loop check
2020-08-28 18:08:20 +02:00
begin
@service.remove_fd (fdclient)
2020-08-28 18:08:20 +02:00
rescue e
Baguette::Log.error "remove_fd: 2 #{e}"
2020-08-28 18:08:20 +02:00
end
2019-08-01 00:44:38 +02:00
# 5. removing both the client and the service from the switchtable
fdservice = @switchtable[fdclient]?
@switchtable = @switchtable.select do |fdc, fds|
2019-08-01 00:44:38 +02:00
fdc != fdclient && fds != fdclient
end
2019-08-10 15:31:19 +02:00
# 6. removing the client and the service from is_client
@is_client = @is_client.select do |fd,v| fd != fdclient end
@is_json = @is_json.select do |fd,v| fd != fdclient end
@fd_to_websocket.select! do |fd, ws|
fd != fdclient
end
2020-08-28 18:08:20 +02:00
begin
if fdservice.nil?
Baguette::Log.debug "client #{fdclient} aleady has its service removed"
else
@service.remove_fd (fdservice)
service = @fd_to_ipcclient[fdservice]
2020-08-23 17:30:54 +02:00
@fd_to_ipcclient = @fd_to_ipcclient.select do |k, v|
k != fdservice
end
2019-08-10 15:31:19 +02:00
@is_client = @is_client.select do |fd,v| fd != fdservice end
# perform the close at the end
# on crash, this service still is removed from the list of listened fd
service.close
end
2020-08-28 18:08:20 +02:00
rescue e
Baguette::Log.error "remove_fd: 3 #{e}"
2020-08-28 18:08:20 +02:00
end
rescue e
Baguette::Log.error "in InstanceStorage#remove_fd: #{e}"
2019-08-01 00:44:38 +02:00
end
end
2020-08-23 17:30:54 +02:00
class Context
class_property service = IPC::SwitchingService.new service_name
class_property context = InstanceStorage.new service
end
2019-08-01 00:44:38 +02:00
2020-08-23 17:30:54 +02:00
# by default, listen on any IP address
server = TCPServer.new(Context.host, Context.port_to_listen)
Context.service << server.fd
2019-08-01 00:44:38 +02:00
2020-08-23 17:30:54 +02:00
def websocket_client_connection(client)
2019-08-01 00:44:38 +02:00
request = HTTP::Request.from_io client
2020-08-28 18:08:20 +02:00
if Context.print_messages
pp! request
end
2019-08-01 00:44:38 +02:00
if request.nil?
raise "#REQUEST IS NIL"
2019-08-01 00:44:38 +02:00
end
2019-09-29 18:39:47 +02:00
if request.is_a? HTTP::Status && request == HTTP::Status::BAD_REQUEST
raise "BAD REQUEST DAZE~"
2019-08-01 00:44:38 +02:00
end
2019-09-29 18:39:47 +02:00
if request.is_a? HTTP::Status
raise "Not bad request but still pretty bad: #{request.to_s}"
end
2019-08-01 00:44:38 +02:00
# FIXME: check they actually wanted to upgrade to websocket
key = request.headers["Sec-WebSocket-Key"]
response_key = Digest::SHA1.base64digest key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
# puts response_key
# HTTP inside bru
headers_header = "HTTP/1.1 101 Switching Protocols"
headers = HTTP::Headers {
"Upgrade" => "websocket",
"Connection" => "Upgrade",
"Sec-WebSocket-Accept" => response_key
}
headers = headers.map { |key, value| "#{key}: #{value[0]}\r\n" }.join
2019-08-10 15:31:19 +02:00
# requested service, fd
2020-08-23 17:30:54 +02:00
req_service = request.path.lchop.sub "ws/", ""
2019-08-10 15:31:19 +02:00
if req_service.empty?
client.close
return
end
# The client may ask to transcript JSON-based messages into IPC messages.
# To that end, the client may send the name of the service it wants to reach with the prefix ".JSON".
if req_service.ends_with? ".JSON"
2020-08-23 17:30:54 +02:00
Context.context.is_json[client.fd] = true
req_service = req_service.gsub /.JSON$/, ""
else
2020-08-23 17:30:54 +02:00
Context.context.is_json[client.fd] = false
end
2020-08-23 17:30:54 +02:00
# Hack to preserve the daemon naming convention.
if req_service == "tracker"
2020-08-23 17:30:54 +02:00
req_service = "tracking"
end
websocket_connection_procedure req_service, client.fd
# If the requested service is trackingd, send the IP address of the client
if req_service == "tracking"
2020-08-28 18:08:20 +02:00
real_ip_address = request.headers["X-Real-IP"]? || client.remote_address.address
2020-08-23 17:30:54 +02:00
sfd = Context.context.switchtable[client.fd]
2020-08-28 02:02:19 +02:00
Baguette::Log.info "trackingd - sending the IP address #{real_ip_address} to fd #{sfd}"
# message = IPC::Message.from_json(JSON).to_packet
# => JSON has to include these attributes: mtype, utype, payload
# message = IPC::Message.new mtype, utype, payload
2020-09-20 12:54:47 +02:00
message = IPC::Message.new sfd, 1, 1.to_u8, "{\"ipaddress\": \"#{real_ip_address}\"}"
2020-08-28 18:08:20 +02:00
if Context.print_messages
Baguette::Log.info "to trackingd: #{message.to_s}"
end
serv = WrappedTCPFileDescriptor.new(fd: sfd, family: Socket::Family::INET)
serv.send message.to_packet
end
2020-08-28 18:08:20 +02:00
if Context.print_messages
Baguette::Log.info "to client: #{headers_header}\n#{headers.to_s}"
end
2019-08-01 00:44:38 +02:00
client.send "#{headers_header}\n#{headers.to_s}\r\n"
wsclient = WebSocket.new client
wsclient.on_pong do |m|
2020-08-28 02:02:19 +02:00
Baguette::Log.debug "pong #{m}"
end
2020-08-23 17:30:54 +02:00
Context.context.is_client[client.fd] = true
2019-08-01 00:44:38 +02:00
# listen to the client's file descriptor
2020-08-23 17:30:54 +02:00
Context.context.service << client.fd
2019-08-01 00:44:38 +02:00
# puts "#{CBLUE}new client: #{client.fd}#{CRESET}"
# registering the client into storing structures to avoid being garbage collected
2020-08-23 17:30:54 +02:00
Context.context.fd_to_tcpsocket[client.fd] = client
Context.context.fd_to_websocket[client.fd] = wsclient
2019-08-01 00:44:38 +02:00
end
2020-08-23 17:30:54 +02:00
def closing_client (fdclient : Int)
Baguette::Log.warning "Closing client #{fdclient}"
2020-08-23 17:30:54 +02:00
Context.context.remove_fd fdclient
2019-08-01 00:44:38 +02:00
end
# first message from the client: requested service name
2019-08-10 15:31:19 +02:00
# 1. connection to the service
# 2. listening on the service fd
# 3. bounding both file descriptors (through switchtable hash)
# 4. indicating that the client is connected (in is_client)
2020-08-23 17:30:54 +02:00
def websocket_connection_procedure (requested_service : String, clientfd : Int32)
2019-08-01 00:44:38 +02:00
begin
2020-08-23 17:30:54 +02:00
# 1. establishing a connection to the service
newservice = IPC::Client.new requested_service
new_service_fd = newservice.fd.not_nil!
Context.context.fd_to_ipcclient[new_service_fd] = newservice
2019-08-01 00:44:38 +02:00
2020-08-23 17:30:54 +02:00
# 2. listening on the client fd and the service fd
Context.context.service << new_service_fd
2019-08-01 00:44:38 +02:00
# cannot perform automatic switching due to websockets headers
2019-08-10 15:31:19 +02:00
# future version of the libipc lib should include some workaround, probably
2019-08-01 00:44:38 +02:00
# service.switch.add fdclient, newservice.fd
2020-08-23 17:30:54 +02:00
# 3. bounding the client and the service fd
Context.context.switchtable[clientfd] = new_service_fd
Context.context.switchtable[new_service_fd] = clientfd
2019-08-01 00:44:38 +02:00
2020-08-23 17:30:54 +02:00
# 4. the client is then connected, send it a message
Context.context.is_client[clientfd] = true
Context.context.is_client[new_service_fd] = false
2019-08-01 00:44:38 +02:00
rescue e
Baguette::Log.error "Exception during connection to the service: #{e}"
2020-08-23 17:30:54 +02:00
Context.context.remove_fd clientfd
end
end
class FragmentBuffer
property buffer : String = String.new
end
2020-08-23 17:30:54 +02:00
def websocket_switching_procedure (activefd : Int)
2019-08-01 00:44:38 +02:00
begin
2020-09-14 16:15:21 +02:00
# Baguette::Log.title "activefd is #{activefd}"
2020-08-23 17:30:54 +02:00
if Context.context.is_client[activefd]
# Baguette::Log.title "activefd #{activefd} is a client"
2019-08-01 00:44:38 +02:00
# The client is a WebSocket on top of a TCP connection
2020-08-23 17:30:54 +02:00
client = Context.context.fd_to_tcpsocket[activefd]
wsclient = Context.context.fd_to_websocket[activefd]
fb = FragmentBuffer.new
loop do
begin
2020-01-17 13:01:07 +01:00
message = wsclient.run_once
rescue e
Baguette::Log.error "Exception (receiving a message) #{e}"
2020-08-23 17:30:54 +02:00
Context.context.remove_fd activefd
2020-09-01 00:44:12 +02:00
break
end
2019-08-01 00:44:38 +02:00
2020-02-04 02:06:13 +01:00
# Checking the internals of WebSocket, then the contained IO within, to know if there is still something to read in the socket.
2020-01-17 13:01:07 +01:00
still_something_to_read = ! wsclient.ws.io.empty?
2019-08-01 00:44:38 +02:00
if wsclient.closed?
Baguette::Log.info "client #{activefd} is closing"
Context.context.remove_fd activefd
2020-09-01 00:44:12 +02:00
break
end
2019-08-01 00:44:38 +02:00
if message.nil?
Baguette::Log.error "message received from #{activefd} is nil"
Context.context.remove_fd activefd
2020-09-01 00:44:12 +02:00
if still_something_to_read
Baguette::Log.info "Still something to read, but #{activefd} was removed"
next
end
break
end
2020-01-17 13:01:07 +01:00
case message
when WebSocket::Error
Baguette::Log.error "An error occured with client #{activefd}"
Context.context.remove_fd activefd
2020-09-01 00:44:12 +02:00
if still_something_to_read
Baguette::Log.debug "Still something to read, but #{activefd} was removed"
next
end
2020-01-17 13:01:07 +01:00
return
when WebSocket::Ping
Baguette::Log.debug "Received a ping message"
if still_something_to_read
2020-09-01 00:44:12 +02:00
Baguette::Log.debug "Still something to read"
next
end
break
2020-01-17 13:01:07 +01:00
when WebSocket::Pong
Baguette::Log.debug "Received a pong message"
if still_something_to_read
2020-09-01 00:44:12 +02:00
Baguette::Log.debug "Still something to read"
next
end
break
2020-01-17 13:01:07 +01:00
when WebSocket::Close
Baguette::Log.debug "Received a close message"
Context.context.remove_fd activefd
if still_something_to_read
2020-09-01 00:44:12 +02:00
Baguette::Log.debug "Still something to read"
next
end
2020-09-01 00:44:12 +02:00
break
2020-01-17 13:01:07 +01:00
when WebSocket::NotFinal
Baguette::Log.warning "Received only part of a message"
# TODO: check if the message is OK when multiplexing
# pp! message
fb.buffer = fb.buffer + message.message
if still_something_to_read
2020-09-01 00:44:12 +02:00
Baguette::Log.debug "Still something to read"
next
end
2020-01-17 13:01:07 +01:00
break
2020-01-17 13:01:07 +01:00
when Bytes
# TODO: when receiving a binary message
# we should test the format and maybe its content
Baguette::Log.warning "Received a binary message (not supported)"
if still_something_to_read
Baguette::Log.info "Still something to read"
next
end
end
# In case there was a previous messagee within a fragment.
if fb.buffer.size > 0
Baguette::Log.warning "SHOULD reconstitute the message!!"
end
if message.is_a?(String) && fb.buffer.size > 0
Baguette::Log.warning "Reconstitute the message!!"
message = fb.buffer + message
fb.buffer = String.new
end
2020-08-23 17:30:54 +02:00
if Context.context.is_json[activefd] && message.is_a?(String)
2020-08-28 18:08:20 +02:00
if Context.print_messages
j = JSON.parse message
Baguette::Log.info "received from client #{activefd}"
pp! j["payload"]
end
2020-02-04 02:06:13 +01:00
message = IPC::Message.from_json(message).to_packet
end
# client => service
2020-08-23 17:30:54 +02:00
fdservice = Context.context.switchtable[activefd]
# XXX: this is not a TCP fd, but since behind the scene this is compatible, I'm hacking a bit
2020-02-04 02:06:13 +01:00
# Also, I changed the "finalize" method of the TCPFileDescriptor class not to close the socket
# when the object is GC.
serv = WrappedTCPFileDescriptor.new(fd: fdservice, family: Socket::Family::INET)
2020-08-23 17:30:54 +02:00
#serv = Context.context.fd_to_ipcclient[fdservice]
serv.send message
2019-08-01 00:44:38 +02:00
break unless still_something_to_read
2019-08-01 00:44:38 +02:00
end # loop over the remaining messages to read on the websocket
2019-08-10 15:31:19 +02:00
else
2019-08-01 00:44:38 +02:00
# service => client
2020-08-23 17:30:54 +02:00
fdclient = Context.context.switchtable[activefd]
wsclient = Context.context.fd_to_websocket[fdclient]
2019-08-01 00:44:38 +02:00
2020-08-23 17:30:54 +02:00
serv = Context.context.fd_to_ipcclient[activefd]
2019-08-01 00:44:38 +02:00
message = serv.read
2020-08-23 17:30:54 +02:00
if Context.context.is_json[fdclient]
buf = message.to_json
2020-08-28 18:08:20 +02:00
if Context.print_messages
j = JSON.parse buf
Baguette::Log.info "received from service #{activefd}"
pp! j["payload"]
end
else
2020-02-04 02:06:13 +01:00
buf = message.to_packet
end
2019-08-01 00:44:38 +02:00
wsclient.send buf
end
rescue e
Baguette::Log.error "Exception during message transfer: #{e}"
2020-08-23 17:30:54 +02:00
if Context.context.is_client[activefd]
closing_client activefd
2019-08-10 15:31:19 +02:00
else
2020-08-23 17:30:54 +02:00
clientfd = Context.context.switchtable[activefd]
closing_client clientfd
2019-08-01 00:44:38 +02:00
end
end
end
2020-08-23 17:30:54 +02:00
def sending_ping_messages
Context.context.fd_to_websocket.each do |fd, ws|
2020-01-17 13:01:07 +01:00
begin
ws.ping "hello from #{fd}"
rescue e
Baguette::Log.error "#{CRED}Exception: #{e}#{CRESET}, already closed client #{fd}"
2020-01-17 13:01:07 +01:00
begin
2020-08-23 17:30:54 +02:00
Context.context.remove_fd fd
2020-01-17 13:01:07 +01:00
rescue e
Baguette::Log.error "#{CRED}Cannot remove #{fd} from clients: #{e}#{CRESET}"
2020-01-17 13:01:07 +01:00
end
end
end
end
# Every few seconds, the service should trigger the timer
2020-01-17 13:01:07 +01:00
# Allowing the sending of Ping messages to clients
2020-08-23 17:30:54 +02:00
Context.service.base_timer = Context.timer_delay
2020-08-23 17:30:54 +02:00
Context.service.loop do |event|
2020-08-26 16:50:14 +02:00
begin
case event
when IPC::Event::Timer
2020-09-01 00:44:12 +02:00
Baguette::Log.info "IPC::Event::Timer" if Context.print_timer
2020-08-26 16:50:14 +02:00
sending_ping_messages
when IPC::Event::Connection
2020-08-28 02:02:19 +02:00
Baguette::Log.debug "IPC::Event::Connection: #{event.fd}"
2020-08-26 16:50:14 +02:00
when IPC::Event::Disconnection
2020-08-28 02:02:19 +02:00
Baguette::Log.debug "IPC::Event::Disconnection: #{event.fd}"
2020-08-26 16:50:14 +02:00
when IPC::Event::ExtraSocket
2020-08-28 02:02:19 +02:00
Baguette::Log.debug "IPC::Event::ExtraSocket: #{event.fd}"
2020-08-26 16:50:14 +02:00
# 1. accept new websocket clients
if server.fd == event.fd
client = server.accept
begin
websocket_client_connection client
2020-08-28 02:02:19 +02:00
Baguette::Log.info "new client: #{client.fd}"
2020-08-26 16:50:14 +02:00
rescue e
2020-08-28 02:02:19 +02:00
Baguette::Log.error "Exception: #{e}"
2020-08-26 16:50:14 +02:00
client.close
end
next
end
2019-08-01 00:44:38 +02:00
2020-08-26 16:50:14 +02:00
# 2. active fd != server fd
activefd = event.fd
if activefd <= 0
2020-08-28 02:02:19 +02:00
Baguette::Log.error "faulty activefd: #{activefd}"
2020-08-26 16:50:14 +02:00
end
websocket_switching_procedure activefd
2019-08-01 00:44:38 +02:00
2020-08-26 16:50:14 +02:00
when IPC::Event::Switch
2020-08-28 02:02:19 +02:00
Baguette::Log.debug "IPC::Event::Switch: from fd #{event.fd}"
2020-08-26 16:50:14 +02:00
raise "Not implemented."
2019-08-01 00:44:38 +02:00
2020-08-26 16:50:14 +02:00
# IPC::Event::Message has to be the last entry
# because ExtraSocket and Switch inherit from Message class
when IPC::Event::MessageSent
2020-08-28 02:02:19 +02:00
Baguette::Log.error "IPC::Event::MessageSent: #{event.fd}"
2019-08-01 00:44:38 +02:00
2020-08-26 16:50:14 +02:00
when IPC::Event::MessageReceived
2020-08-28 02:02:19 +02:00
Baguette::Log.debug "IPC::Event::MessageReceived: #{event.fd}"
2020-08-26 16:50:14 +02:00
raise "Not implemented."
end
rescue e
2020-08-28 02:02:19 +02:00
Baguette::Log.error "IPC loop final catch: #{e}"
2019-08-01 00:44:38 +02:00
end
end