From 958227d5563d76f4f983b7cabb6948897d93bd4b Mon Sep 17 00:00:00 2001
From: rinpatch <rinpatch@sdf.org>
Date: Fri, 15 Mar 2019 01:36:29 +0300
Subject: [PATCH 1/2] MediaProxy: parse filename from content-disposition for
 non-whitelisted types

---
 lib/pleroma/reverse_proxy.ex | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)

diff --git a/lib/pleroma/reverse_proxy.ex b/lib/pleroma/reverse_proxy.ex
index 6298b92f4..39ede8619 100644
--- a/lib/pleroma/reverse_proxy.ex
+++ b/lib/pleroma/reverse_proxy.ex
@@ -311,7 +311,25 @@ defp build_resp_content_disposition_header(headers, opts) do
       end
 
     if attachment? do
-      disposition = "attachment; filename=" <> Keyword.get(opts, :attachment_name, "attachment")
+      name =
+        try do
+          {{"content-disposition", content_disposition_string}, _} =
+            List.keytake(headers, "content-disposition", 0)
+
+          [name] =
+            Regex.run(
+              ~r/filename=\"(.*)\"/u,
+              content_disposition_string || "",
+              capture: :all_but_first
+            )
+
+          name
+        rescue
+          MatchError -> Keyword.get(opts, :attachment_name, "attachment")
+        end
+
+      disposition = "attachment; filename=" <> name
+
       List.keystore(headers, "content-disposition", 0, {"content-disposition", disposition})
     else
       headers

From d02f1120f9fe8e048bac6665e95e51648a50c53b Mon Sep 17 00:00:00 2001
From: rinpatch <rinpatch@sdf.org>
Date: Fri, 15 Mar 2019 08:29:51 +0300
Subject: [PATCH 2/2] Content-Disposition regex improvements

---
 lib/pleroma/reverse_proxy.ex | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/lib/pleroma/reverse_proxy.ex b/lib/pleroma/reverse_proxy.ex
index 39ede8619..a3f177fec 100644
--- a/lib/pleroma/reverse_proxy.ex
+++ b/lib/pleroma/reverse_proxy.ex
@@ -316,9 +316,9 @@ defp build_resp_content_disposition_header(headers, opts) do
           {{"content-disposition", content_disposition_string}, _} =
             List.keytake(headers, "content-disposition", 0)
 
-          [name] =
+          [name | _] =
             Regex.run(
-              ~r/filename=\"(.*)\"/u,
+              ~r/filename="((?:[^"\\]|\\.)*)"/u,
               content_disposition_string || "",
               capture: :all_but_first
             )
@@ -328,7 +328,7 @@ defp build_resp_content_disposition_header(headers, opts) do
           MatchError -> Keyword.get(opts, :attachment_name, "attachment")
         end
 
-      disposition = "attachment; filename=" <> name
+      disposition = "attachment; filename=\"#{name}\""
 
       List.keystore(headers, "content-disposition", 0, {"content-disposition", disposition})
     else