Class: EventMachine::WebSocket::HandlerFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/em-websocket/handler_factory.rb

Constant Summary collapse

PATH =
/^(\w+) (\/[^\s]*) HTTP\/1\.1$/
HEADER =
/^([^:]+):\s*(.+)$/

Class Method Summary collapse

Class Method Details

.build(data, secure = false, debug = false) ⇒ Object

Raises:



7
8
9
10
11
12
13
14
15
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
# File 'lib/em-websocket/handler_factory.rb', line 7

def self.build(data, secure = false, debug = false)
  request = {}
  response = nil

  lines = data.split("\r\n")

  # extract request path
  first_line = lines.shift.match(PATH)
  raise HandshakeError, "Invalid HTTP header" unless first_line
  request['Method'] = first_line[1].strip
  request['Path'] = first_line[2].strip

  unless request["Method"] == "GET"
    raise HandshakeError, "Must be GET request"
  end

  # extract query string values
  request['Query'] = Addressable::URI.parse(request['Path']).query_values ||= {}
  # extract remaining headers
  lines.each do |line|
    h = HEADER.match(line)
    request[h[1].strip] = h[2].strip if h
  end
  request['Third-Key'] = lines.last

  unless request['Connection'] == 'Upgrade' and request['Upgrade'] == 'WebSocket'
    raise HandshakeError, "Connection and Upgrade headers required"
  end

  # transform headers
  protocol = (secure ? "wss" : "ws")
  request['Host'] = Addressable::URI.parse("#{protocol}://"+request['Host'])

  version = request['Sec-WebSocket-Key1'] ? 76 : 75

  case version
  when 75
    Handler75.new(request, response, debug)
  when 76
    Handler76.new(request, response, debug)
  else
    raise WebSocketError, "Must not happen"
  end
end