2022-03-15 17:57:46 +00:00
|
|
|
//go:build darwin || freebsd
|
|
|
|
|
2023-08-24 11:42:17 +01:00
|
|
|
package arpdb
|
2022-03-15 17:57:46 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2024-08-27 18:42:10 +01:00
|
|
|
"log/slog"
|
2022-03-15 17:57:46 +00:00
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
|
2024-08-27 18:42:10 +01:00
|
|
|
"github.com/AdguardTeam/golibs/logutil/slogutil"
|
2022-03-15 17:57:46 +00:00
|
|
|
)
|
|
|
|
|
2024-08-27 18:42:10 +01:00
|
|
|
func newARPDB(logger *slog.Logger) (arp *cmdARPDB) {
|
2022-03-15 17:57:46 +00:00
|
|
|
return &cmdARPDB{
|
2024-08-27 18:42:10 +01:00
|
|
|
logger: logger,
|
|
|
|
parse: parseArpA,
|
2022-03-15 17:57:46 +00:00
|
|
|
ns: &neighs{
|
|
|
|
mu: &sync.RWMutex{},
|
|
|
|
ns: make([]Neighbor, 0),
|
|
|
|
},
|
2022-04-19 13:01:49 +01: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 17:57:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-19 13:01:49 +01:00
|
|
|
// parseArpA parses the output of the "arp -a -n" command on macOS and FreeBSD.
|
2022-03-15 17:57:46 +00:00
|
|
|
// The expected input format:
|
|
|
|
//
|
2022-08-31 16:57:02 +01:00
|
|
|
// host.name (192.168.0.1) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet]
|
2024-08-27 18:42:10 +01:00
|
|
|
func parseArpA(logger *slog.Logger, sc *bufio.Scanner, lenHint int) (ns []Neighbor) {
|
2022-03-15 17:57:46 +00:00
|
|
|
ns = make([]Neighbor, 0, lenHint)
|
|
|
|
for sc.Scan() {
|
|
|
|
ln := sc.Text()
|
|
|
|
|
|
|
|
fields := strings.Fields(ln)
|
|
|
|
if len(fields) < 4 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2023-08-24 11:42:17 +01:00
|
|
|
ipStr := fields[1]
|
|
|
|
if len(ipStr) < 2 {
|
2022-03-15 17:57:46 +00:00
|
|
|
continue
|
2023-08-24 11:42:17 +01:00
|
|
|
}
|
|
|
|
|
2024-08-27 18:42:10 +01:00
|
|
|
host := validatedHostname(logger, fields[0])
|
|
|
|
n, err := newNeighbor(host, ipStr[1:len(ipStr)-1], fields[3])
|
2023-08-24 11:42:17 +01:00
|
|
|
if err != nil {
|
2024-08-27 18:42:10 +01:00
|
|
|
logger.Debug("parsing arp output", "line", ln, slogutil.KeyError, err)
|
2022-10-25 13:08:12 +01:00
|
|
|
|
2022-03-15 17:57:46 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-08-27 18:42:10 +01:00
|
|
|
ns = append(ns, *n)
|
2022-03-15 17:57:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return ns
|
|
|
|
}
|