fix: use UUID for temporary file names

This commit is contained in:
Elias Schneider
2025-04-06 15:08:06 +02:00
parent ec626ee797
commit ccc18d716f

View File

@@ -3,14 +3,12 @@ package utils
import ( import (
"errors" "errors"
"fmt" "fmt"
"hash/crc64"
"io" "io"
"mime/multipart" "mime/multipart"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"time"
"github.com/google/uuid"
"github.com/pocket-id/pocket-id/backend/resources" "github.com/pocket-id/pocket-id/backend/resources"
) )
@@ -80,22 +78,7 @@ func SaveFile(file *multipart.FileHeader, dst string) error {
// SaveFileStream saves a stream to a file. // SaveFileStream saves a stream to a file.
func SaveFileStream(r io.Reader, dstFileName string) error { func SaveFileStream(r io.Reader, dstFileName string) error {
// Our strategy is to save to a separate file and then rename it to override the original file // Our strategy is to save to a separate file and then rename it to override the original file
// First, get a temp file name that doesn't exist already tmpFileName := dstFileName + "." + uuid.NewString() + "-tmp"
var tmpFileName string
var i int64
for {
seed := strconv.FormatInt(time.Now().UnixNano()+i, 10)
suffix := crc64.Checksum([]byte(dstFileName+seed), crc64.MakeTable(crc64.ISO))
tmpFileName = dstFileName + "." + strconv.FormatUint(suffix, 10)
exists, err := FileExists(tmpFileName)
if err != nil {
return fmt.Errorf("failed to check if file '%s' exists: %w", tmpFileName, err)
}
if !exists {
break
}
i++
}
// Write to the temporary file // Write to the temporary file
tmpFile, err := os.Create(tmpFileName) tmpFile, err := os.Create(tmpFileName)