Class: Lich::Common::WebSocket::Stream

Inherits:
Object
  • Object
show all
Defined in:
documented/common/websocket/stream.rb

Overview

A WebSocket connection presented as a drop-in replacement for the TCPSocket that Games::Game.open normally hands to @socket: #puts, #gets, #wait_readable, #close, #closed?, #sync=, #to_io. Everything above the transport (line-based XML parsing, the reader/parser threads) stays unaware that the bytes underneath are riding inside RFC 6455 frames over TLS on 443 instead of a raw game-port socket -- see Genie5#356 phase 2.

See Also:

Defined Under Namespace

Classes: ConnectionError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io, prefill: "".b) ⇒ Stream

Returns a new instance of Stream.

Parameters:

  • io (OpenSSL::SSL::SSLSocket) —

    a connected socket, past the WS opening handshake

  • prefill (String) (defaults to: "".b) —

    any frame bytes already read past the handshake response



116
117
118
119
120
121
122
123
124
125
# File 'documented/common/websocket/stream.rb', line 116

def initialize(io, prefill: "".b)
  @io = io
  @reader = Frame::Reader.new
  @line_buffer = +"".b
  @write_mutex = Mutex.new
  @closed = false
  @eof = false
  @pending_error = nil
  ingest(@reader.feed(prefill)) unless prefill.empty?
end

Class Method Details

.connect(host:, port:, path:, origin: nil, subprotocol: nil, user_agent: nil, extra_headers: {}, connect_timeout: 10) {|Socket| ... } ⇒ Stream

Opens a TCP connection, wraps it in TLS, performs the WebSocket opening handshake, and returns a ready-to-use Stream.

Parameters:

  • host (String) —

    hostname to dial, present via SNI, verify the TLS certificate against, and send as the handshake's Host header -- all four uses share the one value, exactly like a browser's new WebSocket(url) derives all of them from the URL's host. Callers that need a different hostname than the raw GAMEHOST (see GameTransport, which knows the real client dials a fixed per-family host rather than the literal GAMEHOST) are expected to resolve that before calling here, not pass the unresolved GAMEHOST and expect this method to compensate.

  • port (Integer) —

    TCP port to connect to (443 for the shim)

  • path (String) —

    request path, e.g. "/shim/1234"

  • origin (String, nil) (defaults to: nil) —

    Origin header for the handshake

  • subprotocol (String, nil) (defaults to: nil) —

    Sec-WebSocket-Protocol to request

  • user_agent (String, nil) (defaults to: nil) —

    User-Agent header for the handshake

  • extra_headers (Hash) (defaults to: {}) —

    extra handshake headers

  • connect_timeout (Numeric) (defaults to: 10) —

    seconds to bound the TCP connect

Yields:

  • (Socket) —

    the raw, not-yet-TLS-wrapped socket, immediately after connect -- the hook GameTransport uses to apply SocketConfigurator before TLS/WS overhead begins

Returns:

Raises:



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'documented/common/websocket/stream.rb', line 50

def self.connect(host:, port:, path:, origin: nil, subprotocol: nil,
                 user_agent: nil, extra_headers: {}, connect_timeout: 10)
  connected = false
  raw_socket = Socket.tcp(host, port, connect_timeout: connect_timeout)
  yield raw_socket if block_given?

  ssl_socket = wrap_tls(raw_socket, host)
  key = Handshake.generate_key
  ssl_socket.write(Handshake.request(host: host, path: path, key: key, origin: origin,
                                     subprotocol: subprotocol, user_agent: user_agent,
                                     extra_headers: extra_headers))

  header_block, remainder = read_handshake_response(ssl_socket)
  Handshake.validate_response(header_block, key: key, subprotocol: subprotocol)

  stream = new(ssl_socket, prefill: remainder)
  # Deliberately after new, not before: initialize feeds +remainder+
  # through the frame reader, which can itself raise (a malformed
  # frame arriving in the same TLS read as the 101) -- setting this
  # any earlier would make the ensure below think the connect
  # succeeded and skip closing raw_socket on exactly that failure.
  connected = true
  stream
