1 # Pleroma: A lightweight social networking server
2 # Copyright © 2015-2020 Tymon Tobolski <https://github.com/teamon/tesla/blob/master/lib/tesla/middleware/follow_redirects.ex>
3 # Copyright © 2020 Pleroma Authors <https://pleroma.social/>
4 # SPDX-License-Identifier: AGPL-3.0-only
6 defmodule Pleroma.HTTP.Middleware.FollowRedirects do
8 Pool-aware version of https://github.com/teamon/tesla/blob/master/lib/tesla/middleware/follow_redirects.ex
12 - `:max_redirects` - limit number of redirects (default: `5`)
15 alias Pleroma.Gun.ConnectionPool
17 @behaviour Tesla.Middleware
20 @redirect_statuses [301, 302, 303, 307, 308]
22 @impl Tesla.Middleware
23 def call(env, next, opts \\ []) do
24 max = Keyword.get(opts, :max_redirects, @max_redirects)
26 redirect(env, next, max)
29 defp redirect(env, next, left) do
30 opts = env.opts[:adapter]
32 case Tesla.run(env, next) do
33 {:ok, %{status: status} = res} when status in @redirect_statuses and left > 0 ->
36 case Tesla.get_header(res, "location") do
41 location = parse_location(location, res)
43 case get_conn(location, opts) do
45 %{env | opts: Keyword.put(env.opts, :adapter, opts)}
46 |> new_request(res.status, location)
47 |> redirect(next, left - 1)
54 {:ok, %{status: status}} when status in @redirect_statuses ->
56 {:error, {__MODULE__, :too_many_redirects}}
63 unless opts[:body_as] == :chunks do
71 defp get_conn(location, opts) do
72 uri = URI.parse(location)
74 case ConnectionPool.get_conn(uri, opts) do
76 {:ok, Keyword.merge(opts, conn: conn)}
83 defp release_conn(opts) do
84 ConnectionPool.release_conn(opts[:conn])
87 # The 303 (See Other) redirect was added in HTTP/1.1 to indicate that the originally
88 # requested resource is not available, however a related resource (or another redirect)
89 # available via GET is available at the specified location.
90 # https://tools.ietf.org/html/rfc7231#section-6.4.4
91 defp new_request(env, 303, location), do: %{env | url: location, method: :get, query: []}
93 # The 307 (Temporary Redirect) status code indicates that the target
94 # resource resides temporarily under a different URI and the user agent
95 # MUST NOT change the request method (...)
96 # https://tools.ietf.org/html/rfc7231#section-6.4.7
97 defp new_request(env, 307, location), do: %{env | url: location}
99 defp new_request(env, _, location), do: %{env | url: location, query: []}
101 defp parse_location("https://" <> _rest = location, _env), do: location
102 defp parse_location("http://" <> _rest = location, _env), do: location
104 defp parse_location(location, env) do
107 |> URI.merge(location)