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

81 lines
1.8 KiB
Ruby

module WebSocket
class Driver
class Server < Driver
EVENTS = %w[open message error close]
def initialize(socket, options = {})
super
@http = HTTP::Request.new
@delegate = nil
end
def env
@http.complete? ? @http.env : nil
end
def url
return nil unless e = env
url = "ws://#{e['HTTP_HOST']}"
url << e['PATH_INFO']
url << "?#{e['QUERY_STRING']}" unless e['QUERY_STRING'] == ''
url
end
%w[add_extension set_header start frame text binary ping close].each do |method|
define_method(method) do |*args, &block|
if @delegate
@delegate.__send__(method, *args, &block)
else
@queue << [method, args, block]
true
end
end
end
%w[protocol version].each do |method|
define_method(method) do
@delegate && @delegate.__send__(method)
end
end
def parse(chunk)
return @delegate.parse(chunk) if @delegate
@http.parse(chunk)
return fail_request('Invalid HTTP request') if @http.error?
return unless @http.complete?
@delegate = Driver.rack(self, @options)
open
EVENTS.each do |event|
@delegate.on(event) { |e| emit(event, e) }
end
emit(:connect, ConnectEvent.new)
end
def write(buffer)
@socket.write(buffer)
end
private
def fail_request(message)
emit(:error, ProtocolError.new(message))
emit(:close, CloseEvent.new(Hybi::ERRORS[:protocol_error], message))
end
def open
@queue.each do |method, args, block|
@delegate.__send__(method, *args, &block)
end
@queue = []
end
end
end
end