Documentation
¶
Overview ¶
Package mesh provides Hamachi-like mesh networking functionality.
Index ¶
- Constants
- Variables
- func DefaultPathCostFunc(latency time.Duration, hopCount int) int
- type BroadcastConfig
- type BroadcastHandler
- type BroadcastManager
- func (bm *BroadcastManager) AddGroupMember(groupID, peerID string)
- func (bm *BroadcastManager) Anycast(groupID string, payload []byte) error
- func (bm *BroadcastManager) Broadcast(payload []byte, ttl int) error
- func (bm *BroadcastManager) GetGroupMembers(groupID string) []string
- func (bm *BroadcastManager) GetGroups() []*MulticastGroup
- func (bm *BroadcastManager) HandleMessage(fromPeerID string, data []byte) error
- func (bm *BroadcastManager) IsGroupMember(groupID, peerID string) bool
- func (bm *BroadcastManager) JoinGroup(groupID, groupName string)
- func (bm *BroadcastManager) LeaveGroup(groupID string)
- func (bm *BroadcastManager) Multicast(groupID string, payload []byte, ttl int) error
- func (bm *BroadcastManager) RegisterHandler(broadcastType BroadcastType, handler BroadcastHandler)
- func (bm *BroadcastManager) RemoveGroupMember(groupID, peerID string)
- func (bm *BroadcastManager) SetSendFunc(sendFunc func(peerID string, data []byte) error)
- func (bm *BroadcastManager) Start() error
- func (bm *BroadcastManager) Stop() error
- type BroadcastMessage
- type BroadcastType
- type Config
- type ConnectionConfig
- type ConnectionType
- type DeviceConfig
- type DiscoveryClient
- func (c *DiscoveryClient) Events() <-chan PeerEvent
- func (c *DiscoveryClient) IsConnected() bool
- func (c *DiscoveryClient) ListPeers() ([]PeerInfo, error)
- func (c *DiscoveryClient) Start(ctx context.Context) error
- func (c *DiscoveryClient) Stop() error
- func (c *DiscoveryClient) UpdateEndpoints(endpoints []Endpoint) error
- type DiscoveryConfig
- type Endpoint
- type EthernetBroadcastHandler
- type ForwardingEntry
- type HelloAckMessage
- type HelloMessage
- type IPAllocator
- type Lease
- type LinkInfo
- type LinkStateUpdate
- type MeshNode
- func (n *MeshNode) GetConnectedPeers() []*Peer
- func (n *MeshNode) GetPeer(peerID string) (*Peer, bool)
- func (n *MeshNode) GetPeers() []*Peer
- func (n *MeshNode) GetRoutes() []*Route
- func (n *MeshNode) LocalIP() netip.Addr
- func (n *MeshNode) LocalPeerID() string
- func (n *MeshNode) Start(ctx context.Context) error
- func (n *MeshNode) Stats() NodeStats
- func (n *MeshNode) Status() NodeStatus
- func (n *MeshNode) Stop() error
- type MeshRouter
- func (r *MeshRouter) AddDirectRoute(peerID string, peerIP netip.Addr, latency time.Duration)
- func (r *MeshRouter) AddRoute(route *Route)
- func (r *MeshRouter) ExpireRoutes()
- func (r *MeshRouter) GetAllRoutes() []*Route
- func (r *MeshRouter) GetBestRoutes() []*Route
- func (r *MeshRouter) GetDirectPeers() []string
- func (r *MeshRouter) GetForwardingTable() []ForwardingEntry
- func (r *MeshRouter) GetNextHop(destPeerID string) string
- func (r *MeshRouter) GetNextHopByIP(ip netip.Addr) string
- func (r *MeshRouter) GetRoute(peerID string) *Route
- func (r *MeshRouter) GetRouteByIP(ip netip.Addr) *Route
- func (r *MeshRouter) GetStats() RouteTableStats
- func (r *MeshRouter) IsDirect(peerID string) bool
- func (r *MeshRouter) OnRouteChanged(callback func(*Route))
- func (r *MeshRouter) RemoveDirectRoute(peerID string)
- func (r *MeshRouter) UpdateLatency(peerID string, latency time.Duration)
- type MulticastGroup
- type NodeStats
- type NodeStatus
- type PathCostFunc
- type Peer
- func (p *Peer) AddBytesReceived(n int64)
- func (p *Peer) AddBytesSent(n int64)
- func (p *Peer) AddEndpoint(endpoint Endpoint)
- func (p *Peer) ClearEndpoints()
- func (p *Peer) Clone() *Peer
- func (p *Peer) GetEndpoints() []Endpoint
- func (p *Peer) GetMetadata(key string) (string, bool)
- func (p *Peer) IsConnected() bool
- func (p *Peer) IsReachable() bool
- func (p *Peer) RemoveEndpoint(address string, port uint16)
- func (p *Peer) SetConnectionType(connType ConnectionType)
- func (p *Peer) SetLatency(latency time.Duration)
- func (p *Peer) SetMetadata(key, value string) bool
- func (p *Peer) SetStatus(status PeerStatus)
- func (p *Peer) SetVirtualIP(ip netip.Addr)
- func (p *Peer) SetVirtualMAC(mac net.HardwareAddr)
- func (p *Peer) UpdateLastSeen()
- type PeerEvent
- type PeerInfo
- type PeerRegistry
- func (r *PeerRegistry) Add(peer *Peer)
- func (r *PeerRegistry) All() []*Peer
- func (r *PeerRegistry) Clear()
- func (r *PeerRegistry) Connected() []*Peer
- func (r *PeerRegistry) Count() int
- func (r *PeerRegistry) Get(id string) (*Peer, bool)
- func (r *PeerRegistry) GetByIP(ip netip.Addr) (*Peer, bool)
- func (r *PeerRegistry) GetByMAC(mac net.HardwareAddr) (*Peer, bool)
- func (r *PeerRegistry) Remove(id string)
- func (r *PeerRegistry) UpdatePeerIP(peer *Peer, newIP netip.Addr)
- func (r *PeerRegistry) UpdatePeerMAC(peer *Peer, newMAC net.HardwareAddr)
- type PeerStatus
- type PoolAllocator
- func (a *PoolAllocator) Allocate(peerID string) (netip.Addr, error)
- func (a *PoolAllocator) AllocateSpecific(peerID string, addr netip.Addr) error
- func (a *PoolAllocator) Available() int
- func (a *PoolAllocator) Expire() int
- func (a *PoolAllocator) GetAllLeases() []Lease
- func (a *PoolAllocator) GetIP(peerID string) (netip.Addr, bool)
- func (a *PoolAllocator) GetPeer(addr netip.Addr) (string, bool)
- func (a *PoolAllocator) Prefix() netip.Prefix
- func (a *PoolAllocator) Release(peerID string) error
- func (a *PoolAllocator) Renew(peerID string) error
- func (a *PoolAllocator) StartExpiryWorker(interval time.Duration, stopCh <-chan struct{})
- func (a *PoolAllocator) Used() int
- type PoolConfig
- type ProtocolConfig
- type ProtocolMessage
- type ProtocolMessageType
- type RegistrationRequest
- type RegistrationResponse
- type Route
- type RouteAnnouncement
- type RouteTableStats
- type RouteType
- type RouteWithdrawal
- type RouterConfig
- type RoutingProtocol
- func (p *RoutingProtocol) HandleMessage(fromPeerID string, data []byte) error
- func (p *RoutingProtocol) NotifyPeerConnected(peerID string, peerIP netip.Addr, latency time.Duration)
- func (p *RoutingProtocol) NotifyPeerDisconnected(peerID string)
- func (p *RoutingProtocol) SetSendFunc(sendFunc func(peerID string, msg []byte) error)
- func (p *RoutingProtocol) Start() error
- func (p *RoutingProtocol) Stop() error
- func (p *RoutingProtocol) WithdrawRoute(destPeerID string)
- type STUNConfig
- type SecurityConfig
- type TURNConfig
- type TURNServer
Constants ¶
const ( // MaxMetadataKeys is the maximum number of metadata keys per peer MaxMetadataKeys = 50 // MaxMetadataKeyLen is the maximum length of a metadata key MaxMetadataKeyLen = 64 // MaxMetadataValueLen is the maximum length of a metadata value MaxMetadataValueLen = 256 )
Peer metadata limits
const (
// MaxSeenMessages is the maximum number of seen message IDs to track
MaxSeenMessages = 10000
)
Broadcast limits
Variables ¶
var ( ErrDiscoveryNotConnected = errors.New("discovery: not connected to server") ErrDiscoveryFailed = errors.New("discovery: registration failed") ErrDiscoveryTimeout = errors.New("discovery: operation timed out") )
Common discovery errors.
var ( ErrNoAvailableAddress = errors.New("ipam: no available address in pool") ErrAddressInUse = errors.New("ipam: address already in use") ErrAddressOutOfRange = errors.New("ipam: address out of pool range") ErrPeerNotFound = errors.New("ipam: peer not found") ErrAddressReserved = errors.New("ipam: address is reserved") )
Common IPAM errors.
var ( ErrNodeNotStarted = errors.New("mesh: node not started") ErrNodeAlreadyRunning = errors.New("mesh: node already running") ErrNoPeerConnection = errors.New("mesh: no connection to peer") ErrDeviceNotConfigured = errors.New("mesh: device not configured") )
MeshNode errors.
Functions ¶
Types ¶
type BroadcastConfig ¶
type BroadcastConfig struct {
// SeenMsgsTTL is how long to remember seen messages.
SeenMsgsTTL time.Duration
// DefaultTTL is the default TTL for broadcasts.
DefaultTTL int
// CleanupInterval is the interval for cleaning up seen messages.
CleanupInterval time.Duration
}
BroadcastConfig contains broadcast manager configuration.
func DefaultBroadcastConfig ¶
func DefaultBroadcastConfig() BroadcastConfig
DefaultBroadcastConfig returns a default broadcast configuration.
type BroadcastHandler ¶
type BroadcastHandler func(msg *BroadcastMessage)
BroadcastHandler handles received broadcast messages.
type BroadcastManager ¶
type BroadcastManager struct {
// contains filtered or unexported fields
}
BroadcastManager manages broadcast and multicast messaging.
func NewBroadcastManager ¶
func NewBroadcastManager(localPeerID string, router *MeshRouter, config BroadcastConfig) *BroadcastManager
NewBroadcastManager creates a new broadcast manager.
func (*BroadcastManager) AddGroupMember ¶
func (bm *BroadcastManager) AddGroupMember(groupID, peerID string)
AddGroupMember adds a member to a group.
func (*BroadcastManager) Anycast ¶
func (bm *BroadcastManager) Anycast(groupID string, payload []byte) error
Anycast sends a message to the closest member of a group.
func (*BroadcastManager) Broadcast ¶
func (bm *BroadcastManager) Broadcast(payload []byte, ttl int) error
Broadcast sends a message to all peers in the mesh.
func (*BroadcastManager) GetGroupMembers ¶
func (bm *BroadcastManager) GetGroupMembers(groupID string) []string
GetGroupMembers returns members of a group.
func (*BroadcastManager) GetGroups ¶
func (bm *BroadcastManager) GetGroups() []*MulticastGroup
GetGroups returns all joined groups.
func (*BroadcastManager) HandleMessage ¶
func (bm *BroadcastManager) HandleMessage(fromPeerID string, data []byte) error
HandleMessage handles an incoming broadcast message.
func (*BroadcastManager) IsGroupMember ¶
func (bm *BroadcastManager) IsGroupMember(groupID, peerID string) bool
IsGroupMember checks if a peer is a member of a group.
func (*BroadcastManager) JoinGroup ¶
func (bm *BroadcastManager) JoinGroup(groupID, groupName string)
JoinGroup joins a multicast group.
func (*BroadcastManager) LeaveGroup ¶
func (bm *BroadcastManager) LeaveGroup(groupID string)
LeaveGroup leaves a multicast group.
func (*BroadcastManager) Multicast ¶
func (bm *BroadcastManager) Multicast(groupID string, payload []byte, ttl int) error
Multicast sends a message to all members of a group.
func (*BroadcastManager) RegisterHandler ¶
func (bm *BroadcastManager) RegisterHandler(broadcastType BroadcastType, handler BroadcastHandler)
RegisterHandler registers a handler for a broadcast type.
func (*BroadcastManager) RemoveGroupMember ¶
func (bm *BroadcastManager) RemoveGroupMember(groupID, peerID string)
RemoveGroupMember removes a member from a group.
func (*BroadcastManager) SetSendFunc ¶
func (bm *BroadcastManager) SetSendFunc(sendFunc func(peerID string, data []byte) error)
SetSendFunc sets the function used to send messages.
func (*BroadcastManager) Start ¶
func (bm *BroadcastManager) Start() error
Start starts the broadcast manager.
func (*BroadcastManager) Stop ¶
func (bm *BroadcastManager) Stop() error
Stop stops the broadcast manager.
type BroadcastMessage ¶
type BroadcastMessage struct {
// ID is a unique message identifier.
ID string `json:"id"`
// Type is the broadcast type.
Type BroadcastType `json:"type"`
// SrcPeerID is the source peer ID.
SrcPeerID string `json:"src_peer_id"`
// GroupID is the multicast group (for multicast/anycast).
GroupID string `json:"group_id,omitempty"`
// TTL is the time-to-live (hop count).
TTL int `json:"ttl"`
// Timestamp is when the message was created.
Timestamp time.Time `json:"timestamp"`
// Payload is the message data.
Payload []byte `json:"payload"`
}
BroadcastMessage represents a broadcast message.
type BroadcastType ¶
type BroadcastType int
BroadcastType represents the type of broadcast.
const ( // BroadcastTypeFlood sends to all peers. BroadcastTypeFlood BroadcastType = iota // BroadcastTypeMulticast sends to a specific group. BroadcastTypeMulticast // BroadcastTypeAnycast sends to the closest peer in a group. BroadcastTypeAnycast )
func (BroadcastType) String ¶
func (t BroadcastType) String() string
String returns a human-readable string for the broadcast type.
type Config ¶
type Config struct {
// Enabled controls whether mesh networking is active (default: false).
Enabled bool `yaml:"enabled" json:"enabled"`
// NetworkID is the unique identifier for this mesh network.
NetworkID string `yaml:"network_id" json:"network_id"`
// NetworkCIDR is the CIDR block for virtual IP allocation (e.g., "10.100.0.0/16").
NetworkCIDR string `yaml:"network_cidr" json:"network_cidr"`
// PeerName is the friendly name for this peer in the network.
PeerName string `yaml:"peer_name" json:"peer_name"`
// Device contains network device configuration.
Device DeviceConfig `yaml:"device" json:"device"`
// Discovery contains peer discovery settings.
Discovery DiscoveryConfig `yaml:"discovery" json:"discovery"`
// STUN contains STUN server configuration for NAT traversal.
STUN STUNConfig `yaml:"stun" json:"stun"`
// TURN contains TURN server configuration for relay.
TURN TURNConfig `yaml:"turn" json:"turn"`
// Connection contains P2P connection settings.
Connection ConnectionConfig `yaml:"connection" json:"connection"`
// Security contains security settings.
Security SecurityConfig `yaml:"security" json:"security"`
}
Config contains mesh network configuration.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a mesh configuration with sensible defaults.
func (*Config) NetworkPrefix ¶
NetworkPrefix returns the parsed network prefix.
type ConnectionConfig ¶
type ConnectionConfig struct {
// DirectConnect controls whether to attempt direct P2P connections (default: true).
DirectConnect bool `yaml:"direct_connect" json:"direct_connect"`
// RelayEnabled controls whether to use relay when direct fails (default: true).
RelayEnabled bool `yaml:"relay_enabled" json:"relay_enabled"`
// RelayViaPeers controls whether to relay through other peers (default: true).
RelayViaPeers bool `yaml:"relay_via_peers" json:"relay_via_peers"`
// ConnectTimeout is the timeout for establishing connections (default: 30s).
ConnectTimeout time.Duration `yaml:"connect_timeout" json:"connect_timeout"`
// KeepAliveInterval is the interval for keep-alive packets (default: 25s).
KeepAliveInterval time.Duration `yaml:"keep_alive_interval" json:"keep_alive_interval"`
}
ConnectionConfig contains P2P connection settings.
type ConnectionType ¶
type ConnectionType string
ConnectionType represents how a peer is connected.
const ( // ConnectionTypeDirect means direct P2P connection. ConnectionTypeDirect ConnectionType = "direct" // ConnectionTypeRelayed means connection through a TURN server. ConnectionTypeRelayed ConnectionType = "relayed" // ConnectionTypeMultiHop means connection through other peers. ConnectionTypeMultiHop ConnectionType = "multi_hop" )
type DeviceConfig ¶
type DeviceConfig struct {
// Type is the device type: "tun" (Layer 3) or "tap" (Layer 2).
Type string `yaml:"type" json:"type"`
// Name is the interface name (e.g., "mesh0").
Name string `yaml:"name" json:"name"`
// MTU is the Maximum Transmission Unit (default: 1400).
MTU int `yaml:"mtu" json:"mtu"`
// MACAddress is the MAC address for TAP devices (auto-generated if empty).
MACAddress string `yaml:"mac_address,omitempty" json:"mac_address,omitempty"`
}
DeviceConfig contains network device settings for mesh networking.
func (*DeviceConfig) ToDeviceConfig ¶
func (c *DeviceConfig) ToDeviceConfig(address string) device.Config
ToDeviceConfig converts mesh device config to device.Config.
type DiscoveryClient ¶
type DiscoveryClient struct {
// contains filtered or unexported fields
}
DiscoveryClient handles peer discovery through the central server.
func NewDiscoveryClient ¶
func NewDiscoveryClient(config DiscoveryConfig, networkID string, localPeer *Peer, registry *PeerRegistry) *DiscoveryClient
NewDiscoveryClient creates a new discovery client.
func (*DiscoveryClient) Events ¶
func (c *DiscoveryClient) Events() <-chan PeerEvent
Events returns the channel for peer events.
func (*DiscoveryClient) IsConnected ¶
func (c *DiscoveryClient) IsConnected() bool
IsConnected returns whether the client is connected to the discovery server.
func (*DiscoveryClient) ListPeers ¶
func (c *DiscoveryClient) ListPeers() ([]PeerInfo, error)
ListPeers retrieves all peers from the discovery server.
func (*DiscoveryClient) Start ¶
func (c *DiscoveryClient) Start(ctx context.Context) error
Start starts the discovery client.
func (*DiscoveryClient) Stop ¶
func (c *DiscoveryClient) Stop() error
Stop stops the discovery client.
func (*DiscoveryClient) UpdateEndpoints ¶
func (c *DiscoveryClient) UpdateEndpoints(endpoints []Endpoint) error
UpdateEndpoints updates this peer's endpoints on the discovery server.
type DiscoveryConfig ¶
type DiscoveryConfig struct {
// Server is the discovery server address (e.g., "bifrost.example.com:8080").
Server string `yaml:"server" json:"server"`
// HeartbeatInterval is how often to send heartbeats (default: 30s).
HeartbeatInterval time.Duration `yaml:"heartbeat_interval" json:"heartbeat_interval"`
// PeerTimeout is how long before a peer is considered offline (default: 90s).
PeerTimeout time.Duration `yaml:"peer_timeout" json:"peer_timeout"`
// Token is the authentication token for the discovery server.
Token string `yaml:"token,omitempty" json:"token,omitempty"`
}
DiscoveryConfig contains peer discovery settings.
type Endpoint ¶
type Endpoint struct {
// Address is the IP address or hostname.
Address string `json:"address"`
// Port is the port number.
Port uint16 `json:"port"`
// Type is the endpoint type: "local", "reflexive", "relay".
Type string `json:"type"`
// Priority is used for endpoint selection.
Priority int `json:"priority"`
}
Endpoint represents a network endpoint for a peer.
type EthernetBroadcastHandler ¶
type EthernetBroadcastHandler struct {
// contains filtered or unexported fields
}
EthernetBroadcastHandler handles Ethernet broadcast frames for TAP devices.
func NewEthernetBroadcastHandler ¶
func NewEthernetBroadcastHandler(manager *BroadcastManager) *EthernetBroadcastHandler
NewEthernetBroadcastHandler creates a new Ethernet broadcast handler.
func (*EthernetBroadcastHandler) HandleFrame ¶
func (h *EthernetBroadcastHandler) HandleFrame(dstMAC net.HardwareAddr, frame []byte) error
HandleFrame handles an Ethernet broadcast/multicast frame.
type ForwardingEntry ¶
type ForwardingEntry struct {
DestIP netip.Prefix
NextHopIP netip.Addr
Interface string
Metric int
}
ForwardingEntry represents an entry in the forwarding table.
type HelloAckMessage ¶
type HelloAckMessage struct {
PeerID string `json:"peer_id"`
VirtualIP netip.Addr `json:"virtual_ip"`
RequestTime time.Time `json:"request_time"`
ResponseTime time.Time `json:"response_time"`
}
HelloAckMessage acknowledges a hello.
type HelloMessage ¶
type HelloMessage struct {
PeerID string `json:"peer_id"`
VirtualIP netip.Addr `json:"virtual_ip"`
Timestamp time.Time `json:"timestamp"`
Neighbors []string `json:"neighbors,omitempty"`
}
HelloMessage is a periodic keepalive.
type IPAllocator ¶
type IPAllocator interface {
// Allocate allocates an IP address for a peer.
Allocate(peerID string) (netip.Addr, error)
// AllocateSpecific allocates a specific IP address for a peer.
AllocateSpecific(peerID string, addr netip.Addr) error
// Release releases an IP address allocation.
Release(peerID string) error
// GetIP returns the IP address for a peer.
GetIP(peerID string) (netip.Addr, bool)
// GetPeer returns the peer ID for an IP address.
GetPeer(addr netip.Addr) (string, bool)
// Available returns the number of available addresses.
Available() int
// Used returns the number of used addresses.
Used() int
}
IPAllocator manages virtual IP address allocation for a mesh network.
type Lease ¶
type Lease struct {
PeerID string `json:"peer_id"`
Address netip.Addr `json:"address"`
Allocated time.Time `json:"allocated"`
Expires time.Time `json:"expires,omitempty"`
Static bool `json:"static"`
}
Lease represents an IP address lease.
type LinkInfo ¶
type LinkInfo struct {
NeighborID string `json:"neighbor_id"`
Latency time.Duration `json:"latency"`
State string `json:"state"` // up, down, degraded
}
LinkInfo describes a link to a neighbor.
type LinkStateUpdate ¶
type LinkStateUpdate struct {
PeerID string `json:"peer_id"`
SeqNum uint64 `json:"seq_num"`
Links []LinkInfo `json:"links"`
Timestamp time.Time `json:"timestamp"`
}
LinkStateUpdate contains link state information.
type MeshNode ¶
type MeshNode struct {
// contains filtered or unexported fields
}
MeshNode is the central orchestrator that ties all mesh networking components together.
func NewMeshNode ¶
NewMeshNode creates a new mesh node with the given configuration.
func (*MeshNode) GetConnectedPeers ¶
GetConnectedPeers returns all connected peers.
func (*MeshNode) LocalPeerID ¶
LocalPeerID returns the local peer ID.
func (*MeshNode) Status ¶
func (n *MeshNode) Status() NodeStatus
Status returns the current node status.
type MeshRouter ¶
type MeshRouter struct {
// contains filtered or unexported fields
}
MeshRouter manages the mesh routing table.
func NewMeshRouter ¶
func NewMeshRouter(config RouterConfig) *MeshRouter
NewMeshRouter creates a new mesh router.
func (*MeshRouter) AddDirectRoute ¶
AddDirectRoute adds a direct route to a peer.
func (*MeshRouter) AddRoute ¶
func (r *MeshRouter) AddRoute(route *Route)
AddRoute adds or updates a route.
func (*MeshRouter) ExpireRoutes ¶
func (r *MeshRouter) ExpireRoutes()
ExpireRoutes removes stale routes.
func (*MeshRouter) GetAllRoutes ¶
func (r *MeshRouter) GetAllRoutes() []*Route
GetAllRoutes returns all routes.
func (*MeshRouter) GetBestRoutes ¶
func (r *MeshRouter) GetBestRoutes() []*Route
GetBestRoutes returns the best route to each destination.
func (*MeshRouter) GetDirectPeers ¶
func (r *MeshRouter) GetDirectPeers() []string
GetDirectPeers returns all directly connected peers.
func (*MeshRouter) GetForwardingTable ¶
func (r *MeshRouter) GetForwardingTable() []ForwardingEntry
GetForwardingTable returns the forwarding table.
func (*MeshRouter) GetNextHop ¶
func (r *MeshRouter) GetNextHop(destPeerID string) string
GetNextHop returns the next hop peer ID for a destination.
func (*MeshRouter) GetNextHopByIP ¶
func (r *MeshRouter) GetNextHopByIP(ip netip.Addr) string
GetNextHopByIP returns the next hop peer ID for a virtual IP.
func (*MeshRouter) GetRoute ¶
func (r *MeshRouter) GetRoute(peerID string) *Route
GetRoute returns the best route to a peer.
func (*MeshRouter) GetRouteByIP ¶
func (r *MeshRouter) GetRouteByIP(ip netip.Addr) *Route
GetRouteByIP returns the route for a virtual IP.
func (*MeshRouter) GetStats ¶
func (r *MeshRouter) GetStats() RouteTableStats
GetStats returns routing table statistics.
func (*MeshRouter) IsDirect ¶
func (r *MeshRouter) IsDirect(peerID string) bool
IsDirect returns whether there's a direct route to a peer.
func (*MeshRouter) OnRouteChanged ¶
func (r *MeshRouter) OnRouteChanged(callback func(*Route))
OnRouteChanged sets the route change callback.
func (*MeshRouter) RemoveDirectRoute ¶
func (r *MeshRouter) RemoveDirectRoute(peerID string)
RemoveDirectRoute removes a direct route to a peer.
func (*MeshRouter) UpdateLatency ¶
func (r *MeshRouter) UpdateLatency(peerID string, latency time.Duration)
UpdateLatency updates the latency for a direct route.
type MulticastGroup ¶
type MulticastGroup struct {
// ID is the group identifier.
ID string
// Name is the human-readable group name.
Name string
// Members are the peer IDs in the group.
Members map[string]bool
// JoinedAt is when this peer joined the group.
JoinedAt time.Time
}
MulticastGroup represents a multicast group.
type NodeStats ¶
type NodeStats struct {
Status NodeStatus `json:"status"`
PeerCount int `json:"peer_count"`
ConnectedPeers int `json:"connected_peers"`
DirectConnections int `json:"direct_connections"`
RelayedConnections int `json:"relayed_connections"`
BytesSent int64 `json:"bytes_sent"`
BytesReceived int64 `json:"bytes_received"`
PacketsSent int64 `json:"packets_sent"`
PacketsReceived int64 `json:"packets_received"`
Uptime time.Duration `json:"uptime"`
}
NodeStats contains mesh node statistics.
type NodeStatus ¶
type NodeStatus string
NodeStatus represents the current status of the mesh node.
const ( NodeStatusStopped NodeStatus = "stopped" NodeStatusStarting NodeStatus = "starting" NodeStatusRunning NodeStatus = "running" NodeStatusStopping NodeStatus = "stopping" NodeStatusError NodeStatus = "error" )
type PathCostFunc ¶
PathCostFunc calculates the cost of a path.
type Peer ¶
type Peer struct {
// ID is the unique identifier for this peer.
ID string `json:"id"`
// Name is the friendly name for this peer.
Name string `json:"name"`
// VirtualIP is the virtual IP address assigned to this peer.
VirtualIP netip.Addr `json:"virtual_ip"`
// VirtualMAC is the virtual MAC address for TAP mode.
VirtualMAC net.HardwareAddr `json:"virtual_mac,omitempty"`
// PublicKey is the peer's Ed25519 public key (base64 encoded).
PublicKey string `json:"public_key"`
// Endpoints is the list of known endpoints for this peer.
Endpoints []Endpoint `json:"endpoints"`
// Status is the current connection status.
Status PeerStatus `json:"status"`
// ConnectionType is how we're connected to this peer.
ConnectionType ConnectionType `json:"connection_type,omitempty"`
// Latency is the measured latency to this peer.
Latency time.Duration `json:"latency,omitempty"`
// LastSeen is when we last saw activity from this peer.
LastSeen time.Time `json:"last_seen"`
// JoinedAt is when this peer joined the network.
JoinedAt time.Time `json:"joined_at"`
// Metadata contains arbitrary peer metadata.
Metadata map[string]string `json:"metadata,omitempty"`
// BytesSent is the number of bytes sent to this peer.
BytesSent int64 `json:"bytes_sent"`
// BytesReceived is the number of bytes received from this peer.
BytesReceived int64 `json:"bytes_received"`
// contains filtered or unexported fields
}
Peer represents a peer in the mesh network.
func (*Peer) AddBytesReceived ¶
AddBytesReceived adds to the bytes received counter.
func (*Peer) AddBytesSent ¶
AddBytesSent adds to the bytes sent counter.
func (*Peer) AddEndpoint ¶
AddEndpoint adds an endpoint to the peer.
func (*Peer) GetEndpoints ¶
GetEndpoints returns a copy of all endpoints.
func (*Peer) GetMetadata ¶
GetMetadata gets a metadata value.
func (*Peer) IsConnected ¶
IsConnected returns true if the peer is connected (directly or via relay).
func (*Peer) IsReachable ¶
IsReachable returns true if the peer might be reachable.
func (*Peer) RemoveEndpoint ¶
RemoveEndpoint removes an endpoint from the peer.
func (*Peer) SetConnectionType ¶
func (p *Peer) SetConnectionType(connType ConnectionType)
SetConnectionType sets how we're connected to this peer.
func (*Peer) SetLatency ¶
SetLatency sets the measured latency.
func (*Peer) SetMetadata ¶
SetMetadata sets a metadata value. Returns false if the key/value exceeds limits or max keys reached.
func (*Peer) SetStatus ¶
func (p *Peer) SetStatus(status PeerStatus)
SetStatus sets the peer's connection status.
func (*Peer) SetVirtualIP ¶
SetVirtualIP sets the peer's virtual IP address.
func (*Peer) SetVirtualMAC ¶
func (p *Peer) SetVirtualMAC(mac net.HardwareAddr)
SetVirtualMAC sets the peer's virtual MAC address.
func (*Peer) UpdateLastSeen ¶
func (p *Peer) UpdateLastSeen()
UpdateLastSeen updates the last seen timestamp.
type PeerEvent ¶
type PeerEvent struct {
Type string `json:"type"` // "join", "leave", "update"
Peer PeerInfo `json:"peer"`
Timestamp time.Time `json:"timestamp"`
}
PeerEvent represents a peer-related event from the discovery server.
type PeerInfo ¶
type PeerInfo struct {
ID string `json:"id"`
Name string `json:"name"`
PublicKey string `json:"public_key"`
VirtualIP string `json:"virtual_ip,omitempty"`
Endpoints []Endpoint `json:"endpoints,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
PeerInfo is the peer information exchanged with the discovery server.
type PeerRegistry ¶
type PeerRegistry struct {
// contains filtered or unexported fields
}
PeerRegistry manages all known peers in a mesh network.
func NewPeerRegistry ¶
func NewPeerRegistry() *PeerRegistry
NewPeerRegistry creates a new peer registry.
func (*PeerRegistry) Connected ¶
func (r *PeerRegistry) Connected() []*Peer
Connected returns all connected peers.
func (*PeerRegistry) Get ¶
func (r *PeerRegistry) Get(id string) (*Peer, bool)
Get returns a peer by ID.
func (*PeerRegistry) GetByIP ¶
func (r *PeerRegistry) GetByIP(ip netip.Addr) (*Peer, bool)
GetByIP returns a peer by virtual IP.
func (*PeerRegistry) GetByMAC ¶
func (r *PeerRegistry) GetByMAC(mac net.HardwareAddr) (*Peer, bool)
GetByMAC returns a peer by virtual MAC.
func (*PeerRegistry) Remove ¶
func (r *PeerRegistry) Remove(id string)
Remove removes a peer from the registry.
func (*PeerRegistry) UpdatePeerIP ¶
func (r *PeerRegistry) UpdatePeerIP(peer *Peer, newIP netip.Addr)
UpdatePeerIP updates the IP index when a peer's IP changes.
func (*PeerRegistry) UpdatePeerMAC ¶
func (r *PeerRegistry) UpdatePeerMAC(peer *Peer, newMAC net.HardwareAddr)
UpdatePeerMAC updates the MAC index when a peer's MAC changes.
type PeerStatus ¶
type PeerStatus string
PeerStatus represents the connection status of a peer.
const ( // PeerStatusDiscovered means the peer was found but not yet connected. PeerStatusDiscovered PeerStatus = "discovered" // PeerStatusConnecting means a connection is being established. PeerStatusConnecting PeerStatus = "connecting" // PeerStatusConnected means the peer is directly connected. PeerStatusConnected PeerStatus = "connected" // PeerStatusRelayed means the peer is connected via relay. PeerStatusRelayed PeerStatus = "relayed" // PeerStatusUnreachable means the peer cannot be reached. PeerStatusUnreachable PeerStatus = "unreachable" // PeerStatusOffline means the peer is offline. PeerStatusOffline PeerStatus = "offline" )
type PoolAllocator ¶
type PoolAllocator struct {
// contains filtered or unexported fields
}
PoolAllocator allocates IP addresses from a pool.
func NewPoolAllocator ¶
func NewPoolAllocator(config PoolConfig) (*PoolAllocator, error)
NewPoolAllocator creates a new IP pool allocator.
func (*PoolAllocator) Allocate ¶
func (a *PoolAllocator) Allocate(peerID string) (netip.Addr, error)
Allocate allocates an IP address for a peer.
func (*PoolAllocator) AllocateSpecific ¶
func (a *PoolAllocator) AllocateSpecific(peerID string, addr netip.Addr) error
AllocateSpecific allocates a specific IP address for a peer.
func (*PoolAllocator) Available ¶
func (a *PoolAllocator) Available() int
Available returns the number of available addresses.
func (*PoolAllocator) GetAllLeases ¶
func (a *PoolAllocator) GetAllLeases() []Lease
GetAllLeases returns all current leases.
func (*PoolAllocator) GetIP ¶
func (a *PoolAllocator) GetIP(peerID string) (netip.Addr, bool)
GetIP returns the IP address for a peer.
func (*PoolAllocator) GetPeer ¶
func (a *PoolAllocator) GetPeer(addr netip.Addr) (string, bool)
GetPeer returns the peer ID for an IP address.
func (*PoolAllocator) Prefix ¶
func (a *PoolAllocator) Prefix() netip.Prefix
Prefix returns the network prefix.
func (*PoolAllocator) Release ¶
func (a *PoolAllocator) Release(peerID string) error
Release releases an IP address allocation.
func (*PoolAllocator) Renew ¶
func (a *PoolAllocator) Renew(peerID string) error
Renew renews a lease for a peer.
func (*PoolAllocator) StartExpiryWorker ¶
func (a *PoolAllocator) StartExpiryWorker(interval time.Duration, stopCh <-chan struct{})
StartExpiryWorker starts a background goroutine that periodically expires old leases.
func (*PoolAllocator) Used ¶
func (a *PoolAllocator) Used() int
Used returns the number of used addresses.
type PoolConfig ¶
type PoolConfig struct {
// NetworkCIDR is the network CIDR (e.g., "10.100.0.0/16").
NetworkCIDR string
// GatewayAddress is the gateway IP (usually first usable address).
// If empty, it won't be reserved.
GatewayAddress string
// LeaseTTL is the lease duration (0 = no expiry).
LeaseTTL time.Duration
// ReservedAddresses is a list of additional addresses to reserve.
ReservedAddresses []string
}
PoolConfig contains IP pool configuration.
type ProtocolConfig ¶
type ProtocolConfig struct {
// HelloInterval is the interval between hello messages.
HelloInterval time.Duration
// RouteAnnounceInterval is the interval between route announcements.
RouteAnnounceInterval time.Duration
// RouteExpiryInterval is the route expiry check interval.
RouteExpiryInterval time.Duration
// DefaultTTL is the default TTL for messages.
DefaultTTL int
// MaxRouteAge is the maximum age of a route before expiry.
MaxRouteAge time.Duration
// SplitHorizon enables split horizon (don't announce routes back to source).
SplitHorizon bool
// PoisonReverse enables poison reverse (announce withdrawn routes with infinite metric).
PoisonReverse bool
}
ProtocolConfig contains routing protocol configuration.
func DefaultProtocolConfig ¶
func DefaultProtocolConfig() ProtocolConfig
DefaultProtocolConfig returns a default protocol configuration.
type ProtocolMessage ¶
type ProtocolMessage struct {
Type ProtocolMessageType `json:"type"`
SrcPeerID string `json:"src_peer_id"`
SeqNum uint64 `json:"seq_num"`
TTL int `json:"ttl"`
Timestamp time.Time `json:"timestamp"`
Payload json.RawMessage `json:"payload,omitempty"`
}
ProtocolMessage is the base protocol message.
type ProtocolMessageType ¶
type ProtocolMessageType byte
ProtocolMessageType represents the type of protocol message.
const ( // MsgTypeRouteAnnounce announces routes to neighbors. MsgTypeRouteAnnounce ProtocolMessageType = iota + 1 // MsgTypeRouteRequest requests routes from neighbors. MsgTypeRouteRequest // MsgTypeRouteWithdraw withdraws a previously announced route. MsgTypeRouteWithdraw // MsgTypeHello is a periodic hello/keepalive message. MsgTypeHello // MsgTypeHelloAck acknowledges a hello message. MsgTypeHelloAck // MsgTypeLinkState announces link state updates. MsgTypeLinkState )
func (ProtocolMessageType) String ¶
func (t ProtocolMessageType) String() string
String returns a human-readable string for the message type.
type RegistrationRequest ¶
type RegistrationRequest struct {
NetworkID string `json:"network_id"`
Peer PeerInfo `json:"peer"`
}
RegistrationRequest is sent to register with the discovery server.
type RegistrationResponse ¶
type RegistrationResponse struct {
Success bool `json:"success"`
VirtualIP string `json:"virtual_ip"`
Message string `json:"message,omitempty"`
Peers []PeerInfo `json:"peers,omitempty"`
}
RegistrationResponse is received from the discovery server.
type Route ¶
type Route struct {
// DestPeerID is the destination peer ID.
DestPeerID string
// DestIP is the destination virtual IP.
DestIP netip.Addr
// NextHop is the next hop peer ID (empty for direct routes).
NextHop string
// Type is the route type.
Type RouteType
// Metric is the route cost (lower is better).
Metric int
// Latency is the measured latency.
Latency time.Duration
// HopCount is the number of hops.
HopCount int
// LastUpdated is when the route was last updated.
LastUpdated time.Time
// Active indicates if the route is currently active.
Active bool
}
Route represents a route to a peer.
type RouteAnnouncement ¶
type RouteAnnouncement struct {
DestPeerID string `json:"dest_peer_id"`
DestIP netip.Addr `json:"dest_ip"`
Metric int `json:"metric"`
HopCount int `json:"hop_count"`
Path []string `json:"path,omitempty"` // For loop prevention
}
RouteAnnouncement contains route information.
type RouteTableStats ¶
type RouteTableStats struct {
TotalRoutes int
DirectRoutes int
NextHopRoutes int
RelayRoutes int
Destinations int
}
RouteTableStats contains routing table statistics.
type RouteWithdrawal ¶
type RouteWithdrawal struct {
DestPeerID string `json:"dest_peer_id"`
}
RouteWithdrawal indicates a route is no longer available.
type RouterConfig ¶
type RouterConfig struct {
// LocalPeerID is the local peer ID.
LocalPeerID string
// LocalIP is the local virtual IP.
LocalIP netip.Addr
// MaxHops is the maximum number of hops.
MaxHops int
// RouteTimeout is the route expiry timeout.
RouteTimeout time.Duration
// PathCostFunc calculates path costs.
PathCostFunc PathCostFunc
}
RouterConfig contains router configuration.
func DefaultRouterConfig ¶
func DefaultRouterConfig() RouterConfig
DefaultRouterConfig returns a default router configuration.
type RoutingProtocol ¶
type RoutingProtocol struct {
// contains filtered or unexported fields
}
RoutingProtocol manages the mesh routing protocol.
func NewRoutingProtocol ¶
func NewRoutingProtocol(localPeerID string, localIP netip.Addr, router *MeshRouter, config ProtocolConfig) *RoutingProtocol
NewRoutingProtocol creates a new routing protocol handler.
func (*RoutingProtocol) HandleMessage ¶
func (p *RoutingProtocol) HandleMessage(fromPeerID string, data []byte) error
HandleMessage handles an incoming protocol message.
func (*RoutingProtocol) NotifyPeerConnected ¶
func (p *RoutingProtocol) NotifyPeerConnected(peerID string, peerIP netip.Addr, latency time.Duration)
NotifyPeerConnected notifies the protocol of a new peer connection.
func (*RoutingProtocol) NotifyPeerDisconnected ¶
func (p *RoutingProtocol) NotifyPeerDisconnected(peerID string)
NotifyPeerDisconnected notifies the protocol of a peer disconnection.
func (*RoutingProtocol) SetSendFunc ¶
func (p *RoutingProtocol) SetSendFunc(sendFunc func(peerID string, msg []byte) error)
SetSendFunc sets the function used to send messages to peers.
func (*RoutingProtocol) Start ¶
func (p *RoutingProtocol) Start() error
Start starts the routing protocol.
func (*RoutingProtocol) Stop ¶
func (p *RoutingProtocol) Stop() error
Stop stops the routing protocol.
func (*RoutingProtocol) WithdrawRoute ¶
func (p *RoutingProtocol) WithdrawRoute(destPeerID string)
WithdrawRoute withdraws a route from neighbors.
type STUNConfig ¶
type STUNConfig struct {
// Servers is a list of STUN server addresses.
Servers []string `yaml:"servers" json:"servers"`
// Timeout is the timeout for STUN requests (default: 5s).
Timeout time.Duration `yaml:"timeout" json:"timeout"`
}
STUNConfig contains STUN server configuration.
type SecurityConfig ¶
type SecurityConfig struct {
// PrivateKey is the Ed25519 private key for this peer (base64 encoded).
// If empty, a new key pair will be generated.
PrivateKey string `yaml:"private_key,omitempty" json:"private_key,omitempty"`
// AllowedPeers is a list of allowed peer public keys (empty = allow all).
AllowedPeers []string `yaml:"allowed_peers,omitempty" json:"allowed_peers,omitempty"`
// RequireEncryption controls whether all connections must be encrypted (default: true).
RequireEncryption bool `yaml:"require_encryption" json:"require_encryption"`
}
SecurityConfig contains security settings.
type TURNConfig ¶
type TURNConfig struct {
// Servers is a list of TURN server configurations.
Servers []TURNServer `yaml:"servers" json:"servers"`
// Enabled controls whether TURN relay is enabled (default: true).
Enabled bool `yaml:"enabled" json:"enabled"`
}
TURNConfig contains TURN server configuration.
type TURNServer ¶
type TURNServer struct {
// URL is the TURN server URL (e.g., "turn:turn.example.com:3478").
URL string `yaml:"url" json:"url"`
// Username for TURN authentication.
Username string `yaml:"username" json:"username"`
// Password for TURN authentication.
Password string `yaml:"password" json:"password"`
}
TURNServer contains a single TURN server configuration.