badguardhome/dhcpd/network_utils.go

313 lines
7.3 KiB
Go
Raw Normal View History

Fix #1069 install: check static ip Squashed commit of the following: commit 57466233cbeb89aff82d8610778f7c3b60fe8426 Merge: 2df5f281 867bf545 Author: Andrey Meshkov <am@adguard.com> Date: Thu Feb 13 18:39:15 2020 +0300 Merge branch 'master' into 1069-install-static-ip commit 2df5f281c4f5949b92edd4747ece60ff73799e54 Author: Andrey Meshkov <am@adguard.com> Date: Thu Feb 13 18:35:54 2020 +0300 *: lang fix commit b4649a6b2781741979531faf862b88c2557f1445 Merge: c2785253 f61d5f0f Author: Andrey Meshkov <am@adguard.com> Date: Thu Feb 13 16:47:30 2020 +0300 *(home): fixed issues with setting static IP on Mac commit c27852537d2f5ce62b16c43f4241a15d0fb8c9fd Author: Andrey Meshkov <am@adguard.com> Date: Thu Feb 13 14:14:30 2020 +0300 +(dhcpd): added static IP for MacOS commit f61d5f0f85a954120b2676a5153f10a05662cf42 Author: Ildar Kamalov <i.kamalov@adguard.com> Date: Thu Feb 13 14:13:35 2020 +0300 + client: show confirm before setting static IP commit 7afa16fbe76dff4485d166f6164bae171e0110c9 Author: Ildar Kamalov <i.kamalov@adguard.com> Date: Thu Feb 13 13:51:52 2020 +0300 - client: fix text commit 019bff0851c584302fa44317fc748b3319be9470 Author: Ildar Kamalov <i.kamalov@adguard.com> Date: Thu Feb 13 13:49:16 2020 +0300 - client: pass all params to the check_config request commit 194bed72f567ae815cbd424e2df1ac5be65e0c02 Author: Andrey Meshkov <am@adguard.com> Date: Wed Feb 12 17:12:16 2020 +0300 *: fix home_test commit 9359f6b55f5e36dd311fb85b6a83bb6227308f03 Merge: ae299058 c5ca2a77 Author: Andrey Meshkov <am@adguard.com> Date: Wed Feb 12 15:54:54 2020 +0300 Merge with master commit ae2990582defd8062b99c546b2a932a8ba06c35d Author: Andrey Meshkov <am@adguard.com> Date: Wed Feb 12 15:53:36 2020 +0300 *(global): refactoring - moved runtime properties to Context commit d8d48c53869a94d18c5ea7bcf78613e83b24bfd8 Author: Andrey Meshkov <am@adguard.com> Date: Wed Feb 12 15:04:25 2020 +0300 *(dhcpd): refactoring, use dhcpd/network_utils where possible commit 8d039c572f0e5f5245bd155a4e4d35400e6962c6 Author: Ildar Kamalov <i.kamalov@adguard.com> Date: Fri Feb 7 18:37:39 2020 +0300 - client: fix button position commit 26c47e59dd63317bdb959cb416e7c1c0bfdf7dc1 Author: Ildar Kamalov <i.kamalov@adguard.com> Date: Fri Feb 7 18:08:56 2020 +0300 - client: fix static ip description commit cb12babc4698d048478570303af8955a35e8531d Author: Andrey Meshkov <am@adguard.com> Date: Fri Feb 7 17:08:39 2020 +0300 *: lower log level for some commands commit d9001ff84852d708e400d039503141929e06d774 Author: Andrey Meshkov <am@adguard.com> Date: Fri Feb 7 16:17:59 2020 +0300 *(documentation): updated openapi commit 1d213d53c88d5009a4b1d33d4cfa9e215c644bec Merge: 8406d7d2 80861860 Author: Andrey Meshkov <am@adguard.com> Date: Fri Feb 7 15:16:46 2020 +0300 *: merge with master commit 8406d7d28827ce1ed9d9f6770ce1700681811535 Author: Ildar Kamalov <i.kamalov@adguard.com> Date: Fri Jan 31 16:52:22 2020 +0300 - client: fix locales commit fb476b011768367be51010c89754dcd23b383f5a Author: Simon Zolin <s.zolin@adguard.com> Date: Fri Jan 31 13:29:03 2020 +0300 linter commit 84b5708e71c88a9643d402ab630270f5e7bf35b8 Author: Simon Zolin <s.zolin@adguard.com> Date: Fri Jan 31 13:27:53 2020 +0300 linter commit 143a86a28a3465776f803f6b99b9f3c64b26400e Author: Simon Zolin <s.zolin@adguard.com> Date: Fri Jan 31 13:26:47 2020 +0300 linter ... and 7 more commits
2020-02-13 15:42:07 +00:00
package dhcpd
import (
"errors"
"fmt"
"io/ioutil"
"net"
"os/exec"
"regexp"
"runtime"
"strings"
"github.com/AdguardTeam/AdGuardHome/util"
"github.com/AdguardTeam/golibs/file"
"github.com/AdguardTeam/golibs/log"
)
// Check if network interface has a static IP configured
// Supports: Raspbian.
func HasStaticIP(ifaceName string) (bool, error) {
if runtime.GOOS == "linux" {
body, err := ioutil.ReadFile("/etc/dhcpcd.conf")
if err != nil {
return false, err
}
return hasStaticIPDhcpcdConf(string(body), ifaceName), nil
}
if runtime.GOOS == "darwin" {
return hasStaticIPDarwin(ifaceName)
}
return false, fmt.Errorf("Cannot check if IP is static: not supported on %s", runtime.GOOS)
}
// Set a static IP for the specified network interface
func SetStaticIP(ifaceName string) error {
if runtime.GOOS == "linux" {
return setStaticIPDhcpdConf(ifaceName)
}
if runtime.GOOS == "darwin" {
return setStaticIPDarwin(ifaceName)
}
return fmt.Errorf("Cannot set static IP on %s", runtime.GOOS)
}
// for dhcpcd.conf
func hasStaticIPDhcpcdConf(dhcpConf, ifaceName string) bool {
lines := strings.Split(dhcpConf, "\n")
nameLine := fmt.Sprintf("interface %s", ifaceName)
withinInterfaceCtx := false
for _, line := range lines {
line = strings.TrimSpace(line)
if withinInterfaceCtx && len(line) == 0 {
// an empty line resets our state
withinInterfaceCtx = false
}
if len(line) == 0 || line[0] == '#' {
continue
}
line = strings.TrimSpace(line)
if !withinInterfaceCtx {
if line == nameLine {
// we found our interface
withinInterfaceCtx = true
}
} else {
if strings.HasPrefix(line, "interface ") {
// we found another interface - reset our state
withinInterfaceCtx = false
continue
}
if strings.HasPrefix(line, "static ip_address=") {
return true
}
}
}
return false
}
// Get gateway IP address
func getGatewayIP(ifaceName string) string {
cmd := exec.Command("ip", "route", "show", "dev", ifaceName)
log.Tracef("executing %s %v", cmd.Path, cmd.Args)
d, err := cmd.Output()
if err != nil || cmd.ProcessState.ExitCode() != 0 {
return ""
}
fields := strings.Fields(string(d))
if len(fields) < 3 || fields[0] != "default" {
return ""
}
ip := net.ParseIP(fields[2])
if ip == nil {
return ""
}
return fields[2]
}
// setStaticIPDhcpdConf - updates /etc/dhcpd.conf and sets the current IP address to be static
func setStaticIPDhcpdConf(ifaceName string) error {
ip := util.GetSubnet(ifaceName)
if len(ip) == 0 {
return errors.New("Can't get IP address")
}
ip4, _, err := net.ParseCIDR(ip)
if err != nil {
return err
}
gatewayIP := getGatewayIP(ifaceName)
add := updateStaticIPDhcpcdConf(ifaceName, ip, gatewayIP, ip4.String())
body, err := ioutil.ReadFile("/etc/dhcpcd.conf")
if err != nil {
return err
}
body = append(body, []byte(add)...)
err = file.SafeWrite("/etc/dhcpcd.conf", body)
if err != nil {
return err
}
return nil
}
// updates dhcpd.conf content -- sets static IP address there
// for dhcpcd.conf
func updateStaticIPDhcpcdConf(ifaceName, ip, gatewayIP, dnsIP string) string {
var body []byte
add := fmt.Sprintf("\ninterface %s\nstatic ip_address=%s\n",
ifaceName, ip)
body = append(body, []byte(add)...)
if len(gatewayIP) != 0 {
add = fmt.Sprintf("static routers=%s\n",
gatewayIP)
body = append(body, []byte(add)...)
}
add = fmt.Sprintf("static domain_name_servers=%s\n\n",
dnsIP)
body = append(body, []byte(add)...)
return string(body)
}
// Check if network interface has a static IP configured
// Supports: MacOS.
func hasStaticIPDarwin(ifaceName string) (bool, error) {
portInfo, err := getCurrentHardwarePortInfo(ifaceName)
if err != nil {
return false, err
}
return portInfo.static, nil
}
// setStaticIPDarwin - uses networksetup util to set the current IP address to be static
// Additionally it configures the current DNS servers as well
func setStaticIPDarwin(ifaceName string) error {
portInfo, err := getCurrentHardwarePortInfo(ifaceName)
if err != nil {
return err
}
if portInfo.static {
return errors.New("IP address is already static")
}
dnsAddrs, err := getEtcResolvConfServers()
if err != nil {
return err
}
args := make([]string, 0)
args = append(args, "-setdnsservers", portInfo.name)
args = append(args, dnsAddrs...)
// Setting DNS servers is necessary when configuring a static IP
code, _, err := util.RunCommand("networksetup", args...)
if err != nil {
return err
}
if code != 0 {
return fmt.Errorf("Failed to set DNS servers, code=%d", code)
}
// Actually configures hardware port to have static IP
code, _, err = util.RunCommand("networksetup", "-setmanual",
portInfo.name, portInfo.ip, portInfo.subnet, portInfo.gatewayIP)
if err != nil {
return err
}
if code != 0 {
return fmt.Errorf("Failed to set DNS servers, code=%d", code)
}
return nil
}
// getCurrentHardwarePortInfo gets information the specified network interface
func getCurrentHardwarePortInfo(ifaceName string) (hardwarePortInfo, error) {
// First of all we should find hardware port name
m := getNetworkSetupHardwareReports()
hardwarePort, ok := m[ifaceName]
if !ok {
return hardwarePortInfo{}, fmt.Errorf("Could not find hardware port for %s", ifaceName)
}
return getHardwarePortInfo(hardwarePort)
}
// getNetworkSetupHardwareReports parses the output of the `networksetup -listallhardwareports` command
// it returns a map where the key is the interface name, and the value is the "hardware port"
// returns nil if it fails to parse the output
func getNetworkSetupHardwareReports() map[string]string {
_, out, err := util.RunCommand("networksetup", "-listallhardwareports")
if err != nil {
return nil
}
re, err := regexp.Compile("Hardware Port: (.*?)\nDevice: (.*?)\n")
if err != nil {
return nil
}
m := make(map[string]string, 0)
matches := re.FindAllStringSubmatch(out, -1)
for i := range matches {
port := matches[i][1]
device := matches[i][2]
m[device] = port
}
return m
}
// hardwarePortInfo - information obtained using MacOS networksetup
// about the current state of the internet connection
type hardwarePortInfo struct {
name string
ip string
subnet string
gatewayIP string
static bool
}
func getHardwarePortInfo(hardwarePort string) (hardwarePortInfo, error) {
h := hardwarePortInfo{}
_, out, err := util.RunCommand("networksetup", "-getinfo", hardwarePort)
if err != nil {
return h, err
}
re := regexp.MustCompile("IP address: (.*?)\nSubnet mask: (.*?)\nRouter: (.*?)\n")
match := re.FindStringSubmatch(out)
if len(match) == 0 {
return h, errors.New("Could not find hardware port info")
}
h.name = hardwarePort
h.ip = match[1]
h.subnet = match[2]
h.gatewayIP = match[3]
if strings.Index(out, "Manual Configuration") == 0 {
h.static = true
}
return h, nil
}
// Gets a list of nameservers currently configured in the /etc/resolv.conf
func getEtcResolvConfServers() ([]string, error) {
body, err := ioutil.ReadFile("/etc/resolv.conf")
if err != nil {
return nil, err
}
re := regexp.MustCompile("nameserver ([a-zA-Z0-9.:]+)")
matches := re.FindAllStringSubmatch(string(body), -1)
if len(matches) == 0 {
return nil, errors.New("Found no DNS servers in /etc/resolv.conf")
}
addrs := make([]string, 0)
for i := range matches {
addrs = append(addrs, matches[i][1])
}
return addrs, nil
}