rescue StandardError => e
  raise ConnectionError, "#{e.class}: #{e.message}"
ensure
  # rescue alone misses a stalled connect/handshake killed via
  # Thread#kill (open_with_timeout's connect-timeout watchdog) --
  # Thread#kill skips rescue but still runs ensure.
  raw_socket.close if raw_socket && !connected && !raw_socket.closed?
end

Instance Method Details

#close ⇒ Object

Best-effort close handshake, then tears down the underlying socket.



193
194
195
196
197
198
199
200
# File 'documented/common/websocket/stream.rb', line 193

def close
  write_frame([1000].pack("n"), opcode: Frame::OPCODE_CLOSE) unless @closed
rescue StandardError
  nil
ensure
  @closed = true
  @io.close rescue nil
end

#closed? ⇒ Boolean

Returns true if the stream is closed or the underlying socket is closed.

Returns:

  • (Boolean)


205
206
207
# File 'documented/common/websocket/stream.rb', line 205

def closed?
  @closed || @io.closed?
end

#gets ⇒ String?

Blocks until a full line is available and returns it (including its trailing newline, matching IO#gets), or returns nil at EOF. A final, non-newline-terminated fragment left over at EOF is returned once, then subsequent calls return nil -- also matching IO#gets. A framing violation defers the same way EOF does: any lines it decoded before hitting the violation are returned first, one #gets call at a time, and only once the buffer is drained does the stashed error actually raise -- so a caller salvages the last, most explanatory lines before the connection is torn down instead of losing them to the exception that unwound past them.

Returns:

Raises:



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'documented/common/websocket/stream.rb', line 153

def gets
  loop do
    line = extract_line!
    return line if line

    if @pending_error
      # A newline-less tail decoded before the violation is exactly
      # the kind of data #decoded_messages exists to preserve --
      # flush it the same way EOF does before finally raising, so
      # the deferred error doesn't defeat that as its very last step.
      tail = flush_remaining!
      return tail if tail

      raise @pending_error
    end

    return flush_remaining! if @eof

    pump_until_readable!
  end
end

#puts(str) ⇒ true

Sends str as a single text frame, appending "\n" if it doesn't already end with one -- mirroring IO#puts, which is what callers (Game._puts) expect.

Parameters:

Returns:

  • (true)


133
134
135
136
137
138
# File 'documented/common/websocket/stream.rb', line 133

def puts(str)
  line = str.to_s
  line = "#{line}\n" unless line.end_with?("\n")
  write_frame(line, opcode: Frame::OPCODE_TEXT)
  true
end

#sync=(_value) ⇒ Object

No-op: every #puts already writes one complete frame in a single #write call, so there's no internal buffering to flush.



211
212
213
# File 'documented/common/websocket/stream.rb', line 211

def sync=(_value)
  true
end

#to_io ⇒ IO

Returns the underlying IO object for use with IO#select and similar calls.

Returns:

  • (IO)


218
219
220
# File 'documented/common/websocket/stream.rb', line 218

def to_io
  @io.to_io
end

#wait_readable(timeout = nil) ⇒ Boolean

Returns true once a #gets call can return (with a line or by raising @pending_error) without blocking on the network.

Parameters:

  • timeout (Numeric, nil) (defaults to: nil) —

    seconds to wait; nil blocks indefinitely

Returns:

  • (Boolean) —

    true once a #gets call can return (with a line or by raising @pending_error) without blocking on the network



178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'documented/common/websocket/stream.rb', line 178

def wait_readable(timeout = nil)
  return true if line_ready? || @eof || @pending_error

  deadline = timeout ? monotonic_now + timeout : nil
  loop do
    return true if line_ready? || @eof || @pending_error

    remaining = deadline ? deadline - monotonic_now : nil
    return false if deadline && remaining <= 0

    return true if pump_once(remaining)
  end
end