2022-03-15 20:57:46 +03:00
|
|
|
//go:build darwin || freebsd
|
|
|
|
|
|
|
|
package aghnet
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"net"
|
2022-10-25 15:08:12 +03:00
|
|
|
"net/netip"
|
2022-03-15 20:57:46 +03:00
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/AdguardTeam/golibs/log"
|
|
|
|
"github.com/AdguardTeam/golibs/netutil"
|
|
|
|
)
|
|
|
|
|
2022-04-19 15:01:49 +03:00
|
|
|
func newARPDB() (arp *cmdARPDB) {
|
2022-03-15 20:57:46 +03:00
|
|
|
return &cmdARPDB{
|
2022-03-30 15:11:57 +03:00
|
|
|
parse: parseArpA,
|
2022-03-15 20:57:46 +03:00
|
|
|
ns: &neighs{
|
|
|
|
mu: &sync.RWMutex{},
|
|
|
|
ns: make([]Neighbor, 0),
|
|
|
|
},
|
2022-04-19 15:01:49 +03:00
|
|
|
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"},
|
2022-03-15 20:57:46 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-19 15:01:49 +03:00
|
|
|
// parseArpA parses the output of the "arp -a -n" command on macOS and FreeBSD.
|
2022-03-15 20:57:46 +03:00
|
|
|
// The expected input format:
|
|
|
|
//
|
2022-08-31 18:57:02 +03:00
|
|
|
// host.name (192.168.0.1) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet]
|
2022-03-15 20:57:46 +03:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
n := Neighbor{}
|
|
|
|
|
|
|
|
if ipStr := fields[1]; len(ipStr) < 2 {
|
|
|
|
continue
|
2022-10-25 15:08:12 +03:00
|
|
|
} else if ip, err := netip.ParseAddr(ipStr[1 : len(ipStr)-1]); err != nil {
|
|
|
|
log.Debug("arpdb: parsing arp output: ip: %s", err)
|
|
|
|
|
2022-03-15 20:57:46 +03:00
|
|
|
continue
|
|
|
|
} else {
|
|
|
|
n.IP = ip
|
|
|
|
}
|
|
|
|
|
|
|
|
hwStr := fields[3]
|
2022-10-25 15:08:12 +03:00
|
|
|
mac, err := net.ParseMAC(hwStr)
|
|
|
|
if err != nil {
|
|
|
|
log.Debug("arpdb: parsing arp output: mac: %s", err)
|
|
|
|
|
2022-03-15 20:57:46 +03:00
|
|
|
continue
|
|
|
|
} else {
|
|
|
|
n.MAC = mac
|
|
|
|
}
|
|
|
|
|
|
|
|
host := fields[0]
|
2022-10-25 15:08:12 +03:00
|
|
|
err = netutil.ValidateDomainName(host)
|
|
|
|
if err != nil {
|
|
|
|
log.Debug("arpdb: parsing arp output: host: %s", err)
|
2022-03-15 20:57:46 +03:00
|
|
|
} else {
|
|
|
|
n.Name = host
|
|
|
|
}
|
|
|
|
|
|
|
|
ns = append(ns, n)
|
|
|
|
}
|
|
|
|
|
|
|
|
return ns
|
|
|
|
}
|