Class: Relay

Inherits:
EventMachine::Connection
  • Object
show all
Defined in:
lib/relay.rb

Instance Method Summary collapse

Constructor Details

#initialize(side, logproc) ⇒ Relay



2
3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/relay.rb', line 2

def initialize(side, logproc)
  super
  pause
  @ws = nil
  @sig = nil
  @completion = nil
  @closed = false
  @unbind_sent = false
  @unbind_recv = false
  @remote_ip = nil
  @connection_inactivity_timeout = 0.0
  @log = lambda { |msg, **ctx| logproc[msg, side: side, ip: @remote_ip, sig: @sig, **ctx] }
end

Instance Method Details

#bind(ws, remote_ip) ⇒ Object



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
# File 'lib/relay.rb', line 16

def bind(ws, remote_ip)
  @ws = ws
  @sig = "#{ws.signature}.#{signature}"
  @completion = EventMachine::Completion.new
  @closed = false
  @unbind_sent = false
  @unbind_recv = false
  @remote_ip = remote_ip
  @connection_inactivity_timeout = comm_inactivity_timeout
  @log.call "[+] bind."
  @ws.onbinary do |data|
    if @closed
      @log.call "[~] data discard, bound closed.", connerror: error?, bytes: data.bytesize
    else
      send_data(data)
    end
  end
  @ws.onmessage do |msg|
    if msg == "unbind"
      @unbind_recv = true
      if @unbind_sent
        @completion.succeed
      else
        close_connection
      end
    else
      @log.call "[!] unexpected text on websocket.", msg: msg
    end
  end
  @ws.onclose do
    close_connection
    @completion.fail
    close_info = @ws.instance_variable_get(:@handler).instance_variable_get(:@close_info) || {}
    code = close_info[:code]
    reason = close_info[:reason]
    if reason
      reason = reason.empty? ? nil : reason.inspect
    end
    @log.call "[-] websocket is closed.", code: code, reason: reason
  end
  resume
  @completion
end

#receive_data(data) ⇒ Object



60
61
62
# File 'lib/relay.rb', line 60

def receive_data(data)
  @ws.send_binary(data)
end

#unbind(errno) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/relay.rb', line 64

def unbind(errno)
  if errno
    if errno == Errno::ETIMEDOUT && @connection_inactivity_timeout > 0
      reason = "inactivity"
    elsif errno.respond_to?(:exception)
      reason = errno.exception.message
      reason[0] = reason[0].downcase
    else
      # win: errno can be set to :unknown on windows
      reason = errno.to_s
    end
    reason = reason.inspect
  end
  @log.call "[-] unbind.", reason: reason
  @closed = true
  if @ws&.state == :connected
    @ws.send_text("unbind")
    @unbind_sent = true
    @completion&.succeed if @unbind_recv
  end
end