feat(node): expose fresh network interface and hardware status
This commit is contained in:
@@ -12,10 +12,13 @@ import (
|
||||
)
|
||||
|
||||
type Network struct {
|
||||
Name string `json:"name"`
|
||||
Up bool `json:"up"`
|
||||
Addresses []string `json:"addresses"`
|
||||
AddressesReadable bool `json:"addresses_readable"`
|
||||
Name string `json:"name"`
|
||||
Up bool `json:"up"`
|
||||
Addresses []string `json:"addresses"`
|
||||
AddressesReadable bool `json:"addresses_readable"`
|
||||
Kind string `json:"kind,omitempty"`
|
||||
Connection *NetworkConnection `json:"connection,omitempty"`
|
||||
Hardware *NetworkHardware `json:"hardware,omitempty"`
|
||||
}
|
||||
type USB struct {
|
||||
Port string `json:"port"`
|
||||
@@ -74,6 +77,9 @@ func Host(root string) Inventory {
|
||||
}
|
||||
var warnings []string
|
||||
v.Networks, v.NetworksReadable, warnings = readNetworks(net.Interfaces, func(it net.Interface) ([]net.Addr, error) { return it.Addrs() })
|
||||
if runtime.GOOS == "linux" && root == "/" {
|
||||
annotateNetworks(root, v.Networks, hostNetworkCache.snapshot(time.Now()))
|
||||
}
|
||||
v.Warnings = append(v.Warnings, warnings...)
|
||||
entries, err := os.ReadDir(filepath.Join(root, "sys/bus/usb/devices"))
|
||||
v.USBReadable = err == nil
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Hardware describes reported facts, not whether an adapter is physically
|
||||
// inside the enclosure: USB can be internal and PCI can be hot-pluggable.
|
||||
type NetworkHardware struct {
|
||||
Bus string `json:"bus,omitempty"`
|
||||
Vendor string `json:"vendor,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
}
|
||||
|
||||
type networkObservation struct {
|
||||
NetworkConnection
|
||||
Hardware NetworkHardware
|
||||
}
|
||||
|
||||
func networkBus(path string) string {
|
||||
target, err := os.Readlink(filepath.Join(path, "device/subsystem"))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
switch bus := filepath.Base(target); bus {
|
||||
case "usb", "pci", "sdio", "platform", "virtio":
|
||||
return bus
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func networkHardwareText(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "--" || len(value) > 256 || !utf8.ValidString(value) {
|
||||
return ""
|
||||
}
|
||||
for _, r := range value {
|
||||
if unicode.IsControl(r) {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNetworkHardwareUsesOSMetadataEvenWhenDisconnected(t *testing.T) {
|
||||
rows := parseNetworkConnections("GENERAL.DEVICE:arbitrary-name\nGENERAL.TYPE:wifi\nGENERAL.STATE:30 (disconnected)\nGENERAL.VENDOR:Acme\\: radios\nGENERAL.PRODUCT:USB <radio>\nGENERAL.DEVICE:second\nGENERAL.TYPE:wifi\nGENERAL.STATE:100\n")
|
||||
if rows["arbitrary-name"].Hardware.Vendor != "Acme: radios" || rows["arbitrary-name"].Hardware.Model != "USB <radio>" || rows["second"].Hardware != (NetworkHardware{}) {
|
||||
t.Fatal(rows)
|
||||
}
|
||||
root := t.TempDir()
|
||||
for name, bus := range map[string]string{"arbitrary-name": "usb", "second": "pci", "wlx-not-a-usb-proof": ""} {
|
||||
path := filepath.Join(root, "sys/class/net", name)
|
||||
if err := os.MkdirAll(filepath.Join(path, "wireless"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Join(path, "device"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bus != "" {
|
||||
if err := os.Symlink("../../../../bus/"+bus, filepath.Join(path, "device/subsystem")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
networks := []Network{{Name: "arbitrary-name"}, {Name: "second"}, {Name: "wlx-not-a-usb-proof"}}
|
||||
annotateNetworks(root, networks, rows)
|
||||
if networks[0].Hardware.Bus != "usb" || networks[0].Hardware.Model != "USB <radio>" || networks[0].Connection.State != "disconnected" || networks[1].Hardware.Bus != "pci" || networks[2].Hardware != nil {
|
||||
t.Fatal(networks)
|
||||
}
|
||||
// Losing NetworkManager metadata must not erase the independently observed bus.
|
||||
offline := []Network{{Name: "arbitrary-name"}}
|
||||
annotateNetworks(root, offline, nil)
|
||||
if offline[0].Hardware.Bus != "usb" || offline[0].Hardware.Model != "" || offline[0].Connection != nil {
|
||||
t.Fatal(offline)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkHardwareRejectsInvalidOrUnboundedNames(t *testing.T) {
|
||||
for _, name := range []string{"--", strings.Repeat("a", 257), "radio\x00name", "radio\tname", string([]byte{255})} {
|
||||
if got := networkHardwareText(name); got != "" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
if got := networkHardwareText(" Example radio "); got != "Example radio" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
path := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(path, "device"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink("../../bus/unknown-bus", filepath.Join(path, "device/subsystem")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if networkBus(path) != "" {
|
||||
t.Fatal("invented bus")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// NetworkConnection describes the OS link, not Internet reachability or VPN health.
|
||||
type NetworkConnection struct {
|
||||
State string `json:"state"`
|
||||
SSID string `json:"ssid,omitempty"`
|
||||
SignalPercent *int `json:"signal_percent,omitempty"`
|
||||
CollectedAt string `json:"collected_at"`
|
||||
}
|
||||
|
||||
type networkInventoryCache struct {
|
||||
mu sync.Mutex
|
||||
checked time.Time
|
||||
busy bool
|
||||
rows map[string]networkObservation
|
||||
collect func() map[string]networkObservation
|
||||
}
|
||||
|
||||
var hostNetworkCache = networkInventoryCache{collect: collectNetworkConnections}
|
||||
|
||||
// Slow or unavailable NetworkManager must never delay a heartbeat. Only one
|
||||
// bounded read runs at a time; failed reads replace old data instead of renewing it.
|
||||
func (c *networkInventoryCache) snapshot(now time.Time) map[string]networkObservation {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if !c.busy && (c.checked.IsZero() || now.Sub(c.checked) >= 5*time.Second) {
|
||||
c.busy = true
|
||||
go func() {
|
||||
rows := c.collect()
|
||||
for name, row := range rows {
|
||||
row.CollectedAt = now.UTC().Format(time.RFC3339Nano)
|
||||
rows[name] = row
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.rows, c.checked, c.busy = rows, now, false
|
||||
c.mu.Unlock()
|
||||
}()
|
||||
}
|
||||
if c.checked.IsZero() || now.Sub(c.checked) > 15*time.Second {
|
||||
return nil
|
||||
}
|
||||
copy := make(map[string]networkObservation, len(c.rows))
|
||||
for name, row := range c.rows {
|
||||
copy[name] = row
|
||||
}
|
||||
return copy
|
||||
}
|
||||
|
||||
type networkOutput struct{ buffer bytes.Buffer }
|
||||
|
||||
func (b *networkOutput) Len() int { return b.buffer.Len() }
|
||||
func (b *networkOutput) String() string { return b.buffer.String() }
|
||||
|
||||
func (b *networkOutput) Write(p []byte) (int, error) {
|
||||
if b.Len()+len(p) > 64*1024 {
|
||||
return 0, errors.New("network metadata exceeds bound")
|
||||
}
|
||||
return b.buffer.Write(p)
|
||||
}
|
||||
|
||||
func collectNetworkConnections() map[string]networkObservation {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond)
|
||||
defer cancel()
|
||||
// device show reads NetworkManager's cache. It does not scan, modify a
|
||||
// connection or read saved credentials. No shell or operator input is used.
|
||||
cmd := exec.CommandContext(ctx, "/usr/bin/nmcli", "--terse", "--escape", "yes", "--fields",
|
||||
"GENERAL.DEVICE,GENERAL.TYPE,GENERAL.STATE,GENERAL.VENDOR,GENERAL.PRODUCT,AP.IN-USE,AP.SSID,AP.SIGNAL", "device", "show")
|
||||
cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C", "DBUS_SYSTEM_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket"}
|
||||
var output networkOutput
|
||||
cmd.Stdout = &output
|
||||
cmd.WaitDelay = 100 * time.Millisecond
|
||||
if cmd.Run() != nil {
|
||||
return nil
|
||||
}
|
||||
return parseNetworkConnections(output.String())
|
||||
}
|
||||
|
||||
func nmValue(value string) string {
|
||||
var out strings.Builder
|
||||
for i := 0; i < len(value); i++ {
|
||||
if value[i] == '\\' && i+1 < len(value) && (value[i+1] == ':' || value[i+1] == '\\') {
|
||||
i++
|
||||
}
|
||||
out.WriteByte(value[i])
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func parseNetworkConnections(raw string) map[string]networkObservation {
|
||||
rows := make(map[string]networkObservation)
|
||||
var name, kind, state, vendor, model string
|
||||
aps := make(map[string]map[string]string)
|
||||
flush := func() {
|
||||
if name == "" || len(name) > 64 || (kind != "wifi" && kind != "ethernet") {
|
||||
return
|
||||
}
|
||||
row := networkObservation{NetworkConnection: NetworkConnection{State: "unknown"}, Hardware: NetworkHardware{Vendor: networkHardwareText(vendor), Model: networkHardwareText(model)}}
|
||||
switch state {
|
||||
case "100":
|
||||
row.State = "connected"
|
||||
case "30":
|
||||
row.State = "disconnected"
|
||||
case "20":
|
||||
row.State = "unavailable"
|
||||
case "40", "50", "60", "70", "80", "90":
|
||||
row.State = "connecting"
|
||||
case "110":
|
||||
row.State = "disconnecting"
|
||||
case "120":
|
||||
row.State = "failed"
|
||||
}
|
||||
if kind == "wifi" && row.State == "connected" {
|
||||
var active []map[string]string
|
||||
for _, ap := range aps {
|
||||
if ap["IN-USE"] == "*" {
|
||||
active = append(active, ap)
|
||||
}
|
||||
}
|
||||
if len(active) == 1 {
|
||||
ssid := active[0]["SSID"]
|
||||
if len(ssid) <= 32 && utf8.ValidString(ssid) && !strings.ContainsAny(ssid, "\r\n\x00") {
|
||||
row.SSID = ssid
|
||||
}
|
||||
if n, err := strconv.Atoi(active[0]["SIGNAL"]); err == nil && n >= 0 && n <= 100 {
|
||||
row.SignalPercent = &n
|
||||
}
|
||||
}
|
||||
}
|
||||
rows[name] = row
|
||||
}
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
key, value, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
if line != "" {
|
||||
return nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
value = nmValue(value)
|
||||
switch key {
|
||||
case "GENERAL.DEVICE":
|
||||
flush()
|
||||
name, kind, state, vendor, model, aps = value, "", "", "", "", make(map[string]map[string]string)
|
||||
case "GENERAL.TYPE":
|
||||
kind = value
|
||||
case "GENERAL.VENDOR":
|
||||
vendor = value
|
||||
case "GENERAL.PRODUCT":
|
||||
model = value
|
||||
case "GENERAL.STATE":
|
||||
state, _, _ = strings.Cut(value, " ")
|
||||
default:
|
||||
if strings.HasPrefix(key, "AP[") {
|
||||
id, field, valid := strings.Cut(key, "].")
|
||||
if valid && (field == "IN-USE" || field == "SSID" || field == "SIGNAL") {
|
||||
if aps[id] == nil {
|
||||
aps[id] = make(map[string]string)
|
||||
}
|
||||
aps[id][field] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return rows
|
||||
}
|
||||
|
||||
func annotateNetworks(root string, networks []Network, rows map[string]networkObservation) {
|
||||
for i := range networks {
|
||||
n := &networks[i]
|
||||
path := filepath.Join(root, "sys/class/net", n.Name)
|
||||
n.Kind = "unknown"
|
||||
if _, err := os.Stat(filepath.Join(path, "wireless")); err == nil {
|
||||
n.Kind = "wifi"
|
||||
} else if kind, err := os.ReadFile(filepath.Join(path, "type")); err == nil {
|
||||
if _, err := os.Stat(filepath.Join(path, "device")); err == nil && strings.TrimSpace(string(kind)) == "1" {
|
||||
n.Kind = "ethernet"
|
||||
} else {
|
||||
n.Kind = "virtual"
|
||||
}
|
||||
}
|
||||
if n.Kind == "wifi" || n.Kind == "ethernet" {
|
||||
hardware := NetworkHardware{Bus: networkBus(path)}
|
||||
if row, ok := rows[n.Name]; ok {
|
||||
n.Connection = &row.NetworkConnection
|
||||
hardware.Vendor, hardware.Model = row.Hardware.Vendor, row.Hardware.Model
|
||||
}
|
||||
if hardware != (NetworkHardware{}) {
|
||||
n.Hardware = &hardware
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNetworkConnectionsOnlyExposeAssociatedSSID(t *testing.T) {
|
||||
rows := parseNetworkConnections(`GENERAL.DEVICE:wlan0
|
||||
GENERAL.TYPE:wifi
|
||||
GENERAL.STATE:100 (connected)
|
||||
AP[1].IN-USE:
|
||||
AP[2].IN-USE:*
|
||||
AP[1].SSID:unrelated-neighbour
|
||||
AP[2].SSID:Lab\: one\\two
|
||||
AP[1].SIGNAL:100
|
||||
AP[2].SIGNAL:0
|
||||
|
||||
GENERAL.DEVICE:wlan1
|
||||
GENERAL.TYPE:wifi
|
||||
GENERAL.STATE:30 (disconnected)
|
||||
AP[1].IN-USE:*
|
||||
AP[1].SSID:stale-association
|
||||
AP[1].SIGNAL:70
|
||||
|
||||
GENERAL.DEVICE:eth0
|
||||
GENERAL.TYPE:ethernet
|
||||
GENERAL.STATE:20 (unavailable)
|
||||
|
||||
GENERAL.DEVICE:wt0
|
||||
GENERAL.TYPE:wireguard
|
||||
GENERAL.STATE:100 (connected)
|
||||
`)
|
||||
row := rows["wlan0"]
|
||||
if len(rows) != 3 || row.State != "connected" || row.SSID != `Lab: one\two` || row.SignalPercent == nil || *row.SignalPercent != 0 {
|
||||
t.Fatal(rows)
|
||||
}
|
||||
if rows["wlan1"].SSID != "" || rows["wlan1"].SignalPercent != nil || rows["eth0"].State != "unavailable" {
|
||||
t.Fatal(rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkConnectionsUnknownAndAmbiguousAreNotInvented(t *testing.T) {
|
||||
for _, state := range []string{"", "200", "100"} {
|
||||
row := parseNetworkConnections("GENERAL.DEVICE:wlan0\nGENERAL.TYPE:wifi\nGENERAL.STATE:" + state + "\nAP[1].IN-USE:*\nAP[2].IN-USE:*\nAP[1].SSID:first\nAP[2].SSID:second\n")["wlan0"]
|
||||
if row.SSID != "" || row.SignalPercent != nil || (state != "100" && row.State != "unknown") {
|
||||
t.Fatal(row)
|
||||
}
|
||||
}
|
||||
row := parseNetworkConnections("GENERAL.DEVICE:wlan0\nGENERAL.TYPE:wifi\nGENERAL.STATE:100\nAP[1].IN-USE:*\nAP[1].SSID:" + strings.Repeat("x", 33) + "\nAP[1].SIGNAL:101")["wlan0"]
|
||||
if row.SSID != "" || row.SignalPercent != nil {
|
||||
t.Fatal(row)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkInventoryClassifiesPhysicalInterfacesWithoutNameHeuristics(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
for name, dirs := range map[string][]string{"radio": {"wireless", "device"}, "cable": {"device"}, "tunnel": {}} {
|
||||
base := filepath.Join(root, "sys/class/net", name)
|
||||
if err := os.MkdirAll(base, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, dir := range dirs {
|
||||
if err := os.MkdirAll(filepath.Join(base, dir), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(base, "type"), []byte("1\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rows := []Network{{Name: "radio"}, {Name: "cable"}, {Name: "tunnel"}, {Name: "missing"}}
|
||||
annotateNetworks(root, rows, map[string]networkObservation{"radio": {NetworkConnection: NetworkConnection{State: "connected", SSID: "test"}}, "tunnel": {NetworkConnection: NetworkConnection{State: "connected"}}})
|
||||
if rows[0].Kind != "wifi" || rows[0].Connection.SSID != "test" || rows[1].Kind != "ethernet" || rows[2].Kind != "virtual" || rows[2].Connection != nil || rows[3].Kind != "unknown" {
|
||||
t.Fatal(rows)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkInventoryCacheNeverWaitsForOSAndExpires(t *testing.T) {
|
||||
started, release := make(chan struct{}, 2), make(chan struct{})
|
||||
defer close(release)
|
||||
c := networkInventoryCache{collect: func() map[string]networkObservation { started <- struct{}{}; <-release; return nil }}
|
||||
now := time.Now()
|
||||
returned := make(chan struct{})
|
||||
go func() { c.snapshot(now); close(returned) }()
|
||||
select {
|
||||
case <-returned:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("snapshot blocked on OS")
|
||||
}
|
||||
<-started
|
||||
for range 10 {
|
||||
if c.snapshot(now) != nil {
|
||||
t.Fatal("invented initial data")
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-started:
|
||||
t.Fatal("parallel collector")
|
||||
default:
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.rows, c.checked = map[string]networkObservation{"wlan0": {NetworkConnection: NetworkConnection{State: "connected", SSID: "old"}}}, now
|
||||
c.mu.Unlock()
|
||||
if len(c.snapshot(now.Add(10*time.Second))) != 1 || c.snapshot(now.Add(16*time.Second)) != nil {
|
||||
t.Fatal("freshness bound")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkOutputBound(t *testing.T) {
|
||||
var b networkOutput
|
||||
if _, err := b.Write(make([]byte, 64*1024)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := b.Write([]byte{1}); err == nil || b.Len() != 64*1024 {
|
||||
t.Fatal("unbounded metadata")
|
||||
}
|
||||
var pipe networkOutput
|
||||
if _, err := io.Copy(&pipe, io.LimitReader(strings.NewReader(strings.Repeat("x", 65537)), 65537)); err == nil || pipe.Len() > 65536 {
|
||||
t.Fatal("reader optimization bypassed output bound")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user