2017-05-26 08:57:09 +01:00
|
|
|
// Copyright 2017 Vector Creations Ltd
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2017-10-11 18:16:53 +01:00
|
|
|
package routing
|
2017-05-26 08:57:09 +01:00
|
|
|
|
|
|
|
import (
|
2017-09-21 15:44:00 +01:00
|
|
|
"context"
|
2017-05-26 08:57:09 +01:00
|
|
|
"encoding/json"
|
2017-05-26 13:42:51 +01:00
|
|
|
"fmt"
|
2017-05-31 12:46:21 +01:00
|
|
|
"io"
|
2021-02-17 13:54:53 +00:00
|
|
|
"io/ioutil"
|
2017-06-01 15:04:41 +01:00
|
|
|
"mime"
|
2017-05-26 08:57:09 +01:00
|
|
|
"net/http"
|
2020-06-16 18:31:38 +01:00
|
|
|
"net/url"
|
2017-05-31 12:46:21 +01:00
|
|
|
"os"
|
2017-05-31 16:56:11 +01:00
|
|
|
"path/filepath"
|
2017-05-26 13:42:51 +01:00
|
|
|
"regexp"
|
2017-05-31 12:46:21 +01:00
|
|
|
"strconv"
|
2017-06-07 00:12:49 +01:00
|
|
|
"strings"
|
2017-05-31 16:56:11 +01:00
|
|
|
"sync"
|
2020-06-17 11:53:26 +01:00
|
|
|
"unicode"
|
2017-05-26 08:57:09 +01:00
|
|
|
|
|
|
|
"github.com/matrix-org/dendrite/clientapi/jsonerror"
|
2017-05-31 12:46:21 +01:00
|
|
|
"github.com/matrix-org/dendrite/mediaapi/fileutils"
|
|
|
|
"github.com/matrix-org/dendrite/mediaapi/storage"
|
2017-06-07 00:12:49 +01:00
|
|
|
"github.com/matrix-org/dendrite/mediaapi/thumbnailer"
|
2017-05-26 08:57:09 +01:00
|
|
|
"github.com/matrix-org/dendrite/mediaapi/types"
|
2020-12-02 17:41:00 +00:00
|
|
|
"github.com/matrix-org/dendrite/setup/config"
|
2017-05-26 08:57:09 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
|
|
|
"github.com/matrix-org/util"
|
2017-09-19 11:40:21 +01:00
|
|
|
"github.com/pkg/errors"
|
2017-11-16 10:12:02 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2017-05-26 08:57:09 +01:00
|
|
|
)
|
|
|
|
|
2017-05-26 13:42:51 +01:00
|
|
|
const mediaIDCharacters = "A-Za-z0-9_=-"
|
|
|
|
|
|
|
|
// Note: unfortunately regex.MustCompile() cannot be assigned to a const
|
2020-05-13 12:04:54 +01:00
|
|
|
var mediaIDRegex = regexp.MustCompile("^[" + mediaIDCharacters + "]+$")
|
2017-05-26 13:42:51 +01:00
|
|
|
|
2020-06-17 14:26:45 +01:00
|
|
|
// Regular expressions to help us cope with Content-Disposition parsing
|
|
|
|
var rfc2183 = regexp.MustCompile(`filename\=utf-8\"(.*)\"`)
|
|
|
|
var rfc6266 = regexp.MustCompile(`filename\*\=utf-8\'\'(.*)`)
|
|
|
|
|
2017-06-07 00:12:49 +01:00
|
|
|
// downloadRequest metadata included in or derivable from a download or thumbnail request
|
2017-05-26 08:57:09 +01:00
|
|
|
// https://matrix.org/docs/spec/client_server/r0.2.0.html#get-matrix-media-r0-download-servername-mediaid
|
2017-06-07 00:12:49 +01:00
|
|
|
// http://matrix.org/docs/spec/client_server/r0.2.0.html#get-matrix-media-r0-thumbnail-servername-mediaid
|
2017-05-26 08:57:09 +01:00
|
|
|
type downloadRequest struct {
|
2017-06-07 00:12:49 +01:00
|
|
|
MediaMetadata *types.MediaMetadata
|
|
|
|
IsThumbnailRequest bool
|
|
|
|
ThumbnailSize types.ThumbnailSize
|
|
|
|
Logger *log.Entry
|
2020-06-17 11:53:26 +01:00
|
|
|
DownloadFilename string
|
2017-05-26 08:57:09 +01:00
|
|
|
}
|
|
|
|
|
2019-07-18 08:40:10 +01:00
|
|
|
// Download implements GET /download and GET /thumbnail
|
2017-05-31 12:46:21 +01:00
|
|
|
// Files from this server (i.e. origin == cfg.ServerName) are served directly
|
2017-05-31 16:56:11 +01:00
|
|
|
// Files from remote servers (i.e. origin != cfg.ServerName) are cached locally.
|
|
|
|
// If they are present in the cache, they are served directly.
|
|
|
|
// If they are not present in the cache, they are obtained from the remote server and
|
|
|
|
// simultaneously served back to the client and written into the cache.
|
2017-09-19 11:40:21 +01:00
|
|
|
func Download(
|
|
|
|
w http.ResponseWriter,
|
|
|
|
req *http.Request,
|
|
|
|
origin gomatrixserverlib.ServerName,
|
|
|
|
mediaID types.MediaID,
|
2020-08-10 14:18:04 +01:00
|
|
|
cfg *config.MediaAPI,
|
2020-01-03 14:07:05 +00:00
|
|
|
db storage.Database,
|
2017-09-21 16:20:10 +01:00
|
|
|
client *gomatrixserverlib.Client,
|
2017-09-19 11:40:21 +01:00
|
|
|
activeRemoteRequests *types.ActiveRemoteRequests,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
|
|
|
isThumbnailRequest bool,
|
2020-06-17 11:53:26 +01:00
|
|
|
customFilename string,
|
2017-09-19 11:40:21 +01:00
|
|
|
) {
|
|
|
|
dReq := &downloadRequest{
|
2017-05-26 08:57:09 +01:00
|
|
|
MediaMetadata: &types.MediaMetadata{
|
|
|
|
MediaID: mediaID,
|
|
|
|
Origin: origin,
|
|
|
|
},
|
2017-06-07 00:12:49 +01:00
|
|
|
IsThumbnailRequest: isThumbnailRequest,
|
2017-05-31 13:30:57 +01:00
|
|
|
Logger: util.GetLogger(req.Context()).WithFields(log.Fields{
|
|
|
|
"Origin": origin,
|
|
|
|
"MediaID": mediaID,
|
|
|
|
}),
|
2020-06-17 11:53:26 +01:00
|
|
|
DownloadFilename: customFilename,
|
2017-05-26 08:57:09 +01:00
|
|
|
}
|
|
|
|
|
2017-09-19 11:40:21 +01:00
|
|
|
if dReq.IsThumbnailRequest {
|
2017-06-07 00:12:49 +01:00
|
|
|
width, err := strconv.Atoi(req.FormValue("width"))
|
|
|
|
if err != nil {
|
|
|
|
width = -1
|
|
|
|
}
|
|
|
|
height, err := strconv.Atoi(req.FormValue("height"))
|
|
|
|
if err != nil {
|
|
|
|
height = -1
|
|
|
|
}
|
2017-09-19 11:40:21 +01:00
|
|
|
dReq.ThumbnailSize = types.ThumbnailSize{
|
2017-06-07 00:12:49 +01:00
|
|
|
Width: width,
|
|
|
|
Height: height,
|
|
|
|
ResizeMethod: strings.ToLower(req.FormValue("method")),
|
|
|
|
}
|
2017-09-19 11:40:21 +01:00
|
|
|
dReq.Logger.WithFields(log.Fields{
|
|
|
|
"RequestedWidth": dReq.ThumbnailSize.Width,
|
|
|
|
"RequestedHeight": dReq.ThumbnailSize.Height,
|
|
|
|
"RequestedResizeMethod": dReq.ThumbnailSize.ResizeMethod,
|
2017-06-07 00:12:49 +01:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-05-26 08:57:09 +01:00
|
|
|
// request validation
|
2017-09-19 11:40:21 +01:00
|
|
|
if resErr := dReq.Validate(); resErr != nil {
|
|
|
|
dReq.jsonErrorResponse(w, *resErr)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-09-21 15:44:00 +01:00
|
|
|
metadata, err := dReq.doDownload(
|
2017-09-21 16:20:10 +01:00
|
|
|
req.Context(), w, cfg, db, client,
|
|
|
|
activeRemoteRequests, activeThumbnailGeneration,
|
2017-09-21 15:44:00 +01:00
|
|
|
)
|
2017-09-19 11:40:21 +01:00
|
|
|
if err != nil {
|
|
|
|
// TODO: Handle the fact we might have started writing the response
|
2020-05-11 11:01:24 +01:00
|
|
|
dReq.jsonErrorResponse(w, util.JSONResponse{
|
|
|
|
Code: http.StatusNotFound,
|
|
|
|
JSON: jsonerror.NotFound("Failed to download: " + err.Error()),
|
|
|
|
})
|
2017-05-26 08:57:09 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-09-19 11:40:21 +01:00
|
|
|
if metadata == nil {
|
|
|
|
dReq.jsonErrorResponse(w, util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusNotFound,
|
2017-09-19 11:40:21 +01:00
|
|
|
JSON: jsonerror.NotFound("File not found"),
|
|
|
|
})
|
2017-05-31 12:46:21 +01:00
|
|
|
return
|
|
|
|
}
|
2017-09-19 11:40:21 +01:00
|
|
|
|
2017-05-26 08:57:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *downloadRequest) jsonErrorResponse(w http.ResponseWriter, res util.JSONResponse) {
|
|
|
|
// Marshal JSON response into raw bytes to send as the HTTP body
|
|
|
|
resBytes, err := json.Marshal(res.JSON)
|
|
|
|
if err != nil {
|
|
|
|
r.Logger.WithError(err).Error("Failed to marshal JSONResponse")
|
|
|
|
// this should never fail to be marshalled so drop err to the floor
|
2020-05-11 11:01:24 +01:00
|
|
|
res = util.MessageResponse(http.StatusNotFound, "Download request failed: "+err.Error())
|
2017-05-26 08:57:09 +01:00
|
|
|
resBytes, _ = json.Marshal(res.JSON)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set status code and write the body
|
|
|
|
w.WriteHeader(res.Code)
|
2022-01-31 10:48:28 +00:00
|
|
|
r.Logger.WithField("code", res.Code).Tracef("Responding (%d bytes)", len(resBytes))
|
2017-09-20 10:59:19 +01:00
|
|
|
|
|
|
|
// we don't really care that much if we fail to write the error response
|
|
|
|
w.Write(resBytes) // nolint: errcheck
|
2017-05-26 08:57:09 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Validate validates the downloadRequest fields
|
|
|
|
func (r *downloadRequest) Validate() *util.JSONResponse {
|
2017-09-20 14:15:38 +01:00
|
|
|
if !mediaIDRegex.MatchString(string(r.MediaMetadata.MediaID)) {
|
2017-05-26 08:57:09 +01:00
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusNotFound,
|
2017-05-26 13:42:51 +01:00
|
|
|
JSON: jsonerror.NotFound(fmt.Sprintf("mediaId must be a non-empty string using only characters in %v", mediaIDCharacters)),
|
2017-05-26 08:57:09 +01:00
|
|
|
}
|
|
|
|
}
|
2017-05-26 13:59:45 +01:00
|
|
|
// Note: the origin will be validated either by comparison to the configured server name of this homeserver
|
|
|
|
// or by a DNS SRV record lookup when creating a request for remote files
|
2017-05-26 08:57:09 +01:00
|
|
|
if r.MediaMetadata.Origin == "" {
|
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusNotFound,
|
2017-05-26 08:57:09 +01:00
|
|
|
JSON: jsonerror.NotFound("serverName must be a non-empty string"),
|
|
|
|
}
|
|
|
|
}
|
2017-06-07 00:12:49 +01:00
|
|
|
|
|
|
|
if r.IsThumbnailRequest {
|
|
|
|
if r.ThumbnailSize.Width <= 0 || r.ThumbnailSize.Height <= 0 {
|
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2017-06-07 00:12:49 +01:00
|
|
|
JSON: jsonerror.Unknown("width and height must be greater than 0"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Default method to scale if not set
|
|
|
|
if r.ThumbnailSize.ResizeMethod == "" {
|
2017-09-20 15:25:25 +01:00
|
|
|
r.ThumbnailSize.ResizeMethod = types.Scale
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
2017-09-20 15:25:25 +01:00
|
|
|
if r.ThumbnailSize.ResizeMethod != types.Crop && r.ThumbnailSize.ResizeMethod != types.Scale {
|
2017-06-07 00:12:49 +01:00
|
|
|
return &util.JSONResponse{
|
2018-03-13 15:55:45 +00:00
|
|
|
Code: http.StatusBadRequest,
|
2017-06-07 00:12:49 +01:00
|
|
|
JSON: jsonerror.Unknown("method must be one of crop or scale"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-05-26 08:57:09 +01:00
|
|
|
return nil
|
|
|
|
}
|
2017-05-31 12:46:21 +01:00
|
|
|
|
2017-09-19 11:40:21 +01:00
|
|
|
func (r *downloadRequest) doDownload(
|
2017-09-21 15:44:00 +01:00
|
|
|
ctx context.Context,
|
2017-09-19 11:40:21 +01:00
|
|
|
w http.ResponseWriter,
|
2020-08-10 14:18:04 +01:00
|
|
|
cfg *config.MediaAPI,
|
2020-01-03 14:07:05 +00:00
|
|
|
db storage.Database,
|
2017-09-21 16:20:10 +01:00
|
|
|
client *gomatrixserverlib.Client,
|
2017-09-19 11:40:21 +01:00
|
|
|
activeRemoteRequests *types.ActiveRemoteRequests,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
|
|
|
) (*types.MediaMetadata, error) {
|
2017-05-31 12:46:21 +01:00
|
|
|
// check if we have a record of the media in our database
|
2017-09-21 15:44:00 +01:00
|
|
|
mediaMetadata, err := db.GetMediaMetadata(
|
|
|
|
ctx, r.MediaMetadata.MediaID, r.MediaMetadata.Origin,
|
|
|
|
)
|
2017-05-31 13:29:28 +01:00
|
|
|
if err != nil {
|
2021-02-17 13:54:53 +00:00
|
|
|
return nil, fmt.Errorf("db.GetMediaMetadata: %w", err)
|
2017-05-31 13:29:28 +01:00
|
|
|
}
|
|
|
|
if mediaMetadata == nil {
|
2017-06-19 15:21:04 +01:00
|
|
|
if r.MediaMetadata.Origin == cfg.Matrix.ServerName {
|
2017-05-31 12:46:21 +01:00
|
|
|
// If we do not have a record and the origin is local, the file is not found
|
2017-09-19 11:40:21 +01:00
|
|
|
return nil, nil
|
2017-05-31 12:46:21 +01:00
|
|
|
}
|
2017-05-31 16:56:11 +01:00
|
|
|
// If we do not have a record and the origin is remote, we need to fetch it and respond with that file
|
2017-09-21 15:44:00 +01:00
|
|
|
resErr := r.getRemoteFile(
|
2017-09-21 16:20:10 +01:00
|
|
|
ctx, client, cfg, db, activeRemoteRequests, activeThumbnailGeneration,
|
2017-09-21 15:44:00 +01:00
|
|
|
)
|
2017-06-01 11:32:15 +01:00
|
|
|
if resErr != nil {
|
2017-09-19 11:40:21 +01:00
|
|
|
return nil, resErr
|
2017-06-01 11:32:15 +01:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// If we have a record, we can respond from the local file
|
|
|
|
r.MediaMetadata = mediaMetadata
|
2017-05-31 12:46:21 +01:00
|
|
|
}
|
2017-09-21 15:44:00 +01:00
|
|
|
return r.respondFromLocalFile(
|
2020-08-10 14:18:04 +01:00
|
|
|
ctx, w, cfg.AbsBasePath, activeThumbnailGeneration,
|
|
|
|
cfg.MaxThumbnailGenerators, db,
|
|
|
|
cfg.DynamicThumbnails, cfg.ThumbnailSizes,
|
2017-09-21 15:44:00 +01:00
|
|
|
)
|
2017-05-31 12:46:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// respondFromLocalFile reads a file from local storage and writes it to the http.ResponseWriter
|
2017-09-19 11:40:21 +01:00
|
|
|
// If no file was found then returns nil, nil
|
|
|
|
func (r *downloadRequest) respondFromLocalFile(
|
2017-09-21 15:44:00 +01:00
|
|
|
ctx context.Context,
|
2017-09-19 11:40:21 +01:00
|
|
|
w http.ResponseWriter,
|
|
|
|
absBasePath config.Path,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
|
|
|
maxThumbnailGenerators int,
|
2020-01-03 14:07:05 +00:00
|
|
|
db storage.Database,
|
2017-09-19 11:40:21 +01:00
|
|
|
dynamicThumbnails bool,
|
|
|
|
thumbnailSizes []config.ThumbnailSize,
|
|
|
|
) (*types.MediaMetadata, error) {
|
2017-05-31 12:46:21 +01:00
|
|
|
filePath, err := fileutils.GetPathFromBase64Hash(r.MediaMetadata.Base64Hash, absBasePath)
|
|
|
|
if err != nil {
|
2021-02-17 13:54:53 +00:00
|
|
|
return nil, fmt.Errorf("fileutils.GetPathFromBase64Hash: %w", err)
|
2017-05-31 12:46:21 +01:00
|
|
|
}
|
|
|
|
file, err := os.Open(filePath)
|
2017-09-20 14:54:17 +01:00
|
|
|
defer file.Close() // nolint: errcheck, staticcheck, megacheck
|
2017-05-31 12:46:21 +01:00
|
|
|
if err != nil {
|
2021-02-17 13:54:53 +00:00
|
|
|
return nil, fmt.Errorf("os.Open: %w", err)
|
2017-05-31 12:46:21 +01:00
|
|
|
}
|
|
|
|
stat, err := file.Stat()
|
|
|
|
if err != nil {
|
2021-02-17 13:54:53 +00:00
|
|
|
return nil, fmt.Errorf("file.Stat: %w", err)
|
2017-05-31 12:46:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if r.MediaMetadata.FileSizeBytes > 0 && int64(r.MediaMetadata.FileSizeBytes) != stat.Size() {
|
|
|
|
r.Logger.WithFields(log.Fields{
|
|
|
|
"fileSizeDatabase": r.MediaMetadata.FileSizeBytes,
|
|
|
|
"fileSizeDisk": stat.Size(),
|
|
|
|
}).Warn("File size in database and on-disk differ.")
|
2017-09-19 11:40:21 +01:00
|
|
|
return nil, errors.New("file size in database and on-disk differ")
|
2017-05-31 12:46:21 +01:00
|
|
|
}
|
|
|
|
|
2017-06-07 00:12:49 +01:00
|
|
|
var responseFile *os.File
|
|
|
|
var responseMetadata *types.MediaMetadata
|
|
|
|
if r.IsThumbnailRequest {
|
2017-09-21 15:44:00 +01:00
|
|
|
thumbFile, thumbMetadata, resErr := r.getThumbnailFile(
|
|
|
|
ctx, types.Path(filePath), activeThumbnailGeneration, maxThumbnailGenerators,
|
|
|
|
db, dynamicThumbnails, thumbnailSizes,
|
|
|
|
)
|
2017-06-07 00:12:49 +01:00
|
|
|
if thumbFile != nil {
|
2017-09-20 10:59:19 +01:00
|
|
|
defer thumbFile.Close() // nolint: errcheck
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
|
|
|
if resErr != nil {
|
2017-09-19 11:40:21 +01:00
|
|
|
return nil, resErr
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
|
|
|
if thumbFile == nil {
|
|
|
|
r.Logger.WithFields(log.Fields{
|
|
|
|
"UploadName": r.MediaMetadata.UploadName,
|
|
|
|
"Base64Hash": r.MediaMetadata.Base64Hash,
|
|
|
|
"FileSizeBytes": r.MediaMetadata.FileSizeBytes,
|
|
|
|
"ContentType": r.MediaMetadata.ContentType,
|
2022-01-31 10:48:28 +00:00
|
|
|
}).Trace("No good thumbnail found. Responding with original file.")
|
2017-06-07 00:12:49 +01:00
|
|
|
responseFile = file
|
|
|
|
responseMetadata = r.MediaMetadata
|
|
|
|
} else {
|
2022-01-31 10:48:28 +00:00
|
|
|
r.Logger.Trace("Responding with thumbnail")
|
2017-06-07 00:12:49 +01:00
|
|
|
responseFile = thumbFile
|
|
|
|
responseMetadata = thumbMetadata.MediaMetadata
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
r.Logger.WithFields(log.Fields{
|
|
|
|
"UploadName": r.MediaMetadata.UploadName,
|
|
|
|
"Base64Hash": r.MediaMetadata.Base64Hash,
|
|
|
|
"FileSizeBytes": r.MediaMetadata.FileSizeBytes,
|
|
|
|
"ContentType": r.MediaMetadata.ContentType,
|
2022-01-31 10:48:28 +00:00
|
|
|
}).Trace("Responding with file")
|
2017-06-07 00:12:49 +01:00
|
|
|
responseFile = file
|
|
|
|
responseMetadata = r.MediaMetadata
|
2020-06-17 11:53:26 +01:00
|
|
|
if err := r.addDownloadFilenameToHeaders(w, responseMetadata); err != nil {
|
|
|
|
return nil, err
|
2019-07-08 14:06:17 +01:00
|
|
|
}
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
2017-05-31 12:46:21 +01:00
|
|
|
|
2017-06-07 00:12:49 +01:00
|
|
|
w.Header().Set("Content-Type", string(responseMetadata.ContentType))
|
|
|
|
w.Header().Set("Content-Length", strconv.FormatInt(int64(responseMetadata.FileSizeBytes), 10))
|
2017-05-31 12:46:21 +01:00
|
|
|
contentSecurityPolicy := "default-src 'none';" +
|
|
|
|
" script-src 'none';" +
|
|
|
|
" plugin-types application/pdf;" +
|
|
|
|
" style-src 'unsafe-inline';" +
|
|
|
|
" object-src 'self';"
|
|
|
|
w.Header().Set("Content-Security-Policy", contentSecurityPolicy)
|
|
|
|
|
2017-09-19 11:40:21 +01:00
|
|
|
if _, err := io.Copy(w, responseFile); err != nil {
|
2021-02-17 13:54:53 +00:00
|
|
|
return nil, fmt.Errorf("io.Copy: %w", err)
|
2017-05-31 12:46:21 +01:00
|
|
|
}
|
2017-09-19 11:40:21 +01:00
|
|
|
return responseMetadata, nil
|
2017-05-31 12:46:21 +01:00
|
|
|
}
|
2017-05-31 16:56:11 +01:00
|
|
|
|
2020-06-17 11:53:26 +01:00
|
|
|
func (r *downloadRequest) addDownloadFilenameToHeaders(
|
|
|
|
w http.ResponseWriter,
|
|
|
|
responseMetadata *types.MediaMetadata,
|
|
|
|
) error {
|
|
|
|
// If the requestor supplied a filename to name the download then
|
|
|
|
// use that, otherwise use the filename from the response metadata.
|
|
|
|
filename := string(responseMetadata.UploadName)
|
|
|
|
if r.DownloadFilename != "" {
|
|
|
|
filename = r.DownloadFilename
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(filename) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
unescaped, err := url.PathUnescape(filename)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("url.PathUnescape: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
isASCII := true // Is the string ASCII or UTF-8?
|
|
|
|
quote := `` // Encloses the string (ASCII only)
|
|
|
|
for i := 0; i < len(unescaped); i++ {
|
|
|
|
if unescaped[i] > unicode.MaxASCII {
|
|
|
|
isASCII = false
|
|
|
|
}
|
|
|
|
if unescaped[i] == 0x20 || unescaped[i] == 0x3B {
|
|
|
|
// If the filename contains a space or a semicolon, which
|
|
|
|
// are special characters in Content-Disposition
|
|
|
|
quote = `"`
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We don't necessarily want a full escape as the Content-Disposition
|
|
|
|
// can take many of the characters that PathEscape would otherwise and
|
|
|
|
// browser support for encoding is a bit wild, so we'll escape only
|
|
|
|
// the characters that we know will mess up the parsing of the
|
|
|
|
// Content-Disposition header elements themselves
|
|
|
|
unescaped = strings.ReplaceAll(unescaped, `\`, `\\"`)
|
|
|
|
unescaped = strings.ReplaceAll(unescaped, `"`, `\"`)
|
|
|
|
|
|
|
|
if isASCII {
|
|
|
|
// For ASCII filenames, we should only quote the filename if
|
|
|
|
// it needs to be done, e.g. it contains a space or a character
|
|
|
|
// that would otherwise be parsed as a control character in the
|
|
|
|
// Content-Disposition header
|
|
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf(
|
|
|
|
`inline; filename=%s%s%s`,
|
|
|
|
quote, unescaped, quote,
|
|
|
|
))
|
|
|
|
} else {
|
|
|
|
// For UTF-8 filenames, we quote always, as that's the standard
|
|
|
|
w.Header().Set("Content-Disposition", fmt.Sprintf(
|
2020-06-17 14:26:45 +01:00
|
|
|
`inline; filename*=utf-8''%s`,
|
|
|
|
url.QueryEscape(unescaped),
|
2020-06-17 11:53:26 +01:00
|
|
|
))
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-06-07 00:12:49 +01:00
|
|
|
// Note: Thumbnail generation may be ongoing asynchronously.
|
2017-09-19 11:40:21 +01:00
|
|
|
// If no thumbnail was found then returns nil, nil, nil
|
|
|
|
func (r *downloadRequest) getThumbnailFile(
|
2017-09-21 15:44:00 +01:00
|
|
|
ctx context.Context,
|
2017-09-19 11:40:21 +01:00
|
|
|
filePath types.Path,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
|
|
|
maxThumbnailGenerators int,
|
2020-01-03 14:07:05 +00:00
|
|
|
db storage.Database,
|
2017-09-19 11:40:21 +01:00
|
|
|
dynamicThumbnails bool,
|
|
|
|
thumbnailSizes []config.ThumbnailSize,
|
|
|
|
) (*os.File, *types.ThumbnailMetadata, error) {
|
2017-06-07 00:12:49 +01:00
|
|
|
var thumbnail *types.ThumbnailMetadata
|
2017-09-19 11:40:21 +01:00
|
|
|
var err error
|
2017-06-07 00:12:49 +01:00
|
|
|
|
|
|
|
if dynamicThumbnails {
|
2017-09-21 15:44:00 +01:00
|
|
|
thumbnail, err = r.generateThumbnail(
|
|
|
|
ctx, filePath, r.ThumbnailSize, activeThumbnailGeneration,
|
|
|
|
maxThumbnailGenerators, db,
|
|
|
|
)
|
2017-09-19 11:40:21 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// If dynamicThumbnails is true but there are too many thumbnails being actively generated, we can fall back
|
|
|
|
// to trying to use a pre-generated thumbnail
|
|
|
|
if thumbnail == nil {
|
2017-09-19 11:40:21 +01:00
|
|
|
var thumbnails []*types.ThumbnailMetadata
|
2017-09-21 15:44:00 +01:00
|
|
|
thumbnails, err = db.GetThumbnails(
|
|
|
|
ctx, r.MediaMetadata.MediaID, r.MediaMetadata.Origin,
|
|
|
|
)
|
2017-06-07 00:12:49 +01:00
|
|
|
if err != nil {
|
2021-02-17 13:54:53 +00:00
|
|
|
return nil, nil, fmt.Errorf("db.GetThumbnails: %w", err)
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// If we get a thumbnailSize, a pre-generated thumbnail would be best but it is not yet generated.
|
|
|
|
// If we get a thumbnail, we're done.
|
|
|
|
var thumbnailSize *types.ThumbnailSize
|
|
|
|
thumbnail, thumbnailSize = thumbnailer.SelectThumbnail(r.ThumbnailSize, thumbnails, thumbnailSizes)
|
|
|
|
// If dynamicThumbnails is true and we are not over-loaded then we would have generated what was requested above.
|
|
|
|
// So we don't try to generate a pre-generated thumbnail here.
|
2017-09-20 14:15:38 +01:00
|
|
|
if thumbnailSize != nil && !dynamicThumbnails {
|
2017-06-07 00:12:49 +01:00
|
|
|
r.Logger.WithFields(log.Fields{
|
|
|
|
"Width": thumbnailSize.Width,
|
|
|
|
"Height": thumbnailSize.Height,
|
|
|
|
"ResizeMethod": thumbnailSize.ResizeMethod,
|
2022-01-31 10:48:28 +00:00
|
|
|
}).Debug("Pre-generating thumbnail for immediate response.")
|
2017-09-21 15:44:00 +01:00
|
|
|
thumbnail, err = r.generateThumbnail(
|
|
|
|
ctx, filePath, *thumbnailSize, activeThumbnailGeneration,
|
|
|
|
maxThumbnailGenerators, db,
|
|
|
|
)
|
2017-09-19 11:40:21 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if thumbnail == nil {
|
|
|
|
return nil, nil, nil
|
|
|
|
}
|
|
|
|
r.Logger = r.Logger.WithFields(log.Fields{
|
|
|
|
"Width": thumbnail.ThumbnailSize.Width,
|
|
|
|
"Height": thumbnail.ThumbnailSize.Height,
|
|
|
|
"ResizeMethod": thumbnail.ThumbnailSize.ResizeMethod,
|
|
|
|
"FileSizeBytes": thumbnail.MediaMetadata.FileSizeBytes,
|
|
|
|
"ContentType": thumbnail.MediaMetadata.ContentType,
|
|
|
|
})
|
|
|
|
thumbPath := string(thumbnailer.GetThumbnailPath(types.Path(filePath), thumbnail.ThumbnailSize))
|
|
|
|
thumbFile, err := os.Open(string(thumbPath))
|
|
|
|
if err != nil {
|
2017-09-20 10:59:19 +01:00
|
|
|
thumbFile.Close() // nolint: errcheck
|
2021-02-17 13:54:53 +00:00
|
|
|
return nil, nil, fmt.Errorf("os.Open: %w", err)
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
|
|
|
thumbStat, err := thumbFile.Stat()
|
|
|
|
if err != nil {
|
2017-09-20 10:59:19 +01:00
|
|
|
thumbFile.Close() // nolint: errcheck
|
2021-02-17 13:54:53 +00:00
|
|
|
return nil, nil, fmt.Errorf("thumbFile.Stat: %w", err)
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
|
|
|
if types.FileSizeBytes(thumbStat.Size()) != thumbnail.MediaMetadata.FileSizeBytes {
|
2017-09-20 10:59:19 +01:00
|
|
|
thumbFile.Close() // nolint: errcheck
|
2017-09-19 11:40:21 +01:00
|
|
|
return nil, nil, errors.New("thumbnail file sizes on disk and in database differ")
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
|
|
|
return thumbFile, thumbnail, nil
|
|
|
|
}
|
|
|
|
|
2017-09-19 11:40:21 +01:00
|
|
|
func (r *downloadRequest) generateThumbnail(
|
2017-09-21 15:44:00 +01:00
|
|
|
ctx context.Context,
|
2017-09-19 11:40:21 +01:00
|
|
|
filePath types.Path,
|
|
|
|
thumbnailSize types.ThumbnailSize,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
|
|
|
maxThumbnailGenerators int,
|
2020-01-03 14:07:05 +00:00
|
|
|
db storage.Database,
|
2017-09-19 11:40:21 +01:00
|
|
|
) (*types.ThumbnailMetadata, error) {
|
|
|
|
r.Logger.WithFields(log.Fields{
|
2017-06-07 00:12:49 +01:00
|
|
|
"Width": thumbnailSize.Width,
|
|
|
|
"Height": thumbnailSize.Height,
|
|
|
|
"ResizeMethod": thumbnailSize.ResizeMethod,
|
|
|
|
})
|
2017-09-21 15:44:00 +01:00
|
|
|
busy, err := thumbnailer.GenerateThumbnail(
|
|
|
|
ctx, filePath, thumbnailSize, r.MediaMetadata,
|
|
|
|
activeThumbnailGeneration, maxThumbnailGenerators, db, r.Logger,
|
|
|
|
)
|
2017-06-07 00:12:49 +01:00
|
|
|
if err != nil {
|
2021-02-17 13:54:53 +00:00
|
|
|
return nil, fmt.Errorf("thumbnailer.GenerateThumbnail: %w", err)
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
|
|
|
if busy {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
var thumbnail *types.ThumbnailMetadata
|
2017-09-21 15:44:00 +01:00
|
|
|
thumbnail, err = db.GetThumbnail(
|
|
|
|
ctx, r.MediaMetadata.MediaID, r.MediaMetadata.Origin,
|
|
|
|
thumbnailSize.Width, thumbnailSize.Height, thumbnailSize.ResizeMethod,
|
|
|
|
)
|
2017-06-07 00:12:49 +01:00
|
|
|
if err != nil {
|
2021-02-17 13:54:53 +00:00
|
|
|
return nil, fmt.Errorf("db.GetThumbnail: %w", err)
|
2017-06-07 00:12:49 +01:00
|
|
|
}
|
|
|
|
return thumbnail, nil
|
|
|
|
}
|
|
|
|
|
2017-06-01 11:32:15 +01:00
|
|
|
// getRemoteFile fetches the remote file and caches it locally
|
2017-05-31 16:56:11 +01:00
|
|
|
// A hash map of active remote requests to a struct containing a sync.Cond is used to only download remote files once,
|
|
|
|
// regardless of how many download requests are received.
|
2017-06-01 11:32:15 +01:00
|
|
|
// Note: The named errorResponse return variable is used in a deferred broadcast of the metadata and error response to waiting goroutines.
|
2017-09-19 11:40:21 +01:00
|
|
|
func (r *downloadRequest) getRemoteFile(
|
2017-09-21 15:44:00 +01:00
|
|
|
ctx context.Context,
|
2017-09-21 16:20:10 +01:00
|
|
|
client *gomatrixserverlib.Client,
|
2020-08-10 14:18:04 +01:00
|
|
|
cfg *config.MediaAPI,
|
2020-01-03 14:07:05 +00:00
|
|
|
db storage.Database,
|
2017-09-19 11:40:21 +01:00
|
|
|
activeRemoteRequests *types.ActiveRemoteRequests,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
|
|
|
) (errorResponse error) {
|
2017-06-01 11:32:15 +01:00
|
|
|
// Note: getMediaMetadataFromActiveRequest uses mutexes and conditions from activeRemoteRequests
|
|
|
|
mediaMetadata, resErr := r.getMediaMetadataFromActiveRequest(activeRemoteRequests)
|
2017-05-31 16:56:11 +01:00
|
|
|
if resErr != nil {
|
|
|
|
return resErr
|
|
|
|
} else if mediaMetadata != nil {
|
2017-06-01 11:32:15 +01:00
|
|
|
// If we got metadata from an active request, we can respond from the local file
|
2017-05-31 16:56:11 +01:00
|
|
|
r.MediaMetadata = mediaMetadata
|
|
|
|
} else {
|
2017-06-01 11:32:15 +01:00
|
|
|
// Note: This is an active request that MUST broadcastMediaMetadata to wake up waiting goroutines!
|
|
|
|
// Note: broadcastMediaMetadata uses mutexes and conditions from activeRemoteRequests
|
2017-06-01 13:44:00 +01:00
|
|
|
defer func() {
|
|
|
|
// Note: errorResponse is the named return variable so we wrap this in a closure to re-evaluate the arguments at defer-time
|
2017-06-01 13:54:59 +01:00
|
|
|
if err := recover(); err != nil {
|
2017-09-19 11:40:21 +01:00
|
|
|
r.broadcastMediaMetadata(activeRemoteRequests, errors.New("paniced"))
|
2017-06-01 13:54:59 +01:00
|
|
|
panic(err)
|
|
|
|
}
|
2017-06-01 13:44:00 +01:00
|
|
|
r.broadcastMediaMetadata(activeRemoteRequests, errorResponse)
|
|
|
|
}()
|
2017-06-01 11:32:15 +01:00
|
|
|
|
|
|
|
// check if we have a record of the media in our database
|
2017-09-21 15:44:00 +01:00
|
|
|
mediaMetadata, err := db.GetMediaMetadata(
|
|
|
|
ctx, r.MediaMetadata.MediaID, r.MediaMetadata.Origin,
|
|
|
|
)
|
2017-06-01 11:32:15 +01:00
|
|
|
if err != nil {
|
2021-02-17 13:54:53 +00:00
|
|
|
return fmt.Errorf("db.GetMediaMetadata: %w", err)
|
2017-06-01 11:32:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if mediaMetadata == nil {
|
|
|
|
// If we do not have a record, we need to fetch the remote file first and then respond from the local file
|
2017-09-21 15:44:00 +01:00
|
|
|
err := r.fetchRemoteFileAndStoreMetadata(
|
2017-09-21 16:20:10 +01:00
|
|
|
ctx, client,
|
2022-05-02 09:47:16 +01:00
|
|
|
cfg.AbsBasePath, cfg.MaxFileSizeBytes, db,
|
2020-08-10 14:18:04 +01:00
|
|
|
cfg.ThumbnailSizes, activeThumbnailGeneration,
|
|
|
|
cfg.MaxThumbnailGenerators,
|
2017-09-21 15:44:00 +01:00
|
|
|
)
|
2017-09-19 11:40:21 +01:00
|
|
|
if err != nil {
|
2022-03-16 11:16:27 +00:00
|
|
|
r.Logger.WithError(err).Errorf("r.fetchRemoteFileAndStoreMetadata: failed to fetch remote file")
|
|
|
|
return err
|
2017-06-01 11:32:15 +01:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// If we have a record, we can respond from the local file
|
|
|
|
r.MediaMetadata = mediaMetadata
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
|
|
|
}
|
2017-09-19 11:40:21 +01:00
|
|
|
return nil
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
|
|
|
|
2017-09-19 11:40:21 +01:00
|
|
|
func (r *downloadRequest) getMediaMetadataFromActiveRequest(activeRemoteRequests *types.ActiveRemoteRequests) (*types.MediaMetadata, error) {
|
2017-06-01 11:32:15 +01:00
|
|
|
// Check if there is an active remote request for the file
|
|
|
|
mxcURL := "mxc://" + string(r.MediaMetadata.Origin) + "/" + string(r.MediaMetadata.MediaID)
|
|
|
|
|
2017-05-31 16:56:11 +01:00
|
|
|
activeRemoteRequests.Lock()
|
|
|
|
defer activeRemoteRequests.Unlock()
|
|
|
|
|
|
|
|
if activeRemoteRequestResult, ok := activeRemoteRequests.MXCToResult[mxcURL]; ok {
|
2022-01-31 10:48:28 +00:00
|
|
|
r.Logger.Trace("Waiting for another goroutine to fetch the remote file.")
|
2017-05-31 16:56:11 +01:00
|
|
|
|
2017-06-01 07:39:35 +01:00
|
|
|
// NOTE: Wait unlocks and locks again internally. There is still a deferred Unlock() that will unlock this.
|
2017-05-31 16:56:11 +01:00
|
|
|
activeRemoteRequestResult.Cond.Wait()
|
2017-09-19 11:40:21 +01:00
|
|
|
if activeRemoteRequestResult.Error != nil {
|
|
|
|
return nil, activeRemoteRequestResult.Error
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
|
|
|
|
2017-06-01 11:32:15 +01:00
|
|
|
if activeRemoteRequestResult.MediaMetadata == nil {
|
2017-09-19 11:40:21 +01:00
|
|
|
return nil, nil
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
2017-06-01 11:32:15 +01:00
|
|
|
|
|
|
|
return activeRemoteRequestResult.MediaMetadata, nil
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// No active remote request so create one
|
|
|
|
activeRemoteRequests.MXCToResult[mxcURL] = &types.RemoteRequestResult{
|
|
|
|
Cond: &sync.Cond{L: activeRemoteRequests},
|
|
|
|
}
|
2017-06-01 11:32:15 +01:00
|
|
|
|
2017-05-31 16:56:11 +01:00
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2017-06-01 11:32:15 +01:00
|
|
|
// broadcastMediaMetadata broadcasts the media metadata and error response to waiting goroutines
|
2017-05-31 16:56:11 +01:00
|
|
|
// Only the owner of the activeRemoteRequestResult for this origin and media ID should call this function.
|
2017-09-19 11:40:21 +01:00
|
|
|
func (r *downloadRequest) broadcastMediaMetadata(activeRemoteRequests *types.ActiveRemoteRequests, err error) {
|
2017-06-01 11:32:15 +01:00
|
|
|
activeRemoteRequests.Lock()
|
|
|
|
defer activeRemoteRequests.Unlock()
|
|
|
|
mxcURL := "mxc://" + string(r.MediaMetadata.Origin) + "/" + string(r.MediaMetadata.MediaID)
|
|
|
|
if activeRemoteRequestResult, ok := activeRemoteRequests.MXCToResult[mxcURL]; ok {
|
2022-01-31 10:48:28 +00:00
|
|
|
r.Logger.Trace("Signalling other goroutines waiting for this goroutine to fetch the file.")
|
2017-06-01 11:32:15 +01:00
|
|
|
activeRemoteRequestResult.MediaMetadata = r.MediaMetadata
|
2017-09-19 11:40:21 +01:00
|
|
|
activeRemoteRequestResult.Error = err
|
2017-06-01 11:32:15 +01:00
|
|
|
activeRemoteRequestResult.Cond.Broadcast()
|
|
|
|
}
|
|
|
|
delete(activeRemoteRequests.MXCToResult, mxcURL)
|
|
|
|
}
|
2017-05-31 16:56:11 +01:00
|
|
|
|
2017-06-01 11:32:15 +01:00
|
|
|
// fetchRemoteFileAndStoreMetadata fetches the file from the remote server and stores its metadata in the database
|
2017-09-19 11:40:21 +01:00
|
|
|
func (r *downloadRequest) fetchRemoteFileAndStoreMetadata(
|
2017-09-21 15:44:00 +01:00
|
|
|
ctx context.Context,
|
2017-09-21 16:20:10 +01:00
|
|
|
client *gomatrixserverlib.Client,
|
2017-09-19 11:40:21 +01:00
|
|
|
absBasePath config.Path,
|
|
|
|
maxFileSizeBytes config.FileSizeBytes,
|
2020-01-03 14:07:05 +00:00
|
|
|
db storage.Database,
|
2017-09-19 11:40:21 +01:00
|
|
|
thumbnailSizes []config.ThumbnailSize,
|
|
|
|
activeThumbnailGeneration *types.ActiveThumbnailGeneration,
|
|
|
|
maxThumbnailGenerators int,
|
|
|
|
) error {
|
2017-09-21 16:20:10 +01:00
|
|
|
finalPath, duplicate, err := r.fetchRemoteFile(
|
|
|
|
ctx, client, absBasePath, maxFileSizeBytes,
|
|
|
|
)
|
2017-09-19 11:40:21 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
r.Logger.WithFields(log.Fields{
|
|
|
|
"Base64Hash": r.MediaMetadata.Base64Hash,
|
|
|
|
"UploadName": r.MediaMetadata.UploadName,
|
|
|
|
"FileSizeBytes": r.MediaMetadata.FileSizeBytes,
|
2017-06-07 00:12:49 +01:00
|
|
|
"ContentType": r.MediaMetadata.ContentType,
|
2022-01-31 10:48:28 +00:00
|
|
|
}).Debug("Storing file metadata to media repository database")
|
2017-05-31 16:56:11 +01:00
|
|
|
|
|
|
|
// FIXME: timeout db request
|
2017-09-21 15:44:00 +01:00
|
|
|
if err := db.StoreMediaMetadata(ctx, r.MediaMetadata); err != nil {
|
2017-05-31 16:56:11 +01:00
|
|
|
// If the file is a duplicate (has the same hash as an existing file) then
|
|
|
|
// there is valid metadata in the database for that file. As such we only
|
|
|
|
// remove the file if it is not a duplicate.
|
2017-09-20 14:15:38 +01:00
|
|
|
if !duplicate {
|
2017-05-31 16:56:11 +01:00
|
|
|
finalDir := filepath.Dir(string(finalPath))
|
|
|
|
fileutils.RemoveDir(types.Path(finalDir), r.Logger)
|
|
|
|
}
|
|
|
|
// NOTE: It should really not be possible to fail the uniqueness test here so
|
|
|
|
// there is no need to handle that separately
|
2017-09-19 11:40:21 +01:00
|
|
|
return errors.New("failed to store file metadata in DB")
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
|
|
|
|
2017-06-07 00:12:49 +01:00
|
|
|
go func() {
|
2017-09-21 15:44:00 +01:00
|
|
|
busy, err := thumbnailer.GenerateThumbnails(
|
|
|
|
context.Background(), finalPath, thumbnailSizes, r.MediaMetadata,
|
|
|
|
activeThumbnailGeneration, maxThumbnailGenerators, db, r.Logger,
|
|
|
|
)
|
2017-06-07 00:12:49 +01:00
|
|
|
if err != nil {
|
|
|
|
r.Logger.WithError(err).Warn("Error generating thumbnails")
|
|
|
|
}
|
|
|
|
if busy {
|
|
|
|
r.Logger.Warn("Maximum number of active thumbnail generators reached. Skipping pre-generation.")
|
|
|
|
}
|
|
|
|
}()
|
2017-05-31 16:56:11 +01:00
|
|
|
|
|
|
|
r.Logger.WithFields(log.Fields{
|
|
|
|
"UploadName": r.MediaMetadata.UploadName,
|
|
|
|
"Base64Hash": r.MediaMetadata.Base64Hash,
|
|
|
|
"FileSizeBytes": r.MediaMetadata.FileSizeBytes,
|
2017-06-07 00:12:49 +01:00
|
|
|
"ContentType": r.MediaMetadata.ContentType,
|
2022-01-31 10:48:28 +00:00
|
|
|
}).Debug("Remote file cached")
|
2017-05-31 16:56:11 +01:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-17 13:54:53 +00:00
|
|
|
func (r *downloadRequest) GetContentLengthAndReader(contentLengthHeader string, body *io.ReadCloser, maxFileSizeBytes config.FileSizeBytes) (int64, io.Reader, error) {
|
|
|
|
reader := *body
|
|
|
|
var contentLength int64
|
|
|
|
|
|
|
|
if contentLengthHeader != "" {
|
|
|
|
// A Content-Length header is provided. Let's try to parse it.
|
|
|
|
parsedLength, parseErr := strconv.ParseInt(contentLengthHeader, 10, 64)
|
|
|
|
if parseErr != nil {
|
|
|
|
r.Logger.WithError(parseErr).Warn("Failed to parse content length")
|
|
|
|
return 0, nil, fmt.Errorf("strconv.ParseInt: %w", parseErr)
|
|
|
|
}
|
2021-06-22 10:01:44 +01:00
|
|
|
if maxFileSizeBytes > 0 && parsedLength > int64(maxFileSizeBytes) {
|
2021-02-17 13:54:53 +00:00
|
|
|
return 0, nil, fmt.Errorf(
|
|
|
|
"remote file size (%d bytes) exceeds locally configured max media size (%d bytes)",
|
|
|
|
parsedLength, maxFileSizeBytes,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// We successfully parsed the Content-Length, so we'll return a limited
|
|
|
|
// reader that restricts us to reading only up to this size.
|
|
|
|
reader = ioutil.NopCloser(io.LimitReader(*body, parsedLength))
|
|
|
|
contentLength = parsedLength
|
|
|
|
} else {
|
|
|
|
// Content-Length header is missing. If we have a maximum file size
|
|
|
|
// configured then we'll just make sure that the reader is limited to
|
|
|
|
// that size. We'll return a zero content length, but that's OK, since
|
|
|
|
// ultimately it will get rewritten later when the temp file is written
|
|
|
|
// to disk.
|
|
|
|
if maxFileSizeBytes > 0 {
|
|
|
|
reader = ioutil.NopCloser(io.LimitReader(*body, int64(maxFileSizeBytes)))
|
|
|
|
}
|
|
|
|
contentLength = 0
|
|
|
|
}
|
|
|
|
|
|
|
|
return contentLength, reader, nil
|
|
|
|
}
|
|
|
|
|
2017-09-21 16:20:10 +01:00
|
|
|
func (r *downloadRequest) fetchRemoteFile(
|
|
|
|
ctx context.Context,
|
|
|
|
client *gomatrixserverlib.Client,
|
|
|
|
absBasePath config.Path,
|
|
|
|
maxFileSizeBytes config.FileSizeBytes,
|
|
|
|
) (types.Path, bool, error) {
|
2022-01-31 10:48:28 +00:00
|
|
|
r.Logger.Debug("Fetching remote file")
|
2017-05-31 16:56:11 +01:00
|
|
|
|
|
|
|
// create request for remote file
|
2022-03-16 11:16:27 +00:00
|
|
|
resp, err := client.CreateMediaDownloadRequest(ctx, r.MediaMetadata.Origin, string(r.MediaMetadata.MediaID))
|
2022-03-18 16:21:15 +00:00
|
|
|
if err != nil || (resp != nil && resp.StatusCode != http.StatusOK) {
|
|
|
|
if resp != nil && resp.StatusCode == http.StatusNotFound {
|
2022-03-16 11:16:27 +00:00
|
|
|
return "", false, fmt.Errorf("File with media ID %q does not exist on %s", r.MediaMetadata.MediaID, r.MediaMetadata.Origin)
|
|
|
|
}
|
|
|
|
return "", false, fmt.Errorf("file with media ID %q could not be downloaded from %s", r.MediaMetadata.MediaID, r.MediaMetadata.Origin)
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
2017-09-20 10:59:19 +01:00
|
|
|
defer resp.Body.Close() // nolint: errcheck
|
2017-05-31 16:56:11 +01:00
|
|
|
|
2021-02-17 13:54:53 +00:00
|
|
|
// The reader returned here will be limited either by the Content-Length
|
|
|
|
// and/or the configured maximum media size.
|
|
|
|
contentLength, reader, parseErr := r.GetContentLengthAndReader(resp.Header.Get("Content-Length"), &resp.Body, maxFileSizeBytes)
|
|
|
|
if parseErr != nil {
|
|
|
|
return "", false, parseErr
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
2021-02-17 13:54:53 +00:00
|
|
|
|
2021-11-02 16:35:15 +00:00
|
|
|
if maxFileSizeBytes > 0 && contentLength > int64(maxFileSizeBytes) {
|
2017-09-19 11:40:21 +01:00
|
|
|
// TODO: Bubble up this as a 413
|
|
|
|
return "", false, fmt.Errorf("remote file is too large (%v > %v bytes)", contentLength, maxFileSizeBytes)
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
2021-02-17 13:54:53 +00:00
|
|
|
|
2017-05-31 16:56:11 +01:00
|
|
|
r.MediaMetadata.FileSizeBytes = types.FileSizeBytes(contentLength)
|
|
|
|
r.MediaMetadata.ContentType = types.ContentType(resp.Header.Get("Content-Type"))
|
2020-06-17 14:26:45 +01:00
|
|
|
|
|
|
|
dispositionHeader := resp.Header.Get("Content-Disposition")
|
|
|
|
if _, params, e := mime.ParseMediaType(dispositionHeader); e == nil {
|
|
|
|
if params["filename"] != "" {
|
|
|
|
r.MediaMetadata.UploadName = types.Filename(params["filename"])
|
|
|
|
} else if params["filename*"] != "" {
|
|
|
|
r.MediaMetadata.UploadName = types.Filename(params["filename*"])
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if matches := rfc6266.FindStringSubmatch(dispositionHeader); len(matches) > 1 {
|
|
|
|
// Always prefer the RFC6266 UTF-8 name if possible
|
|
|
|
r.MediaMetadata.UploadName = types.Filename(matches[1])
|
|
|
|
} else if matches := rfc2183.FindStringSubmatch(dispositionHeader); len(matches) > 1 {
|
|
|
|
// Otherwise, see if an RFC2183 name was provided (ASCII only)
|
|
|
|
r.MediaMetadata.UploadName = types.Filename(matches[1])
|
|
|
|
}
|
2017-06-01 15:04:41 +01:00
|
|
|
}
|
2017-05-31 16:56:11 +01:00
|
|
|
|
2022-01-31 10:48:28 +00:00
|
|
|
r.Logger.Trace("Transferring remote file")
|
2017-05-31 16:56:11 +01:00
|
|
|
|
|
|
|
// The file data is hashed but is NOT used as the MediaID, unlike in Upload. The hash is useful as a
|
|
|
|
// method of deduplicating files to save storage, as well as a way to conduct
|
|
|
|
// integrity checks on the file data in the repository.
|
|
|
|
// Data is truncated to maxFileSizeBytes. Content-Length was reported as 0 < Content-Length <= maxFileSizeBytes so this is OK.
|
2021-02-17 13:54:53 +00:00
|
|
|
hash, bytesWritten, tmpDir, err := fileutils.WriteTempFile(ctx, reader, absBasePath)
|
2017-05-31 16:56:11 +01:00
|
|
|
if err != nil {
|
|
|
|
r.Logger.WithError(err).WithFields(log.Fields{
|
|
|
|
"MaxFileSizeBytes": maxFileSizeBytes,
|
|
|
|
}).Warn("Error while downloading file from remote server")
|
2017-09-19 11:40:21 +01:00
|
|
|
return "", false, errors.New("file could not be downloaded from remote server")
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
|
|
|
|
2022-01-31 10:48:28 +00:00
|
|
|
r.Logger.Trace("Remote file transferred")
|
2017-05-31 16:56:11 +01:00
|
|
|
|
|
|
|
// It's possible the bytesWritten to the temporary file is different to the reported Content-Length from the remote
|
|
|
|
// request's response. bytesWritten is therefore used as it is what would be sent to clients when reading from the local
|
|
|
|
// file.
|
|
|
|
r.MediaMetadata.FileSizeBytes = types.FileSizeBytes(bytesWritten)
|
|
|
|
r.MediaMetadata.Base64Hash = hash
|
|
|
|
|
|
|
|
// The database is the source of truth so we need to have moved the file first
|
|
|
|
finalPath, duplicate, err := fileutils.MoveFileWithHashCheck(tmpDir, r.MediaMetadata, absBasePath, r.Logger)
|
|
|
|
if err != nil {
|
2021-02-17 13:54:53 +00:00
|
|
|
return "", false, fmt.Errorf("fileutils.MoveFileWithHashCheck: %w", err)
|
2017-05-31 16:56:11 +01:00
|
|
|
}
|
|
|
|
if duplicate {
|
2022-01-31 10:48:28 +00:00
|
|
|
r.Logger.WithField("dst", finalPath).Trace("File was stored previously - discarding duplicate")
|
2017-05-31 16:56:11 +01:00
|
|
|
// Continue on to store the metadata in the database
|
|
|
|
}
|
|
|
|
|
|
|
|
return types.Path(finalPath), duplicate, nil
|
|
|
|
}
|