class DEBUGGER__::UI_CDP::WebSocketServer

Public Class Methods

new(s) click to toggle source
# File debug-1.4.0/lib/debug/server_cdp.rb, line 171
def initialize s
  @sock = s
end

Public Instance Methods

extract_data() click to toggle source
# File debug-1.4.0/lib/debug/server_cdp.rb, line 212
def extract_data
  first_group = @sock.getbyte
  fin = first_group & 0b10000000 != 128
  raise 'Unsupported' if fin

  opcode = first_group & 0b00001111
  raise Detach if opcode == 8
  raise "Unsupported: #{opcode}" unless opcode == 1

  second_group = @sock.getbyte
  mask = second_group & 0b10000000 == 128
  raise 'The client must mask all frames' unless mask
  payload_len = second_group & 0b01111111
  # TODO: Support other payload_lengths
  if payload_len == 126
    payload_len = @sock.gets(2).unpack('n*')[0]
  end

  masking_key = []
  4.times { masking_key << @sock.getbyte }
  unmasked = []
  payload_len.times do |n|
    masked = @sock.getbyte
    unmasked << (masked ^ masking_key[n % 4])
  end
  JSON.parse unmasked.pack 'c*'
end
handshake() click to toggle source
# File debug-1.4.0/lib/debug/server_cdp.rb, line 175
def handshake
  req = @sock.readpartial 4096
  $stderr.puts '[>]' + req if SHOW_PROTOCOL

  if req.match /^Sec-WebSocket-Key: (.*)\r\n/
    accept = Base64.strict_encode64 Digest::SHA1.digest "#{$1}258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
    @sock.print "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: #{accept}\r\n\r\n"
  else
    "Unknown request: #{req}"
  end
end
send(**msg) click to toggle source
# File debug-1.4.0/lib/debug/server_cdp.rb, line 187
def send **msg
  msg = JSON.generate(msg)
  frame = []
  fin = 0b10000000
  opcode = 0b00000001
  frame << fin + opcode

  mask = 0b00000000 # A server must not mask any frames in a WebSocket Protocol.
  bytesize = msg.bytesize
  if bytesize < 126
    payload_len = bytesize
  elsif bytesize < 2 ** 16
    payload_len = 0b01111110
    ex_payload_len = [bytesize].pack('n*').bytes
  else
    payload_len = 0b01111111
    ex_payload_len = [bytesize].pack('Q>').bytes
  end

  frame << mask + payload_len
  frame.push *ex_payload_len if ex_payload_len
  frame.push *msg.bytes
  @sock.print frame.pack 'c*'
end