3
0
Fork 0
websocketd/src/websocketd.cr

337 lines
9.1 KiB
Crystal
Raw Normal View History

2020-07-04 22:31:17 +02:00
require "option_parser"
require "ipc"
require "socket"
require "./colors"
require "json"
require "socket"
require "http/server"
require "base64"
require "digest"
require "./utils"
2020-07-10 16:22:31 +02:00
require "./instance_storage.cr"
2020-07-04 22:31:17 +02:00
# All modifications to standard libraries go there.
require "./lib_modifications.cr"
class CLI
# service instance parameters
# they can be changed via the cli
class_property service_name : String = "websocket"
class_property host : String = "0.0.0.0"
class_property port_to_listen : UInt16 = 1234
class_property timer_delay : Int32 = 30_000 # 30 seconds
class_property verbosity : Int32 = 1
end
2020-07-04 22:31:17 +02:00
OptionParser.parse do |parser|
parser.on "-l host", "--l host", "IP address to listen on." do |h|
CLI.host = h
2020-07-04 22:31:17 +02:00
end
parser.on "-p port", "--port port", "Port to listen on." do |port|
CLI.port_to_listen = port.to_u16
2020-07-04 22:31:17 +02:00
end
parser.on "-s service-name", "--service-name service-name", "Service name." do |name|
CLI.service_name = name
2020-07-04 22:31:17 +02:00
end
parser.on "-t timer-delay", "--timer-delay timer-delay", "Timer delay (in seconds)" do |t|
CLI.timer_delay = t.to_i32 * 1000 # stored in ms
2020-07-04 22:31:17 +02:00
end
parser.on "-v verbosity-level", "--verbosity level", "Verbosity." do |opt|
CLI.verbosity = opt.to_i
2020-07-04 22:31:17 +02:00
end
parser.on "-h", "--help", "Show this help" do
puts parser
exit 0
end
end
def sending_ping_messages
2020-07-10 16:22:31 +02:00
Context.context.fd_to_websocket.each do |fd, ws|
begin
ws.ping "hello from #{fd}"
rescue e
puts "#{CRED}Exception: #{e}#{CRESET}, already closed client #{fd}"
begin
Context.context.remove_fd fd
rescue e
puts "#{CRED}Cannot remove #{fd} from clients: #{e}#{CRESET}"
end
end
end
2020-07-04 22:31:17 +02:00
end
def ws_http_upgrade(client)
2020-07-04 22:31:17 +02:00
request = HTTP::Request.from_io client
if request.nil?
raise "#REQUEST IS NIL"
end
if request.is_a? HTTP::Status && request == HTTP::Status::BAD_REQUEST
raise "BAD REQUEST DAZE~"
end
if request.is_a? HTTP::Status
raise "Not bad request but still pretty bad: #{request.to_s}"
end
# 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
# requested service, fd
req_service = request.path.lchop
if req_service.ends_with? ".JSON"
2020-07-10 16:22:31 +02:00
Context.context.is_json[client.fd] = true
2020-07-04 22:31:17 +02:00
req_service = req_service.gsub /.JSON$/, ""
else
2020-07-10 16:22:31 +02:00
Context.context.is_json[client.fd] = false
2020-07-04 22:31:17 +02:00
end
# TODO: if trackerd, send the IP address of the client
2020-07-10 16:22:31 +02:00
# if req_service == "tracker"
# puts "tracker - sending the IP address"
# puts "connection from #{client.remote_address}"
# sfd = Context.context.switchtable[client.fd]
# # message = IPC::Message.from_json(JSON).to_packet
# # => JSON has to include these attributes: mtype, utype, payload
# # message = IPC::Message.new mtype, utype, payload
# remote_address = client.remote_address.address
# message = IPC::Message.new 1, 1.to_u8, "{\"ipaddress\": \"#{remote_address}\"}"
# serv = WrappedTCPFileDescriptor.new(fd: sfd, family: Socket::Family::INET)
# serv.send message.to_packet
# end
2020-07-04 22:31:17 +02:00
# puts "#{headers_header}\n#{headers.to_s}\r\n"
client.send "#{headers_header}\n#{headers.to_s}\r\n"
wsclient = WebSocket.new client
wsclient.on_pong do |m|
puts "pong #{m}"
end
# registering the client into storing structures to avoid being garbage collected
2020-07-10 16:22:31 +02:00
Context.context.fd_to_websocket[client.fd] = wsclient
2020-07-04 22:31:17 +02:00
2020-07-10 16:22:31 +02:00
req_service
end
def handle_new_clients(service, server)
# TODO: this is a lot of C-like notation, should be changed.
# In the client accept function
# 1. accept TCP/WS connection
client = server.accept
# 2. upgrade HTTP connections and get the service name in the URI path.
req_service = ws_http_upgrade client
puts "requested service: #{req_service}"
2020-07-04 22:31:17 +02:00
# 3. connect to the service via ipc_connection_switched
LibIPC.ipc_connection_switched service.pointer, req_service
2020-07-10 16:22:31 +02:00
# puts "ipc_connection_switched: OK"
req_service_fd = service.context.pollfd[service.context.size - 1].fd
# 4. add client fd in the context, type = switched via ipc_ctx_fd_type
service << client.fd
2020-07-10 16:22:31 +02:00
# service.pp
LibIPC.ipc_ctx_fd_type service.pointer, client.fd, LibIPC::ConnectionType::Switched
2020-07-10 16:22:31 +02:00
# puts "ipc_ctx_fd_type: OK"
# 5. add both fd in switched via ipc_switching_add
2020-07-10 16:22:31 +02:00
LibIPC.ipc_ctx_switching_add service.pointer, client.fd, req_service_fd
# service.pp
# puts "ipc_switching_add: OK"
proc_cb_in = ->my_cb_in(Int32, Pointer(LibIPC::Message))
proc_cb_out = ->my_cb_out(Int32, Pointer(LibIPC::Message))
# 6. change client callbacks via ipc_switching_callbacks
# only the client callbacks are changed, since the associated server is a simple libipc service
2020-07-10 16:22:31 +02:00
puts "#{CGREEN}BEFORE ipc_switching_callbacks#{CRESET}"
LibIPC.ipc_switching_callbacks service.pointer, client.fd, proc_cb_in, proc_cb_out
puts "ipc_switching_callbacks: OK"
puts "#{CBLUE}new client:#{CRESET} #{client.fd}" unless CLI.verbosity == 0
rescue e
puts "Exception: #{CRED}#{e}#{CRESET}"
unless client.nil?
client.not_nil!.close
2020-07-04 22:31:17 +02:00
end
end
def my_cb_out(fd : Int32, pm : Pointer(LibIPC::Message))
puts "OUT fd is #{fd}"
2020-07-10 16:22:31 +02:00
wsclient = Context.context.fd_to_websocket[fd]
message = IPC::Message.new pm
pp! message
if Context.context.is_json[fd]
puts "OUT: this is a JSON client"
buf = message.to_json
else
puts "OUT: this is NOT a JSON client (fake, always JSON right now)"
# buf = message.to_packet
buf = message.to_json
end
puts "OUT: SENDING"
wsclient.send buf
return LibIPC::IPCCB::NoError
2020-07-10 16:22:31 +02:00
rescue e
puts "#{CRED}Exception during message transfer:#{CRESET} #{e}"
Context.context.remove_fd fd
return LibIPC::IPCCB::Error
2020-07-04 22:31:17 +02:00
end
2020-07-10 16:22:31 +02:00
def my_cb_in(fd : Int32, pm : LibIPC::Message*)
puts "IN fd is #{fd}"
2020-07-10 16:22:31 +02:00
message = IPC::Message.new pm
wsclient = Context.context.fd_to_websocket[fd]
message = wsclient.run_once
if wsclient.closed?
puts "#{CBLUE}client is closed#{CRESET}"
Context.context.remove_fd fd
return LibIPC::IPCCB::Closing
end
if message.nil?
puts "#{CRED}message is nil#{CRESET}"
Context.context.remove_fd fd
return LibIPC::IPCCB::Closing
end
case message
when WebSocket::Error
puts "#{CRED}An error occured#{CRESET}"
Context.context.remove_fd fd
return LibIPC::IPCCB::Error
when WebSocket::Ping
puts "#{CBLUE}Received a ping message#{CRESET}"
Context.context.remove_fd fd
return LibIPC::IPCCB::Ignore
when WebSocket::Pong
puts "#{CBLUE}Received a pong message#{CRESET}"
return LibIPC::IPCCB::Ignore
when WebSocket::Close
puts "#{CBLUE}Received a close message#{CRESET}"
Context.context.remove_fd fd
return LibIPC::IPCCB::Closing
when WebSocket::NotFinal
puts "#{CBLUE}Received only part of a message: NOT IMPLEMENTED#{CRESET}"
Context.context.remove_fd fd
return LibIPC::IPCCB::Error
when Bytes
# TODO: when receiving a binary message
# we should test the format and maybe its content
puts "#{CBLUE}Received a binary message: NOT IMPLEMENTED, YET#{CRESET}"
Context.context.remove_fd fd
return LibIPC::IPCCB::Error
when String
puts "#{CBLUE}Received a String message#{CRESET}"
end
if Context.context.is_json[fd] && message.is_a?(String)
puts "#{CRED}CECI EST DU JSON#{CRESET}"
message = IPC::Message.from_json(message).to_packet
end
pp! message
# TODO: take the received message and convert it in pm
return LibIPC::IPCCB::NoError
2020-07-10 16:22:31 +02:00
rescue e
puts "#{CRED}Exception (receiving a message)#{CRESET} #{e}"
tcp = WrappedTCPFileDescriptor.new(fd: fd, family: Socket::Family::INET)
tcp.close
Context.context.remove_fd fd
return LibIPC::IPCCB::Error
2020-07-04 22:31:17 +02:00
end
2020-07-10 16:22:31 +02:00
def info(str : String)
if CLI.verbosity > 0
puts str
end
end
class Context
class_property context = InstanceStorage.new
end
2020-07-04 22:31:17 +02:00
def main
# by default, listen on any IP address
server = TCPServer.new(CLI.host, CLI.port_to_listen)
service = IPC::Server.new CLI.service_name
service << server.fd
# Every few seconds, the service should trigger the timer
# Allowing the sending of Ping messages to clients
service.base_timer = CLI.timer_delay
service.timer = CLI.timer_delay
service.loop do |event|
2020-07-10 16:22:31 +02:00
info "current state of the context:"
service.pp
case event
when IPC::Event::Timer
2020-07-10 16:22:31 +02:00
info "#{CORANGE}IPC::Event::Timer#{CRESET}"
sending_ping_messages
when IPC::Event::Connection
2020-07-10 16:22:31 +02:00
info "#{CBLUE}IPC::Event::Connection#{CRESET}: #{event.fd}"
when IPC::Event::Disconnection
2020-07-10 16:22:31 +02:00
info "#{CBLUE}IPC::Event::Disconnection#{CRESET}: #{event.fd}"
Context.context.remove_fd event.fd
when IPC::Event::ExtraSocket
2020-07-10 16:22:31 +02:00
info "#{CBLUE}IPC::Event::ExtraSocket#{CRESET}: #{event.fd}"
2020-07-04 22:31:17 +02:00
if server.fd != event.fd
raise "Error: the only extra socket should be the TCP/WS server"
2020-07-04 22:31:17 +02:00
end
handle_new_clients(service, server)
2020-07-04 22:31:17 +02:00
when IPC::Event::Switch
2020-07-10 16:22:31 +02:00
info "\033[36mIPC::Event::Switch#{CRESET}: from fd #{event.fd}"
2020-07-04 22:31:17 +02:00
2020-07-10 16:22:31 +02:00
# raise "Not implemented."
2020-07-04 22:31:17 +02:00
when IPC::Event::MessageSent
2020-07-10 16:22:31 +02:00
info "Message sent, for #{event.fd}"
2020-07-04 22:31:17 +02:00
when IPC::Event::MessageReceived
2020-07-10 16:22:31 +02:00
info "#{CBLUE}IPC::Event::Message#{CRESET}: #{event.fd}"
2020-07-04 22:31:17 +02:00
raise "Not implemented."
end
2020-07-04 22:31:17 +02:00
end
end
main