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.AdapterHelper.Gun do
6 @behaviour Pleroma.HTTP.AdapterHelper
8 alias Pleroma.HTTP.AdapterHelper
12 alias Pleroma.Pool.Connections
15 connect_timeout: 5_000,
16 domain_lookup_timeout: 5_000,
17 tls_handshake_timeout: 5_000,
20 await_up_timeout: 5_000
23 @spec options(keyword(), URI.t()) :: keyword()
24 def options(connection_opts \\ [], %URI{} = uri) do
25 proxy = Pleroma.Config.get([:http, :proxy_url], nil)
28 |> Keyword.merge(Pleroma.Config.get([:http, :adapter], []))
29 |> add_scheme_opts(uri)
30 |> AdapterHelper.maybe_add_proxy(AdapterHelper.format_proxy(proxy))
31 |> maybe_get_conn(uri, connection_opts)
34 @spec after_request(keyword()) :: :ok
35 def after_request(opts) do
36 with conn when not is_nil(conn) <- opts[:conn],
37 body_as when body_as != :chunks <- opts[:body_as] do
38 Connections.checkout(conn, self(), :gun_connections)
44 defp add_scheme_opts(opts, %URI{scheme: "http"}), do: opts
46 defp add_scheme_opts(opts, %URI{scheme: "https", host: host}) do
48 certificates_verification: true,
52 cacertfile: CAStore.file_path(),
54 reuse_sessions: false,
55 verify_fun: {&:ssl_verify_hostname.verify_fun/3, [check_hostname: format_host(host)]},
60 Keyword.merge(opts, adapter_opts)
63 defp maybe_get_conn(adapter_opts, uri, connection_opts) do
64 {receive_conn?, opts} =
66 |> Keyword.merge(connection_opts)
67 |> Keyword.pop(:receive_conn, true)
69 if Connections.alive?(:gun_connections) and receive_conn? do
70 try_to_get_conn(uri, opts)
76 defp try_to_get_conn(uri, opts) do
77 case Connections.checkin(uri, :gun_connections) do
80 "Gun connections pool checkin was not successful. Trying to open conn for next request."
83 Task.start(fn -> Pleroma.Gun.Conn.open(uri, :gun_connections, opts) end)
86 conn when is_pid(conn) ->
87 Logger.debug("received conn #{inspect(conn)} #{Connections.compose_uri_log(uri)}")
90 |> Keyword.put(:conn, conn)
91 |> Keyword.put(:close_conn, false)
95 @spec format_host(String.t()) :: charlist()
96 def format_host(host) do
97 host_charlist = to_charlist(host)
99 case :inet.parse_address(host_charlist) do
101 :idna.encode(host_charlist)