write jsonrpc2.yml atomically

* previously, the `jsonrpc2.yml` file was written with
  `ioutil.WriteFile`, which doesn't write the file automatically.

  That means, if the signal-cli config directory resides on a slow
  (network) storage, it's possible that the file is written partially,
  when the signal-cli-rest-api process attemps to read it.

  In order to avoid that, write the contents of the `jsonrpc2.yml` to a
  tmp file first and then rename it with `os.Rename` afterwards.

see #893
This commit is contained in:
Bernhard B committed 2026-10-09 16:16:47 +02:00
1 parent a8d6bd664b
commit 8990c1fd69
1 file changed
+41 -2
+41 -2
View File
@@ -2,11 +2,50 @@ package utils
import (
"errors"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
"path/filepath"
"gopkg.in/yaml.v2"
)
func writeFileAtomic(name string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(name)
f, err := os.CreateTemp(dir, ".tmp-*")
if err != nil {
return err
}
tmp := f.Name()
defer os.Remove(tmp)
err = f.Chmod(perm)
if err != nil {
f.Close()
return err
}
_, err = f.Write(data)
if err != nil {
f.Close()
return err
}
err = f.Sync()
if err != nil {
f.Close()
return err
}
err = f.Close()
if err != nil {
return err
}
return os.Rename(tmp, name)
}
type SignalCliTrustMode int
const (
@@ -92,5 +131,5 @@ func (c *SignalCliApiConfig) Persist() error {
return err
}
return ioutil.WriteFile(c.path, out, 0644)
return writeFileAtomic(c.path, out, 0644)
}