2019-09-27 21:59:23 +00:00
|
|
|
# Pleroma: A lightweight social networking server
|
2021-01-13 06:49:20 +00:00
|
|
|
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
|
2019-09-27 21:59:23 +00:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2020-06-24 06:30:32 +00:00
|
|
|
defmodule Pleroma.Web.Plugs.RemoteIp do
|
2019-09-27 21:59:23 +00:00
|
|
|
@moduledoc """
|
|
|
|
This is a shim to call [`RemoteIp`](https://git.pleroma.social/pleroma/remote_ip) but with runtime configuration.
|
|
|
|
"""
|
|
|
|
|
2020-10-06 22:02:46 +00:00
|
|
|
alias Pleroma.Config
|
2020-03-13 18:15:42 +00:00
|
|
|
|
2019-09-27 21:59:23 +00:00
|
|
|
@behaviour Plug
|
|
|
|
|
|
|
|
def init(_), do: nil
|
|
|
|
|
2020-03-13 18:15:42 +00:00
|
|
|
def call(%{remote_ip: original_remote_ip} = conn, _) do
|
2020-10-06 22:02:46 +00:00
|
|
|
if Config.get([__MODULE__, :enabled]) do
|
2022-12-14 12:38:48 +00:00
|
|
|
{headers, proxies} = remote_ip_opts()
|
|
|
|
new_remote_ip = RemoteIp.from(conn.req_headers, headers: headers, proxies: proxies)
|
|
|
|
|
|
|
|
if new_remote_ip != original_remote_ip do
|
|
|
|
Map.put(conn, :remote_ip, new_remote_ip)
|
|
|
|
else
|
|
|
|
conn
|
|
|
|
end
|
2019-09-27 21:59:23 +00:00
|
|
|
else
|
|
|
|
conn
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-10-06 22:26:31 +00:00
|
|
|
defp remote_ip_opts do
|
2022-12-14 12:38:48 +00:00
|
|
|
headers = Config.get([__MODULE__, :headers], [])
|
2020-10-06 22:02:46 +00:00
|
|
|
reserved = Config.get([__MODULE__, :reserved], [])
|
2019-09-27 21:59:23 +00:00
|
|
|
|
|
|
|
proxies =
|
2020-10-06 22:02:46 +00:00
|
|
|
Config.get([__MODULE__, :proxies], [])
|
2019-09-27 21:59:23 +00:00
|
|
|
|> Enum.concat(reserved)
|
2020-10-05 16:48:41 +00:00
|
|
|
|> Enum.map(&maybe_add_cidr/1)
|
2019-09-27 21:59:23 +00:00
|
|
|
|
|
|
|
{headers, proxies}
|
|
|
|
end
|
2020-10-05 16:48:41 +00:00
|
|
|
|
|
|
|
defp maybe_add_cidr(proxy) when is_binary(proxy) do
|
2022-12-14 12:38:48 +00:00
|
|
|
cond do
|
|
|
|
"/" in String.codepoints(proxy) -> proxy
|
|
|
|
InetCidr.v4?(InetCidr.parse_address!(proxy)) -> proxy <> "/32"
|
|
|
|
InetCidr.v6?(InetCidr.parse_address!(proxy)) -> proxy <> "/128"
|
|
|
|
end
|
2020-10-05 16:48:41 +00:00
|
|
|
end
|
2019-09-27 21:59:23 +00:00
|
|
|
end
|