2020-08-11 11:04:26 +03:00
|
|
|
defmodule PlausibleWeb.RemoteIp do
|
|
|
|
def get(conn) do
|
2021-05-03 17:30:54 +03:00
|
|
|
cf_connecting_ip = List.first(Plug.Conn.get_req_header(conn, "cf-connecting-ip"))
|
2022-01-15 17:57:25 +03:00
|
|
|
x_forwarded_for = List.first(Plug.Conn.get_req_header(conn, "x-forwarded-for"))
|
|
|
|
b_forwarded_for = List.first(Plug.Conn.get_req_header(conn, "b-forwarded-for"))
|
2021-05-21 14:57:00 +03:00
|
|
|
forwarded = List.first(Plug.Conn.get_req_header(conn, "forwarded"))
|
2020-08-11 11:04:26 +03:00
|
|
|
|
2021-05-03 17:30:54 +03:00
|
|
|
cond do
|
|
|
|
cf_connecting_ip ->
|
2022-01-15 17:57:25 +03:00
|
|
|
clean_ip(cf_connecting_ip)
|
2021-05-03 17:30:54 +03:00
|
|
|
|
2022-01-15 17:57:25 +03:00
|
|
|
b_forwarded_for ->
|
|
|
|
parse_forwarded_for(b_forwarded_for)
|
|
|
|
|
|
|
|
x_forwarded_for ->
|
|
|
|
parse_forwarded_for(x_forwarded_for)
|
2021-05-03 17:30:54 +03:00
|
|
|
|
2021-05-21 14:57:00 +03:00
|
|
|
forwarded ->
|
|
|
|
Regex.named_captures(~r/for=(?<for>[^;,]+).*$/, forwarded)
|
|
|
|
|> Map.get("for")
|
|
|
|
# IPv6 addresses are enclosed in quote marks and square brackets: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
|
|
|
|
|> String.trim("\"")
|
2021-06-03 10:36:06 +03:00
|
|
|
|> clean_ip
|
2021-05-21 14:57:00 +03:00
|
|
|
|
2021-05-03 17:30:54 +03:00
|
|
|
true ->
|
|
|
|
to_string(:inet_parse.ntoa(conn.remote_ip))
|
2020-08-11 11:04:26 +03:00
|
|
|
end
|
|
|
|
end
|
2021-06-02 15:30:25 +03:00
|
|
|
|
2021-06-03 10:36:06 +03:00
|
|
|
# Removes port from both IPv4 and IPv6 addresses. From https://regexr.com/3hpvt
|
|
|
|
# Removes surrounding [] of an IPv6 address
|
|
|
|
@port_regex ~r/((\.\d+)|(\]))(?<port>:[0-9]+)$/
|
|
|
|
defp clean_ip(ip_and_port) do
|
|
|
|
ip =
|
|
|
|
case Regex.named_captures(@port_regex, ip_and_port) do
|
|
|
|
%{"port" => port} -> String.trim_trailing(ip_and_port, port)
|
|
|
|
_ -> ip_and_port
|
|
|
|
end
|
|
|
|
|
|
|
|
ip
|
|
|
|
|> String.trim_leading("[")
|
|
|
|
|> String.trim_trailing("]")
|
2021-06-02 15:30:25 +03:00
|
|
|
end
|
2022-01-15 17:57:25 +03:00
|
|
|
|
|
|
|
defp parse_forwarded_for(header) do
|
|
|
|
String.split(header, ",")
|
|
|
|
|> Enum.map(&String.trim/1)
|
|
|
|
|> List.first()
|
|
|
|
|> clean_ip
|
|
|
|
end
|
2020-08-11 11:04:26 +03:00
|
|
|
end
|