Skip to content
Snippets Groups Projects
Commit bf8abdd7 authored by Travis Ralston's avatar Travis Ralston
Browse files

Sniff content type during download for disposition

parent 773b1973
No related branches found
No related tags found
No related merge requests found
...@@ -15,11 +15,13 @@ import ( ...@@ -15,11 +15,13 @@ import (
"strings" "strings"
"github.com/alioygur/is" "github.com/alioygur/is"
"github.com/gabriel-vasile/mimetype"
"github.com/getsentry/sentry-go" "github.com/getsentry/sentry-go"
"github.com/turt2live/matrix-media-repo/api/_responses" "github.com/turt2live/matrix-media-repo/api/_responses"
"github.com/turt2live/matrix-media-repo/common" "github.com/turt2live/matrix-media-repo/common"
"github.com/turt2live/matrix-media-repo/common/rcontext" "github.com/turt2live/matrix-media-repo/common/rcontext"
"github.com/turt2live/matrix-media-repo/util" "github.com/turt2live/matrix-media-repo/util"
"github.com/turt2live/matrix-media-repo/util/readers"
) )
type GeneratorFn = func(r *http.Request, ctx rcontext.RequestContext) interface{} type GeneratorFn = func(r *http.Request, ctx rcontext.RequestContext) interface{}
...@@ -94,9 +96,26 @@ beforeParseDownload: ...@@ -94,9 +96,26 @@ beforeParseDownload:
goto beforeParseDownload // reprocess `res` goto beforeParseDownload // reprocess `res`
} }
contentType = downloadRes.ContentType contentType = "application/octet-stream"
expectedBytes = downloadRes.SizeBytes expectedBytes = downloadRes.SizeBytes
// Don't rely on user-supplied values for content-type
br := readers.NewBufferReadsReader(downloadRes.Data)
if mimeType, err := mimetype.DetectReader(br); err != nil {
rctx.Log.Warn("Non-fatal error sniffing mime type of download: ", err)
sentry.CaptureException(err)
} else if mimeType != nil {
contentType = mimeType.String()
}
ogReader := downloadRes.Data
downloadRes.Data = readers.NewCancelCloser(io.NopCloser(br.GetRewoundReader()), func() {
_ = ogReader.Close()
})
if contentType != downloadRes.ContentType {
rctx.Log.Debugf("Expected '%s' content type but ended up with '%s'", downloadRes.ContentType, contentType)
}
if shouldCache { if shouldCache {
headers.Set("Cache-Control", "private, max-age=259200") // 3 days headers.Set("Cache-Control", "private, max-age=259200") // 3 days
} }
...@@ -107,7 +126,7 @@ beforeParseDownload: ...@@ -107,7 +126,7 @@ beforeParseDownload:
disposition := downloadRes.TargetDisposition disposition := downloadRes.TargetDisposition
if disposition == "" { if disposition == "" {
disposition = "inline" disposition = "attachment"
} else if disposition == "infer" { } else if disposition == "infer" {
if contentType == "" { if contentType == "" {
disposition = "attachment" disposition = "attachment"
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment