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

69 lines
1.7 KiB
Ruby

module WebSocket
class Driver
class Proxy
include EventEmitter
PORTS = {'ws' => 80, 'wss' => 443}
attr_reader :status, :headers
def initialize(client, origin, options)
super()
@client = client
@http = HTTP::Response.new
@socket = client.instance_variable_get(:@socket)
@origin = URI.parse(@socket.url)
@url = URI.parse(origin)
@options = options
@state = 0
@headers = Headers.new
@headers['Host'] = @origin.host + (@origin.port ? ":#{@origin.port}" : '')
@headers['Connection'] = 'keep-alive'
@headers['Proxy-Connection'] = 'keep-alive'
if @url.user
auth = Base64.strict_encode64([@url.user, @url.password] * ':')
@headers['Proxy-Authorization'] = 'Basic ' + auth
end
end
def set_header(name, value)
return false unless @state == 0
@headers[name] = value
true
end
def start
return false unless @state == 0
@state = 1
port = @origin.port || PORTS[@origin.scheme]
start = "CONNECT #{@origin.host}:#{port} HTTP/1.1"
headers = [start, @headers.to_s, '']
@socket.write(headers.join("\r\n"))
true
end
def parse(chunk)
@http.parse(chunk)
return unless @http.complete?
@status = @http.code
@headers = Headers.new(@http.headers)
if @status == 200
emit(:connect, ConnectEvent.new)
else
message = "Can't establish a connection to the server at #{@socket.url}"
emit(:error, ProtocolError.new(message))
end
end
end
end
end