2018-12-23 20:04:54 +00:00
|
|
|
# Pleroma: A lightweight social networking server
|
2023-01-02 20:38:50 +00:00
|
|
|
# Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
|
2018-12-23 20:04:54 +00:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
|
2018-11-23 17:40:45 +01:00
|
|
|
defmodule Pleroma.ReverseProxy do
|
2025-10-20 22:10:28 +02:00
|
|
|
alias Pleroma.Utils.URIEncoding
|
|
|
|
|
|
2020-07-10 17:10:48 +02:00
|
|
|
@range_headers ~w(range if-range)
|
2021-02-22 14:46:59 -06:00
|
|
|
@keep_req_headers ~w(accept accept-encoding cache-control if-modified-since) ++
|
2020-07-10 17:10:48 +02:00
|
|
|
~w(if-unmodified-since if-none-match) ++ @range_headers
|
2020-03-13 11:30:27 -05:00
|
|
|
@resp_cache_headers ~w(etag date last-modified)
|
2018-11-23 17:40:45 +01:00
|
|
|
@keep_resp_headers @resp_cache_headers ++
|
2024-06-04 22:44:56 -04:00
|
|
|
~w(content-length content-type content-disposition content-encoding) ++
|
2020-07-10 11:04:19 -05:00
|
|
|
~w(content-range accept-ranges vary)
|
2026-07-27 16:32:38 +04:00
|
|
|
@default_cache_control_header "public, max-age=1209600, immutable, no-transform"
|
2018-11-23 17:40:45 +01:00
|
|
|
@valid_resp_codes [200, 206, 304]
|
2018-11-30 19:12:03 +01:00
|
|
|
@max_read_duration :timer.seconds(30)
|
2018-11-23 17:40:45 +01:00
|
|
|
@max_body_length :infinity
|
2019-10-01 20:00:27 +00:00
|
|
|
@failed_request_ttl :timer.seconds(60)
|
2018-11-23 17:40:45 +01:00
|
|
|
@methods ~w(GET HEAD)
|
|
|
|
|
|
2025-03-11 14:18:36 +04:00
|
|
|
@allowed_mime_types Pleroma.Config.get([Pleroma.Upload, :allowed_mime_types], [])
|
|
|
|
|
|
2020-12-18 17:44:46 +01:00
|
|
|
@cachex Pleroma.Config.get([:cachex, :provider], Cachex)
|
|
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
defmodule StreamError do
|
|
|
|
|
@moduledoc false
|
|
|
|
|
defexception [:url, :reason]
|
|
|
|
|
|
|
|
|
|
@impl true
|
|
|
|
|
def message(%{url: url, reason: reason}) do
|
|
|
|
|
"reverse proxy stream from #{url} failed: #{inspect(reason)}"
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2020-05-11 23:21:53 +03:00
|
|
|
def max_read_duration_default, do: @max_read_duration
|
2020-09-05 20:19:09 +03:00
|
|
|
def default_cache_control_header, do: @default_cache_control_header
|
2020-05-11 23:21:53 +03:00
|
|
|
|
2018-11-23 17:40:45 +01:00
|
|
|
@moduledoc """
|
|
|
|
|
A reverse proxy.
|
|
|
|
|
|
|
|
|
|
Pleroma.ReverseProxy.call(conn, url, options)
|
|
|
|
|
|
|
|
|
|
It is not meant to be added into a plug pipeline, but to be called from another plug or controller.
|
|
|
|
|
|
|
|
|
|
Supports `#{inspect(@methods)}` HTTP methods, and only allows `#{inspect(@valid_resp_codes)}` status codes.
|
|
|
|
|
|
|
|
|
|
Responses are chunked to the client while downloading from the upstream.
|
|
|
|
|
|
|
|
|
|
Some request / responses headers are preserved:
|
|
|
|
|
|
|
|
|
|
* request: `#{inspect(@keep_req_headers)}`
|
|
|
|
|
* response: `#{inspect(@keep_resp_headers)}`
|
|
|
|
|
|
|
|
|
|
Options:
|
|
|
|
|
|
|
|
|
|
* `redirect_on_failure` (default `false`). Redirects the client to the real remote URL if there's any HTTP
|
|
|
|
|
errors. Any error during body processing will not be redirected as the response is chunked. This may expose
|
|
|
|
|
remote URL, clients IPs, ….
|
|
|
|
|
|
|
|
|
|
* `max_body_length` (default `#{inspect(@max_body_length)}`): limits the content length to be approximately the
|
|
|
|
|
specified length. It is validated with the `content-length` header and also verified when proxying.
|
|
|
|
|
|
|
|
|
|
* `max_read_duration` (default `#{inspect(@max_read_duration)}` ms): the total time the connection is allowed to
|
|
|
|
|
read from the remote upstream.
|
|
|
|
|
|
2019-10-01 20:00:27 +00:00
|
|
|
* `failed_request_ttl` (default `#{inspect(@failed_request_ttl)}` ms): the time the failed request is cached and cannot be retried.
|
|
|
|
|
|
2018-11-23 17:40:45 +01:00
|
|
|
* `inline_content_types`:
|
|
|
|
|
* `true` will not alter `content-disposition` (up to the upstream),
|
|
|
|
|
* `false` will add `content-disposition: attachment` to any request,
|
2026-08-13 18:11:18 +02:00
|
|
|
* a list of whitelisted content types
|
2018-11-23 17:40:45 +01:00
|
|
|
|
|
|
|
|
* `req_headers`, `resp_headers` additional headers.
|
|
|
|
|
|
2020-03-13 09:37:57 +03:00
|
|
|
* `http`: options for [hackney](https://github.com/benoitc/hackney) or [gun](https://github.com/ninenines/gun).
|
2018-11-23 17:40:45 +01:00
|
|
|
|
|
|
|
|
"""
|
2020-02-11 10:12:57 +03:00
|
|
|
@default_options [pool: :media]
|
2018-11-23 17:40:45 +01:00
|
|
|
|
|
|
|
|
@inline_content_types [
|
2026-07-25 00:06:03 +04:00
|
|
|
"image/apng",
|
|
|
|
|
"image/avif",
|
|
|
|
|
"image/bmp",
|
2018-11-23 17:40:45 +01:00
|
|
|
"image/gif",
|
|
|
|
|
"image/jpeg",
|
|
|
|
|
"image/jpg",
|
|
|
|
|
"image/png",
|
|
|
|
|
"image/svg+xml",
|
2026-07-25 00:06:03 +04:00
|
|
|
"image/webp",
|
2018-11-23 17:40:45 +01:00
|
|
|
"audio/mpeg",
|
|
|
|
|
"audio/mp3",
|
|
|
|
|
"video/webm",
|
|
|
|
|
"video/mp4",
|
|
|
|
|
"video/quicktime"
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
require Logger
|
|
|
|
|
import Plug.Conn
|
|
|
|
|
|
|
|
|
|
@type option() ::
|
2024-01-20 17:37:27 -05:00
|
|
|
{:max_read_duration, non_neg_integer() | :infinity}
|
2018-11-23 17:40:45 +01:00
|
|
|
| {:max_body_length, non_neg_integer() | :infinity}
|
2024-01-20 17:37:27 -05:00
|
|
|
| {:failed_request_ttl, non_neg_integer() | :infinity}
|
Pleroma.Web.Plugs.UploadedMedia: dialyzer error
lib/pleroma/web/plugs/uploaded_media.ex:98:call
The function call will not succeed.
Pleroma.ReverseProxy.call(
_conn :: %Plug.Conn{
:adapter => {atom(), _},
:assigns => %{atom() => _},
:body_params => %Plug.Conn.Unfetched{:aspect => atom(), binary() => _},
:cookies => %Plug.Conn.Unfetched{:aspect => atom(), binary() => _},
:halted => boolean(),
:host => binary(),
:method => binary(),
:owner => pid(),
:params => %Plug.Conn.Unfetched{:aspect => atom(), binary() => _},
:path_info => [binary()],
:path_params => %{binary() => binary() | [any()] | map()},
:port => char(),
:private => %{atom() => _},
:query_params => %Plug.Conn.Unfetched{
:aspect => atom(),
binary() => binary() | [any()] | map()
},
:query_string => binary(),
:remote_ip =>
{byte(), byte(), byte(), byte()}
| {char(), char(), char(), char(), char(), char(), char(), char()},
:req_cookies => %Plug.Conn.Unfetched{:aspect => atom(), binary() => binary()},
:req_headers => [{_, _}],
:request_path => binary(),
:resp_body =>
nil
| binary()
| maybe_improper_list(
binary() | maybe_improper_list(any(), binary() | []) | byte(),
binary() | []
),
:resp_cookies => %{binary() => map()},
:resp_headers => [{_, _}],
:scheme => :http | :https,
:script_name => [binary()],
:secret_key_base => nil | binary(),
:state =>
:chunked | :file | :sent | :set | :set_chunked | :set_file | :unset | :upgraded,
:status => nil | non_neg_integer()
},
_url :: any(),
_proxy_opts :: [{:http, [{:follow_redirect, true} | {:pool, :upload}, ...]}, ...]
)
breaks the contract
(Plug.Conn.t(), url :: String.t(), [option()]) :: Plug.Conn.t()
2024-01-28 10:20:44 -05:00
|
|
|
| {:http, keyword()}
|
2018-11-23 17:40:45 +01:00
|
|
|
| {:req_headers, [{String.t(), String.t()}]}
|
|
|
|
|
| {:resp_headers, [{String.t(), String.t()}]}
|
Pleroma.Web.Plugs.UploadedMedia: dialyzer error
lib/pleroma/web/plugs/uploaded_media.ex:98:call
The function call will not succeed.
Pleroma.ReverseProxy.call(
_conn :: %Plug.Conn{
:adapter => {atom(), _},
:assigns => %{atom() => _},
:body_params => %Plug.Conn.Unfetched{:aspect => atom(), binary() => _},
:cookies => %Plug.Conn.Unfetched{:aspect => atom(), binary() => _},
:halted => boolean(),
:host => binary(),
:method => binary(),
:owner => pid(),
:params => %Plug.Conn.Unfetched{:aspect => atom(), binary() => _},
:path_info => [binary()],
:path_params => %{binary() => binary() | [any()] | map()},
:port => char(),
:private => %{atom() => _},
:query_params => %Plug.Conn.Unfetched{
:aspect => atom(),
binary() => binary() | [any()] | map()
},
:query_string => binary(),
:remote_ip =>
{byte(), byte(), byte(), byte()}
| {char(), char(), char(), char(), char(), char(), char(), char()},
:req_cookies => %Plug.Conn.Unfetched{:aspect => atom(), binary() => binary()},
:req_headers => [{_, _}],
:request_path => binary(),
:resp_body =>
nil
| binary()
| maybe_improper_list(
binary() | maybe_improper_list(any(), binary() | []) | byte(),
binary() | []
),
:resp_cookies => %{binary() => map()},
:resp_headers => [{_, _}],
:scheme => :http | :https,
:script_name => [binary()],
:secret_key_base => nil | binary(),
:state =>
:chunked | :file | :sent | :set | :set_chunked | :set_file | :unset | :upgraded,
:status => nil | non_neg_integer()
},
_url :: any(),
_proxy_opts :: [{:http, [{:follow_redirect, true} | {:pool, :upload}, ...]}, ...]
)
breaks the contract
(Plug.Conn.t(), url :: String.t(), [option()]) :: Plug.Conn.t()
2024-01-28 10:20:44 -05:00
|
|
|
| {:inline_content_types, boolean() | list(String.t())}
|
2018-11-23 17:40:45 +01:00
|
|
|
| {:redirect_on_failure, boolean()}
|
|
|
|
|
|
Pleroma.Web.Plugs.UploadedMedia: dialyzer error
lib/pleroma/web/plugs/uploaded_media.ex:98:call
The function call will not succeed.
Pleroma.ReverseProxy.call(
_conn :: %Plug.Conn{
:adapter => {atom(), _},
:assigns => %{atom() => _},
:body_params => %Plug.Conn.Unfetched{:aspect => atom(), binary() => _},
:cookies => %Plug.Conn.Unfetched{:aspect => atom(), binary() => _},
:halted => boolean(),
:host => binary(),
:method => binary(),
:owner => pid(),
:params => %Plug.Conn.Unfetched{:aspect => atom(), binary() => _},
:path_info => [binary()],
:path_params => %{binary() => binary() | [any()] | map()},
:port => char(),
:private => %{atom() => _},
:query_params => %Plug.Conn.Unfetched{
:aspect => atom(),
binary() => binary() | [any()] | map()
},
:query_string => binary(),
:remote_ip =>
{byte(), byte(), byte(), byte()}
| {char(), char(), char(), char(), char(), char(), char(), char()},
:req_cookies => %Plug.Conn.Unfetched{:aspect => atom(), binary() => binary()},
:req_headers => [{_, _}],
:request_path => binary(),
:resp_body =>
nil
| binary()
| maybe_improper_list(
binary() | maybe_improper_list(any(), binary() | []) | byte(),
binary() | []
),
:resp_cookies => %{binary() => map()},
:resp_headers => [{_, _}],
:scheme => :http | :https,
:script_name => [binary()],
:secret_key_base => nil | binary(),
:state =>
:chunked | :file | :sent | :set | :set_chunked | :set_file | :unset | :upgraded,
:status => nil | non_neg_integer()
},
_url :: any(),
_proxy_opts :: [{:http, [{:follow_redirect, true} | {:pool, :upload}, ...]}, ...]
)
breaks the contract
(Plug.Conn.t(), url :: String.t(), [option()]) :: Plug.Conn.t()
2024-01-28 10:20:44 -05:00
|
|
|
@spec call(Plug.Conn.t(), String.t(), list(option())) :: Plug.Conn.t()
|
2018-12-09 12:12:48 +03:00
|
|
|
def call(_conn, _url, _opts \\ [])
|
|
|
|
|
|
|
|
|
|
def call(conn = %{method: method}, url, opts) when method in @methods do
|
2026-07-22 16:18:04 +04:00
|
|
|
client_opts =
|
|
|
|
|
@default_options
|
|
|
|
|
|> Keyword.merge(Keyword.get(opts, :http, []))
|
|
|
|
|
|> Keyword.put_new(
|
|
|
|
|
:recv_timeout,
|
|
|
|
|
receive_timeout(opts)
|
|
|
|
|
)
|
2018-11-23 17:40:45 +01:00
|
|
|
|
|
|
|
|
req_headers = build_req_headers(conn.req_headers, opts)
|
|
|
|
|
|
|
|
|
|
opts =
|
|
|
|
|
if filename = Pleroma.Web.MediaProxy.filename(url) do
|
|
|
|
|
Keyword.put_new(opts, :attachment_name, filename)
|
|
|
|
|
else
|
|
|
|
|
opts
|
|
|
|
|
end
|
|
|
|
|
|
2020-12-18 17:44:46 +01:00
|
|
|
with {:ok, nil} <- @cachex.get(:failed_proxy_url_cache, url),
|
2026-07-17 20:35:17 +04:00
|
|
|
{:ok, code, headers, client} <-
|
|
|
|
|
request_with_constraints(method, url, req_headers, client_opts, opts) do
|
2018-11-23 17:40:45 +01:00
|
|
|
response(conn, client, url, code, headers, opts)
|
|
|
|
|
else
|
2019-10-01 20:00:27 +00:00
|
|
|
{:ok, true} ->
|
|
|
|
|
conn
|
|
|
|
|
|> error_or_redirect(url, 500, "Request failed", opts)
|
|
|
|
|
|> halt()
|
|
|
|
|
|
2018-11-23 17:40:45 +01:00
|
|
|
{:ok, code, headers} ->
|
|
|
|
|
head_response(conn, url, code, headers, opts)
|
|
|
|
|
|> halt()
|
|
|
|
|
|
|
|
|
|
{:error, {:invalid_http_response, code}} ->
|
|
|
|
|
Logger.error("#{__MODULE__}: request to #{inspect(url)} failed with HTTP status #{code}")
|
2019-10-01 20:00:27 +00:00
|
|
|
track_failed_url(url, code, opts)
|
2018-11-23 17:40:45 +01:00
|
|
|
|
|
|
|
|
conn
|
|
|
|
|
|> error_or_redirect(
|
|
|
|
|
url,
|
|
|
|
|
code,
|
|
|
|
|
"Request failed: " <> Plug.Conn.Status.reason_phrase(code),
|
|
|
|
|
opts
|
|
|
|
|
)
|
|
|
|
|
|> halt()
|
|
|
|
|
|
|
|
|
|
{:error, error} ->
|
|
|
|
|
Logger.error("#{__MODULE__}: request to #{inspect(url)} failed: #{inspect(error)}")
|
2019-10-01 20:00:27 +00:00
|
|
|
track_failed_url(url, error, opts)
|
2018-11-23 17:40:45 +01:00
|
|
|
|
|
|
|
|
conn
|
|
|
|
|
|> error_or_redirect(url, 500, "Request failed", opts)
|
|
|
|
|
|> halt()
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
def call(conn, _, _) do
|
|
|
|
|
conn
|
|
|
|
|
|> send_resp(400, Plug.Conn.Status.reason_phrase(400))
|
|
|
|
|
|> halt()
|
|
|
|
|
end
|
|
|
|
|
|
2020-02-11 10:12:57 +03:00
|
|
|
defp request(method, url, headers, opts) do
|
2018-11-23 17:40:45 +01:00
|
|
|
method = method |> String.downcase() |> String.to_existing_atom()
|
|
|
|
|
|
2025-07-30 17:32:08 -07:00
|
|
|
url = maybe_encode_url(url)
|
|
|
|
|
|
2025-09-08 22:05:49 +02:00
|
|
|
Logger.debug("#{__MODULE__} #{method} #{url} #{inspect(headers)}")
|
|
|
|
|
|
2020-02-11 10:12:57 +03:00
|
|
|
case client().request(method, url, headers, "", opts) do
|
2018-11-23 17:40:45 +01:00
|
|
|
{:ok, code, headers, client} when code in @valid_resp_codes ->
|
|
|
|
|
{:ok, code, downcase_headers(headers), client}
|
|
|
|
|
|
|
|
|
|
{:ok, code, headers} when code in @valid_resp_codes ->
|
|
|
|
|
{:ok, code, downcase_headers(headers)}
|
|
|
|
|
|
fix(reverse_proxy): release the HTTP client on every outcome
Three paths obtained a client ref and abandoned it without closing:
the content-length rejection in call/3, the invalid-status clause in
request/4, and the success branch of response/6.
Under Hackney 4 an abandoned ref is a permanent process leak. A conn
that finishes or errors without an explicit stop parks in `closed` or
`connected` and never terminates: closed/3 only arms its stop timer for
pooled conns, `connected` gets no state_timeout when idle_timeout is
infinity, and a non-pooled conn monitors hackney_conn_sup rather than
its caller, so the owner-DOWN cleanup never fires. Each parked process
pins every refc binary it read, which for proxied video is tens of MB.
Releasing on every outcome means the gun client must stop releasing in
stream_body/1, or the ref would be removed twice.
Hackney does reclaim a pooled connection itself for a response that
cannot carry a body (204, 304, HEAD), so those refs are marked and left
alone; stopping one would evict a connection another request may
already hold. The mark is gated on the request actually being pooled,
since a direct or proxy-tunnelled conn is never checked in and leaks
unless we stop it.
2026-07-25 18:46:43 +04:00
|
|
|
{:ok, code, _, client} ->
|
|
|
|
|
client().close(client)
|
2018-11-23 17:40:45 +01:00
|
|
|
{:error, {:invalid_http_response, code}}
|
|
|
|
|
|
2020-07-26 19:18:21 +03:00
|
|
|
{:ok, code, _} ->
|
|
|
|
|
{:error, {:invalid_http_response, code}}
|
2018-11-23 17:40:45 +01:00
|
|
|
|
|
|
|
|
{:error, error} ->
|
|
|
|
|
{:error, error}
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2026-07-17 20:35:17 +04:00
|
|
|
defp request_with_constraints(method, url, headers, client_opts, opts) do
|
2026-07-27 16:32:38 +04:00
|
|
|
method
|
|
|
|
|
|> request(url, headers, client_opts)
|
|
|
|
|
|> constrain_response(Keyword.get(opts, :max_body_length, @max_body_length))
|
|
|
|
|
end
|
2026-07-17 20:35:17 +04:00
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
defp constrain_response({:ok, code, headers, client}, limit) do
|
|
|
|
|
case header_length_constraint(headers, limit) do
|
|
|
|
|
{:ok, headers} ->
|
|
|
|
|
{:ok, code, headers, client}
|
|
|
|
|
|
|
|
|
|
error ->
|
|
|
|
|
client().close(client)
|
|
|
|
|
error
|
|
|
|
|
end
|
|
|
|
|
end
|
2026-07-17 20:35:17 +04:00
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
defp constrain_response({:ok, code, headers}, limit) do
|
|
|
|
|
case header_length_constraint(headers, limit) do
|
|
|
|
|
{:ok, headers} -> {:ok, code, headers}
|
|
|
|
|
error -> error
|
2026-07-17 20:35:17 +04:00
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
defp constrain_response(response, _limit), do: response
|
|
|
|
|
|
2018-11-23 17:40:45 +01:00
|
|
|
defp response(conn, client, url, status, headers, opts) do
|
2020-07-10 17:10:48 +02:00
|
|
|
Logger.debug("#{__MODULE__} #{status} #{url} #{inspect(headers)}")
|
|
|
|
|
|
2018-11-23 17:40:45 +01:00
|
|
|
result =
|
|
|
|
|
conn
|
|
|
|
|
|> put_resp_headers(build_resp_headers(headers, opts))
|
|
|
|
|
|> send_chunked(status)
|
2026-08-13 18:11:18 +02:00
|
|
|
|> chunk_reply(client, opts)
|
fix(reverse_proxy): release the HTTP client on every outcome
Three paths obtained a client ref and abandoned it without closing:
the content-length rejection in call/3, the invalid-status clause in
request/4, and the success branch of response/6.
Under Hackney 4 an abandoned ref is a permanent process leak. A conn
that finishes or errors without an explicit stop parks in `closed` or
`connected` and never terminates: closed/3 only arms its stop timer for
pooled conns, `connected` gets no state_timeout when idle_timeout is
infinity, and a non-pooled conn monitors hackney_conn_sup rather than
its caller, so the owner-DOWN cleanup never fires. Each parked process
pins every refc binary it read, which for proxied video is tens of MB.
Releasing on every outcome means the gun client must stop releasing in
stream_body/1, or the ref would be removed twice.
Hackney does reclaim a pooled connection itself for a response that
cannot carry a body (204, 304, HEAD), so those refs are marked and left
alone; stopping one would evict a connection another request may
already hold. The mark is gated on the request actually being pooled,
since a direct or proxy-tunnelled conn is never checked in and leaks
unless we stop it.
2026-07-25 18:46:43 +04:00
|
|
|
|
2018-11-23 17:40:45 +01:00
|
|
|
case result do
|
|
|
|
|
{:ok, conn} ->
|
|
|
|
|
halt(conn)
|
|
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
{:error, {:downstream, _error}, conn} ->
|
2019-07-09 16:54:13 +00:00
|
|
|
client().close(client)
|
2018-11-23 17:40:45 +01:00
|
|
|
halt(conn)
|
|
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
{:error, {:upstream, error}, conn} ->
|
2023-11-28 17:17:46 +00:00
|
|
|
Logger.warning(
|
2018-11-23 17:40:45 +01:00
|
|
|
"#{__MODULE__} request to #{url} failed while reading/chunking: #{inspect(error)}"
|
|
|
|
|
)
|
|
|
|
|
|
2019-07-09 16:54:13 +00:00
|
|
|
client().close(client)
|
2026-07-27 16:32:38 +04:00
|
|
|
track_failed_url(url, error, opts)
|
|
|
|
|
raise_stream_error(conn, url, error)
|
2018-11-23 17:40:45 +01:00
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2026-08-13 18:11:18 +02:00
|
|
|
defp chunk_reply(conn, client, opts) do
|
2018-11-23 17:40:45 +01:00
|
|
|
chunk_reply(conn, client, opts, 0, 0)
|
|
|
|
|
end
|
|
|
|
|
|
2026-07-25 00:06:03 +04:00
|
|
|
defp chunk_reply(conn, client, opts, sent_so_far, duration) do
|
2026-08-13 18:11:18 +02:00
|
|
|
with {:ok, duration} <-
|
|
|
|
|
check_read_duration(
|
|
|
|
|
duration,
|
|
|
|
|
Keyword.get(opts, :max_read_duration, @max_read_duration)
|
|
|
|
|
),
|
|
|
|
|
{:ok, data, client} <- client().stream_body(client),
|
|
|
|
|
{:ok, duration} <- increase_read_duration(duration),
|
2018-11-23 17:40:45 +01:00
|
|
|
sent_so_far = sent_so_far + byte_size(data),
|
2019-08-16 10:00:18 -05:00
|
|
|
:ok <-
|
|
|
|
|
body_size_constraint(
|
|
|
|
|
sent_so_far,
|
|
|
|
|
Keyword.get(opts, :max_body_length, @max_body_length)
|
|
|
|
|
),
|
2026-07-27 16:32:38 +04:00
|
|
|
{:ok, conn} <- write_chunk(conn, data) do
|
2018-11-23 17:40:45 +01:00
|
|
|
chunk_reply(conn, client, opts, sent_so_far, duration)
|
|
|
|
|
else
|
|
|
|
|
:done -> {:ok, conn}
|
2026-07-27 16:32:38 +04:00
|
|
|
{:error, {source, error}} -> {:error, {source, error}, conn}
|
|
|
|
|
{:error, error} -> {:error, {:upstream, error}, conn}
|
2026-07-25 00:06:03 +04:00
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
defp write_chunk(conn, data) do
|
|
|
|
|
case chunk(conn, data) do
|
|
|
|
|
{:error, error} -> {:error, {:downstream, error}}
|
|
|
|
|
result -> result
|
2026-07-25 00:06:03 +04:00
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2020-07-10 17:10:48 +02:00
|
|
|
defp head_response(conn, url, code, headers, opts) do
|
|
|
|
|
Logger.debug("#{__MODULE__} #{code} #{url} #{inspect(headers)}")
|
|
|
|
|
|
2018-11-23 17:40:45 +01:00
|
|
|
conn
|
|
|
|
|
|> put_resp_headers(build_resp_headers(headers, opts))
|
|
|
|
|
|> send_resp(code, "")
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
defp error_or_redirect(conn, url, code, body, opts) do
|
|
|
|
|
if Keyword.get(opts, :redirect_on_failure, false) do
|
|
|
|
|
conn
|
|
|
|
|
|> Phoenix.Controller.redirect(external: url)
|
|
|
|
|
|> halt()
|
|
|
|
|
else
|
|
|
|
|
conn
|
|
|
|
|
|> send_resp(code, body)
|
|
|
|
|
|> halt
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
defp downcase_headers(headers) do
|
|
|
|
|
Enum.map(headers, fn {k, v} ->
|
|
|
|
|
{String.downcase(k), v}
|
|
|
|
|
end)
|
|
|
|
|
end
|
|
|
|
|
|
2018-11-23 18:57:27 +01:00
|
|
|
defp get_content_type(headers) do
|
2018-11-23 23:59:24 +01:00
|
|
|
{_, content_type} =
|
|
|
|
|
List.keyfind(headers, "content-type", 0, {"content-type", "application/octet-stream"})
|
|
|
|
|
|
|
|
|
|
[content_type | _] = String.split(content_type, ";")
|
2018-11-23 18:57:27 +01:00
|
|
|
content_type
|
|
|
|
|
end
|
|
|
|
|
|
2018-11-23 17:40:45 +01:00
|
|
|
defp put_resp_headers(conn, headers) do
|
|
|
|
|
Enum.reduce(headers, conn, fn {k, v}, conn ->
|
|
|
|
|
put_resp_header(conn, k, v)
|
|
|
|
|
end)
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
defp build_req_headers(headers, opts) do
|
2018-12-09 12:12:48 +03:00
|
|
|
headers
|
|
|
|
|
|> downcase_headers()
|
|
|
|
|
|> Enum.filter(fn {k, _} -> k in @keep_req_headers end)
|
2020-07-10 17:10:48 +02:00
|
|
|
|> build_req_range_or_encoding_header(opts)
|
|
|
|
|
|> build_req_user_agent_header(opts)
|
2026-07-25 00:06:03 +04:00
|
|
|
|> merge_headers(Keyword.get(opts, :req_headers, []))
|
2020-07-10 17:10:48 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
|
|
# Disable content-encoding if any @range_headers are requested (see #1823).
|
|
|
|
|
defp build_req_range_or_encoding_header(headers, _opts) do
|
|
|
|
|
range? = Enum.any?(headers, fn {header, _} -> Enum.member?(@range_headers, header) end)
|
|
|
|
|
|
2026-08-13 18:11:18 +02:00
|
|
|
if range? && List.keymember?(headers, "accept-encoding", 0) do
|
|
|
|
|
List.keydelete(headers, "accept-encoding", 0)
|
|
|
|
|
else
|
|
|
|
|
headers
|
2020-07-10 17:10:48 +02:00
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2021-02-22 14:46:59 -06:00
|
|
|
defp build_req_user_agent_header(headers, _opts) do
|
|
|
|
|
List.keystore(
|
|
|
|
|
headers,
|
|
|
|
|
"user-agent",
|
|
|
|
|
0,
|
|
|
|
|
{"user-agent", Pleroma.Application.user_agent()}
|
|
|
|
|
)
|
2018-11-23 17:40:45 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
|
|
defp build_resp_headers(headers, opts) do
|
2018-11-23 23:59:24 +01:00
|
|
|
headers
|
|
|
|
|
|> Enum.filter(fn {k, _} -> k in @keep_resp_headers end)
|
|
|
|
|
|> build_resp_cache_headers(opts)
|
2025-03-11 14:18:36 +04:00
|
|
|
|> sanitise_content_type()
|
2018-11-23 23:59:24 +01:00
|
|
|
|> build_resp_content_disposition_header(opts)
|
2026-07-27 16:32:38 +04:00
|
|
|
|> merge_headers(Keyword.get(opts, :resp_headers, []))
|
|
|
|
|
|> ensure_no_transform()
|
|
|
|
|
end
|
|
|
|
|
|
2026-08-13 18:11:18 +02:00
|
|
|
defp merge_headers(headers, extra_headers) do
|
|
|
|
|
Enum.reduce(extra_headers, headers, fn {key, value}, headers ->
|
|
|
|
|
List.keystore(headers, String.downcase(key), 0, {String.downcase(key), value})
|
|
|
|
|
end)
|
|
|
|
|
end
|
|
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
defp ensure_no_transform(headers) do
|
|
|
|
|
{_, cache_control} =
|
|
|
|
|
List.keyfind(headers, "cache-control", 0, {"cache-control", @default_cache_control_header})
|
|
|
|
|
|
|
|
|
|
directives =
|
|
|
|
|
cache_control
|
|
|
|
|
|> String.split(",")
|
|
|
|
|
|> Enum.map(&(&1 |> String.trim() |> String.downcase()))
|
|
|
|
|
|
|
|
|
|
if "no-transform" in directives do
|
|
|
|
|
headers
|
|
|
|
|
else
|
|
|
|
|
replace_header(headers, "cache-control", cache_control <> ", no-transform")
|
|
|
|
|
end
|
2018-11-23 17:40:45 +01:00
|
|
|
end
|
|
|
|
|
|
2025-03-11 14:18:36 +04:00
|
|
|
defp sanitise_content_type(headers) do
|
|
|
|
|
original_ct = get_content_type(headers)
|
|
|
|
|
|
|
|
|
|
safe_ct =
|
|
|
|
|
Pleroma.Web.Plugs.Utils.get_safe_mime_type(
|
|
|
|
|
%{allowed_mime_types: @allowed_mime_types},
|
|
|
|
|
original_ct
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
[
|
|
|
|
|
{"content-type", safe_ct}
|
|
|
|
|
| Enum.filter(headers, fn {k, _v} -> k != "content-type" end)
|
|
|
|
|
]
|
|
|
|
|
end
|
|
|
|
|
|
2018-12-09 12:12:48 +03:00
|
|
|
defp build_resp_cache_headers(headers, _opts) do
|
2018-11-23 17:40:45 +01:00
|
|
|
has_cache? = Enum.any?(headers, fn {k, _} -> k in @resp_cache_headers end)
|
2019-01-21 15:17:24 +01:00
|
|
|
|
|
|
|
|
cond do
|
|
|
|
|
has_cache? ->
|
2020-03-13 11:46:40 -05:00
|
|
|
# There's caching header present but no cache-control -- we need to set our own
|
|
|
|
|
# as Plug defaults to "max-age=0, private, must-revalidate"
|
2020-03-13 12:42:06 -05:00
|
|
|
List.keystore(
|
|
|
|
|
headers,
|
|
|
|
|
"cache-control",
|
|
|
|
|
0,
|
|
|
|
|
{"cache-control", @default_cache_control_header}
|
|
|
|
|
)
|
2019-01-21 15:17:24 +01:00
|
|
|
|
|
|
|
|
true ->
|
|
|
|
|
List.keystore(
|
|
|
|
|
headers,
|
|
|
|
|
"cache-control",
|
|
|
|
|
0,
|
|
|
|
|
{"cache-control", @default_cache_control_header}
|
|
|
|
|
)
|
2018-11-23 17:40:45 +01:00
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
defp build_resp_content_disposition_header(headers, opts) do
|
|
|
|
|
opt = Keyword.get(opts, :inline_content_types, @inline_content_types)
|
|
|
|
|
|
2018-11-23 18:57:27 +01:00
|
|
|
content_type = get_content_type(headers)
|
2018-11-23 17:40:45 +01:00
|
|
|
|
|
|
|
|
attachment? =
|
|
|
|
|
cond do
|
|
|
|
|
is_list(opt) && !Enum.member?(opt, content_type) -> true
|
|
|
|
|
opt == false -> true
|
|
|
|
|
true -> false
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
if attachment? do
|
2019-03-15 01:36:29 +03:00
|
|
|
name =
|
|
|
|
|
try do
|
|
|
|
|
{{"content-disposition", content_disposition_string}, _} =
|
|
|
|
|
List.keytake(headers, "content-disposition", 0)
|
|
|
|
|
|
2019-03-15 08:29:51 +03:00
|
|
|
[name | _] =
|
2019-03-15 01:36:29 +03:00
|
|
|
Regex.run(
|
2019-03-15 08:29:51 +03:00
|
|
|
~r/filename="((?:[^"\\]|\\.)*)"/u,
|
2019-03-15 01:36:29 +03:00
|
|
|
content_disposition_string || "",
|
|
|
|
|
capture: :all_but_first
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
name
|
|
|
|
|
rescue
|
|
|
|
|
MatchError -> Keyword.get(opts, :attachment_name, "attachment")
|
|
|
|
|
end
|
|
|
|
|
|
2019-03-15 08:29:51 +03:00
|
|
|
disposition = "attachment; filename=\"#{name}\""
|
2019-03-15 01:36:29 +03:00
|
|
|
|
2026-07-25 00:06:03 +04:00
|
|
|
replace_header(headers, "content-disposition", disposition)
|
2018-11-23 17:40:45 +01:00
|
|
|
else
|
2026-08-13 18:11:18 +02:00
|
|
|
headers
|
2018-11-23 17:40:45 +01:00
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2026-07-25 00:06:03 +04:00
|
|
|
defp replace_header(headers, key, value) do
|
|
|
|
|
[{key, value} | Enum.reject(headers, fn {header, _} -> header == key end)]
|
|
|
|
|
end
|
fix(reverse_proxy): release the HTTP client on every outcome
Three paths obtained a client ref and abandoned it without closing:
the content-length rejection in call/3, the invalid-status clause in
request/4, and the success branch of response/6.
Under Hackney 4 an abandoned ref is a permanent process leak. A conn
that finishes or errors without an explicit stop parks in `closed` or
`connected` and never terminates: closed/3 only arms its stop timer for
pooled conns, `connected` gets no state_timeout when idle_timeout is
infinity, and a non-pooled conn monitors hackney_conn_sup rather than
its caller, so the owner-DOWN cleanup never fires. Each parked process
pins every refc binary it read, which for proxied video is tens of MB.
Releasing on every outcome means the gun client must stop releasing in
stream_body/1, or the ref would be removed twice.
Hackney does reclaim a pooled connection itself for a response that
cannot carry a body (204, 304, HEAD), so those refs are marked and left
alone; stopping one would evict a connection another request may
already hold. The mark is gated on the request actually being pooled,
since a direct or proxy-tunnelled conn is never checked in and leaks
unless we stop it.
2026-07-25 18:46:43 +04:00
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
defp header_length_constraint(headers, limit) do
|
|
|
|
|
lengths =
|
|
|
|
|
for {"content-length", value} <- headers,
|
|
|
|
|
do: parse_content_length(value)
|
fix(reverse_proxy): release the HTTP client on every outcome
Three paths obtained a client ref and abandoned it without closing:
the content-length rejection in call/3, the invalid-status clause in
request/4, and the success branch of response/6.
Under Hackney 4 an abandoned ref is a permanent process leak. A conn
that finishes or errors without an explicit stop parks in `closed` or
`connected` and never terminates: closed/3 only arms its stop timer for
pooled conns, `connected` gets no state_timeout when idle_timeout is
infinity, and a non-pooled conn monitors hackney_conn_sup rather than
its caller, so the owner-DOWN cleanup never fires. Each parked process
pins every refc binary it read, which for proxied video is tens of MB.
Releasing on every outcome means the gun client must stop releasing in
stream_body/1, or the ref would be removed twice.
Hackney does reclaim a pooled connection itself for a response that
cannot carry a body (204, 304, HEAD), so those refs are marked and left
alone; stopping one would evict a connection another request may
already hold. The mark is gated on the request actually being pooled,
since a direct or proxy-tunnelled conn is never checked in and leaks
unless we stop it.
2026-07-25 18:46:43 +04:00
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
case Enum.uniq(lengths) do
|
|
|
|
|
[] ->
|
|
|
|
|
{:ok, headers}
|
|
|
|
|
|
|
|
|
|
[size] when is_integer(size) ->
|
|
|
|
|
case body_size_constraint(size, limit) do
|
|
|
|
|
:ok -> {:ok, replace_header(headers, "content-length", to_string(size))}
|
|
|
|
|
error -> error
|
|
|
|
|
end
|
2018-11-23 17:40:45 +01:00
|
|
|
|
|
|
|
|
_ ->
|
2026-07-27 16:32:38 +04:00
|
|
|
{:error, :invalid_content_length}
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
defp parse_content_length(value) when is_binary(value) do
|
|
|
|
|
case Integer.parse(value) do
|
|
|
|
|
{size, ""} when size >= 0 -> size
|
|
|
|
|
_ -> :invalid
|
2018-11-23 17:40:45 +01:00
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
defp parse_content_length(_value), do: :invalid
|
2018-11-23 17:40:45 +01:00
|
|
|
|
2026-07-17 20:35:17 +04:00
|
|
|
defp body_size_constraint(size, limit) when is_integer(limit) and limit > 0 and size > limit do
|
2018-11-23 17:40:45 +01:00
|
|
|
{:error, :body_too_large}
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
defp body_size_constraint(_, _), do: :ok
|
|
|
|
|
|
|
|
|
|
defp check_read_duration(duration, max)
|
|
|
|
|
when is_integer(duration) and is_integer(max) and max > 0 do
|
|
|
|
|
if duration > max do
|
|
|
|
|
{:error, :read_duration_exceeded}
|
|
|
|
|
else
|
|
|
|
|
{:ok, {duration, :erlang.system_time(:millisecond)}}
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2026-07-25 00:06:03 +04:00
|
|
|
defp check_read_duration(_, _), do: {:ok, :no_duration_limit}
|
2018-11-23 17:40:45 +01:00
|
|
|
|
2026-07-22 16:18:04 +04:00
|
|
|
defp receive_timeout(opts) do
|
|
|
|
|
case Keyword.get(opts, :max_read_duration, @max_read_duration) do
|
|
|
|
|
timeout when is_integer(timeout) and timeout > 0 -> timeout
|
|
|
|
|
_ -> :infinity
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2026-07-25 00:06:03 +04:00
|
|
|
defp increase_read_duration(:no_duration_limit), do: {:ok, :no_duration_limit}
|
2018-11-23 17:40:45 +01:00
|
|
|
|
|
|
|
|
defp increase_read_duration({previous_duration, started})
|
|
|
|
|
when is_integer(previous_duration) and is_integer(started) do
|
|
|
|
|
duration = :erlang.system_time(:millisecond) - started
|
|
|
|
|
{:ok, previous_duration + duration}
|
|
|
|
|
end
|
|
|
|
|
|
2021-06-02 16:34:32 -05:00
|
|
|
defp client, do: Pleroma.ReverseProxy.Client.Wrapper
|
2019-10-01 20:00:27 +00:00
|
|
|
|
2026-07-27 16:32:38 +04:00
|
|
|
# Neither Plug adapter exposes a public way to abort a committed response.
|
|
|
|
|
# Cowboy finalizes chunked HTTP/1 responses when the request process exits,
|
|
|
|
|
# so terminate the connection first to leave the response visibly incomplete.
|
|
|
|
|
defp raise_stream_error(
|
|
|
|
|
%Plug.Conn{adapter: {Plug.Cowboy.Conn, %{pid: connection_pid}}} = conn,
|
|
|
|
|
url,
|
|
|
|
|
error
|
|
|
|
|
) do
|
|
|
|
|
if Plug.Conn.get_http_protocol(conn) in [:"HTTP/1.0", :"HTTP/1.1"] do
|
|
|
|
|
Process.exit(connection_pid, :kill)
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
raise StreamError, url: url, reason: error
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
# Bandit turns this exception into RST_STREAM; a regular exception sends an
|
|
|
|
|
# empty DATA frame with END_STREAM and makes the partial body look complete.
|
|
|
|
|
defp raise_stream_error(
|
|
|
|
|
%Plug.Conn{
|
|
|
|
|
adapter: {Bandit.Adapter, %{transport: %{stream_id: stream_id}}}
|
|
|
|
|
},
|
|
|
|
|
url,
|
|
|
|
|
error
|
|
|
|
|
) do
|
|
|
|
|
raise Bandit.HTTP2.Errors.StreamError,
|
|
|
|
|
message: StreamError.message(%StreamError{url: url, reason: error}),
|
|
|
|
|
error_code: Bandit.HTTP2.Errors.internal_error(),
|
|
|
|
|
stream_id: stream_id
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
defp raise_stream_error(_conn, url, error) do
|
|
|
|
|
raise StreamError, url: url, reason: error
|
|
|
|
|
end
|
|
|
|
|
|
2019-10-11 22:52:38 +03:00
|
|
|
defp track_failed_url(url, error, opts) do
|
2019-10-01 20:00:27 +00:00
|
|
|
ttl =
|
2019-10-11 22:52:38 +03:00
|
|
|
unless error in [:body_too_large, 400, 204] do
|
2019-10-01 20:00:27 +00:00
|
|
|
Keyword.get(opts, :failed_request_ttl, @failed_request_ttl)
|
|
|
|
|
else
|
|
|
|
|
nil
|
|
|
|
|
end
|
|
|
|
|
|
2020-12-18 17:44:46 +01:00
|
|
|
@cachex.put(:failed_proxy_url_cache, url, true, ttl: ttl)
|
2019-10-01 20:00:27 +00:00
|
|
|
end
|
2024-06-04 22:44:56 -04:00
|
|
|
|
2025-07-30 17:32:08 -07:00
|
|
|
# Only when Tesla adapter is Hackney or Finch does the URL
|
|
|
|
|
# need encoding before Reverse Proxying as both end up
|
|
|
|
|
# using the raw Hackney client and cannot leverage our
|
|
|
|
|
# EncodeUrl Tesla middleware
|
|
|
|
|
# Also do it for test environment
|
|
|
|
|
defp maybe_encode_url(url) do
|
|
|
|
|
case Application.get_env(:tesla, :adapter) do
|
2025-10-20 22:10:28 +02:00
|
|
|
Tesla.Adapter.Hackney -> URIEncoding.encode_url(url)
|
|
|
|
|
{Tesla.Adapter.Finch, _} -> URIEncoding.encode_url(url)
|
|
|
|
|
Tesla.Mock -> URIEncoding.encode_url(url)
|
2025-07-30 17:32:08 -07:00
|
|
|
_ -> url
|
|
|
|
|
end
|
|
|
|
|
end
|
2018-11-23 17:40:45 +01:00
|
|
|
end
|