2017-05-26 14:49:54 +00: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.
|
|
|
|
|
|
|
|
package fileutils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2020-08-26 14:38:34 +00:00
|
|
|
"context"
|
2017-05-26 14:49:54 +00:00
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/base64"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
|
2020-05-21 13:40:13 +00:00
|
|
|
"github.com/matrix-org/dendrite/internal/config"
|
2017-05-26 14:49:54 +00:00
|
|
|
"github.com/matrix-org/dendrite/mediaapi/types"
|
2020-08-26 14:38:34 +00:00
|
|
|
"github.com/matrix-org/util"
|
2017-11-16 10:12:02 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2017-05-26 14:49:54 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// GetPathFromBase64Hash evaluates the path to a media file from its Base64Hash
|
2017-05-31 05:06:42 +00:00
|
|
|
// 3 subdirectories are created for more manageable browsing and use the remainder as the file name.
|
|
|
|
// For example, if Base64Hash is 'qwerty', the path will be 'q/w/erty/file'.
|
2017-06-19 14:21:04 +00:00
|
|
|
func GetPathFromBase64Hash(base64Hash types.Base64Hash, absBasePath config.Path) (string, error) {
|
2017-05-31 05:06:42 +00:00
|
|
|
if len(base64Hash) < 3 {
|
|
|
|
return "", fmt.Errorf("Invalid filePath (Base64Hash too short - min 3 characters): %q", base64Hash)
|
|
|
|
}
|
|
|
|
if len(base64Hash) > 255 {
|
2017-05-26 14:49:54 +00:00
|
|
|
return "", fmt.Errorf("Invalid filePath (Base64Hash too long - max 255 characters): %q", base64Hash)
|
|
|
|
}
|
|
|
|
|
2017-05-31 05:07:48 +00:00
|
|
|
filePath, err := filepath.Abs(filepath.Join(
|
2017-05-26 14:49:54 +00:00
|
|
|
string(absBasePath),
|
2017-05-31 05:06:42 +00:00
|
|
|
string(base64Hash[0:1]),
|
|
|
|
string(base64Hash[1:2]),
|
|
|
|
string(base64Hash[2:]),
|
|
|
|
"file",
|
2017-05-26 14:49:54 +00:00
|
|
|
))
|
|
|
|
if err != nil {
|
2020-03-18 12:48:51 +00:00
|
|
|
return "", fmt.Errorf("Unable to construct filePath: %w", err)
|
2017-05-26 14:49:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// check if the absolute absBasePath is a prefix of the absolute filePath
|
|
|
|
// if so, no directory escape has occurred and the filePath is valid
|
|
|
|
// Note: absBasePath is already absolute
|
2017-09-20 13:15:38 +00:00
|
|
|
if !strings.HasPrefix(filePath, string(absBasePath)) {
|
2017-05-26 14:49:54 +00:00
|
|
|
return "", fmt.Errorf("Invalid filePath (not within absBasePath %v): %v", absBasePath, filePath)
|
|
|
|
}
|
|
|
|
|
|
|
|
return filePath, nil
|
|
|
|
}
|
|
|
|
|
2017-05-26 15:15:54 +00:00
|
|
|
// MoveFileWithHashCheck checks for hash collisions when moving a temporary file to its final path based on metadata
|
|
|
|
// The final path is based on the hash of the file.
|
|
|
|
// If the final path exists and the file size matches, the file does not need to be moved.
|
|
|
|
// In error cases where the file is not a duplicate, the caller may decide to remove the final path.
|
|
|
|
// Returns the final path of the file, whether it is a duplicate and an error.
|
2017-06-19 14:21:04 +00:00
|
|
|
func MoveFileWithHashCheck(tmpDir types.Path, mediaMetadata *types.MediaMetadata, absBasePath config.Path, logger *log.Entry) (types.Path, bool, error) {
|
2017-05-26 15:15:54 +00:00
|
|
|
// Note: in all error and success cases, we need to remove the temporary directory
|
|
|
|
defer RemoveDir(tmpDir, logger)
|
|
|
|
duplicate := false
|
|
|
|
finalPath, err := GetPathFromBase64Hash(mediaMetadata.Base64Hash, absBasePath)
|
|
|
|
if err != nil {
|
2020-03-18 12:48:51 +00:00
|
|
|
return "", duplicate, fmt.Errorf("failed to get file path from metadata: %w", err)
|
2017-05-26 15:15:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var stat os.FileInfo
|
2017-05-31 05:08:21 +00:00
|
|
|
// Note: The double-negative is intentional as os.IsExist(err) != !os.IsNotExist(err).
|
|
|
|
// The functions are error checkers to be used in different cases.
|
|
|
|
if stat, err = os.Stat(finalPath); !os.IsNotExist(err) {
|
2017-05-26 15:15:54 +00:00
|
|
|
duplicate = true
|
|
|
|
if stat.Size() == int64(mediaMetadata.FileSizeBytes) {
|
|
|
|
return types.Path(finalPath), duplicate, nil
|
|
|
|
}
|
|
|
|
return "", duplicate, fmt.Errorf("downloaded file with hash collision but different file size (%v)", finalPath)
|
|
|
|
}
|
|
|
|
err = moveFile(
|
2017-05-31 05:07:48 +00:00
|
|
|
types.Path(filepath.Join(string(tmpDir), "content")),
|
2017-05-26 15:15:54 +00:00
|
|
|
types.Path(finalPath),
|
|
|
|
)
|
|
|
|
if err != nil {
|
2020-03-18 12:48:51 +00:00
|
|
|
return "", duplicate, fmt.Errorf("failed to move file to final destination (%v): %w", finalPath, err)
|
2017-05-26 15:15:54 +00:00
|
|
|
}
|
|
|
|
return types.Path(finalPath), duplicate, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveDir removes a directory and logs a warning in case of errors
|
|
|
|
func RemoveDir(dir types.Path, logger *log.Entry) {
|
|
|
|
dirErr := os.RemoveAll(string(dir))
|
|
|
|
if dirErr != nil {
|
|
|
|
logger.WithError(dirErr).WithField("dir", dir).Warn("Failed to remove directory")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-26 14:38:34 +00:00
|
|
|
// WriteTempFile writes to a new temporary file.
|
|
|
|
// The file is deleted if there was an error while writing.
|
|
|
|
func WriteTempFile(
|
|
|
|
ctx context.Context, reqReader io.Reader, maxFileSizeBytes config.FileSizeBytes, absBasePath config.Path,
|
|
|
|
) (hash types.Base64Hash, size types.FileSizeBytes, path types.Path, err error) {
|
2017-09-20 09:59:19 +00:00
|
|
|
size = -1
|
2020-08-26 14:38:34 +00:00
|
|
|
logger := util.GetLogger(ctx)
|
2017-05-26 15:15:54 +00:00
|
|
|
tmpFileWriter, tmpFile, tmpDir, err := createTempFileWriter(absBasePath)
|
|
|
|
if err != nil {
|
2017-09-20 09:59:19 +00:00
|
|
|
return
|
2017-05-26 15:15:54 +00:00
|
|
|
}
|
2020-08-26 14:38:34 +00:00
|
|
|
defer func() {
|
|
|
|
err2 := tmpFile.Close()
|
|
|
|
if err == nil {
|
|
|
|
err = err2
|
|
|
|
}
|
|
|
|
}()
|
2017-05-26 15:15:54 +00:00
|
|
|
|
2020-08-28 08:46:32 +00:00
|
|
|
// If the max_file_size_bytes configuration option is set to a positive
|
|
|
|
// number then limit the upload to that size. Otherwise, just read the
|
|
|
|
// whole file.
|
|
|
|
limitedReader := reqReader
|
|
|
|
if maxFileSizeBytes > 0 {
|
|
|
|
limitedReader = io.LimitReader(reqReader, int64(maxFileSizeBytes))
|
|
|
|
}
|
2017-05-26 15:15:54 +00:00
|
|
|
// Hash the file data. The hash will be returned. 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.
|
|
|
|
hasher := sha256.New()
|
|
|
|
teeReader := io.TeeReader(limitedReader, hasher)
|
|
|
|
bytesWritten, err := io.Copy(tmpFileWriter, teeReader)
|
|
|
|
if err != nil && err != io.EOF {
|
2020-08-26 14:38:34 +00:00
|
|
|
RemoveDir(tmpDir, logger)
|
2017-09-20 09:59:19 +00:00
|
|
|
return
|
2017-05-26 15:15:54 +00:00
|
|
|
}
|
|
|
|
|
2017-09-20 09:59:19 +00:00
|
|
|
err = tmpFileWriter.Flush()
|
|
|
|
if err != nil {
|
2020-08-26 14:38:34 +00:00
|
|
|
RemoveDir(tmpDir, logger)
|
2017-09-20 09:59:19 +00:00
|
|
|
return
|
|
|
|
}
|
2017-05-26 15:15:54 +00:00
|
|
|
|
2017-09-20 09:59:19 +00:00
|
|
|
hash = types.Base64Hash(base64.RawURLEncoding.EncodeToString(hasher.Sum(nil)[:]))
|
|
|
|
size = types.FileSizeBytes(bytesWritten)
|
|
|
|
path = tmpDir
|
|
|
|
return
|
2017-05-26 15:15:54 +00:00
|
|
|
}
|
|
|
|
|
2017-05-26 14:49:54 +00:00
|
|
|
// moveFile attempts to move the file src to dst
|
|
|
|
func moveFile(src types.Path, dst types.Path) error {
|
2017-05-31 05:07:48 +00:00
|
|
|
dstDir := filepath.Dir(string(dst))
|
2017-05-26 14:49:54 +00:00
|
|
|
|
|
|
|
err := os.MkdirAll(dstDir, 0770)
|
|
|
|
if err != nil {
|
2020-03-18 12:48:51 +00:00
|
|
|
return fmt.Errorf("Failed to make directory: %w", err)
|
2017-05-26 14:49:54 +00:00
|
|
|
}
|
|
|
|
err = os.Rename(string(src), string(dst))
|
|
|
|
if err != nil {
|
2020-03-18 12:48:51 +00:00
|
|
|
return fmt.Errorf("Failed to move directory: %w", err)
|
2017-05-26 14:49:54 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2017-06-19 14:21:04 +00:00
|
|
|
func createTempFileWriter(absBasePath config.Path) (*bufio.Writer, *os.File, types.Path, error) {
|
2017-05-26 15:15:54 +00:00
|
|
|
tmpDir, err := createTempDir(absBasePath)
|
2017-05-26 14:49:54 +00:00
|
|
|
if err != nil {
|
2020-03-18 12:48:51 +00:00
|
|
|
return nil, nil, "", fmt.Errorf("Failed to create temp dir: %w", err)
|
2017-05-26 14:49:54 +00:00
|
|
|
}
|
2017-09-07 11:50:39 +00:00
|
|
|
writer, tmpFile, err := createFileWriter(tmpDir)
|
2017-05-26 15:15:54 +00:00
|
|
|
if err != nil {
|
2020-03-18 12:48:51 +00:00
|
|
|
return nil, nil, "", fmt.Errorf("Failed to create file writer: %w", err)
|
2017-05-26 15:15:54 +00:00
|
|
|
}
|
|
|
|
return writer, tmpFile, tmpDir, nil
|
|
|
|
}
|
2017-05-26 14:49:54 +00:00
|
|
|
|
2017-05-26 15:15:54 +00:00
|
|
|
// createTempDir creates a tmp/<random string> directory within baseDirectory and returns its path
|
2017-06-19 14:21:04 +00:00
|
|
|
func createTempDir(baseDirectory config.Path) (types.Path, error) {
|
2017-05-31 05:07:48 +00:00
|
|
|
baseTmpDir := filepath.Join(string(baseDirectory), "tmp")
|
2017-05-26 15:15:54 +00:00
|
|
|
if err := os.MkdirAll(baseTmpDir, 0770); err != nil {
|
2020-03-18 12:48:51 +00:00
|
|
|
return "", fmt.Errorf("Failed to create base temp dir: %w", err)
|
2017-05-26 14:49:54 +00:00
|
|
|
}
|
2017-05-26 15:15:54 +00:00
|
|
|
tmpDir, err := ioutil.TempDir(baseTmpDir, "")
|
2017-05-26 14:49:54 +00:00
|
|
|
if err != nil {
|
2020-03-18 12:48:51 +00:00
|
|
|
return "", fmt.Errorf("Failed to create temp dir: %w", err)
|
2017-05-26 15:15:54 +00:00
|
|
|
}
|
|
|
|
return types.Path(tmpDir), nil
|
|
|
|
}
|
|
|
|
|
2017-09-07 11:50:39 +00:00
|
|
|
// createFileWriter creates a buffered file writer with a new file
|
2017-05-26 15:15:54 +00:00
|
|
|
// The caller should flush the writer before closing the file.
|
|
|
|
// Returns the file handle as it needs to be closed when writing is complete
|
2017-09-07 11:50:39 +00:00
|
|
|
func createFileWriter(directory types.Path) (*bufio.Writer, *os.File, error) {
|
|
|
|
filePath := filepath.Join(string(directory), "content")
|
2017-05-26 15:15:54 +00:00
|
|
|
file, err := os.Create(filePath)
|
|
|
|
if err != nil {
|
2020-03-18 12:48:51 +00:00
|
|
|
return nil, nil, fmt.Errorf("Failed to create file: %w", err)
|
2017-05-26 14:49:54 +00:00
|
|
|
}
|
2017-05-26 15:15:54 +00:00
|
|
|
|
|
|
|
return bufio.NewWriter(file), file, nil
|
2017-05-26 14:49:54 +00:00
|
|
|
}
|