summaryrefslogtreecommitdiff
path: root/lib/pleroma/gun/conn.ex
blob: fb7153a16a2fc48c67b4c567326d5d880c23a3f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# Pleroma: A lightweight social networking server
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only

defmodule Pleroma.Gun.Conn do
  @moduledoc """
  Struct for gun connection data
  """
  alias Pleroma.Gun
  alias Pleroma.Pool.Connections

  require Logger

  @type gun_state :: :init | :up | :down
  @type conn_state :: :init | :active | :idle

  @type t :: %__MODULE__{
          conn: pid(),
          gun_state: gun_state(),
          conn_state: conn_state(),
          used_by: [GenServer.from()],
          awaited_by: [GenServer.from()],
          last_reference: pos_integer(),
          crf: float(),
          retries: pos_integer()
        }

  defstruct conn: nil,
            gun_state: :init,
            conn_state: :init,
            used_by: [],
            awaited_by: [],
            last_reference: 0,
            crf: 1,
            retries: 0

  @spec open(URI.t(), atom(), keyword()) :: :ok
  def open(%URI{} = uri, name, opts \\ []) do
    pool_opts = Pleroma.Config.get([:connections_pool], [])

    opts =
      opts
      |> Enum.into(%{})
      |> Map.put_new(:retry, pool_opts[:retry] || 1)
      |> Map.put_new(:retry_timeout, pool_opts[:retry_timeout] || 1000)
      |> Map.put_new(:await_up_timeout, pool_opts[:await_up_timeout] || 5_000)
      |> maybe_add_tls_opts(uri)

    key = "#{uri.scheme}:#{uri.host}:#{uri.port}"

    max_connections = pool_opts[:max_connections] || 125

    with {:ok, conn_pid} <- try_open(name, uri, opts, max_connections) do
      :ok = Gun.set_owner(conn_pid, Process.whereis(name))
      Connections.update_conn(name, key, conn_pid)
    else
      _error -> Connections.remove_conn(name, key)
    end
  end

  defp try_open(name, uri, opts, max_connections) do
    if Connections.count(name) <= max_connections do
      do_open(uri, opts)
    else
      close_least_used_and_do_open(name, uri, opts)
    end
  end

  defp maybe_add_tls_opts(opts, %URI{scheme: "http"}), do: opts

  defp maybe_add_tls_opts(opts, %URI{scheme: "https", host: host}) do
    charlist_host =
      host
      |> to_charlist()
      |> :idna.encode()

    tls_opts = [
      verify: :verify_peer,
      cacertfile: CAStore.file_path(),
      depth: 20,
      reuse_sessions: false,
      verify_fun: {&:ssl_verify_hostname.verify_fun/3, [check_hostname: charlist_host]}
    ]

    tls_opts =
      if Keyword.keyword?(opts[:tls_opts]) do
        Keyword.merge(tls_opts, opts[:tls_opts])
      else
        tls_opts
      end

    Map.put(opts, :tls_opts, tls_opts)
  end

  defp do_open(uri, %{proxy: {proxy_host, proxy_port}} = opts) do
    connect_opts =
      uri
      |> destination_opts()
      |> add_http2_opts(uri.scheme, Map.get(opts, :tls_opts, []))

    with open_opts <- Map.delete(opts, :tls_opts),
         {:ok, conn} <- Gun.open(proxy_host, proxy_port, open_opts),
         {:ok, _} <- Gun.await_up(conn, opts[:await_up_timeout]),
         stream <- Gun.connect(conn, connect_opts),
         {:response, :fin, 200, _} <- Gun.await(conn, stream) do
      {:ok, conn}
    else
      error ->
        Logger.warn(
          "Opening proxied connection to #{compose_uri_log(uri)} failed with error #{
            inspect(error)
          }"
        )

        error
    end
  end

  defp do_open(uri, %{proxy: {proxy_type, proxy_host, proxy_port}} = opts) do
    version =
      proxy_type
      |> to_string()
      |> String.last()
      |> case do
        "4" -> 4
        _ -> 5
      end

    socks_opts =
      uri
      |> destination_opts()
      |> add_http2_opts(uri.scheme, Map.get(opts, :tls_opts, []))
      |> Map.put(:version, version)

    opts =
      opts
      |> Map.put(:protocols, [:socks])
      |> Map.put(:socks_opts, socks_opts)

    with {:ok, conn} <- Gun.open(proxy_host, proxy_port, opts),
         {:ok, _} <- Gun.await_up(conn, opts[:await_up_timeout]) do
      {:ok, conn}
    else
      error ->
        Logger.warn(
          "Opening socks proxied connection to #{compose_uri_log(uri)} failed with error #{
            inspect(error)
          }"
        )

        error
    end
  end

  defp do_open(%URI{host: host, port: port} = uri, opts) do
    host = Pleroma.HTTP.Connection.format_host(host)

    with {:ok, conn} <- Gun.open(host, port, opts),
         {:ok, _} <- Gun.await_up(conn, opts[:await_up_timeout]) do
      {:ok, conn}
    else
      error ->
        Logger.warn(
          "Opening connection to #{compose_uri_log(uri)} failed with error #{inspect(error)}"
        )

        error
    end
  end

  defp destination_opts(%URI{host: host, port: port}) do
    host = Pleroma.HTTP.Connection.format_host(host)
    %{host: host, port: port}
  end

  defp add_http2_opts(opts, "https", tls_opts) do
    Map.merge(opts, %{protocols: [:http2], transport: :tls, tls_opts: tls_opts})
  end

  defp add_http2_opts(opts, _, _), do: opts

  defp close_least_used_and_do_open(name, uri, opts) do
    with [{key, conn} | _conns] <- Connections.get_unused_conns(name),
         :ok <- Gun.close(conn.conn) do
      Connections.remove_conn(name, key)

      do_open(uri, opts)
    else
      [] -> {:error, :pool_overflowed}
    end
  end

  def compose_uri_log(%URI{scheme: scheme, host: host, path: path}) do
    "#{scheme}://#{host}#{path}"
  end
end