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.Gun.Conn do
10 def open(%URI{} = uri, opts) do
11 pool_opts = Pleroma.Config.get([:connections_pool], [])
16 |> Map.put_new(:retry, pool_opts[:retry] || 1)
17 |> Map.put_new(:retry_timeout, pool_opts[:retry_timeout] || 1000)
18 |> Map.put_new(:await_up_timeout, pool_opts[:await_up_timeout] || 5_000)
19 |> Map.put_new(:supervise, false)
20 |> maybe_add_tls_opts(uri)
25 defp maybe_add_tls_opts(opts, %URI{scheme: "http"}), do: opts
27 defp maybe_add_tls_opts(opts, %URI{scheme: "https", host: host}) do
30 cacertfile: CAStore.file_path(),
32 reuse_sessions: false,
34 {&:ssl_verify_hostname.verify_fun/3,
35 [check_hostname: Pleroma.HTTP.AdapterHelper.format_host(host)]}
39 if Keyword.keyword?(opts[:tls_opts]) do
40 Keyword.merge(tls_opts, opts[:tls_opts])
45 Map.put(opts, :tls_opts, tls_opts)
48 defp do_open(uri, %{proxy: {proxy_host, proxy_port}} = opts) do
52 |> add_http2_opts(uri.scheme, Map.get(opts, :tls_opts, []))
54 with open_opts <- Map.delete(opts, :tls_opts),
55 {:ok, conn} <- Gun.open(proxy_host, proxy_port, open_opts),
56 {:ok, _} <- Gun.await_up(conn, opts[:await_up_timeout]),
57 stream <- Gun.connect(conn, connect_opts),
58 {:response, :fin, 200, _} <- Gun.await(conn, stream) do
63 "Opening proxied connection to #{compose_uri_log(uri)} failed with error #{
72 defp do_open(uri, %{proxy: {proxy_type, proxy_host, proxy_port}} = opts) do
85 |> add_http2_opts(uri.scheme, Map.get(opts, :tls_opts, []))
86 |> Map.put(:version, version)
90 |> Map.put(:protocols, [:socks])
91 |> Map.put(:socks_opts, socks_opts)
93 with {:ok, conn} <- Gun.open(proxy_host, proxy_port, opts),
94 {:ok, _} <- Gun.await_up(conn, opts[:await_up_timeout]) do
99 "Opening socks proxied connection to #{compose_uri_log(uri)} failed with error #{
108 defp do_open(%URI{host: host, port: port} = uri, opts) do
109 host = Pleroma.HTTP.AdapterHelper.parse_host(host)
111 with {:ok, conn} <- Gun.open(host, port, opts),
112 {:ok, _} <- Gun.await_up(conn, opts[:await_up_timeout]) do
117 "Opening connection to #{compose_uri_log(uri)} failed with error #{inspect(error)}"
124 defp destination_opts(%URI{host: host, port: port}) do
125 host = Pleroma.HTTP.AdapterHelper.parse_host(host)
126 %{host: host, port: port}
129 defp add_http2_opts(opts, "https", tls_opts) do
130 Map.merge(opts, %{protocols: [:http2], transport: :tls, tls_opts: tls_opts})
133 defp add_http2_opts(opts, _, _), do: opts
135 def compose_uri_log(%URI{scheme: scheme, host: host, path: path}) do
136 "#{scheme}://#{host}#{path}"