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

Forwarding random port with upnpc #700 #810

Merged
merged 9 commits into from
Jan 12, 2023
32 changes: 24 additions & 8 deletions lib/archethic/networking/port_forwarding.ex
Original file line number Diff line number Diff line change
Expand Up @@ -40,24 +40,35 @@ defmodule Archethic.Networking.PortForwarding do

defp do_try_open_port(port), do: NATDiscovery.open_port(port)

defp fallback(port, _force? = true) do
case do_try_open_port(0) do
defp fallback(port, force?, retries \\ 10)

defp fallback(_, _force? = true, 0) do
Logger.error(
"Port from configuration is used but requires a manuel port forwarding setting on the router"
)

:error
end

defp fallback(port, _force? = true, retries) do
# // If the port is not open, try to open a random port
Logger.info("Trying to open a random port")

rand_port = get_random_port()

case do_try_open_port(rand_port) do
{:ok, port} ->
Logger.info("Use the random port #{port} as fallback")
{:ok, port}

:error ->
Logger.error("Cannot publish the a random port #{port}")

Logger.error(
"Port from configuration is used but requires a manuel port forwarding setting on the router"
)

:error
fallback(port, _force? = true, retries - 1)
end
end

defp fallback(port, _force? = false) do
defp fallback(port, _force? = false, _) do
Logger.warning("No fallback provided for the port #{port}")

Logger.warning(
Expand All @@ -70,4 +81,9 @@ defmodule Archethic.Networking.PortForwarding do
defp ip_lookup_provider do
Application.get_env(:archethic, IPLookup)
end

defp get_random_port() do
49_152..65_535
apoorv-2204 marked this conversation as resolved.
Show resolved Hide resolved
|> Enum.random()
end
end