1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 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(:connect_timeout, pool_opts[:connect_timeout] || 5_000)
17 |> Map.put_new(:supervise, false)
18 |> maybe_add_tls_opts(uri)
23 defp maybe_add_tls_opts(opts, %URI{scheme: "http"}), do: opts
25 defp maybe_add_tls_opts(opts, %URI{scheme: "https"}) do
28 cacertfile: CAStore.file_path(),
30 reuse_sessions: false,
32 customize_hostname_check: [match_fun: :public_key.pkix_verify_hostname_match_fun(:https)]
36 if Keyword.keyword?(opts[:tls_opts]) do
37 Keyword.merge(tls_opts, opts[:tls_opts])
42 Map.put(opts, :tls_opts, tls_opts)
45 defp do_open(uri, %{proxy: {proxy_host, proxy_port}} = opts) do
49 |> add_http2_opts(uri.scheme, Map.get(opts, :tls_opts, []))
51 with open_opts <- Map.delete(opts, :tls_opts),
52 {:ok, conn} <- Gun.open(proxy_host, proxy_port, open_opts),
53 {:ok, protocol} <- Gun.await_up(conn, opts[:connect_timeout]),
54 stream <- Gun.connect(conn, connect_opts),
55 {:response, :fin, 200, _} <- Gun.await(conn, stream) do
60 "Opening proxied connection to #{compose_uri_log(uri)} failed with error #{inspect(error)}"
67 defp do_open(uri, %{proxy: {proxy_type, proxy_host, proxy_port}} = opts) do
80 |> add_http2_opts(uri.scheme, Map.get(opts, :tls_opts, []))
81 |> Map.put(:version, version)
85 |> Map.put(:protocols, [:socks])
86 |> Map.put(:socks_opts, socks_opts)
88 with {:ok, conn} <- Gun.open(proxy_host, proxy_port, opts),
89 {:ok, protocol} <- Gun.await_up(conn, opts[:connect_timeout]) do
94 "Opening socks proxied connection to #{compose_uri_log(uri)} failed with error #{inspect(error)}"
101 defp do_open(%URI{host: host, port: port} = uri, opts) do
102 host = Pleroma.HTTP.AdapterHelper.parse_host(host)
104 with {:ok, conn} <- Gun.open(host, port, opts),
105 {:ok, protocol} <- Gun.await_up(conn, opts[:connect_timeout]) do
106 {:ok, conn, protocol}
110 "Opening connection to #{compose_uri_log(uri)} failed with error #{inspect(error)}"
117 defp destination_opts(%URI{host: host, port: port}) do
118 host = Pleroma.HTTP.AdapterHelper.parse_host(host)
119 %{host: host, port: port}
122 defp add_http2_opts(opts, "https", tls_opts) do
123 Map.merge(opts, %{protocols: [:http2], transport: :tls, tls_opts: tls_opts})
126 defp add_http2_opts(opts, _, _), do: opts
128 def compose_uri_log(%URI{scheme: scheme, host: host, path: path}) do
129 "#{scheme}://#{host}#{path}"