logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma

remote_ip.ex (1323B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Plugs.RemoteIp do
  5. @moduledoc """
  6. This is a shim to call [`RemoteIp`](https://git.pleroma.social/pleroma/remote_ip) but with runtime configuration.
  7. """
  8. import Plug.Conn
  9. @behaviour Plug
  10. @headers ~w[
  11. x-forwarded-for
  12. ]
  13. # https://en.wikipedia.org/wiki/Localhost
  14. # https://en.wikipedia.org/wiki/Private_network
  15. @reserved ~w[
  16. 127.0.0.0/8
  17. ::1/128
  18. fc00::/7
  19. 10.0.0.0/8
  20. 172.16.0.0/12
  21. 192.168.0.0/16
  22. ]
  23. def init(_), do: nil
  24. def call(%{remote_ip: original_remote_ip} = conn, _) do
  25. config = Pleroma.Config.get(__MODULE__, [])
  26. if Keyword.get(config, :enabled, false) do
  27. %{remote_ip: new_remote_ip} = conn = RemoteIp.call(conn, remote_ip_opts(config))
  28. assign(conn, :remote_ip_found, original_remote_ip != new_remote_ip)
  29. else
  30. conn
  31. end
  32. end
  33. defp remote_ip_opts(config) do
  34. headers = config |> Keyword.get(:headers, @headers) |> MapSet.new()
  35. reserved = Keyword.get(config, :reserved, @reserved)
  36. proxies =
  37. config
  38. |> Keyword.get(:proxies, [])
  39. |> Enum.concat(reserved)
  40. |> Enum.map(&InetCidr.parse/1)
  41. {headers, proxies}
  42. end
  43. end