From 859f1590dd25c633358bcc4182a0df66d7c35b09 Mon Sep 17 00:00:00 2001 From: Eugene Bujak Date: Thu, 6 Sep 2018 02:03:03 +0300 Subject: [PATCH] Be more atomic during writing of files -- this prevents other processes from seeing empty or impartial files --- config.go | 13 +++++++++++-- control.go | 8 +++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/config.go b/config.go index b87429b1..f0923601 100644 --- a/config.go +++ b/config.go @@ -108,11 +108,16 @@ func writeConfig() error { log.Printf("Couldn't generate YAML file: %s", err) return err } - err = ioutil.WriteFile(configfile, yamlText, 0644) + err = ioutil.WriteFile(configfile+".tmp", yamlText, 0644) if err != nil { log.Printf("Couldn't write YAML config: %s", err) return err } + err = os.Rename(configfile+".tmp", configfile) + if err != nil { + log.Printf("Couldn't rename YAML config: %s", err) + return err + } return nil } @@ -127,10 +132,14 @@ func writeCoreDNSConfig() error { log.Printf("Couldn't generate DNS config: %s", err) return err } - err = ioutil.WriteFile(corefile, []byte(configtext), 0644) + err = ioutil.WriteFile(corefile+".tmp", []byte(configtext), 0644) if err != nil { log.Printf("Couldn't write DNS config: %s", err) } + err = os.Rename(corefile+".tmp", corefile) + if err != nil { + log.Printf("Couldn't rename DNS config: %s", err) + } return err } diff --git a/control.go b/control.go index e3d11119..57f83114 100644 --- a/control.go +++ b/control.go @@ -929,11 +929,17 @@ func writeFilterFile() error { data = append(data, []byte(rule)...) data = append(data, '\n') } - err := ioutil.WriteFile(filterpath, data, 0644) + err := ioutil.WriteFile(filterpath+".tmp", data, 0644) if err != nil { log.Printf("Couldn't write filter file: %s", err) return err } + + err = os.Rename(filterpath+".tmp", filterpath) + if err != nil { + log.Printf("Couldn't rename filter file: %s", err) + return err + } return nil }