require "option_parser" require "ipc" require "socket" require "./colors" require "./ws" require "json" require "socket" require "http" require "http/server" require "base64" require "digest" require "./utils" class IPC::Connection def initialize(fd : Int32) external_connection = LibIPC::Connection.new external_connection.fd = fd initialize(external_connection) end end class IPC::Message def to_buffer to_message @type, String.new(@payload) end end class WrappedTCPFileDescriptor < TCPSocket # do not close the connection when garbage collected!! def finalize # puts "WrappedTCPFileDescriptor garbage collection!!" # super end end service_name = "websocket" host = "0.0.0.0" port_to_listen = 1234 OptionParser.parse do |parser| parser.on "-l host", "--l host", "IP address to listen on." do |h| host = h end parser.on "-p port", "--port port", "Port to listen on." do |port| port_to_listen = port.to_u16 end parser.on "-s service-name", "--service-name service-name", "Service name." do |name| service_name = name end parser.on "-h", "--help", "Show this help" do puts parser exit 0 end end 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) property fd_to_ipcconnection : Hash(Int32, IPC::Connection) 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 @fd_to_ipcconnection = Hash(Int32, IPC::Connection).new end def remove_fd (fdclient : Int32) # 1. closing both the client and the service fdservice = @switchtable[fdclient]? tcpfdc = @fd_to_tcpsocket[fdclient] # 2. closing the TCP connections tcpfdc.close unless tcpfdc.closed? # 3. removing the client and the service fds from the loop check @service.remove_fd (fdclient) # 5. removing both the client and the service from the switchtable @switchtable = @switchtable.select do |fdc, fds| fdc != fdclient && fds != fdclient end # 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 unless fdservice.nil? service = @fd_to_ipcconnection[fdservice] service.close @service.remove_fd (fdservice) @fd_to_ipcconnection = @fd_to_ipcconnection.select do |k, v| k != fdservice end @is_client = @is_client.select do |fd,v| fd != fdservice end end end end # by default, listen on any IP address server = TCPServer.new(host, port_to_listen) service = IPC::SwitchingService.new service_name service << server.fd context = InstanceStorage.new service def websocket_client_connection(client, context : InstanceStorage) request = HTTP::Request.from_io client # pp! request 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.empty? client.close puts "should send a PATH" 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" context.is_json[client.fd] = true req_service = req_service.gsub /.JSON$/, "" else context.is_json[client.fd] = false end websocket_connection_procedure req_service, client.fd, context # 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 "Received a pong message: #{m}" end context.is_client[client.fd] = true # listen to the client's file descriptor context.service << client.fd # puts "#{CBLUE}new client: #{client.fd}#{CRESET}" # registering the client into storing structures to avoid being garbage collected context.fd_to_tcpsocket[client.fd] = client context.fd_to_websocket[client.fd] = wsclient end def closing_client (fdclient : Int, context : InstanceStorage) puts "#{CBLUE}closing the client:#{CRESET} #{fdclient}" context.remove_fd fdclient end # first message from the client: requested service name # 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) def websocket_connection_procedure (requested_service : String, clientfd : Int32, context : InstanceStorage) begin # 2. establishing a connection to the service newservice = IPC::Connection.new requested_service context.fd_to_ipcconnection[newservice.fd] = newservice # 3. listening on the client fd and the service fd context.service << newservice.fd # cannot perform automatic switching due to websockets headers # future version of the libipc lib should include some workaround, probably # service.switch.add fdclient, newservice.fd # 4. bounding the client and the service fd context.switchtable[clientfd] = newservice.fd context.switchtable[newservice.fd] = clientfd # 5. the client is then connected, send it a message context.is_client[clientfd] = true context.is_client[newservice.fd] = false rescue e puts "#{CRED}Exception during connection to the service:#{CRESET} #{e}" closing_client clientfd, context end end class JSONWSMessage JSON.mapping( mtype: Int32, payload: String ) def initialize (@mtype : Int32, @payload : String) end end class IPC::Message def to_json JSONWSMessage.new(@type.to_i, String.new(@payload)).to_json end end def websocket_switching_procedure (activefd : Int, context : InstanceStorage) # FIXME: debugging purposes begin if context.is_client[activefd] # The client is a WebSocket on top of a TCP connection client = context.fd_to_tcpsocket[activefd] wsclient = context.fd_to_websocket[activefd] begin message = wsclient.read # puts "RECEIVING A MESSAGE from #{activefd}: #{message}" rescue e puts "#{CRED}Exception (receiving a message)#{CRESET} #{e}" closing_client activefd, context return end if wsclient.closed? # puts "#{CBLUE}client is closed#{CRESET}" closing_client client.fd, context return end if message.nil? puts "#{CRED}message is nil#{CRESET}" closing_client client.fd, context return end if message.is_a?(WebSocket::Ping) # puts "#{CBLUE}This is a ping message#{CRESET}" return end if message.is_a?(WebSocket::Pong) # puts "#{CBLUE}This is a pong message#{CRESET}" return end if message.is_a?(WebSocket::Close) # puts "#{CRED}This is a close message#{CRESET}" return end if message.is_a?(Slice(UInt8)) # puts "#{CRED}This is a binary message: not yet implemented#{CRESET}" return end # TODO: verify this if context.is_json[activefd] jsonmessage = JSONWSMessage.from_json message message = to_message jsonmessage.mtype, jsonmessage.payload # puts "JSON TYPE !!!" # pp! jsonmessage # pp! message end # puts "switching: client to service" # print_hexa(String.new(message), "#{CBLUE}Received message hexa#{CRESET}") # client => service fdservice = context.switchtable[activefd] # XXX: this is not a TCP fd, but since behind the scene this is compatible, I'm hacking a bit serv = WrappedTCPFileDescriptor.new(fd: fdservice, family: Socket::Family::INET) #serv = context.fd_to_ipcconnection[fdservice] serv.send message # puts "SENT MESSAGE TO SERVER: #{message}" else # puts "switching: service to client" # service => client # puts "RECEIVING A MESSAGE FROM THE SERVER #{activefd}" fdclient = context.switchtable[activefd] wsclient = context.fd_to_websocket[fdclient] serv = context.fd_to_ipcconnection[activefd] message = serv.read # puts "RECEIVING A MESSAGE FROM THE SERVER #{activefd}: #{message}" # puts "received message from service: #{message.to_s}" if context.is_json[fdclient] buf = message.to_json # puts "JSON TYPE !!!" # pp! buf else buf = message.to_buffer end # TODO: REMOVE THIS # buf = message.to_buffer # print_hexa String.new(buf), "\033[31m Message to send to the client \033[00m " wsclient.send buf end rescue e puts "#{CRED}Exception during message transfer:#{CRESET} #{e}" if context.is_client[activefd] closing_client activefd, context else clientfd = context.switchtable[activefd] closing_client clientfd, context end end end # Every few seconds, the service should trigger the timer service.base_timer = 30 service.loop do |event| case event when IPC::Event::Timer # puts "#{CORANGE}IPC::Event::Timer#{CRESET}" context.fd_to_websocket.each do |fd, ws| begin ws.ping "coucou from #{fd}" rescue e puts "#{CRED}Exception: #{e}#{CRESET}, already closed client #{fd}" begin context.remove_fd fd rescue e puts "#{CRED}Cannot remove #{fd} from clients: #{e}#{CRESET}" end end end when IPC::Event::Connection puts "#{CBLUE}IPC::Event::Connection: #{event.connection.fd}#{CRESET}" when IPC::Event::Disconnection puts "#{CBLUE}IPC::Event::Disconnection: #{event.connection.fd}#{CRESET}" when IPC::Event::ExtraSocket puts "#{CBLUE}IPC::Event::ExtraSocket#{CRESET}" # 1. accept new websocket clients if server.fd == event.connection.fd client = server.accept begin websocket_client_connection client, context puts "#{CBLUE}new client:#{CRESET} #{client.fd}" rescue e puts "Exception: #{CRED}#{e}#{CRESET}" client.close end next end # 2. active fd != server fd activefd = event.connection.fd websocket_switching_procedure activefd, context when IPC::Event::Switch puts "\033[36mIPC::Event::Switch#{CRESET}: from fd #{event.connection.fd}" raise "Not implemented." # IPC::Event::Message has to be the last entry # because ExtraSocket and Switch inherit from Message class when IPC::Event::Message puts "#{CBLUE}IPC::Event::Message#{CRESET}: #{event.connection.fd}" raise "Not implemented." end end