Browse Source

add lockfile to prevent corruption of /etc/hosts

Matthew R. Kasun 3 years ago
parent
commit
7169c232ed
1 changed files with 25 additions and 0 deletions
  1. 25 0
      netclient/functions/mqhandlers.go

+ 25 - 0
netclient/functions/mqhandlers.go

@@ -2,6 +2,9 @@ package functions
 
 
 import (
 import (
 	"encoding/json"
 	"encoding/json"
+	"errors"
+	"fmt"
+	"os"
 	"runtime"
 	"runtime"
 	"strings"
 	"strings"
 	"time"
 	"time"
@@ -243,9 +246,20 @@ func UpdatePeers(client mqtt.Client, msg mqtt.Message) {
 
 
 func setHostDNS(dns, iface string, windows bool) error {
 func setHostDNS(dns, iface string, windows bool) error {
 	etchosts := "/etc/hosts"
 	etchosts := "/etc/hosts"
+	temp := os.TempDir()
+	lockfile := temp + "netclient-lock"
 	if windows {
 	if windows {
 		etchosts = "c:\\windows\\system32\\drivers\\etc\\hosts"
 		etchosts = "c:\\windows\\system32\\drivers\\etc\\hosts"
 	}
 	}
+	if _, err := os.Stat(lockfile); !errors.Is(err, os.ErrNotExist) {
+		return errors.New("/etc/hosts file is locked .... aborting")
+	}
+	lock, err := os.Create(lockfile)
+	if err != nil {
+		return fmt.Errorf("could not create lock file %w", err)
+	}
+	lock.Close()
+	defer os.Remove(lockfile)
 	dnsdata := strings.NewReader(dns)
 	dnsdata := strings.NewReader(dns)
 	profile, err := parser.ParseProfile(dnsdata)
 	profile, err := parser.ParseProfile(dnsdata)
 	if err != nil {
 	if err != nil {
@@ -268,9 +282,20 @@ func setHostDNS(dns, iface string, windows bool) error {
 
 
 func removeHostDNS(iface string, windows bool) error {
 func removeHostDNS(iface string, windows bool) error {
 	etchosts := "/etc/hosts"
 	etchosts := "/etc/hosts"
+	temp := os.TempDir()
+	lockfile := temp + "netclient-lock"
 	if windows {
 	if windows {
 		etchosts = "c:\\windows\\system32\\drivers\\etc\\hosts"
 		etchosts = "c:\\windows\\system32\\drivers\\etc\\hosts"
 	}
 	}
+	if _, err := os.Stat(lockfile); !errors.Is(err, os.ErrNotExist) {
+		return errors.New("/etc/hosts file is locked .... aborting")
+	}
+	lock, err := os.Create(lockfile)
+	if err != nil {
+		return fmt.Errorf("could not create lock file %w", err)
+	}
+	lock.Close()
+	defer os.Remove(lockfile)
 	hosts, err := file.NewFile(etchosts)
 	hosts, err := file.NewFile(etchosts)
 	if err != nil {
 	if err != nil {
 		return err
 		return err