Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use a tmp file and rename to prevent a possible race condition #10693

Merged
merged 3 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions changelog/unreleased/thumbnail-create-and-rename.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Bugfix: Fix possible race condition when a thumbnails is stored in the FS

A race condition could cause the thumbnail service to return a thumbnail
with 0 bytes or with partial content. In order to fix this, the service will
create a temporary file with the contents and then rename that file to its
final location.

https://github.com/owncloud/ocis/pull/10693
26 changes: 22 additions & 4 deletions services/thumbnails/pkg/thumbnail/storage/filesystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,32 @@ func (s FileSystem) Put(key string, img []byte) error {
}

if _, err := os.Stat(imgPath); os.IsNotExist(err) {
f, err := os.Create(imgPath)
f, err := os.CreateTemp(dir, "tmpthumb")
if err != nil {
return errors.Wrapf(err, "could not create file \"%s\"", key)
return errors.Wrapf(err, "could not create temporary file for \"%s\"", key)
}
defer f.Close()

if _, err = f.Write(img); err != nil {
return errors.Wrapf(err, "could not write to file \"%s\"", key)
// if there was a problem writing, remove the temporary file
if _, writeErr := f.Write(img); writeErr != nil {
if remErr := os.Remove(f.Name()); remErr != nil {
return errors.Wrapf(remErr, "could not cleanup temporary file for \"%s\"", key)
}
return errors.Wrapf(writeErr, "could not write to temporary file for \"%s\"", key)
}

rhafer marked this conversation as resolved.
Show resolved Hide resolved
// if there wasn't a problem, ensure the data is written into disk
if synErr := f.Sync(); synErr != nil {
return errors.Wrapf(synErr, "could not sync temporary file data into the disk for \"%s\"", key)
}

// rename the temporary file to the final file
if renErr := os.Rename(f.Name(), imgPath); renErr != nil {
// if we couldn't rename, remove the temporary file
if remErr := os.Remove(f.Name()); remErr != nil {
return errors.Wrapf(remErr, "rename failed and could not cleanup temporary file for \"%s\"", key)
}
return errors.Wrapf(renErr, "could not rename temporary file to \"%s\"", key)
}
}

Expand Down