Skip to content

Commit 34b02b7

Browse files
authored
Merge pull request #74 from bozaro/safe-write-lib
Write library by temporary file creation to avoid in-place modification executed library
2 parents e6f7fb7 + ffa7017 commit 34b02b7

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

util.go

+20-8
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,41 @@
11
package lib
22

33
import (
4+
"fmt"
45
"os"
56
"path/filepath"
67
)
78

89
func writeLib(libDir, libFullName string, content []byte, versionMatched bool) error {
910
libFullPath := filepath.Join(libDir, libFullName)
1011
_, err := os.Stat(libFullPath)
11-
if os.IsNotExist(err) || !versionMatched {
12-
err = os.MkdirAll(libDir, 0777)
12+
if !os.IsNotExist(err) && versionMatched {
13+
return err
14+
}
15+
if err := os.MkdirAll(libDir, 0777); err != nil {
16+
return err
17+
}
18+
for pass := 0; ; pass++ {
19+
tmpFullPath := fmt.Sprintf("%s~%d", libFullPath, pass)
20+
tmpFile, err := os.OpenFile(tmpFullPath, os.O_CREATE|os.O_RDWR|os.O_EXCL, 0755)
1321
if err != nil {
22+
if os.IsExist(err) {
23+
continue
24+
}
1425
return err
1526
}
16-
libFile, err := os.Create(libFullPath)
1727
defer func() {
18-
libFile.Close()
28+
tmpFile.Close()
29+
_ = os.Remove(tmpFullPath)
1930
}()
20-
if err != nil {
31+
32+
if _, err = tmpFile.Write(content); err != nil {
2133
return err
2234
}
23-
_, err = libFile.Write(content)
24-
if err != nil {
35+
if err := os.Rename(tmpFullPath, libFullPath); err != nil {
2536
return err
2637
}
38+
break
2739
}
28-
return err
40+
return nil
2941
}

0 commit comments

Comments
 (0)