all: sync with master; upd chlog
This commit is contained in:
224
internal/arpdb/arpdb.go
Normal file
224
internal/arpdb/arpdb.go
Normal file
@@ -0,0 +1,224 @@
|
||||
// Package arpdb implements the Network Neighborhood Database.
|
||||
package arpdb
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync"
|
||||
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
"github.com/AdguardTeam/golibs/netutil"
|
||||
"golang.org/x/exp/slices"
|
||||
)
|
||||
|
||||
// Variables and functions to substitute in tests.
|
||||
var (
|
||||
// aghosRunCommand is the function to run shell commands.
|
||||
aghosRunCommand = aghos.RunCommand
|
||||
|
||||
// rootDirFS is the filesystem pointing to the root directory.
|
||||
rootDirFS = aghos.RootDirFS()
|
||||
)
|
||||
|
||||
// Interface stores and refreshes the network neighborhood reported by ARP
|
||||
// (Address Resolution Protocol).
|
||||
type Interface interface {
|
||||
// Refresh updates the stored data. It must be safe for concurrent use.
|
||||
Refresh() (err error)
|
||||
|
||||
// Neighbors returnes the last set of data reported by ARP. Both the method
|
||||
// and it's result must be safe for concurrent use.
|
||||
Neighbors() (ns []Neighbor)
|
||||
}
|
||||
|
||||
// New returns the [Interface] properly initialized for the OS.
|
||||
func New() (arp Interface) {
|
||||
return newARPDB()
|
||||
}
|
||||
|
||||
// Empty is the [Interface] implementation that does nothing.
|
||||
type Empty struct{}
|
||||
|
||||
// type check
|
||||
var _ Interface = Empty{}
|
||||
|
||||
// Refresh implements the [Interface] interface for EmptyARPContainer. It does
|
||||
// nothing and always returns nil error.
|
||||
func (Empty) Refresh() (err error) { return nil }
|
||||
|
||||
// Neighbors implements the [Interface] interface for EmptyARPContainer. It
|
||||
// always returns nil.
|
||||
func (Empty) Neighbors() (ns []Neighbor) { return nil }
|
||||
|
||||
// Neighbor is the pair of IP address and MAC address reported by ARP.
|
||||
type Neighbor struct {
|
||||
// Name is the hostname of the neighbor. Empty name is valid since not each
|
||||
// implementation of ARP is able to retrieve that.
|
||||
Name string
|
||||
|
||||
// IP contains either IPv4 or IPv6.
|
||||
IP netip.Addr
|
||||
|
||||
// MAC contains the hardware address.
|
||||
MAC net.HardwareAddr
|
||||
}
|
||||
|
||||
// Clone returns the deep copy of n.
|
||||
func (n Neighbor) Clone() (clone Neighbor) {
|
||||
return Neighbor{
|
||||
Name: n.Name,
|
||||
IP: n.IP,
|
||||
MAC: slices.Clone(n.MAC),
|
||||
}
|
||||
}
|
||||
|
||||
// validatedHostname returns h if it's a valid hostname, or an empty string
|
||||
// otherwise, logging the validation error.
|
||||
func validatedHostname(h string) (host string) {
|
||||
err := netutil.ValidateHostname(h)
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: host: %s", err)
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
// neighs is the helper type that stores neighbors to avoid copying its methods
|
||||
// among all the [Interface] implementations.
|
||||
type neighs struct {
|
||||
mu *sync.RWMutex
|
||||
ns []Neighbor
|
||||
}
|
||||
|
||||
// len returns the length of the neighbors slice. It's safe for concurrent use.
|
||||
func (ns *neighs) len() (l int) {
|
||||
ns.mu.RLock()
|
||||
defer ns.mu.RUnlock()
|
||||
|
||||
return len(ns.ns)
|
||||
}
|
||||
|
||||
// clone returns a deep copy of the underlying neighbors slice. It's safe for
|
||||
// concurrent use.
|
||||
func (ns *neighs) clone() (cloned []Neighbor) {
|
||||
ns.mu.RLock()
|
||||
defer ns.mu.RUnlock()
|
||||
|
||||
cloned = make([]Neighbor, len(ns.ns))
|
||||
for i, n := range ns.ns {
|
||||
cloned[i] = n.Clone()
|
||||
}
|
||||
|
||||
return cloned
|
||||
}
|
||||
|
||||
// reset replaces the underlying slice with the new one. It's safe for
|
||||
// concurrent use.
|
||||
func (ns *neighs) reset(with []Neighbor) {
|
||||
ns.mu.Lock()
|
||||
defer ns.mu.Unlock()
|
||||
|
||||
ns.ns = with
|
||||
}
|
||||
|
||||
// parseNeighsFunc parses the text from sc as if it'd be an output of some
|
||||
// ARP-related command. lenHint is a hint for the size of the allocated slice
|
||||
// of Neighbors.
|
||||
type parseNeighsFunc func(sc *bufio.Scanner, lenHint int) (ns []Neighbor)
|
||||
|
||||
// cmdARPDB is the implementation of the [Interface] that uses command line to
|
||||
// retrieve data.
|
||||
type cmdARPDB struct {
|
||||
parse parseNeighsFunc
|
||||
ns *neighs
|
||||
cmd string
|
||||
args []string
|
||||
}
|
||||
|
||||
// type check
|
||||
var _ Interface = (*cmdARPDB)(nil)
|
||||
|
||||
// Refresh implements the [Interface] interface for *cmdARPDB.
|
||||
func (arp *cmdARPDB) Refresh() (err error) {
|
||||
defer func() { err = errors.Annotate(err, "cmd arpdb: %w") }()
|
||||
|
||||
code, out, err := aghosRunCommand(arp.cmd, arp.args...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("running command: %w", err)
|
||||
} else if code != 0 {
|
||||
return fmt.Errorf("running command: unexpected exit code %d", code)
|
||||
}
|
||||
|
||||
sc := bufio.NewScanner(bytes.NewReader(out))
|
||||
ns := arp.parse(sc, arp.ns.len())
|
||||
if err = sc.Err(); err != nil {
|
||||
// TODO(e.burkov): This error seems unreachable. Investigate.
|
||||
return fmt.Errorf("scanning the output: %w", err)
|
||||
}
|
||||
|
||||
arp.ns.reset(ns)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Neighbors implements the [Interface] interface for *cmdARPDB.
|
||||
func (arp *cmdARPDB) Neighbors() (ns []Neighbor) {
|
||||
return arp.ns.clone()
|
||||
}
|
||||
|
||||
// arpdbs is the [Interface] that combines several [Interface] implementations
|
||||
// and consequently switches between those.
|
||||
type arpdbs struct {
|
||||
// arps is the set of [Interface] implementations to range through.
|
||||
arps []Interface
|
||||
neighs
|
||||
}
|
||||
|
||||
// newARPDBs returns a properly initialized *arpdbs. It begins refreshing from
|
||||
// the first of arps.
|
||||
func newARPDBs(arps ...Interface) (arp *arpdbs) {
|
||||
return &arpdbs{
|
||||
arps: arps,
|
||||
neighs: neighs{
|
||||
mu: &sync.RWMutex{},
|
||||
ns: make([]Neighbor, 0),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// type check
|
||||
var _ Interface = (*arpdbs)(nil)
|
||||
|
||||
// Refresh implements the [Interface] interface for *arpdbs.
|
||||
func (arp *arpdbs) Refresh() (err error) {
|
||||
var errs []error
|
||||
|
||||
for _, a := range arp.arps {
|
||||
err = a.Refresh()
|
||||
if err != nil {
|
||||
errs = append(errs, err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
arp.reset(a.Neighbors())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.Annotate(errors.Join(errs...), "each arpdb failed: %w")
|
||||
}
|
||||
|
||||
// Neighbors implements the [Interface] interface for *arpdbs.
|
||||
//
|
||||
// TODO(e.burkov): Think of a way to avoid cloning the slice twice.
|
||||
func (arp *arpdbs) Neighbors() (ns []Neighbor) {
|
||||
return arp.clone()
|
||||
}
|
||||
74
internal/arpdb/arpdb_bsd.go
Normal file
74
internal/arpdb/arpdb_bsd.go
Normal file
@@ -0,0 +1,74 @@
|
||||
//go:build darwin || freebsd
|
||||
|
||||
package arpdb
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
)
|
||||
|
||||
func newARPDB() (arp *cmdARPDB) {
|
||||
return &cmdARPDB{
|
||||
parse: parseArpA,
|
||||
ns: &neighs{
|
||||
mu: &sync.RWMutex{},
|
||||
ns: make([]Neighbor, 0),
|
||||
},
|
||||
cmd: "arp",
|
||||
// Use -n flag to avoid resolving the hostnames of the neighbors. By
|
||||
// default ARP attempts to resolve the hostnames via DNS. See man 8
|
||||
// arp.
|
||||
//
|
||||
// See also https://github.com/AdguardTeam/AdGuardHome/issues/3157.
|
||||
args: []string{"-a", "-n"},
|
||||
}
|
||||
}
|
||||
|
||||
// parseArpA parses the output of the "arp -a -n" command on macOS and FreeBSD.
|
||||
// The expected input format:
|
||||
//
|
||||
// host.name (192.168.0.1) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet]
|
||||
func parseArpA(sc *bufio.Scanner, lenHint int) (ns []Neighbor) {
|
||||
ns = make([]Neighbor, 0, lenHint)
|
||||
for sc.Scan() {
|
||||
ln := sc.Text()
|
||||
|
||||
fields := strings.Fields(ln)
|
||||
if len(fields) < 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
ipStr := fields[1]
|
||||
if len(ipStr) < 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(ipStr[1 : len(ipStr)-1])
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: ip: %s", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
hwStr := fields[3]
|
||||
mac, err := net.ParseMAC(hwStr)
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: mac: %s", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, Neighbor{
|
||||
IP: ip,
|
||||
MAC: mac,
|
||||
Name: validatedHostname(fields[0]),
|
||||
})
|
||||
}
|
||||
|
||||
return ns
|
||||
}
|
||||
31
internal/arpdb/arpdb_bsd_internal_test.go
Normal file
31
internal/arpdb/arpdb_bsd_internal_test.go
Normal file
@@ -0,0 +1,31 @@
|
||||
//go:build darwin || freebsd
|
||||
|
||||
package arpdb
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
)
|
||||
|
||||
const arpAOutput = `
|
||||
invalid.mac (1.2.3.4) at 12:34:56:78:910 on el0 ifscope [ethernet]
|
||||
invalid.ip (1.2.3.4.5) at ab:cd:ef:ab:cd:12 on ek0 ifscope [ethernet]
|
||||
invalid.fmt 1 at 12:cd:ef:ab:cd:ef on er0 ifscope [ethernet]
|
||||
hostname.one (192.168.1.2) at ab:cd:ef:ab:cd:ef on en0 ifscope [ethernet]
|
||||
hostname.two (::ffff:ffff) at ef:cd:ab:ef:cd:ab on em0 expires in 1198 seconds [ethernet]
|
||||
? (::1234) at aa:bb:cc:dd:ee:ff on ej0 expires in 1918 seconds [ethernet]
|
||||
`
|
||||
|
||||
var wantNeighs = []Neighbor{{
|
||||
Name: "hostname.one",
|
||||
IP: netip.MustParseAddr("192.168.1.2"),
|
||||
MAC: net.HardwareAddr{0xAB, 0xCD, 0xEF, 0xAB, 0xCD, 0xEF},
|
||||
}, {
|
||||
Name: "hostname.two",
|
||||
IP: netip.MustParseAddr("::ffff:ffff"),
|
||||
MAC: net.HardwareAddr{0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB},
|
||||
}, {
|
||||
Name: "",
|
||||
IP: netip.MustParseAddr("::1234"),
|
||||
MAC: net.HardwareAddr{0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF},
|
||||
}}
|
||||
269
internal/arpdb/arpdb_internal_test.go
Normal file
269
internal/arpdb/arpdb_internal_test.go
Normal file
@@ -0,0 +1,269 @@
|
||||
package arpdb
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/AdguardTeam/golibs/errors"
|
||||
"github.com/AdguardTeam/golibs/testutil"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// testdata is the filesystem containing data for testing the package.
|
||||
var testdata fs.FS = os.DirFS("./testdata")
|
||||
|
||||
// RunCmdFunc is the signature of aghos.RunCommand function.
|
||||
type RunCmdFunc func(cmd string, args ...string) (code int, out []byte, err error)
|
||||
|
||||
// substShell replaces the the aghos.RunCommand function used throughout the
|
||||
// package with rc for tests ran under t.
|
||||
func substShell(t testing.TB, rc RunCmdFunc) {
|
||||
t.Helper()
|
||||
|
||||
prev := aghosRunCommand
|
||||
t.Cleanup(func() { aghosRunCommand = prev })
|
||||
aghosRunCommand = rc
|
||||
}
|
||||
|
||||
// mapShell is a substitution of aghos.RunCommand that maps the command to it's
|
||||
// execution result. It's only needed to simplify testing.
|
||||
//
|
||||
// TODO(e.burkov): Perhaps put all the shell interactions behind an interface.
|
||||
type mapShell map[string]struct {
|
||||
err error
|
||||
out string
|
||||
code int
|
||||
}
|
||||
|
||||
// theOnlyCmd returns mapShell that only handles a single command and arguments
|
||||
// combination from cmd.
|
||||
func theOnlyCmd(cmd string, code int, out string, err error) (s mapShell) {
|
||||
return mapShell{cmd: {code: code, out: out, err: err}}
|
||||
}
|
||||
|
||||
// RunCmd is a RunCmdFunc handled by s.
|
||||
func (s mapShell) RunCmd(cmd string, args ...string) (code int, out []byte, err error) {
|
||||
key := strings.Join(append([]string{cmd}, args...), " ")
|
||||
ret, ok := s[key]
|
||||
if !ok {
|
||||
return 0, nil, fmt.Errorf("unexpected shell command %q", key)
|
||||
}
|
||||
|
||||
return ret.code, []byte(ret.out), ret.err
|
||||
}
|
||||
|
||||
func Test_New(t *testing.T) {
|
||||
var a Interface
|
||||
require.NotPanics(t, func() { a = New() })
|
||||
|
||||
assert.NotNil(t, a)
|
||||
}
|
||||
|
||||
// TODO(s.chzhen): Consider moving mocks into aghtest.
|
||||
|
||||
// TestARPDB is the mock implementation of [Interface] to use in tests.
|
||||
type TestARPDB struct {
|
||||
OnRefresh func() (err error)
|
||||
OnNeighbors func() (ns []Neighbor)
|
||||
}
|
||||
|
||||
// type check
|
||||
var _ Interface = (*TestARPDB)(nil)
|
||||
|
||||
// Refresh implements the [Interface] interface for *TestARPDB.
|
||||
func (arp *TestARPDB) Refresh() (err error) {
|
||||
return arp.OnRefresh()
|
||||
}
|
||||
|
||||
// Neighbors implements the [Interface] interface for *TestARPDB.
|
||||
func (arp *TestARPDB) Neighbors() (ns []Neighbor) {
|
||||
return arp.OnNeighbors()
|
||||
}
|
||||
|
||||
func Test_NewARPDBs(t *testing.T) {
|
||||
knownIP := netip.MustParseAddr("1.2.3.4")
|
||||
knownMAC := net.HardwareAddr{0xAB, 0xCD, 0xEF, 0xAB, 0xCD, 0xEF}
|
||||
|
||||
succRefrCount, failRefrCount := 0, 0
|
||||
clnp := func() {
|
||||
succRefrCount, failRefrCount = 0, 0
|
||||
}
|
||||
|
||||
succDB := &TestARPDB{
|
||||
OnRefresh: func() (err error) { succRefrCount++; return nil },
|
||||
OnNeighbors: func() (ns []Neighbor) {
|
||||
return []Neighbor{{Name: "abc", IP: knownIP, MAC: knownMAC}}
|
||||
},
|
||||
}
|
||||
failDB := &TestARPDB{
|
||||
OnRefresh: func() (err error) { failRefrCount++; return errors.Error("refresh failed") },
|
||||
OnNeighbors: func() (ns []Neighbor) { return nil },
|
||||
}
|
||||
|
||||
t.Run("begin_with_success", func(t *testing.T) {
|
||||
t.Cleanup(clnp)
|
||||
|
||||
a := newARPDBs(succDB, failDB)
|
||||
err := a.Refresh()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 1, succRefrCount)
|
||||
assert.Zero(t, failRefrCount)
|
||||
assert.NotEmpty(t, a.Neighbors())
|
||||
})
|
||||
|
||||
t.Run("begin_with_fail", func(t *testing.T) {
|
||||
t.Cleanup(clnp)
|
||||
|
||||
a := newARPDBs(failDB, succDB)
|
||||
err := a.Refresh()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 1, succRefrCount)
|
||||
assert.Equal(t, 1, failRefrCount)
|
||||
assert.NotEmpty(t, a.Neighbors())
|
||||
})
|
||||
|
||||
t.Run("fail_only", func(t *testing.T) {
|
||||
t.Cleanup(clnp)
|
||||
|
||||
wantMsg := "each arpdb failed: refresh failed\nrefresh failed"
|
||||
|
||||
a := newARPDBs(failDB, failDB)
|
||||
err := a.Refresh()
|
||||
require.Error(t, err)
|
||||
|
||||
testutil.AssertErrorMsg(t, wantMsg, err)
|
||||
|
||||
assert.Equal(t, 2, failRefrCount)
|
||||
assert.Empty(t, a.Neighbors())
|
||||
})
|
||||
|
||||
t.Run("fail_after_success", func(t *testing.T) {
|
||||
t.Cleanup(clnp)
|
||||
|
||||
shouldFail := false
|
||||
unstableDB := &TestARPDB{
|
||||
OnRefresh: func() (err error) {
|
||||
if shouldFail {
|
||||
err = errors.Error("unstable failed")
|
||||
}
|
||||
shouldFail = !shouldFail
|
||||
|
||||
return err
|
||||
},
|
||||
OnNeighbors: func() (ns []Neighbor) {
|
||||
if !shouldFail {
|
||||
return failDB.OnNeighbors()
|
||||
}
|
||||
|
||||
return succDB.OnNeighbors()
|
||||
},
|
||||
}
|
||||
a := newARPDBs(unstableDB, succDB)
|
||||
|
||||
// Unstable ARPDB should refresh successfully.
|
||||
err := a.Refresh()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Zero(t, succRefrCount)
|
||||
assert.NotEmpty(t, a.Neighbors())
|
||||
|
||||
// Unstable ARPDB should fail and the succDB should be used.
|
||||
err = a.Refresh()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 1, succRefrCount)
|
||||
assert.NotEmpty(t, a.Neighbors())
|
||||
|
||||
// Unstable ARPDB should refresh successfully again.
|
||||
err = a.Refresh()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 1, succRefrCount)
|
||||
assert.NotEmpty(t, a.Neighbors())
|
||||
})
|
||||
|
||||
t.Run("empty", func(t *testing.T) {
|
||||
a := newARPDBs()
|
||||
require.NoError(t, a.Refresh())
|
||||
|
||||
assert.Empty(t, a.Neighbors())
|
||||
})
|
||||
}
|
||||
|
||||
func TestCmdARPDB_arpa(t *testing.T) {
|
||||
a := &cmdARPDB{
|
||||
cmd: "cmd",
|
||||
parse: parseArpA,
|
||||
ns: &neighs{
|
||||
mu: &sync.RWMutex{},
|
||||
ns: make([]Neighbor, 0),
|
||||
},
|
||||
}
|
||||
|
||||
t.Run("arp_a", func(t *testing.T) {
|
||||
sh := theOnlyCmd("cmd", 0, arpAOutput, nil)
|
||||
substShell(t, sh.RunCmd)
|
||||
|
||||
err := a.Refresh()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, wantNeighs, a.Neighbors())
|
||||
})
|
||||
|
||||
t.Run("runcmd_error", func(t *testing.T) {
|
||||
sh := theOnlyCmd("cmd", 0, "", errors.Error("can't run"))
|
||||
substShell(t, sh.RunCmd)
|
||||
|
||||
err := a.Refresh()
|
||||
testutil.AssertErrorMsg(t, "cmd arpdb: running command: can't run", err)
|
||||
})
|
||||
|
||||
t.Run("bad_code", func(t *testing.T) {
|
||||
sh := theOnlyCmd("cmd", 1, "", nil)
|
||||
substShell(t, sh.RunCmd)
|
||||
|
||||
err := a.Refresh()
|
||||
testutil.AssertErrorMsg(t, "cmd arpdb: running command: unexpected exit code 1", err)
|
||||
})
|
||||
|
||||
t.Run("empty", func(t *testing.T) {
|
||||
sh := theOnlyCmd("cmd", 0, "", nil)
|
||||
substShell(t, sh.RunCmd)
|
||||
|
||||
err := a.Refresh()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Empty(t, a.Neighbors())
|
||||
})
|
||||
}
|
||||
|
||||
func TestEmptyARPDB(t *testing.T) {
|
||||
a := Empty{}
|
||||
|
||||
t.Run("refresh", func(t *testing.T) {
|
||||
var err error
|
||||
require.NotPanics(t, func() {
|
||||
err = a.Refresh()
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
})
|
||||
|
||||
t.Run("neighbors", func(t *testing.T) {
|
||||
var ns []Neighbor
|
||||
require.NotPanics(t, func() {
|
||||
ns = a.Neighbors()
|
||||
})
|
||||
|
||||
assert.Empty(t, ns)
|
||||
})
|
||||
}
|
||||
255
internal/arpdb/arpdb_linux.go
Normal file
255
internal/arpdb/arpdb_linux.go
Normal file
@@ -0,0 +1,255 @@
|
||||
//go:build linux
|
||||
|
||||
package arpdb
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/AdguardTeam/AdGuardHome/internal/aghos"
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
"github.com/AdguardTeam/golibs/stringutil"
|
||||
)
|
||||
|
||||
func newARPDB() (arp *arpdbs) {
|
||||
// Use the common storage among the implementations.
|
||||
ns := &neighs{
|
||||
mu: &sync.RWMutex{},
|
||||
ns: make([]Neighbor, 0),
|
||||
}
|
||||
|
||||
var parseF parseNeighsFunc
|
||||
if aghos.IsOpenWrt() {
|
||||
parseF = parseArpAWrt
|
||||
} else {
|
||||
parseF = parseArpA
|
||||
}
|
||||
|
||||
return newARPDBs(
|
||||
// Try /proc/net/arp first.
|
||||
&fsysARPDB{
|
||||
ns: ns,
|
||||
fsys: rootDirFS,
|
||||
filename: "proc/net/arp",
|
||||
},
|
||||
// Then, try "arp -a -n".
|
||||
&cmdARPDB{
|
||||
parse: parseF,
|
||||
ns: ns,
|
||||
cmd: "arp",
|
||||
// Use -n flag to avoid resolving the hostnames of the neighbors.
|
||||
// By default ARP attempts to resolve the hostnames via DNS. See
|
||||
// man 8 arp.
|
||||
//
|
||||
// See also https://github.com/AdguardTeam/AdGuardHome/issues/3157.
|
||||
args: []string{"-a", "-n"},
|
||||
},
|
||||
// Finally, try "ip neigh".
|
||||
&cmdARPDB{
|
||||
parse: parseIPNeigh,
|
||||
ns: ns,
|
||||
cmd: "ip",
|
||||
args: []string{"neigh"},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// fsysARPDB accesses the ARP cache file to update the database.
|
||||
type fsysARPDB struct {
|
||||
ns *neighs
|
||||
fsys fs.FS
|
||||
filename string
|
||||
}
|
||||
|
||||
// type check
|
||||
var _ Interface = (*fsysARPDB)(nil)
|
||||
|
||||
// Refresh implements the [Interface] interface for *fsysARPDB.
|
||||
func (arp *fsysARPDB) Refresh() (err error) {
|
||||
var f fs.File
|
||||
f, err = arp.fsys.Open(arp.filename)
|
||||
if err != nil {
|
||||
return fmt.Errorf("opening %q: %w", arp.filename, err)
|
||||
}
|
||||
|
||||
sc := bufio.NewScanner(f)
|
||||
// Skip the header.
|
||||
if !sc.Scan() {
|
||||
return nil
|
||||
} else if err = sc.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ns := make([]Neighbor, 0, arp.ns.len())
|
||||
for sc.Scan() {
|
||||
n := parseNeighbor(sc.Text())
|
||||
if n != nil {
|
||||
ns = append(ns, *n)
|
||||
}
|
||||
}
|
||||
|
||||
arp.ns.reset(ns)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseNeighbor parses line into *Neighbor.
|
||||
func parseNeighbor(line string) (n *Neighbor) {
|
||||
fields := stringutil.SplitTrimmed(line, " ")
|
||||
if len(fields) != 6 {
|
||||
return nil
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(fields[0])
|
||||
if err != nil || ip.IsUnspecified() {
|
||||
return nil
|
||||
}
|
||||
|
||||
mac, err := net.ParseMAC(fields[3])
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &Neighbor{
|
||||
IP: ip,
|
||||
MAC: mac,
|
||||
}
|
||||
}
|
||||
|
||||
// Neighbors implements the [Interface] interface for *fsysARPDB.
|
||||
func (arp *fsysARPDB) Neighbors() (ns []Neighbor) {
|
||||
return arp.ns.clone()
|
||||
}
|
||||
|
||||
// parseArpAWrt parses the output of the "arp -a -n" command on OpenWrt. The
|
||||
// expected input format:
|
||||
//
|
||||
// IP address HW type Flags HW address Mask Device
|
||||
// 192.168.11.98 0x1 0x2 5a:92:df:a9:7e:28 * wan
|
||||
func parseArpAWrt(sc *bufio.Scanner, lenHint int) (ns []Neighbor) {
|
||||
if !sc.Scan() {
|
||||
// Skip the header.
|
||||
return
|
||||
}
|
||||
|
||||
ns = make([]Neighbor, 0, lenHint)
|
||||
for sc.Scan() {
|
||||
ln := sc.Text()
|
||||
|
||||
fields := strings.Fields(ln)
|
||||
if len(fields) < 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(fields[0])
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: ip: %s", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
hwStr := fields[3]
|
||||
mac, err := net.ParseMAC(hwStr)
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: mac: %s", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, Neighbor{
|
||||
IP: ip,
|
||||
MAC: mac,
|
||||
})
|
||||
}
|
||||
|
||||
return ns
|
||||
}
|
||||
|
||||
// parseArpA parses the output of the "arp -a -n" command on Linux. The
|
||||
// expected input format:
|
||||
//
|
||||
// hostname (192.168.1.1) at ab:cd:ef:ab:cd:ef [ether] on enp0s3
|
||||
func parseArpA(sc *bufio.Scanner, lenHint int) (ns []Neighbor) {
|
||||
ns = make([]Neighbor, 0, lenHint)
|
||||
for sc.Scan() {
|
||||
ln := sc.Text()
|
||||
|
||||
fields := strings.Fields(ln)
|
||||
if len(fields) < 4 {
|
||||
continue
|
||||
}
|
||||
|
||||
ipStr := fields[1]
|
||||
if len(ipStr) < 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(ipStr[1 : len(ipStr)-1])
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: ip: %s", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
hwStr := fields[3]
|
||||
mac, err := net.ParseMAC(hwStr)
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: mac: %s", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, Neighbor{
|
||||
IP: ip,
|
||||
MAC: mac,
|
||||
Name: validatedHostname(fields[0]),
|
||||
})
|
||||
}
|
||||
|
||||
return ns
|
||||
}
|
||||
|
||||
// parseIPNeigh parses the output of the "ip neigh" command on Linux. The
|
||||
// expected input format:
|
||||
//
|
||||
// 192.168.1.1 dev enp0s3 lladdr ab:cd:ef:ab:cd:ef REACHABLE
|
||||
func parseIPNeigh(sc *bufio.Scanner, lenHint int) (ns []Neighbor) {
|
||||
ns = make([]Neighbor, 0, lenHint)
|
||||
for sc.Scan() {
|
||||
ln := sc.Text()
|
||||
|
||||
fields := strings.Fields(ln)
|
||||
if len(fields) < 5 {
|
||||
continue
|
||||
}
|
||||
|
||||
n := Neighbor{}
|
||||
|
||||
ip, err := netip.ParseAddr(fields[0])
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: ip: %s", err)
|
||||
|
||||
continue
|
||||
} else {
|
||||
n.IP = ip
|
||||
}
|
||||
|
||||
mac, err := net.ParseMAC(fields[4])
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: mac: %s", err)
|
||||
|
||||
continue
|
||||
} else {
|
||||
n.MAC = mac
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
|
||||
return ns
|
||||
}
|
||||
102
internal/arpdb/arpdb_linux_internal_test.go
Normal file
102
internal/arpdb/arpdb_linux_internal_test.go
Normal file
@@ -0,0 +1,102 @@
|
||||
//go:build linux
|
||||
|
||||
package arpdb
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const arpAOutputWrt = `
|
||||
IP address HW type Flags HW address Mask Device
|
||||
1.2.3.4.5 0x1 0x2 aa:bb:cc:dd:ee:ff * wan
|
||||
1.2.3.4 0x1 0x2 12:34:56:78:910 * wan
|
||||
192.168.1.2 0x1 0x2 ab:cd:ef:ab:cd:ef * wan
|
||||
::ffff:ffff 0x1 0x2 ef:cd:ab:ef:cd:ab * wan`
|
||||
|
||||
const arpAOutput = `
|
||||
invalid.mac (1.2.3.4) at 12:34:56:78:910 on el0 ifscope [ethernet]
|
||||
invalid.ip (1.2.3.4.5) at ab:cd:ef:ab:cd:12 on ek0 ifscope [ethernet]
|
||||
invalid.fmt 1 at 12:cd:ef:ab:cd:ef on er0 ifscope [ethernet]
|
||||
? (192.168.1.2) at ab:cd:ef:ab:cd:ef on en0 ifscope [ethernet]
|
||||
? (::ffff:ffff) at ef:cd:ab:ef:cd:ab on em0 expires in 100 seconds [ethernet]`
|
||||
|
||||
const ipNeighOutput = `
|
||||
1.2.3.4.5 dev enp0s3 lladdr aa:bb:cc:dd:ee:ff DELAY
|
||||
1.2.3.4 dev enp0s3 lladdr 12:34:56:78:910 DELAY
|
||||
192.168.1.2 dev enp0s3 lladdr ab:cd:ef:ab:cd:ef DELAY
|
||||
::ffff:ffff dev enp0s3 lladdr ef:cd:ab:ef:cd:ab router STALE`
|
||||
|
||||
var wantNeighs = []Neighbor{{
|
||||
IP: netip.MustParseAddr("192.168.1.2"),
|
||||
MAC: net.HardwareAddr{0xAB, 0xCD, 0xEF, 0xAB, 0xCD, 0xEF},
|
||||
}, {
|
||||
IP: netip.MustParseAddr("::ffff:ffff"),
|
||||
MAC: net.HardwareAddr{0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB},
|
||||
}}
|
||||
|
||||
func TestFSysARPDB(t *testing.T) {
|
||||
require.NoError(t, fstest.TestFS(testdata, "proc_net_arp"))
|
||||
|
||||
a := &fsysARPDB{
|
||||
ns: &neighs{
|
||||
mu: &sync.RWMutex{},
|
||||
ns: make([]Neighbor, 0),
|
||||
},
|
||||
fsys: testdata,
|
||||
filename: "proc_net_arp",
|
||||
}
|
||||
|
||||
err := a.Refresh()
|
||||
require.NoError(t, err)
|
||||
|
||||
ns := a.Neighbors()
|
||||
assert.Equal(t, wantNeighs, ns)
|
||||
}
|
||||
|
||||
func TestCmdARPDB_linux(t *testing.T) {
|
||||
sh := mapShell{
|
||||
"arp -a": {err: nil, out: arpAOutputWrt, code: 0},
|
||||
"ip neigh": {err: nil, out: ipNeighOutput, code: 0},
|
||||
}
|
||||
substShell(t, sh.RunCmd)
|
||||
|
||||
t.Run("wrt", func(t *testing.T) {
|
||||
a := &cmdARPDB{
|
||||
parse: parseArpAWrt,
|
||||
cmd: "arp",
|
||||
args: []string{"-a"},
|
||||
ns: &neighs{
|
||||
mu: &sync.RWMutex{},
|
||||
ns: make([]Neighbor, 0),
|
||||
},
|
||||
}
|
||||
|
||||
err := a.Refresh()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, wantNeighs, a.Neighbors())
|
||||
})
|
||||
|
||||
t.Run("ip_neigh", func(t *testing.T) {
|
||||
a := &cmdARPDB{
|
||||
parse: parseIPNeigh,
|
||||
cmd: "ip",
|
||||
args: []string{"neigh"},
|
||||
ns: &neighs{
|
||||
mu: &sync.RWMutex{},
|
||||
ns: make([]Neighbor, 0),
|
||||
},
|
||||
}
|
||||
err := a.Refresh()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, wantNeighs, a.Neighbors())
|
||||
})
|
||||
}
|
||||
76
internal/arpdb/arpdb_openbsd.go
Normal file
76
internal/arpdb/arpdb_openbsd.go
Normal file
@@ -0,0 +1,76 @@
|
||||
//go:build openbsd
|
||||
|
||||
package arpdb
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
)
|
||||
|
||||
func newARPDB() (arp *cmdARPDB) {
|
||||
return &cmdARPDB{
|
||||
parse: parseArpA,
|
||||
ns: &neighs{
|
||||
mu: &sync.RWMutex{},
|
||||
ns: make([]Neighbor, 0),
|
||||
},
|
||||
cmd: "arp",
|
||||
// Use -n flag to avoid resolving the hostnames of the neighbors. By
|
||||
// default ARP attempts to resolve the hostnames via DNS. See man 8
|
||||
// arp.
|
||||
//
|
||||
// See also https://github.com/AdguardTeam/AdGuardHome/issues/3157.
|
||||
args: []string{"-a", "-n"},
|
||||
}
|
||||
}
|
||||
|
||||
// parseArpA parses the output of the "arp -a -n" command on OpenBSD. The
|
||||
// expected input format:
|
||||
//
|
||||
// Host Ethernet Address Netif Expire Flags
|
||||
// 192.168.1.1 ab:cd:ef:ab:cd:ef em0 19m59s
|
||||
func parseArpA(sc *bufio.Scanner, lenHint int) (ns []Neighbor) {
|
||||
// Skip the header.
|
||||
if !sc.Scan() {
|
||||
return nil
|
||||
}
|
||||
|
||||
ns = make([]Neighbor, 0, lenHint)
|
||||
for sc.Scan() {
|
||||
ln := sc.Text()
|
||||
|
||||
fields := strings.Fields(ln)
|
||||
if len(fields) < 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
n := Neighbor{}
|
||||
|
||||
ip, err := netip.ParseAddr(fields[0])
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: ip: %s", err)
|
||||
|
||||
continue
|
||||
} else {
|
||||
n.IP = ip
|
||||
}
|
||||
|
||||
mac, err := net.ParseMAC(fields[1])
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: mac: %s", err)
|
||||
|
||||
continue
|
||||
} else {
|
||||
n.MAC = mac
|
||||
}
|
||||
|
||||
ns = append(ns, n)
|
||||
}
|
||||
|
||||
return ns
|
||||
}
|
||||
24
internal/arpdb/arpdb_openbsd_internal_test.go
Normal file
24
internal/arpdb/arpdb_openbsd_internal_test.go
Normal file
@@ -0,0 +1,24 @@
|
||||
//go:build openbsd
|
||||
|
||||
package arpdb
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
)
|
||||
|
||||
const arpAOutput = `
|
||||
Host Ethernet Address Netif Expire Flags
|
||||
1.2.3.4.5 aa:bb:cc:dd:ee:ff em0 permanent
|
||||
1.2.3.4 12:34:56:78:910 em0 permanent
|
||||
192.168.1.2 ab:cd:ef:ab:cd:ef em0 19m56s
|
||||
::ffff:ffff ef:cd:ab:ef:cd:ab em0 permanent l
|
||||
`
|
||||
|
||||
var wantNeighs = []Neighbor{{
|
||||
IP: netip.MustParseAddr("192.168.1.2"),
|
||||
MAC: net.HardwareAddr{0xAB, 0xCD, 0xEF, 0xAB, 0xCD, 0xEF},
|
||||
}, {
|
||||
IP: netip.MustParseAddr("::ffff:ffff"),
|
||||
MAC: net.HardwareAddr{0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB},
|
||||
}}
|
||||
68
internal/arpdb/arpdb_windows.go
Normal file
68
internal/arpdb/arpdb_windows.go
Normal file
@@ -0,0 +1,68 @@
|
||||
//go:build windows
|
||||
|
||||
package arpdb
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/AdguardTeam/golibs/log"
|
||||
)
|
||||
|
||||
func newARPDB() (arp *cmdARPDB) {
|
||||
return &cmdARPDB{
|
||||
parse: parseArpA,
|
||||
ns: &neighs{
|
||||
mu: &sync.RWMutex{},
|
||||
ns: make([]Neighbor, 0),
|
||||
},
|
||||
cmd: "arp",
|
||||
args: []string{"/a"},
|
||||
}
|
||||
}
|
||||
|
||||
// parseArpA parses the output of the "arp /a" command on Windows. The expected
|
||||
// input format (the first line is empty):
|
||||
//
|
||||
// Interface: 192.168.56.16 --- 0x7
|
||||
// Internet Address Physical Address Type
|
||||
// 192.168.56.1 0a-00-27-00-00-00 dynamic
|
||||
// 192.168.56.255 ff-ff-ff-ff-ff-ff static
|
||||
func parseArpA(sc *bufio.Scanner, lenHint int) (ns []Neighbor) {
|
||||
ns = make([]Neighbor, 0, lenHint)
|
||||
for sc.Scan() {
|
||||
ln := sc.Text()
|
||||
if ln == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
fields := strings.Fields(ln)
|
||||
if len(fields) != 3 {
|
||||
continue
|
||||
}
|
||||
|
||||
ip, err := netip.ParseAddr(fields[0])
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: ip: %s", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
mac, err := net.ParseMAC(fields[1])
|
||||
if err != nil {
|
||||
log.Debug("arpdb: parsing arp output: mac: %s", err)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
ns = append(ns, Neighbor{
|
||||
IP: ip,
|
||||
MAC: mac,
|
||||
})
|
||||
}
|
||||
|
||||
return ns
|
||||
}
|
||||
23
internal/arpdb/arpdb_windows_internal_test.go
Normal file
23
internal/arpdb/arpdb_windows_internal_test.go
Normal file
@@ -0,0 +1,23 @@
|
||||
//go:build windows
|
||||
|
||||
package arpdb
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
)
|
||||
|
||||
const arpAOutput = `
|
||||
|
||||
Interface: 192.168.1.1 --- 0x7
|
||||
Internet Address Physical Address Type
|
||||
192.168.1.2 ab-cd-ef-ab-cd-ef dynamic
|
||||
::ffff:ffff ef-cd-ab-ef-cd-ab static`
|
||||
|
||||
var wantNeighs = []Neighbor{{
|
||||
IP: netip.MustParseAddr("192.168.1.2"),
|
||||
MAC: net.HardwareAddr{0xAB, 0xCD, 0xEF, 0xAB, 0xCD, 0xEF},
|
||||
}, {
|
||||
IP: netip.MustParseAddr("::ffff:ffff"),
|
||||
MAC: net.HardwareAddr{0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB},
|
||||
}}
|
||||
6
internal/arpdb/testdata/proc_net_arp
vendored
Normal file
6
internal/arpdb/testdata/proc_net_arp
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
IP address HW type Flags HW address Mask Device
|
||||
192.168.1.2 0x1 0x2 ab:cd:ef:ab:cd:ef * wan
|
||||
::ffff:ffff 0x1 0x0 ef:cd:ab:ef:cd:ab * br-lan
|
||||
0.0.0.0 0x0 0x0 00:00:00:00:00:00 * unspec
|
||||
1.2.3.4.5 0x1 0x2 aa:bb:cc:dd:ee:ff * wan
|
||||
1.2.3.4 0x1 0x2 12:34:56:78:910 * wan
|
||||
Reference in New Issue
Block a user