Skip to content

Commit

Permalink
proxy: add final parts for a working proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
RTUnreal committed May 14, 2024
1 parent f21c4e9 commit 05638eb
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions service/proxy/lib/proxy.ex
Original file line number Diff line number Diff line change
Expand Up @@ -68,24 +68,40 @@ defmodule Proxy do
device = Application.fetch_env!(:proxy, :device)

case :gen_tcp.connect(
host,
host |> to_charlist(),
port,
[
# :binary,
# packet: :raw,
:binary,
packet: :raw,
bind_to_device: device,
active: false
],
5
]
) do
{:ok, conn} ->
try do
{:ok, {conaddr, conport}} = :inet.sockname(conn)
Logger.info("local sock: #{:inet.ntoa(conaddr)}:#{conport}")

:gen_tcp.send(
socket,
<<5, 0, 0, 1>> <>
(conaddr
|> Tuple.to_list()
|> Enum.map(&:binary.encode_unsigned/1)
|> Enum.join()) <>
:binary.encode_unsigned(conport)
)

:inet.setopts(socket, active: true)
:inet.setopts(conn, active: true)
loop_sender(socket, conn)
after
:gen_tcp.close(conn)
end

{:error, :ehostunreach} ->
throw_socks_error(socket, 4, "host unreachable")

{:error, :econnrefused} ->
throw_socks_error(socket, 5, "connection refused")

Expand All @@ -100,6 +116,21 @@ defmodule Proxy do
end
end

defp loop_sender(socket, conn) do
receive do
{:tcp, s, data} ->
case s do
^socket ->
:gen_tcp.send(conn, data)

^conn ->
:gen_tcp.send(socket, data)
end
end

loop_sender(socket, conn)
end

defp handle_rfc1929_auth(socket) do
:gen_tcp.send(socket, <<5, 0x2>>)
username = recv(socket, 2, fn <<1, nusername>> -> recv(socket, nusername, & &1) end)
Expand Down

0 comments on commit 05638eb

Please sign in to comment.