1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.HTTP.Connection do
7 Configure Tesla.Client with default and customized adapter options.
11 alias Pleroma.HTTP.AdapterHelper
15 @defaults [pool: :federation]
17 @type ip_address :: ipv4_address() | ipv6_address()
18 @type ipv4_address :: {0..255, 0..255, 0..255, 0..255}
20 {0..65_535, 0..65_535, 0..65_535, 0..65_535, 0..65_535, 0..65_535, 0..65_535, 0..65_535}
21 @type proxy_type() :: :socks4 | :socks5
22 @type host() :: charlist() | ip_address()
25 Merge default connection & adapter options with received ones.
28 @spec options(URI.t(), keyword()) :: keyword()
29 def options(%URI{} = uri, opts \\ []) do
32 |> Keyword.merge(opts)
33 |> adapter().options(uri)
36 defp pool_timeout(opts) do
37 {config_key, default} =
38 if Application.get_env(:tesla, :adapter) == Tesla.Adapter.Gun do
39 {:pools, Config.get([:pools, :default, :timeout])}
41 {:hackney_pools, 10_000}
44 timeout = Config.get([config_key, opts[:pool], :timeout], default)
46 Keyword.merge(opts, timeout: timeout)
49 @spec after_request(keyword()) :: :ok
50 def after_request(opts), do: adapter().after_request(opts)
53 case Application.get_env(:tesla, :adapter) do
54 Tesla.Adapter.Gun -> AdapterHelper.Gun
55 Tesla.Adapter.Hackney -> AdapterHelper.Hackney
60 @spec parse_proxy(String.t() | tuple() | nil) ::
61 {:ok, host(), pos_integer()}
62 | {:ok, proxy_type(), host(), pos_integer()}
66 def parse_proxy(nil), do: nil
68 def parse_proxy(proxy) when is_binary(proxy) do
69 with [host, port] <- String.split(proxy, ":"),
70 {port, ""} <- Integer.parse(port) do
71 {:ok, parse_host(host), port}
74 Logger.warn("Parsing port failed #{inspect(proxy)}")
75 {:error, :invalid_proxy_port}
78 Logger.warn("Parsing port failed #{inspect(proxy)}")
79 {:error, :invalid_proxy_port}
82 Logger.warn("Parsing proxy failed #{inspect(proxy)}")
83 {:error, :invalid_proxy}
87 def parse_proxy(proxy) when is_tuple(proxy) do
88 with {type, host, port} <- proxy do
89 {:ok, type, parse_host(host), port}
92 Logger.warn("Parsing proxy failed #{inspect(proxy)}")
93 {:error, :invalid_proxy}
97 @spec parse_host(String.t() | atom() | charlist()) :: charlist() | ip_address()
98 def parse_host(host) when is_list(host), do: host
99 def parse_host(host) when is_atom(host), do: to_charlist(host)
101 def parse_host(host) when is_binary(host) do
102 host = to_charlist(host)
104 case :inet.parse_address(host) do
105 {:error, :einval} -> host
110 @spec format_host(String.t()) :: charlist()
111 def format_host(host) do
112 host_charlist = to_charlist(host)
114 case :inet.parse_address(host_charlist) do
116 :idna.encode(host_charlist)