netmaker/netclient/local/dns.go

64 lines
1.7 KiB
Go
Raw Normal View History

2021-06-03 12:55:39 +08:00
package local
import (
"io/ioutil"
"os"
"strings"
2021-08-03 06:06:26 +08:00
2021-06-03 12:55:39 +08:00
//"github.com/davecgh/go-spew/spew"
2021-08-03 06:06:26 +08:00
"log"
"os/exec"
2021-08-31 03:58:23 +08:00
2021-09-20 02:03:47 +08:00
"github.com/gravitl/netmaker/netclient/ncutils"
2021-06-03 12:55:39 +08:00
)
2021-10-09 03:07:12 +08:00
// SetDNS - sets the DNS of a local machine
2021-06-03 12:55:39 +08:00
func SetDNS(nameserver string) error {
2021-08-03 06:06:26 +08:00
bytes, err := ioutil.ReadFile("/etc/resolv.conf")
if err != nil {
return err
}
resolvstring := string(bytes)
// //check whether s contains substring text
hasdns := strings.Contains(resolvstring, nameserver)
if hasdns {
return nil
}
resolv, err := os.OpenFile("/etc/resolv.conf", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer resolv.Close()
_, err = resolv.WriteString("nameserver " + nameserver + "\n")
2021-06-03 12:55:39 +08:00
2021-08-03 06:06:26 +08:00
return err
2021-06-03 12:55:39 +08:00
}
2021-10-09 03:07:12 +08:00
// UpdateDNS - updates local DNS of client
2021-06-03 12:55:39 +08:00
func UpdateDNS(ifacename string, network string, nameserver string) error {
2021-09-20 02:03:47 +08:00
if ncutils.IsWindows() {
2021-08-31 03:58:23 +08:00
return nil
}
2021-08-03 06:06:26 +08:00
_, err := exec.LookPath("resolvectl")
if err != nil {
log.Println(err)
log.Println("WARNING: resolvectl not present. Unable to set dns. Install resolvectl or run manually.")
} else {
2021-09-20 02:03:47 +08:00
_, err = ncutils.RunCmd("resolvectl domain "+ifacename+" ~"+network, true)
2021-08-03 06:06:26 +08:00
if err != nil {
log.Println("WARNING: Error encountered setting domain on dns. Aborted setting dns.")
} else {
2021-09-20 02:03:47 +08:00
_, err = ncutils.RunCmd("resolvectl default-route "+ifacename+" false", true)
2021-08-03 06:06:26 +08:00
if err != nil {
log.Println("WARNING: Error encountered setting default-route on dns. Aborted setting dns.")
} else {
2021-09-20 02:03:47 +08:00
_, err = ncutils.RunCmd("resolvectl dns "+ifacename+" "+nameserver, true)
2021-08-03 06:06:26 +08:00
if err != nil {
log.Println("WARNING: Error encountered running resolvectl dns " + ifacename + " " + nameserver)
}
}
}
}
return err
2021-06-03 12:55:39 +08:00
}