mirror of https://github.com/jetkvm/kvm.git
Compare commits
6 Commits
c4ffb0f208
...
b2672e6326
| Author | SHA1 | Date |
|---|---|---|
|
|
b2672e6326 | |
|
|
1e5184284f | |
|
|
826e5155b2 | |
|
|
15484f889e | |
|
|
8957a65cae | |
|
|
19bc958689 |
|
|
@ -3,12 +3,11 @@ package lldp
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/google/gopacket"
|
"github.com/google/gopacket"
|
||||||
"github.com/google/gopacket/afpacket"
|
"github.com/google/gopacket/afpacket"
|
||||||
"github.com/jellydator/ttlcache/v3"
|
|
||||||
"github.com/jetkvm/kvm/internal/logging"
|
"github.com/jetkvm/kvm/internal/logging"
|
||||||
"github.com/rs/zerolog"
|
"github.com/rs/zerolog"
|
||||||
)
|
)
|
||||||
|
|
@ -30,7 +29,8 @@ type LLDP struct {
|
||||||
advertiseOptions *AdvertiseOptions
|
advertiseOptions *AdvertiseOptions
|
||||||
onChange func(neighbors []Neighbor)
|
onChange func(neighbors []Neighbor)
|
||||||
|
|
||||||
neighbors *ttlcache.Cache[neighborCacheKey, Neighbor]
|
neighbors map[neighborCacheKey]Neighbor
|
||||||
|
neighborsMu sync.RWMutex
|
||||||
|
|
||||||
// State tracking
|
// State tracking
|
||||||
txRunning bool
|
txRunning bool
|
||||||
|
|
@ -47,6 +47,8 @@ type AdvertiseOptions struct {
|
||||||
SysName string
|
SysName string
|
||||||
SysDescription string
|
SysDescription string
|
||||||
PortDescription string
|
PortDescription string
|
||||||
|
IPv4Address *net.IP
|
||||||
|
IPv6Address *net.IP
|
||||||
SysCapabilities []string
|
SysCapabilities []string
|
||||||
EnabledCapabilities []string
|
EnabledCapabilities []string
|
||||||
}
|
}
|
||||||
|
|
@ -76,14 +78,12 @@ func NewLLDP(opts *Options) *LLDP {
|
||||||
enableTx: opts.EnableTx,
|
enableTx: opts.EnableTx,
|
||||||
rxWaitGroup: &sync.WaitGroup{},
|
rxWaitGroup: &sync.WaitGroup{},
|
||||||
l: opts.Logger,
|
l: opts.Logger,
|
||||||
neighbors: ttlcache.New(ttlcache.WithTTL[neighborCacheKey, Neighbor](1 * time.Hour)),
|
neighbors: make(map[neighborCacheKey]Neighbor),
|
||||||
onChange: opts.OnChange,
|
onChange: opts.OnChange,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *LLDP) Start() error {
|
func (l *LLDP) Start() error {
|
||||||
go l.neighbors.Start()
|
|
||||||
|
|
||||||
if l.enableRx {
|
if l.enableRx {
|
||||||
if err := l.startRx(); err != nil {
|
if err := l.startRx(); err != nil {
|
||||||
return fmt.Errorf("failed to start RX: %w", err)
|
return fmt.Errorf("failed to start RX: %w", err)
|
||||||
|
|
@ -102,10 +102,10 @@ func (l *LLDP) Start() error {
|
||||||
|
|
||||||
// StartRx starts the LLDP receiver if not already running
|
// StartRx starts the LLDP receiver if not already running
|
||||||
func (l *LLDP) startRx() error {
|
func (l *LLDP) startRx() error {
|
||||||
l.mu.Lock()
|
l.mu.RLock()
|
||||||
running := l.rxRunning
|
running := l.rxRunning
|
||||||
enabled := l.enableRx
|
enabled := l.enableRx
|
||||||
l.mu.Unlock()
|
l.mu.RUnlock()
|
||||||
|
|
||||||
if running || !enabled {
|
if running || !enabled {
|
||||||
return nil
|
return nil
|
||||||
|
|
|
||||||
|
|
@ -21,18 +21,40 @@ type Neighbor struct {
|
||||||
SystemName string `json:"system_name"`
|
SystemName string `json:"system_name"`
|
||||||
SystemDescription string `json:"system_description"`
|
SystemDescription string `json:"system_description"`
|
||||||
TTL uint16 `json:"ttl"`
|
TTL uint16 `json:"ttl"`
|
||||||
ManagementAddress *ManagementAddress `json:"management_address,omitempty"`
|
ManagementAddresses []ManagementAddress `json:"management_addresses"`
|
||||||
Capabilities []string `json:"capabilities"`
|
Capabilities []string `json:"capabilities"`
|
||||||
Values map[string]string `json:"values"`
|
Values map[string]string `json:"values"`
|
||||||
|
cacheTTL time.Time
|
||||||
|
cacheKey neighborCacheKey
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
NeighborSourceLLDP uint8 = 0x1
|
||||||
|
NeighborSourceCDP uint8 = 0x2
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
NeighborSourceMap = map[uint8]string{
|
||||||
|
NeighborSourceLLDP: "lldp",
|
||||||
|
NeighborSourceCDP: "cdp",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
type neighborCacheKey struct {
|
type neighborCacheKey struct {
|
||||||
mac string
|
Mac string
|
||||||
source string
|
Source uint8
|
||||||
}
|
}
|
||||||
|
|
||||||
func (n *Neighbor) cacheKey() neighborCacheKey {
|
func newNeighbor(mac string, source uint8) *Neighbor {
|
||||||
return neighborCacheKey{mac: n.Mac, source: n.Source}
|
return &Neighbor{
|
||||||
|
Mac: mac,
|
||||||
|
Source: NeighborSourceMap[source],
|
||||||
|
Values: make(map[string]string),
|
||||||
|
cacheKey: neighborCacheKey{
|
||||||
|
Mac: mac,
|
||||||
|
Source: source,
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *LLDP) addNeighbor(neighbor *Neighbor, ttl time.Duration) {
|
func (l *LLDP) addNeighbor(neighbor *Neighbor, ttl time.Duration) {
|
||||||
|
|
@ -42,19 +64,18 @@ func (l *LLDP) addNeighbor(neighbor *Neighbor, ttl time.Duration) {
|
||||||
Interface("neighbor", neighbor).
|
Interface("neighbor", neighbor).
|
||||||
Logger()
|
Logger()
|
||||||
|
|
||||||
key := neighbor.cacheKey()
|
l.neighborsMu.RLock()
|
||||||
|
|
||||||
currentNeighbor := l.neighbors.Get(key)
|
_, ok := l.neighbors[neighbor.cacheKey]
|
||||||
if currentNeighbor != nil {
|
if ok {
|
||||||
currentSource := currentNeighbor.Value().Source
|
logger.Trace().Msg("neighbor already exists, updating it")
|
||||||
if currentSource == "lldp" && neighbor.Source != "lldp" {
|
|
||||||
logger.Info().Msg("skip updating neighbor, as LLDP has higher priority")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Trace().Msg("adding neighbor")
|
logger.Trace().Msg("adding neighbor")
|
||||||
l.neighbors.Set(key, *neighbor, ttl)
|
neighbor.cacheTTL = time.Now().Add(ttl)
|
||||||
|
l.neighbors[neighbor.cacheKey] = *neighbor
|
||||||
|
|
||||||
|
l.neighborsMu.RUnlock()
|
||||||
|
|
||||||
l.onChange(l.GetNeighbors())
|
l.onChange(l.GetNeighbors())
|
||||||
}
|
}
|
||||||
|
|
@ -66,17 +87,33 @@ func (l *LLDP) deleteNeighbor(neighbor *Neighbor) {
|
||||||
Logger()
|
Logger()
|
||||||
|
|
||||||
logger.Info().Msg("deleting neighbor")
|
logger.Info().Msg("deleting neighbor")
|
||||||
l.neighbors.Delete(neighbor.cacheKey())
|
|
||||||
|
l.neighborsMu.Lock()
|
||||||
|
delete(l.neighbors, neighbor.cacheKey)
|
||||||
|
l.neighborsMu.Unlock()
|
||||||
|
|
||||||
l.onChange(l.GetNeighbors())
|
l.onChange(l.GetNeighbors())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *LLDP) GetNeighbors() []Neighbor {
|
func (l *LLDP) flushNeighbors() {
|
||||||
items := l.neighbors.Items()
|
l.neighborsMu.Lock()
|
||||||
neighbors := make([]Neighbor, 0, len(items))
|
defer l.neighborsMu.Unlock()
|
||||||
|
|
||||||
for _, item := range items {
|
l.neighbors = make(map[neighborCacheKey]Neighbor)
|
||||||
neighbors = append(neighbors, item.Value())
|
}
|
||||||
|
|
||||||
|
func (l *LLDP) GetNeighbors() []Neighbor {
|
||||||
|
l.neighborsMu.Lock()
|
||||||
|
defer l.neighborsMu.Unlock()
|
||||||
|
|
||||||
|
neighbors := make([]Neighbor, 0)
|
||||||
|
|
||||||
|
for key, neighbor := range l.neighbors {
|
||||||
|
if time.Now().After(neighbor.cacheTTL) {
|
||||||
|
delete(l.neighbors, key)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
neighbors = append(neighbors, neighbor)
|
||||||
}
|
}
|
||||||
|
|
||||||
return neighbors
|
return neighbors
|
||||||
|
|
|
||||||
|
|
@ -88,6 +88,11 @@ func (l *LLDP) setUpCapture() error {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *LLDP) doCapture(logger *zerolog.Logger) {
|
func (l *LLDP) doCapture(logger *zerolog.Logger) {
|
||||||
|
if l.pktSourceRx == nil || l.rxCtx == nil {
|
||||||
|
logger.Error().Msg("packet source or RX context not initialized")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
l.rxWaitGroup.Add(1)
|
l.rxWaitGroup.Add(1)
|
||||||
defer l.rxWaitGroup.Done()
|
defer l.rxWaitGroup.Done()
|
||||||
|
|
||||||
|
|
@ -237,11 +242,7 @@ func capabilitiesToString(capabilities layers.LLDPCapabilities) []string {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *LLDP) handlePacketLLDP(mac string, raw *layers.LinkLayerDiscovery, info *layers.LinkLayerDiscoveryInfo) error {
|
func (l *LLDP) handlePacketLLDP(mac string, raw *layers.LinkLayerDiscovery, info *layers.LinkLayerDiscoveryInfo) error {
|
||||||
n := &Neighbor{
|
n := newNeighbor(mac, NeighborSourceLLDP)
|
||||||
Values: make(map[string]string),
|
|
||||||
Source: "lldp",
|
|
||||||
Mac: mac,
|
|
||||||
}
|
|
||||||
|
|
||||||
ttl := lldpDefaultTTL
|
ttl := lldpDefaultTTL
|
||||||
|
|
||||||
|
|
@ -263,12 +264,12 @@ func (l *LLDP) handlePacketLLDP(mac string, raw *layers.LinkLayerDiscovery, info
|
||||||
n.SystemDescription = info.SysDescription
|
n.SystemDescription = info.SysDescription
|
||||||
n.Values["system_description"] = n.SystemDescription
|
n.Values["system_description"] = n.SystemDescription
|
||||||
case layers.LLDPTLVMgmtAddress:
|
case layers.LLDPTLVMgmtAddress:
|
||||||
n.ManagementAddress = &ManagementAddress{
|
mgmtAddress := parseTlvMgmtAddress(v)
|
||||||
AddressFamily: info.MgmtAddress.Subtype.String(),
|
if mgmtAddress != nil {
|
||||||
Address: net.IP(info.MgmtAddress.Address).String(),
|
n.ManagementAddresses = append(
|
||||||
InterfaceSubtype: info.MgmtAddress.InterfaceSubtype.String(),
|
n.ManagementAddresses,
|
||||||
InterfaceNumber: info.MgmtAddress.InterfaceNumber,
|
lldpMgmtAddressToSerializable(mgmtAddress),
|
||||||
OID: info.MgmtAddress.OID,
|
)
|
||||||
}
|
}
|
||||||
case layers.LLDPTLVSysCapabilities:
|
case layers.LLDPTLVSysCapabilities:
|
||||||
n.Capabilities = capabilitiesToString(info.SysCapabilities.EnabledCap)
|
n.Capabilities = capabilitiesToString(info.SysCapabilities.EnabledCap)
|
||||||
|
|
@ -297,11 +298,7 @@ func (l *LLDP) handlePacketLLDP(mac string, raw *layers.LinkLayerDiscovery, info
|
||||||
|
|
||||||
func (l *LLDP) handlePacketCDP(mac string, raw *layers.CiscoDiscovery, info *layers.CiscoDiscoveryInfo) error {
|
func (l *LLDP) handlePacketCDP(mac string, raw *layers.CiscoDiscovery, info *layers.CiscoDiscoveryInfo) error {
|
||||||
// TODO: implement full CDP parsing
|
// TODO: implement full CDP parsing
|
||||||
n := &Neighbor{
|
n := newNeighbor(mac, NeighborSourceCDP)
|
||||||
Values: make(map[string]string),
|
|
||||||
Source: "cdp",
|
|
||||||
Mac: mac,
|
|
||||||
}
|
|
||||||
|
|
||||||
ttl := cdpDefaultTTL
|
ttl := cdpDefaultTTL
|
||||||
|
|
||||||
|
|
@ -315,27 +312,18 @@ func (l *LLDP) handlePacketCDP(mac string, raw *layers.CiscoDiscovery, info *lay
|
||||||
ttl = time.Duration(n.TTL) * time.Second
|
ttl = time.Duration(n.TTL) * time.Second
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(info.MgmtAddresses) > 0 {
|
for _, addr := range info.MgmtAddresses {
|
||||||
ip := info.MgmtAddresses[0]
|
addrFamily := "ipv4"
|
||||||
ipFamily := "ipv4"
|
if addr.To4() == nil {
|
||||||
if ip.To4() == nil {
|
addrFamily = "ipv6"
|
||||||
ipFamily = "ipv6"
|
|
||||||
}
|
}
|
||||||
|
n.ManagementAddresses = append(n.ManagementAddresses, ManagementAddress{
|
||||||
l.l.Info().
|
AddressFamily: addrFamily,
|
||||||
Str("ip", ip.String()).
|
Address: addr.String(),
|
||||||
Str("ip_family", ipFamily).
|
|
||||||
Interface("ip", ip).
|
|
||||||
Interface("info", info).
|
|
||||||
Msg("parsed IP address")
|
|
||||||
|
|
||||||
n.ManagementAddress = &ManagementAddress{
|
|
||||||
AddressFamily: ipFamily,
|
|
||||||
Address: ip.String(),
|
|
||||||
InterfaceSubtype: "if_name",
|
InterfaceSubtype: "if_name",
|
||||||
InterfaceNumber: 0,
|
InterfaceNumber: 0,
|
||||||
OID: "",
|
OID: "",
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
l.addNeighbor(n, ttl)
|
l.addNeighbor(n, ttl)
|
||||||
|
|
@ -372,7 +360,7 @@ func (l *LLDP) stopCapture() error {
|
||||||
// write an empty packet to the TPacketRx to interrupt the blocking read
|
// write an empty packet to the TPacketRx to interrupt the blocking read
|
||||||
// it's a shitty workaround until https://github.com/google/gopacket/pull/777 is merged,
|
// it's a shitty workaround until https://github.com/google/gopacket/pull/777 is merged,
|
||||||
// or we have a better solution, see https://github.com/google/gopacket/issues/1064
|
// or we have a better solution, see https://github.com/google/gopacket/issues/1064
|
||||||
l.tPacketRx.WritePacketData([]byte{})
|
_ = l.tPacketRx.WritePacketData([]byte{})
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// wait for the goroutine to finish
|
// wait for the goroutine to finish
|
||||||
|
|
@ -402,7 +390,7 @@ func (l *LLDP) stopRx() error {
|
||||||
}
|
}
|
||||||
|
|
||||||
// clean up the neighbors table
|
// clean up the neighbors table
|
||||||
l.neighbors.DeleteAll()
|
l.flushNeighbors()
|
||||||
l.onChange([]Neighbor{})
|
l.onChange([]Neighbor{})
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,131 @@
|
||||||
|
package lldp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/google/gopacket/layers"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
capabilityMap = map[string]uint16{
|
||||||
|
"other": layers.LLDPCapsOther,
|
||||||
|
"repeater": layers.LLDPCapsRepeater,
|
||||||
|
"bridge": layers.LLDPCapsBridge,
|
||||||
|
"wlanap": layers.LLDPCapsWLANAP,
|
||||||
|
"router": layers.LLDPCapsRouter,
|
||||||
|
"phone": layers.LLDPCapsPhone,
|
||||||
|
"docsis": layers.LLDPCapsDocSis,
|
||||||
|
"station_only": layers.LLDPCapsStationOnly,
|
||||||
|
"cvlan": layers.LLDPCapsCVLAN,
|
||||||
|
"svlan": layers.LLDPCapsSVLAN,
|
||||||
|
"tmpr": layers.LLDPCapsTmpr,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
func tlvMgmtAddressToBytes(m *layers.LLDPMgmtAddress) []byte {
|
||||||
|
var b []byte
|
||||||
|
b = append(b, byte(len(m.Address))+1) // TLV Length
|
||||||
|
b = append(b, byte(m.Subtype)) // Address Subtype
|
||||||
|
b = append(b, m.Address...) // Address
|
||||||
|
b = append(b, byte(m.InterfaceSubtype)) // Interface Subtype
|
||||||
|
|
||||||
|
ifIndex := make([]byte, 4) // 4 bytes for the interface number
|
||||||
|
binary.BigEndian.PutUint32(ifIndex, m.InterfaceNumber)
|
||||||
|
b = append(b, ifIndex...)
|
||||||
|
|
||||||
|
b = append(b, 0) // OID type
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func tlvMgmtAddress(m *layers.LLDPMgmtAddress) layers.LinkLayerDiscoveryValue {
|
||||||
|
return layers.LinkLayerDiscoveryValue{
|
||||||
|
Type: layers.LLDPTLVMgmtAddress,
|
||||||
|
Value: tlvMgmtAddressToBytes(m),
|
||||||
|
Length: uint16(len(tlvMgmtAddressToBytes(m))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// if err := checkLLDPTLVLen(v, 9); err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// mlen := v.Value[0]
|
||||||
|
// if err := checkLLDPTLVLen(v, int(mlen+7)); err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// info.MgmtAddress.Subtype = IANAAddressFamily(v.Value[1])
|
||||||
|
// info.MgmtAddress.Address = v.Value[2 : mlen+1]
|
||||||
|
// info.MgmtAddress.InterfaceSubtype = LLDPInterfaceSubtype(v.Value[mlen+1])
|
||||||
|
// info.MgmtAddress.InterfaceNumber = binary.BigEndian.Uint32(v.Value[mlen+2 : mlen+6])
|
||||||
|
// olen := v.Value[mlen+6]
|
||||||
|
// if err := checkLLDPTLVLen(v, int(mlen+7+olen)); err != nil {
|
||||||
|
// return err
|
||||||
|
// }
|
||||||
|
// info.MgmtAddress.OID = string(v.Value[mlen+7 : mlen+7+olen])
|
||||||
|
|
||||||
|
func checkLLDPTLVLen(v layers.LinkLayerDiscoveryValue, l int) (err error) {
|
||||||
|
if len(v.Value) < l {
|
||||||
|
err = fmt.Errorf("invalid TLV %v length %d (wanted minimum %d)", v.Type, len(v.Value), l)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseTlvMgmtAddress parses the Management Address TLV and returns the Management Address
|
||||||
|
// structure.
|
||||||
|
// we don't parse the OID here, as it's not needed for the neighbor cache
|
||||||
|
func parseTlvMgmtAddress(v layers.LinkLayerDiscoveryValue) *layers.LLDPMgmtAddress {
|
||||||
|
if err := checkLLDPTLVLen(v, 9); err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
mlen := v.Value[0]
|
||||||
|
if err := checkLLDPTLVLen(v, int(mlen+7)); err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return &layers.LLDPMgmtAddress{
|
||||||
|
Subtype: layers.IANAAddressFamily(v.Value[1]),
|
||||||
|
Address: v.Value[2 : mlen+1],
|
||||||
|
InterfaceSubtype: layers.LLDPInterfaceSubtype(v.Value[mlen+1]),
|
||||||
|
InterfaceNumber: binary.BigEndian.Uint32(v.Value[mlen+2 : mlen+6]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func lldpMgmtAddressToSerializable(m *layers.LLDPMgmtAddress) ManagementAddress {
|
||||||
|
var addrString string
|
||||||
|
switch m.Subtype {
|
||||||
|
case layers.IANAAddressFamilyIPV4:
|
||||||
|
addrString = net.IP(m.Address).String()
|
||||||
|
case layers.IANAAddressFamilyIPV6:
|
||||||
|
addrString = net.IP(m.Address).String()
|
||||||
|
default:
|
||||||
|
addrString = string(m.Address)
|
||||||
|
}
|
||||||
|
|
||||||
|
return ManagementAddress{
|
||||||
|
AddressFamily: m.Subtype.String(),
|
||||||
|
Address: addrString,
|
||||||
|
InterfaceSubtype: m.InterfaceSubtype.String(),
|
||||||
|
InterfaceNumber: m.InterfaceNumber,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func tlvStringValue(tlvType layers.LLDPTLVType, value string) layers.LinkLayerDiscoveryValue {
|
||||||
|
return layers.LinkLayerDiscoveryValue{
|
||||||
|
Type: tlvType,
|
||||||
|
Value: []byte(value),
|
||||||
|
Length: uint16(len(value)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func toLLDPCapabilitiesBytes(capabilities []string) uint16 {
|
||||||
|
r := uint16(0)
|
||||||
|
for _, capability := range capabilities {
|
||||||
|
mask, ok := capabilityMap[capability]
|
||||||
|
if ok {
|
||||||
|
r |= mask
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
@ -17,57 +17,6 @@ var (
|
||||||
lldpEtherType = layers.EthernetTypeLinkLayerDiscovery
|
lldpEtherType = layers.EthernetTypeLinkLayerDiscovery
|
||||||
)
|
)
|
||||||
|
|
||||||
// func encodeMandatoryTLV(subType byte, id []byte) []byte {
|
|
||||||
// // 1 byte: subtype
|
|
||||||
// // N bytes: ID
|
|
||||||
// b := make([]byte, 1+len(id))
|
|
||||||
// b[0] = byte(subtype)
|
|
||||||
// copy(b[1:], id)
|
|
||||||
|
|
||||||
// return b
|
|
||||||
// }
|
|
||||||
|
|
||||||
// func (l *LLDP) createLLDPPayload() ([]byte, error) {
|
|
||||||
// tlv := &layers.LinkLayerDiscoveryValue{
|
|
||||||
// Type: layers.LLDPTLVChassisID,
|
|
||||||
|
|
||||||
// }
|
|
||||||
|
|
||||||
func tlvStringValue(tlvType layers.LLDPTLVType, value string) layers.LinkLayerDiscoveryValue {
|
|
||||||
return layers.LinkLayerDiscoveryValue{
|
|
||||||
Type: tlvType,
|
|
||||||
Value: []byte(value),
|
|
||||||
Length: uint16(len(value)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
capabilityMap = map[string]uint16{
|
|
||||||
"other": layers.LLDPCapsOther,
|
|
||||||
"repeater": layers.LLDPCapsRepeater,
|
|
||||||
"bridge": layers.LLDPCapsBridge,
|
|
||||||
"wlanap": layers.LLDPCapsWLANAP,
|
|
||||||
"router": layers.LLDPCapsRouter,
|
|
||||||
"phone": layers.LLDPCapsPhone,
|
|
||||||
"docsis": layers.LLDPCapsDocSis,
|
|
||||||
"station_only": layers.LLDPCapsStationOnly,
|
|
||||||
"cvlan": layers.LLDPCapsCVLAN,
|
|
||||||
"svlan": layers.LLDPCapsSVLAN,
|
|
||||||
"tmpr": layers.LLDPCapsTmpr,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
func toLLDPCapabilitiesBytes(capabilities []string) uint16 {
|
|
||||||
r := uint16(0)
|
|
||||||
for _, capability := range capabilities {
|
|
||||||
mask, ok := capabilityMap[capability]
|
|
||||||
if ok {
|
|
||||||
r |= mask
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *LLDP) toPayloadValues() []layers.LinkLayerDiscoveryValue {
|
func (l *LLDP) toPayloadValues() []layers.LinkLayerDiscoveryValue {
|
||||||
// See also: layers.LinkLayerDiscovery.SerializeTo()
|
// See also: layers.LinkLayerDiscovery.SerializeTo()
|
||||||
r := []layers.LinkLayerDiscoveryValue{}
|
r := []layers.LinkLayerDiscoveryValue{}
|
||||||
|
|
@ -88,6 +37,24 @@ func (l *LLDP) toPayloadValues() []layers.LinkLayerDiscoveryValue {
|
||||||
r = append(r, tlvStringValue(layers.LLDPTLVSysDescription, opts.SysDescription))
|
r = append(r, tlvStringValue(layers.LLDPTLVSysDescription, opts.SysDescription))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if opts.IPv4Address != nil {
|
||||||
|
r = append(r, tlvMgmtAddress(&layers.LLDPMgmtAddress{
|
||||||
|
Subtype: layers.IANAAddressFamilyIPV4,
|
||||||
|
Address: opts.IPv4Address.To4(),
|
||||||
|
InterfaceSubtype: layers.LLDPInterfaceSubtypeifIndex,
|
||||||
|
InterfaceNumber: 0,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.IPv6Address != nil {
|
||||||
|
r = append(r, tlvMgmtAddress(&layers.LLDPMgmtAddress{
|
||||||
|
Subtype: layers.IANAAddressFamilyIPV6,
|
||||||
|
Address: opts.IPv6Address.To16(),
|
||||||
|
InterfaceSubtype: layers.LLDPInterfaceSubtypeifIndex,
|
||||||
|
InterfaceNumber: 0,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
if len(opts.SysCapabilities) > 0 {
|
if len(opts.SysCapabilities) > 0 {
|
||||||
value := make([]byte, 4)
|
value := make([]byte, 4)
|
||||||
binary.BigEndian.PutUint16(value[0:2], toLLDPCapabilitiesBytes(opts.SysCapabilities))
|
binary.BigEndian.PutUint16(value[0:2], toLLDPCapabilitiesBytes(opts.SysCapabilities))
|
||||||
|
|
@ -227,7 +194,9 @@ func (l *LLDP) startTx() error {
|
||||||
cancel()
|
cancel()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
l.mu.Lock()
|
||||||
l.txCtx, l.txCancel = context.WithCancel(context.Background())
|
l.txCtx, l.txCancel = context.WithCancel(context.Background())
|
||||||
|
l.mu.Unlock()
|
||||||
|
|
||||||
if err := l.setUpTx(); err != nil {
|
if err := l.setUpTx(); err != nil {
|
||||||
return fmt.Errorf("failed to set up TX: %w", err)
|
return fmt.Errorf("failed to set up TX: %w", err)
|
||||||
|
|
|
||||||
50
network.go
50
network.go
|
|
@ -3,6 +3,7 @@ package kvm
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
|
||||||
"github.com/jetkvm/kvm/internal/confparser"
|
"github.com/jetkvm/kvm/internal/confparser"
|
||||||
|
|
@ -119,6 +120,11 @@ func networkStateChanged(_ string, state types.InterfaceState) {
|
||||||
triggerTimeSyncOnNetworkStateChange()
|
triggerTimeSyncOnNetworkStateChange()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// update the LLDP advertise options
|
||||||
|
if lldpService != nil {
|
||||||
|
_ = lldpService.SetAdvertiseOptions(getLLDPAdvertiseOptions(&state))
|
||||||
|
}
|
||||||
|
|
||||||
// always restart mDNS when the network state changes
|
// always restart mDNS when the network state changes
|
||||||
if mDNS != nil {
|
if mDNS != nil {
|
||||||
restartMdns()
|
restartMdns()
|
||||||
|
|
@ -144,13 +150,29 @@ func validateNetworkConfig() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getLLDPAdvertiseOptions(nm *nmlite.NetworkManager) *lldp.AdvertiseOptions {
|
func getLLDPAdvertiseOptions(state *types.InterfaceState) *lldp.AdvertiseOptions {
|
||||||
return &lldp.AdvertiseOptions{
|
a := &lldp.AdvertiseOptions{
|
||||||
SysName: nm.Hostname(),
|
|
||||||
SysDescription: toLLDPSysDescription(),
|
SysDescription: toLLDPSysDescription(),
|
||||||
SysCapabilities: []string{"other", "router", "wlanap"},
|
SysCapabilities: []string{"other", "router", "wlanap"},
|
||||||
EnabledCapabilities: []string{"other"},
|
EnabledCapabilities: []string{"other"},
|
||||||
}
|
}
|
||||||
|
if state == nil {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
a.SysName = state.Hostname
|
||||||
|
ip4String := state.IPv4Address
|
||||||
|
if ip4String != "" {
|
||||||
|
ip4 := net.ParseIP(ip4String)
|
||||||
|
a.IPv4Address = &ip4
|
||||||
|
}
|
||||||
|
ip6String := state.IPv6Address
|
||||||
|
if ip6String != "" {
|
||||||
|
ip6 := net.ParseIP(ip6String)
|
||||||
|
a.IPv6Address = &ip6
|
||||||
|
}
|
||||||
|
networkLogger.Info().Interface("advertiseOptions", a).Msg("LLDP advertise options")
|
||||||
|
return a
|
||||||
}
|
}
|
||||||
|
|
||||||
func initNetwork() error {
|
func initNetwork() error {
|
||||||
|
|
@ -172,7 +194,12 @@ func initNetwork() error {
|
||||||
|
|
||||||
networkManager = nm
|
networkManager = nm
|
||||||
|
|
||||||
advertiseOptions := getLLDPAdvertiseOptions(nm)
|
ifState, err := nm.GetInterfaceState(NetIfName)
|
||||||
|
if err != nil {
|
||||||
|
networkLogger.Warn().Err(err).Msg("failed to get interface state, LLDP will use the default options")
|
||||||
|
}
|
||||||
|
|
||||||
|
advertiseOptions := getLLDPAdvertiseOptions(ifState)
|
||||||
lldpService = lldp.NewLLDP(&lldp.Options{
|
lldpService = lldp.NewLLDP(&lldp.Options{
|
||||||
InterfaceName: NetIfName,
|
InterfaceName: NetIfName,
|
||||||
EnableRx: nc.ShouldEnableLLDPReceive(),
|
EnableRx: nc.ShouldEnableLLDPReceive(),
|
||||||
|
|
@ -200,7 +227,7 @@ func toLLDPSysDescription() string {
|
||||||
return fmt.Sprintf("JetKVM (app: %s, system: %s)", appVersion.String(), systemVersion.String())
|
return fmt.Sprintf("JetKVM (app: %s, system: %s)", appVersion.String(), systemVersion.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateLLDPOptions(nc *types.NetworkConfig) {
|
func updateLLDPOptions(nc *types.NetworkConfig, ifState *types.InterfaceState) {
|
||||||
if lldpService == nil {
|
if lldpService == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
@ -209,7 +236,16 @@ func updateLLDPOptions(nc *types.NetworkConfig) {
|
||||||
networkLogger.Error().Err(err).Msg("failed to set LLDP RX and TX")
|
networkLogger.Error().Err(err).Msg("failed to set LLDP RX and TX")
|
||||||
}
|
}
|
||||||
|
|
||||||
advertiseOptions := getLLDPAdvertiseOptions(networkManager)
|
if ifState == nil {
|
||||||
|
newIfState, err := networkManager.GetInterfaceState(NetIfName)
|
||||||
|
if err != nil {
|
||||||
|
networkLogger.Warn().Err(err).Msg("failed to get interface state, LLDP will use the default options")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ifState = newIfState
|
||||||
|
}
|
||||||
|
|
||||||
|
advertiseOptions := getLLDPAdvertiseOptions(ifState)
|
||||||
if err := lldpService.SetAdvertiseOptions(advertiseOptions); err != nil {
|
if err := lldpService.SetAdvertiseOptions(advertiseOptions); err != nil {
|
||||||
networkLogger.Error().Err(err).Msg("failed to set LLDP advertise options")
|
networkLogger.Error().Err(err).Msg("failed to set LLDP advertise options")
|
||||||
}
|
}
|
||||||
|
|
@ -343,7 +379,7 @@ func rpcSetNetworkSettings(settings RpcNetworkSettings) (*RpcNetworkSettings, er
|
||||||
config.NetworkConfig = newConfig
|
config.NetworkConfig = newConfig
|
||||||
|
|
||||||
// update the LLDP advertise options
|
// update the LLDP advertise options
|
||||||
updateLLDPOptions(newConfig)
|
updateLLDPOptions(newConfig, nil)
|
||||||
|
|
||||||
l.Debug().Msg("saving new config")
|
l.Debug().Msg("saving new config")
|
||||||
if err := SaveConfig(); err != nil {
|
if err := SaveConfig(); err != nil {
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,8 @@ export default function LLDPNeighborsCard({
|
||||||
<div className="space-y-3 pt-2">
|
<div className="space-y-3 pt-2">
|
||||||
{neighbors.map(neighbor => {
|
{neighbors.map(neighbor => {
|
||||||
const displayName = neighbor.system_name || neighbor.port_description || neighbor.mac;
|
const displayName = neighbor.system_name || neighbor.port_description || neighbor.mac;
|
||||||
return <div className="space-y-3" key={neighbor.mac}>
|
const key = `${neighbor.mac}-${neighbor.source}`;
|
||||||
|
return <div className="space-y-3" key={key}>
|
||||||
<h4 className="text-sm font-semibold font-mono">{displayName}</h4>
|
<h4 className="text-sm font-semibold font-mono">{displayName}</h4>
|
||||||
<div
|
<div
|
||||||
className="rounded-md rounded-l-none border border-slate-500/10 border-l-blue-700/50 bg-white p-4 pl-4 backdrop-blur-sm dark:bg-transparent"
|
className="rounded-md rounded-l-none border border-slate-500/10 border-l-blue-700/50 bg-white p-4 pl-4 backdrop-blur-sm dark:bg-transparent"
|
||||||
|
|
@ -64,8 +65,10 @@ export default function LLDPNeighborsCard({
|
||||||
<LLDPDataLine label="Port Description" value={neighbor.port_description} />
|
<LLDPDataLine label="Port Description" value={neighbor.port_description} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{neighbor.management_address && (
|
{neighbor.management_addresses && neighbor.management_addresses.length > 0 && (
|
||||||
<LLDPDataLine label="Management Address" value={neighbor.management_address.address} />
|
neighbor.management_addresses.map((address, index) => (
|
||||||
|
<LLDPDataLine label="Management Address" value={address.address} key={index} />
|
||||||
|
))
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{neighbor.mac && (
|
{neighbor.mac && (
|
||||||
|
|
|
||||||
|
|
@ -824,7 +824,7 @@ export interface LLDPNeighbor {
|
||||||
system_description: string;
|
system_description: string;
|
||||||
capabilities: string[];
|
capabilities: string[];
|
||||||
ttl: number | null;
|
ttl: number | null;
|
||||||
management_address: LLDPManagementAddress | null;
|
management_addresses: LLDPManagementAddress[];
|
||||||
values: Record<string, string>;
|
values: Record<string, string>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -169,7 +169,10 @@ export default function SettingsNetworkRoute() {
|
||||||
|
|
||||||
const { register, handleSubmit, watch, formState, reset } = formMethods;
|
const { register, handleSubmit, watch, formState, reset } = formMethods;
|
||||||
|
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
|
||||||
const onSubmit = useCallback(async (settings: NetworkSettings) => {
|
const onSubmit = useCallback(async (settings: NetworkSettings) => {
|
||||||
|
|
||||||
if (settings.ipv4_static?.address?.includes("/")) {
|
if (settings.ipv4_static?.address?.includes("/")) {
|
||||||
const parts = settings.ipv4_static.address.split("/");
|
const parts = settings.ipv4_static.address.split("/");
|
||||||
const cidrNotation = Number.parseInt(parts[1]);
|
const cidrNotation = Number.parseInt(parts[1]);
|
||||||
|
|
@ -180,6 +183,7 @@ export default function SettingsNetworkRoute() {
|
||||||
settings.ipv4_static.address = parts[0];
|
settings.ipv4_static.address = parts[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setIsSubmitting(true);
|
||||||
send("setNetworkSettings", { settings }, async (resp) => {
|
send("setNetworkSettings", { settings }, async (resp) => {
|
||||||
if ("error" in resp) {
|
if ("error" in resp) {
|
||||||
notifications.error(m.network_save_settings_failed({ error: resp.error.message || m.unknown_error() }));
|
notifications.error(m.network_save_settings_failed({ error: resp.error.message || m.unknown_error() }));
|
||||||
|
|
@ -197,10 +201,10 @@ export default function SettingsNetworkRoute() {
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to fetch network data:", error);
|
console.error("Failed to fetch network data:", error);
|
||||||
}
|
}
|
||||||
notifications.success(m.network_dhcp_lease_renew_success());
|
setIsSubmitting(false);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}, [fetchNetworkData, reset, send]);
|
}, [fetchNetworkData, reset, send, setIsSubmitting]);
|
||||||
|
|
||||||
const onSubmitGate = useCallback(async (data: FieldValues) => {
|
const onSubmitGate = useCallback(async (data: FieldValues) => {
|
||||||
const settings = prepareSettings(data);
|
const settings = prepareSettings(data);
|
||||||
|
|
@ -326,7 +330,7 @@ export default function SettingsNetworkRoute() {
|
||||||
size="SM"
|
size="SM"
|
||||||
theme="primary"
|
theme="primary"
|
||||||
disabled={!(formState.isDirty || formState.isSubmitting)}
|
disabled={!(formState.isDirty || formState.isSubmitting)}
|
||||||
loading={formState.isSubmitting}
|
loading={formState.isSubmitting || isSubmitting}
|
||||||
type="submit"
|
type="submit"
|
||||||
text={formState.isSubmitting ? m.saving() : m.network_save_settings()}
|
text={formState.isSubmitting ? m.saving() : m.network_save_settings()}
|
||||||
/>
|
/>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue