Files
James Coglan 9ce857b3d4 Revise uses of encoding APIs.
When originally implemented, we still supported Ruby 1.8, which
necessitated checking for encoding methods and using a regex to validate
UTF-8. These checks are now gone.

We tagged many strings as binary when not strictly necessary, either
because we were just going to iterate their bytes or because we were
going to hand them off to the caller which should just write them
directly to a socket. Strings used as buffers to accumulate streaming
input are still tagged as binary to avoid encoding
collision/conversion.

The places where we do need to tag as UTF-8 (i.e. just before emitting
to the application) remain, but copy the string if necessary. This
allows us to work with frozen strings.

Finally, strings passed in via the Driver#text method should be
*transcoded* to UTF-8 if necessary, not merely tagged. The Ruby
String#encode method produces a new string so this should also be safe
with frozen strings.
2016-05-19 21:08:22 +01:00

103 lines
2.4 KiB
Ruby

module WebSocket
class Driver
class Draft75 < Driver
def initialize(socket, options = {})
super
@stage = 0
@closing = false
@headers['Upgrade'] = 'WebSocket'
@headers['Connection'] = 'Upgrade'
@headers['WebSocket-Origin'] = @socket.env['HTTP_ORIGIN']
@headers['WebSocket-Location'] = @socket.url
end
def version
'hixie-75'
end
def close(reason = nil, code = nil)
return false if @ready_state == 3
@ready_state = 3
emit(:close, CloseEvent.new(nil, nil))
true
end
def parse(chunk)
return if @ready_state > 1
@reader.put(chunk)
@reader.each_byte do |octet|
case @stage
when -1 then
@body << octet
send_handshake_body
when 0 then
parse_leading_byte(octet)
when 1 then
@length = (octet & 0x7F) + 128 * @length
if @closing and @length.zero?
return close
elsif (octet & 0x80) != 0x80
if @length.zero?
@stage = 0
else
@skipped = 0
@stage = 2
end
end
when 2 then
if octet == 0xFF
@stage = 0
emit(:message, MessageEvent.new(Driver.encode(@buffer, UNICODE)))
else
if @length
@skipped += 1
@stage = 0 if @skipped == @length
else
@buffer << octet
return close if @buffer.size > @max_length
end
end
end
end
end
def frame(buffer, type = nil, error_type = nil)
return queue([buffer, type, error_type]) if @ready_state == 0
frame = [0x00, buffer, 0xFF].pack('CA*C')
@socket.write(frame)
true
end
private
def handshake_response
start = 'HTTP/1.1 101 Web Socket Protocol Handshake'
headers = [start, @headers.to_s, '']
headers.join("\r\n")
end
def parse_leading_byte(octet)
if (octet & 0x80) == 0x80
@length = 0
@stage = 1
else
@length = nil
@skipped = nil
@buffer = []
@stage = 2
end
end
end
end
end