qb_akkoma/lib/pleroma/web/media_proxy/controller.ex

45 lines
1.5 KiB
Elixir
Raw Normal View History

# Pleroma: A lightweight social networking server
2018-12-31 15:41:47 +00:00
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: AGPL-3.0-only
2017-11-22 18:06:07 +00:00
defmodule Pleroma.Web.MediaProxy.MediaProxyController do
use Pleroma.Web, :controller
2019-02-03 17:44:18 +00:00
alias Pleroma.ReverseProxy
alias Pleroma.Web.MediaProxy
2017-11-22 18:06:07 +00:00
@default_proxy_opts [max_body_length: 25 * 1_048_576, http: [follow_redirect: true]]
2018-11-30 16:44:42 +00:00
2019-02-03 17:44:18 +00:00
def remote(conn, %{"sig" => sig64, "url" => url64} = params) do
2018-12-02 10:24:02 +00:00
with config <- Pleroma.Config.get([:media_proxy], []),
2018-11-23 16:40:45 +00:00
true <- Keyword.get(config, :enabled, false),
{:ok, url} <- MediaProxy.decode_url(sig64, url64),
:ok <- filename_matches(Map.has_key?(params, "filename"), conn.request_path, url) do
2018-12-02 10:24:02 +00:00
ReverseProxy.call(conn, url, Keyword.get(config, :proxy_opts, @default_proxy_opts))
else
2018-03-30 13:01:53 +00:00
false ->
2018-11-23 16:40:45 +00:00
send_resp(conn, 404, Plug.Conn.Status.reason_phrase(404))
2018-03-30 13:01:53 +00:00
{:error, :invalid_signature} ->
2018-11-23 16:40:45 +00:00
send_resp(conn, 403, Plug.Conn.Status.reason_phrase(403))
2018-03-30 13:01:53 +00:00
2018-11-23 16:40:45 +00:00
{:wrong_filename, filename} ->
redirect(conn, external: MediaProxy.build_url(sig64, url64, filename))
2017-11-22 18:06:07 +00:00
end
end
2018-11-23 16:40:45 +00:00
def filename_matches(has_filename, path, url) do
filename = url |> MediaProxy.filename()
2018-03-30 13:01:53 +00:00
if has_filename && filename && does_not_match(path, filename) do
2018-12-10 06:39:57 +00:00
{:wrong_filename, filename}
else
:ok
2017-12-11 01:31:37 +00:00
end
end
defp does_not_match(path, filename) do
basename = Path.basename(path)
basename != filename and URI.decode(basename) != filename and URI.encode(basename) != filename
end
2017-11-22 18:06:07 +00:00
end