Class: Faye::WebSocket::HybiParser::Handshake

Inherits:
Object
  • Object
show all
Defined in:
lib/faye/websocket/hybi_parser/handshake.rb

Constant Summary collapse

GUID =
'258EAFA5-E914-47DA-95CA-C5AB0DC85B11'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, protocols) ⇒ Handshake

Returns a new instance of Handshake.



10
11
12
13
14
15
16
# File 'lib/faye/websocket/hybi_parser/handshake.rb', line 10

def initialize(uri, protocols)
  @uri       = uri
  @protocols = protocols
  @key       = Base64.encode64((1..16).map { rand(255).chr } * '').strip
  @accept    = Base64.encode64(Digest::SHA1.digest(@key + GUID)).strip
  @buffer    = []
end

Instance Attribute Details

#protocolObject (readonly)

Returns the value of attribute protocol.



8
9
10
# File 'lib/faye/websocket/hybi_parser/handshake.rb', line 8

def protocol
  @protocol
end

Instance Method Details

#complete?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/faye/websocket/hybi_parser/handshake.rb', line 51

def complete?
  @buffer[-4..-1] == [0x0D, 0x0A, 0x0D, 0x0A]
end

#parse(data) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/faye/websocket/hybi_parser/handshake.rb', line 37

def parse(data)
  message  = []
  complete = false
  data.each_byte do |byte|
    if complete
      message << byte
    else
      @buffer << byte
      complete ||= complete?
    end
  end
  message
end

#request_dataObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/faye/websocket/hybi_parser/handshake.rb', line 18

def request_data
  hostname = @uri.host + (@uri.port ? ":#{@uri.port}" : '')

  headers = [
    "GET #{@uri.path}#{@uri.query ? '?' : ''}#{@uri.query} HTTP/1.1",
    "Host: #{hostname}",
    "Upgrade: websocket",
    "Connection: Upgrade",
    "Sec-WebSocket-Key: #{@key}",
    "Sec-WebSocket-Version: 13"
  ]

  if @protocols
    headers << "Sec-WebSocket-Protocol: #{@protocols * ', '}"
  end

  (headers + ['','']).join("\r\n")
end

#valid?Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/faye/websocket/hybi_parser/handshake.rb', line 55

def valid?
  data = WebSocket.encode(@buffer)

  response = Net::HTTPResponse.read_new(Net::BufferedIO.new(StringIO.new(data)))
  return false unless response.code.to_i == 101

  upgrade    = response['Upgrade']
  connection = response['Connection']
  protocol   = response['Sec-WebSocket-Protocol']

  @protocol = @protocols && @protocols.include?(protocol) ?
              protocol :
              nil

  upgrade and upgrade =~ /^websocket$/i and
  connection and connection.split(/\s*,\s*/).include?('Upgrade') and
  ((!@protocols and !protocol) or @protocol) and
  response['Sec-WebSocket-Accept'] == @accept
end