0
  7   ˆl–Ãa¾”ªi?u8 ¸Û71hß�þBHäYÇÌc!Zq§žþÈƒu–ÝÇÆÀÄ ½    # Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

class WebsocketServer

  cattr_reader :clients, :options

  def self.run(options)
    @options = options
    @clients = {}

    # By default, we are only logging errors to STDOUT.
    # To turn on some more logging to get some insights, please, provide one of the following parameters:
    #   -n | --info    => info
    #   -v | --verbose => debug

    Rails.configuration.interface = 'websocket'

    AppVersion.start_maintenance_thread(process_name: 'websocket-server')
    Zammad::ProcessDebug.install_thread_status_handler

    # EventMachine resolves its bind address with AI_ADDRCONFIG, which fails even for 127.0.0.1 on IPv6-only hosts (#6536).
    server = TCPServer.new(@options[:b], @options[:p])
    # EventMachine owns the descriptor from here on and closes it on shutdown; Ruby must not close it a second time.
    server.autoclose = false

    EventMachine.epoll
    EventMachine.run do
      Signal.trap('TERM') { EventMachine::WebSocket.stop }
      Signal.trap('INT')  { EventMachine::WebSocket.stop }

      EventMachine.attach_server(server, EventMachine::WebSocket::Connection, host: @options[:b], port: @options[:p], secure: @options[:s], tls_options: @options[:tls_options]) do |ws|

        # register client connection
        ws.onopen do |handshake|
          WebsocketServer.onopen(ws, handshake)
        end

        # unregister client connection
        ws.onclose do
          WebsocketServer.onclose(ws)
        end

        # manage messages
        ws.onmessage do |msg|
          WebsocketServer.onmessage(ws, msg)
        end
      end

      # check unused connections
      EventMachine.add_timer(0.5) do
        WebsocketServer.check_unused_connections
      end

      # check open unused connections, kick all connection without activity in the last 2 minutes
      EventMachine.add_periodic_timer(120) do
        WebsocketServer.check_unused_connections
      end

      EventMachine.add_periodic_timer(20) do
        WebsocketServer.log_status
      end

      EventMachine.add_periodic_timer(0.4) do
        WebsocketServer.send_to_client
      end
    end
  end

  def self.onopen(websocket, handshake)
    headers = handshake.headers
    client_id = websocket.object_id.to_s
    log 'info', 'Client connected.', client_id
    Sessions.create(client_id, {}, { type: 'websocket' })

    return if @clients.include? client_id

    @clients[client_id] = {
      websocket:   websocket,
      last_ping:   Time.now.utc.to_i,
      error_count: 0,
      headers:     headers,
    }
  end

  def self.onclose(websocket)
    client_id = websocket.object_id.to_s
    log 'info', 'Client disconnected.', client_id

    # removed from current client list
    if @clients.include? client_id
      @clients.delete client_id
    end

    Sessions.destroy(client_id)
  end

  def self.onmessage(websocket, msg)
    client_id = websocket.object_id.to_s
    log 'info', "receiving #{msg.to_s.bytesize} bytes", client_id
    log 'debug', "received: #{msg}", client_id
    begin
      log 'info', 'start: parse message to JSON', client_id
      data = JSON.parse(msg)
      log 'info', 'end: parse message to JSON', client_id
    rescue => e
      log 'error', "can't parse message: #{msg}, #{e.inspect}", client_id
      return
    end

    if !data.is_a?(Hash)
      log 'error', "unknown message '#{data.inspect}'", client_id
      return
    end

    # check if connection not already exists
    return if !@clients[client_id]

    Sessions.touch(client_id) # rubocop:disable Rails/SkipsModelValidations
    @clients[client_id][:last_ping] = Time.now.utc.to_i

    if data['event']
      log 'info', "start: execute event '#{data['event']}'", client_id
      message = Sessions::Event.run(
        event:     data['event'],
        payload:   data,
        session:   @clients[client_id][:session],
        headers:   @clients[client_id][:headers],
        client_id: client_id,
        client:    @clients[clien