| 1 | package receiver |
| 2 | |
| 3 | import ( |
| 4 | "math/rand/v2" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "strconv" |
| 8 | ) |
| 9 | |
| 10 | // openTempFileRoot creates a randomly named file in root and returns an open |
| 11 | // handle. It is similar to os.CreateTemp except that the directory must be |
| 12 | // given, the file permissions can be controlled and patterns in the name are |
| 13 | // not supported. The name is always suffixed with a random number. |
| 14 | func openTempFileRoot(root *os.Root, name string, perm os.FileMode) (string, *os.File, error) { |
| 15 | prefix := name |
| 16 | |
| 17 | for attempt := 0; ; { |
| 18 | // Generate a reasonably random name which is unlikely to already |
| 19 | // exist. O_EXCL ensures that existing files generate an error. |
| 20 | name := prefix + strconv.FormatInt(rand.Int64(), 10) |
| 21 | |
| 22 | f, err := root.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, perm) |
| 23 | if !os.IsExist(err) { |
| 24 | return name, f, err |
| 25 | } |
| 26 | |
| 27 | if attempt++; attempt > 10000 { |
| 28 | return "", nil, &os.PathError{ |
| 29 | Op: "tempfile", |
| 30 | Path: name, |
| 31 | Err: os.ErrExist, |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | type pendingFile struct { |
| 38 | root *os.Root |
| 39 | tmpname string |
| 40 | fn string |
| 41 | f *os.File |
| 42 | sync bool |
| 43 | } |
| 44 | |
| 45 | func newPendingFile(root *os.Root, fn string, sync bool) (*pendingFile, error) { |
| 46 | tmpname, f, err := openTempFileRoot(root, "."+filepath.Base(fn), 0o600) |
| 47 | if err != nil { |
| 48 | return nil, err |
| 49 | } |
| 50 | return &pendingFile{ |
| 51 | root: root, |
| 52 | tmpname: tmpname, |
| 53 | fn: fn, |
| 54 | f: f, |
| 55 | sync: sync, |
| 56 | }, nil |
| 57 | } |
| 58 | |
| 59 | func (p *pendingFile) Name() string { |
| 60 | return p.fn |
| 61 | } |
| 62 | |
| 63 | func (p *pendingFile) Write(buf []byte) (n int, _ error) { |
| 64 | return p.f.Write(buf) |
| 65 | } |
| 66 | |
| 67 | func (p *pendingFile) CloseAtomicallyReplace() error { |
| 68 | if p.sync { |
| 69 | // fsync was requested |
| 70 | if err := p.f.Sync(); err != nil { |
| 71 | return err |
| 72 | } |
| 73 | } |
| 74 | if err := p.f.Close(); err != nil { |
| 75 | return err |
| 76 | } |
| 77 | if err := p.root.Rename(p.tmpname, p.fn); err != nil { |
| 78 | return err |
| 79 | } |
| 80 | return nil |
| 81 | } |
| 82 | |
| 83 | func (p *pendingFile) Cleanup() error { |
| 84 | err := p.f.Close() |
| 85 | if err := p.root.Remove(p.tmpname); err != nil { |
| 86 | return err |
| 87 | } |
| 88 | return err |
| 89 | } |