Module: Lich::Common::WebSocket::Frame

Defined in:
documented/common/websocket/frame.rb

Overview

Hand-rolled RFC 6455 frame encode/decode.

Deliberately not pulled from a gem: this is the piece Genie5#356 flags as needing to be bent to whatever the shim's real handshake and framing behavior turns out to be once probed live (subprotocol, Origin enforcement, fragmentation quirks). A small, self-contained implementation is easier to adjust for that than a general-purpose WebSocket client built around browser semantics.

See Also:

Defined Under Namespace

Classes: Message, ProtocolError, Reader

Constant Summary collapse

OPCODE_CONTINUATION =

Opcodes defined by RFC 6455 5.2.

0x0
OPCODE_TEXT =

RFC 6455 opcode for text frames.

0x1
OPCODE_BINARY =

RFC 6455 opcode for binary frames.

0x2
OPCODE_CLOSE =

RFC 6455 opcode for close frames.

0x8
OPCODE_PING =

RFC 6455 opcode for ping frames.

0x9
OPCODE_PONG =

RFC 6455 opcode for pong frames.

0xA
CONTROL_OPCODES =

Set of control opcodes (close, ping, pong) per RFC 6455 5.5.

[OPCODE_CLOSE, OPCODE_PING, OPCODE_PONG].freeze
DATA_OPCODES =

Set of data opcodes (continuation, text, binary) per RFC 6455.

[OPCODE_CONTINUATION, OPCODE_TEXT, OPCODE_BINARY].freeze

Class Method Summary collapse

Class Method Details

.apply_mask(bytes, key) ⇒ String

XORs bytes against a repeating 4-byte key (RFC 6455 5.3). The operation is its own inverse, so this both masks and unmasks.

Parameters:

Returns:

  • (String) —

    a new, masked/unmasked copy of bytes



109
110
111
112
113
114
115
116
117
118
# File 'documented/common/websocket/frame.rb', line 109

def self.apply_mask(bytes, key)
  out = bytes.b
  size = out.bytesize
  i = 0
  while i < size
    out.setbyte(i, out.getbyte(i) ^ key.getbyte(i % 4))
    i += 1
  end
  out
end

.encode(payload, opcode: OPCODE_TEXT) ⇒ String

Builds a single, unfragmented, masked client-to-server frame. Client frames MUST be masked (RFC 6455 5.1); the mask key is generated fresh per frame.

Parameters:

  • payload (String) —

    frame payload; sent as raw (ASCII-8BIT) bytes regardless of the input string's own encoding

  • opcode (Integer) (defaults to: OPCODE_TEXT) —

    one of the OPCODE_* constants

Returns:

  • (String) —

    raw bytes ready to write to the socket



91
92
93
94
95
96
97
98
99
100
101
# File 'documented/common/websocket/frame.rb', line 91

def self.encode(payload, opcode: OPCODE_TEXT)
  payload = payload.to_s.b
  mask_key = SecureRandom.bytes(4)

  frame = +"".b
  frame << (0x80 | (opcode & 0x0F)) # FIN=1, RSV1-3=0
  frame << length_byte_sequence(payload.bytesize)
  frame << mask_key
  frame << apply_mask(payload, mask_key)
  frame
end