Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

initial proxy support #107

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions lib/websockex.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1010,6 +1010,27 @@ defmodule WebSockex do
end
end

defp open_connection(parent, debug, %{conn: conn, proxy_host: nil} = state) do
my_pid = self()
debug = Utils.sys_debug(debug, :connect, state)

task =
Task.async(fn ->
with {:ok, conn} <- WebSockex.Conn.open_socket(conn),
key <- :crypto.strong_rand_bytes(16) |> Base.encode64(),
{:ok, request} <- WebSockex.Conn.build_request(conn, key),
:ok <- WebSockex.Conn.socket_send(conn, request),
{:ok, headers} <- WebSockex.Conn.handle_response(conn, my_pid),
:ok <- validate_handshake(headers, key) do
:ok = WebSockex.Conn.controlling_process(conn, my_pid)
:ok = WebSockex.Conn.set_active(conn)
{:ok, conn}
end
end)

open_loop(parent, debug, Map.put(state, :task, task))
end

defp open_connection(parent, debug, %{conn: conn} = state) do
my_pid = self()
debug = Utils.sys_debug(debug, :connect, state)
Expand All @@ -1018,6 +1039,9 @@ defmodule WebSockex do
Task.async(fn ->
with {:ok, conn} <- WebSockex.Conn.open_socket(conn),
key <- :crypto.strong_rand_bytes(16) |> Base.encode64(),
{:ok, proxy_request} <- WebSockex.Conn.build_proxy_request(conn, conn.proxy_username, conn.proxy_password),
:ok <- WebSockex.Conn.socket_send(conn, proxy_request),
{:ok, _proxy_headers} <- WebSockex.Conn.handle_proxy_response(conn),
{:ok, request} <- WebSockex.Conn.build_request(conn, key),
:ok <- WebSockex.Conn.socket_send(conn, request),
{:ok, headers} <- WebSockex.Conn.handle_response(conn, my_pid),
Expand Down
74 changes: 71 additions & 3 deletions lib/websockex/conn.ex
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ defmodule WebSockex.Conn do
cacerts: nil,
insecure: true,
resp_headers: [],
ssl_options: nil
ssl_options: nil,
proxy_host: nil,
proxy_port: 0,
proxy_username: nil,
proxy_password: nil

@type socket :: :gen_tcp.socket() | :ssl.sslsocket()
@type header :: {field :: String.t(), value :: String.t()}
Expand Down Expand Up @@ -95,7 +99,11 @@ defmodule WebSockex.Conn do
socket_connect_timeout:
Keyword.get(opts, :socket_connect_timeout, @socket_connect_timeout_default),
socket_recv_timeout: Keyword.get(opts, :socket_recv_timeout, @socket_recv_timeout_default),
ssl_options: Keyword.get(opts, :ssl_options, nil)
ssl_options: Keyword.get(opts, :ssl_options, nil),
proxy_host: Keyword.get(opts, :proxy_host, nil),
proxy_port: Keyword.get(opts, :proxy_port, 3128),
proxy_username: Keyword.get(opts, :proxy_username, nil),
proxy_password: Keyword.get(opts, :proxy_password, nil)
}
end

Expand Down Expand Up @@ -149,7 +157,7 @@ defmodule WebSockex.Conn do
@spec open_socket(__MODULE__.t()) :: {:ok, __MODULE__.t()} | {:error, term}
def open_socket(conn)

def open_socket(%{conn_mod: :gen_tcp} = conn) do
def open_socket(%{conn_mod: :gen_tcp, proxy_host: nil} = conn) do
case :gen_tcp.connect(
String.to_charlist(conn.host),
conn.port,
Expand Down Expand Up @@ -179,6 +187,21 @@ defmodule WebSockex.Conn do
end
end

def open_socket(%{conn_mod: :gen_tcp} = conn) do
case :gen_tcp.connect(
String.to_charlist(conn.proxy_host),
conn.proxy_port,
[:binary, active: false, packet: 0],
conn.socket_connect_timeout
) do
{:ok, socket} ->
{:ok, Map.put(conn, :socket, socket)}

{:error, error} ->
{:error, %WebSockex.ConnError{original: error}}
end
end

@doc """
Closes the socket and returns the Conn map without the socket.

Expand Down Expand Up @@ -219,6 +242,24 @@ defmodule WebSockex.Conn do
{:ok, request <> "\r\n\r\n"}
end

def build_proxy_request(conn, proxy_username, proxy_password) do
headers =
[{"Host", conn.host}, {"Proxy-Connection", "keep-alive"}]
|> Enum.map(&format_header/1)

if proxy_username != nil and proxy_password != nil do
end

proxy_credentials = "c3Q1YXY1b2wwd2Rsbms6aW02aTFyNmRoc2pqemc3ZHdtcDRhM2R1dHg="
headers = [format_header({"Proxy-Authorization", "Basic #{proxy_credentials}"}) | headers]

request =
["CONNECT #{conn.host}:#{conn.port} HTTP/1.1" | headers]
|> Enum.join("\r\n")

{:ok, request <> "\r\n\r\n"}
end

@doc """
Waits for the request response, decodes the packet, and returns the response
headers.
Expand All @@ -239,6 +280,20 @@ defmodule WebSockex.Conn do
end
end

@spec handle_proxy_response(__MODULE__.t()) ::
{:ok, [header]} | {:error, reason :: term}
def handle_proxy_response(conn) do
with {:ok, buffer} <- wait_for_response(conn),
{:ok, headers, buffer} <- decode_proxy_response(buffer) do
# Send excess buffer back to the process
unless buffer == "" do
send(self(), {transport(conn.conn_mod), conn.socket, buffer})
end

{:ok, headers}
end
end

@doc """
Sets the socket to active.
"""
Expand Down Expand Up @@ -307,6 +362,19 @@ defmodule WebSockex.Conn do
end
end

defp decode_proxy_response(response) do
case :erlang.decode_packet(:http_bin, response, []) do
{:ok, {:http_response, _version, 200, _message}, rest} ->
decode_headers(rest)

{:ok, {:http_response, _, code, message}, _} ->
{:error, %WebSockex.RequestError{code: code, message: message}}

{:error, error} ->
{:error, error}
end
end

defp decode_headers(rest, headers \\ []) do
case :erlang.decode_packet(:httph_bin, rest, []) do
{:ok, {:http_header, _len, field, _res, value}, rest} ->
Expand Down