Skip to content

Commit b4f2faa

Browse files
authored
Merge pull request #10693 from owncloud/thumbnails_fix_fs_race
fix: use a tmp file and rename to prevent a possible race condition
2 parents 6a3eac3 + f3d91f8 commit b4f2faa

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
Bugfix: Fix possible race condition when a thumbnails is stored in the FS
2+
3+
A race condition could cause the thumbnail service to return a thumbnail
4+
with 0 bytes or with partial content. In order to fix this, the service will
5+
create a temporary file with the contents and then rename that file to its
6+
final location.
7+
8+
https://github.com/owncloud/ocis/pull/10693

services/thumbnails/pkg/thumbnail/storage/filesystem.go

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,14 +62,32 @@ func (s FileSystem) Put(key string, img []byte) error {
6262
}
6363

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

71-
if _, err = f.Write(img); err != nil {
72-
return errors.Wrapf(err, "could not write to file \"%s\"", key)
71+
// if there was a problem writing, remove the temporary file
72+
if _, writeErr := f.Write(img); writeErr != nil {
73+
if remErr := os.Remove(f.Name()); remErr != nil {
74+
return errors.Wrapf(remErr, "could not cleanup temporary file for \"%s\"", key)
75+
}
76+
return errors.Wrapf(writeErr, "could not write to temporary file for \"%s\"", key)
77+
}
78+
79+
// if there wasn't a problem, ensure the data is written into disk
80+
if synErr := f.Sync(); synErr != nil {
81+
return errors.Wrapf(synErr, "could not sync temporary file data into the disk for \"%s\"", key)
82+
}
83+
84+
// rename the temporary file to the final file
85+
if renErr := os.Rename(f.Name(), imgPath); renErr != nil {
86+
// if we couldn't rename, remove the temporary file
87+
if remErr := os.Remove(f.Name()); remErr != nil {
88+
return errors.Wrapf(remErr, "rename failed and could not cleanup temporary file for \"%s\"", key)
89+
}
90+
return errors.Wrapf(renErr, "could not rename temporary file to \"%s\"", key)
7391
}
7492
}
7593

0 commit comments

Comments
 (0)