state

package
v0.4.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	INF = ^(uint32)(0)
	// INFM is the maximum value for a metric that is not a retraction.
	INFM = INF - 1

	// default port
	DefaultPort = 57175
)

Variables

This section is empty.

Functions

func AddrToPrefix

func AddrToPrefix(addr netip.Addr) netip.Prefix

func BundleConfig

func BundleConfig(config string, rootKey NyPrivateKey) (string, error)

BundleConfig first signs the config with the root private key, ensuring the authenticity, then encrypts the message using the bytes of the root public key as the shared key, offering some level of privacy. (assuming the root public key is not shared widely)

func CentralConfigValidator

func CentralConfigValidator(cfg *CentralCfg) error

func DurationToMetric added in v0.4.0

func DurationToMetric(d time.Duration) uint32

func ExpandCentralConfig

func ExpandCentralConfig(cfg *CentralCfg)

func GetIfIP added in v0.4.0

func GetIfIP(itf string, is6 bool) (string, error)

func MakeSet added in v0.4.0

func MakeSet(prefix []netip.Prefix) *netipx.IPSet

func MetricToDuration added in v0.4.0

func MetricToDuration(m uint32) time.Duration

func NameValidator

func NameValidator(s string) error

func NodeConfigValidator

func NodeConfigValidator(central *CentralCfg, node *LocalCfg) error

func OpenBundle

func OpenBundle(data []byte, key []byte) ([]byte, error)

func SealBundle

func SealBundle(data []byte, key []byte) ([]byte, error)

func SignBundle

func SignBundle(data []byte, key NyPrivateKey) ([]byte, error)

func SortPairs

func SortPairs[T cmp.Ordered](pairs []Pair[T, T])

func VerifyBundle

func VerifyBundle(data []byte, key NyPublicKey) ([]byte, error)

Types

type Advertisement struct {
	NodeId
	Expiry        time.Time
	IsPassiveHold bool
	MetricFn      func() uint32
	ExpiryFn      func()
}

type CentralCfg

type CentralCfg struct {
	Dist       *DistributionCfg `yaml:",omitempty"`
	Routers    []RouterCfg
	Clients    []ClientCfg
	Graph      []string
	Timestamp  int64
	ExcludeIPs []netip.Prefix `yaml:"exclude_ips,omitempty"` // split tunnel, default excluded ip ranges for the whole network, if empty, all advertised prefixes will be included
}

func UnbundleConfig

func UnbundleConfig(bundleStr string, pubKey NyPublicKey) (*CentralCfg, error)

func (*CentralCfg) Clone added in v0.4.0

func (c *CentralCfg) Clone() (error, *CentralCfg)

func (*CentralCfg) FindNodeBy

func (e *CentralCfg) FindNodeBy(pkey NyPublicKey) *NodeId

func (*CentralCfg) GetClient

func (e *CentralCfg) GetClient(node NodeId) ClientCfg

func (*CentralCfg) GetNode

func (e *CentralCfg) GetNode(node NodeId) NodeCfg

func (*CentralCfg) GetNodes

func (c *CentralCfg) GetNodes() []NodeCfg

func (*CentralCfg) GetPeers

func (e *CentralCfg) GetPeers(curId NodeId) []NodeId

func (*CentralCfg) GetPrefixes added in v0.4.0

func (c *CentralCfg) GetPrefixes() []netip.Prefix

GetPrefixes returns all unique prefixes from all nodes

func (*CentralCfg) GetRouter

func (e *CentralCfg) GetRouter(node NodeId) RouterCfg

func (*CentralCfg) IsClient

func (e *CentralCfg) IsClient(node NodeId) bool

func (*CentralCfg) IsNode

func (e *CentralCfg) IsNode(node NodeId) bool

func (*CentralCfg) IsRouter

func (e *CentralCfg) IsRouter(node NodeId) bool

func (*CentralCfg) TryGetNode

func (e *CentralCfg) TryGetNode(node NodeId) *NodeCfg

type ClientCfg

type ClientCfg struct {
	NodeCfg `yaml:",inline"`
}

type ConfigState added in v0.4.0

type ConfigState struct {
	CentralCfg
	LocalCfg
}

ConfigState is a struct so we can easily build test harnesses and reload config

type DNSResolver added in v0.4.5

type DNSResolver struct {
	// contains filtered or unexported fields
}

DNSResolver performs Nylon's DNS lookups without changing net.DefaultResolver. A Nylon instance can therefore use its configured DNS servers independently from other instances in the same process.

func NewDNSResolver added in v0.4.5

func NewDNSResolver(servers []string) *DNSResolver

func (*DNSResolver) DialContext added in v0.4.5

func (r *DNSResolver) DialContext(ctx context.Context, network, address string) (net.Conn, error)

DialContext resolves address through this Nylon instance's configured DNS servers before dialing it.

func (*DNSResolver) ResolveName added in v0.4.5

func (r *DNSResolver) ResolveName(ctx context.Context, host string) ([]netip.Addr, error)

func (*DNSResolver) ResolveSRV added in v0.4.5

func (r *DNSResolver) ResolveSRV(ctx context.Context, service, proto, name string) (string, uint16, error)

type DistributionCfg

type DistributionCfg struct {
	Key   NyPublicKey // also used as shared secret, so, although its "public", it's not a good idea to share it.
	Repos []string
}

type Endpoint

type Endpoint interface {
	UpdatePing(ping time.Duration)
	Metric() uint32
	IsRemote() bool
	IsActive() bool
	AsNylonEndpoint() *NylonEndpoint
}

type EndpointResolver added in v0.4.5

type EndpointResolver struct {
	// contains filtered or unexported fields
}

EndpointResolver centrally owns resolved endpoint state for a Nylon instance. Cache entries are shared by every link configured with the same address.

func NewEndpointResolver added in v0.4.5

func NewEndpointResolver(dns *DNSResolver) *EndpointResolver

func (*EndpointResolver) Expire added in v0.4.5

func (r *EndpointResolver) Expire(endpoint string)

Expire makes the next Resolve refresh an endpoint while preserving the last usable value until that refresh succeeds.

func (*EndpointResolver) Get added in v0.4.5

func (r *EndpointResolver) Get(endpoint string) (netip.AddrPort, error)

func (*EndpointResolver) Resolve added in v0.4.5

func (r *EndpointResolver) Resolve(endpoint string, expiry time.Duration) (netip.AddrPort, error)

func (*EndpointResolver) Retain added in v0.4.5

func (r *EndpointResolver) Retain(addresses map[string]struct{})

Retain removes cached resolutions for addresses no longer present in runtime state. In-flight resolutions may finish using a removed entry, but it will no longer be reachable from the central cache.

type FD

type FD struct {
	Seqno  uint16
	Metric uint32
}

func (FD) LogValue added in v0.4.0

func (fd FD) LogValue() slog.Value

type HTTPPrefixHealth added in v0.4.0

type HTTPPrefixHealth struct {
	Prefix netip.Prefix   `yaml:"prefix"`
	URL    string         `yaml:"url"`              // the URL to check
	Delay  *time.Duration `yaml:"delay,omitempty"`  // delay between probes
	Metric *uint32        `yaml:"metric,omitempty"` // metric override
}

func (*HTTPPrefixHealth) GetPrefix added in v0.4.0

func (h *HTTPPrefixHealth) GetPrefix() netip.Prefix

type LocalCfg

type LocalCfg struct {
	// Node Private Key
	Key               NyPrivateKey
	Id                NodeId                // unique id for this node
	Port              uint16                // Address that the data plane can be accessed by
	Dist              *LocalDistributionCfg `yaml:",omitempty"`                   // distribution configuration
	UseSystemRouting  bool                  `yaml:"use_system_routing,omitempty"` // all packets from peers will come out of the TUN interface
	NoTun             bool                  `yaml:"no_tun,omitempty"`             // relay-only mode; requires no advertised addresses or prefixes
	NoNetConfigure    bool                  `yaml:"no_net_configure,omitempty"`   // do not configure system networking at all
	DnsResolvers      []string              `yaml:"dns_resolvers,omitempty"`      // DNS resolvers used for endpoints and config repositories
	InterfaceName     string                `yaml:"interface_name,omitempty"`     // the name of the nylon interface
	LogPath           string                `yaml:"log_path,omitempty"`           // if not empty, nylon will write to this file
	ObservabilityAddr string                `yaml:"observability_addr,omitempty"` // HTTP address for metrics, health, readiness, and service discovery
	UnexcludeIPs      []netip.Prefix        `yaml:"unexclude_ips,omitempty"`      // split tunnel, subtracts from centrally excluded ip ranges
	ExcludeIPs        []netip.Prefix        `yaml:"exclude_ips,omitempty"`        // split tunnel, adds to the centrally excluded ip ranges
	PreUp             []string              `yaml:"pre_up,omitempty"`             // a list of commands executed in order before the nylon interface is brought up
	PreDown           []string              `yaml:"pre_down,omitempty"`           // a list of commands executed in order before the nylon interface is brought down
	PostUp            []string              `yaml:"post_up,omitempty"`            // a list of commands executed in order after the nylon interface is brought up
	PostDown          []string              `yaml:"post_down,omitempty"`          // a list of commands executed in order after the nylon interface is brought down
}

LocalCfg represents local node-level configuration

type LocalDistributionCfg added in v0.3.3

type LocalDistributionCfg struct {
	Key NyPublicKey
	Url string
}

type NeighRoute

type NeighRoute struct {
	PubRoute
	ExpireAt time.Time // when the route expires
}

type Neighbour

type Neighbour struct {
	Id     NodeId
	Routes map[netip.Prefix]NeighRoute
	Eps    []Endpoint
}

func (*Neighbour) BestEndpoint

func (n *Neighbour) BestEndpoint() Endpoint

type NodeCfg

type NodeCfg struct {
	Id        NodeId
	PubKey    NyPublicKey
	Addresses []netip.Addr          `yaml:",omitempty"`
	Prefixes  []PrefixHealthWrapper `yaml:",omitempty"`
}

type NodeId

type NodeId string

type NyPrivateKey

type NyPrivateKey [device.NoisePrivateKeySize]byte

func GenerateKey

func GenerateKey() NyPrivateKey

func (NyPrivateKey) MarshalText

func (k NyPrivateKey) MarshalText() ([]byte, error)

func (NyPrivateKey) Pubkey

func (k NyPrivateKey) Pubkey() NyPublicKey

func (*NyPrivateKey) UnmarshalText

func (k *NyPrivateKey) UnmarshalText(text []byte) error

type NyPublicKey

type NyPublicKey [device.NoisePublicKeySize]byte

func (NyPublicKey) MarshalText

func (k NyPublicKey) MarshalText() ([]byte, error)

func (*NyPublicKey) UnmarshalText

func (k *NyPublicKey) UnmarshalText(text []byte) error

type NylonEndpoint

type NylonEndpoint struct {
	sync.RWMutex // this mutex is for rtt smoothing and metric calculation

	WgEndpoint conn.Endpoint
	Address    string
	// contains filtered or unexported fields
}

func NewEndpoint

func NewEndpoint(address string, remoteInit bool, wgEndpoint conn.Endpoint, t *RouterTunables) *NylonEndpoint

func (*NylonEndpoint) AsNylonEndpoint

func (ep *NylonEndpoint) AsNylonEndpoint() *NylonEndpoint

func (*NylonEndpoint) FilteredPing

func (u *NylonEndpoint) FilteredPing() time.Duration

func (*NylonEndpoint) GetWgEndpoint

func (ep *NylonEndpoint) GetWgEndpoint(device *device.Device, resolver *EndpointResolver) (conn.Endpoint, error)

func (*NylonEndpoint) HighRange

func (u *NylonEndpoint) HighRange() time.Duration

func (*NylonEndpoint) IsActive

func (u *NylonEndpoint) IsActive() bool

func (*NylonEndpoint) IsAlive

func (u *NylonEndpoint) IsAlive() bool

func (*NylonEndpoint) IsRemote

func (u *NylonEndpoint) IsRemote() bool

func (*NylonEndpoint) LowRange

func (u *NylonEndpoint) LowRange() time.Duration

func (*NylonEndpoint) Metric

func (u *NylonEndpoint) Metric() uint32

func (*NylonEndpoint) Renew

func (u *NylonEndpoint) Renew()

func (*NylonEndpoint) StabilizedPing

func (u *NylonEndpoint) StabilizedPing() time.Duration

func (*NylonEndpoint) UpdatePing

func (u *NylonEndpoint) UpdatePing(ping time.Duration)

type NylonOptions added in v0.4.0

type NylonOptions struct {
	DBG_log_probe        bool
	DBG_log_wireguard    bool
	DBG_log_repo_updates bool
	DBG_log_json         bool
	DBG_debug            bool
	DBG_trace            bool
	DBG_trace_tc         bool
}

NylonOptions contains runtime flags set at startup (typically from CLI flags).

func DefaultNylonOptions added in v0.4.0

func DefaultNylonOptions() NylonOptions

type Pair

type Pair[Ty1, Ty2 any] struct {
	V1 Ty1
	V2 Ty2
}

Pair is only used in-memory, not serialized

func MakeSortedPair

func MakeSortedPair[T cmp.Ordered](a, b T) Pair[T, T]

func ParseGraph

func ParseGraph(graph []string, nodes []string) ([]Pair[NodeId, NodeId], error)

ParseGraph Graph syntax is something like this:

Group1 = node1, node2, node3

Group2 = node4, node5

Group1, Group2, OtherNode // Group1, Group2, OtherNode will all be interconnected, but not within Group1 or Group2

Group1, Group1 // every node is connected to every other node

node8, node9 // node8 and node9 will be connected

graph represents the above graph nodes represents a set of unique terminal nodes that the graph will evaluate down to

type PingPrefixHealth added in v0.4.0

type PingPrefixHealth struct {
	Prefix      netip.Prefix   `yaml:"prefix"`
	Addr        netip.Addr     `yaml:"addr"`                   // the address to ping
	MaxFailures *int           `yaml:"max_failures,omitempty"` // number of failures before returning infinite metric
	Delay       *time.Duration `yaml:"delay,omitempty"`        // delay between pings
	BindIf      string         `yaml:"bind_if,omitempty"`      // local interface to bind to
	Metric      *uint32        `yaml:"metric,omitempty"`       // metric override
}

func (*PingPrefixHealth) GetPrefix added in v0.4.0

func (p *PingPrefixHealth) GetPrefix() netip.Prefix

type PrefixHealthConfig added in v0.4.5

type PrefixHealthConfig interface {
	GetPrefix() netip.Prefix
	// contains filtered or unexported methods
}

PrefixHealthConfig is immutable configuration stored in CentralCfg. Runtime workers and their metrics are owned separately by PrefixHealthMonitor.

type PrefixHealthMonitor added in v0.4.5

type PrefixHealthMonitor interface {
	GetMetric() uint32
	Stop()
}

type PrefixHealthWrapper added in v0.4.0

type PrefixHealthWrapper struct {
	PrefixHealth PrefixHealthConfig
}

func (PrefixHealthWrapper) GetPrefix added in v0.4.5

func (p PrefixHealthWrapper) GetPrefix() netip.Prefix

func (PrefixHealthWrapper) MarshalYAML added in v0.4.0

func (p PrefixHealthWrapper) MarshalYAML() (interface{}, error)

func (PrefixHealthWrapper) NewMonitor added in v0.4.5

func (p PrefixHealthWrapper) NewMonitor(log *slog.Logger, tunables *RouterTunables, resolver *DNSResolver) PrefixHealthMonitor

func (PrefixHealthWrapper) SameConfig added in v0.4.4

func (p PrefixHealthWrapper) SameConfig(other PrefixHealthWrapper, tunables *RouterTunables) bool

SameConfig reports whether two prefix health checks have equivalent configuration.

func (PrefixHealthWrapper) StaticMetric added in v0.4.5

func (p PrefixHealthWrapper) StaticMetric() (uint32, bool)

func (*PrefixHealthWrapper) UnmarshalYAML added in v0.4.0

func (p *PrefixHealthWrapper) UnmarshalYAML(unmarshal func(interface{}) error) error

type PubRoute

type PubRoute struct {
	Source
	// FD will depend on which table the route is in. In the neighbour table,
	// it represents the metric advertised by the neighbour.
	// In the selected route table, it represents the metric that
	// the route will be advertised with.
	FD
}

func (PubRoute) LogValue added in v0.4.0

func (r PubRoute) LogValue() slog.Value

func (PubRoute) String

func (r PubRoute) String() string

type RouterCfg

type RouterCfg struct {
	NodeCfg   `yaml:",inline"`
	Endpoints []string
}

RouterCfg represents a central representation of a node that can route

type RouterState

type RouterState struct {
	*RouterTunables
	Id         NodeId
	SelfSeqno  map[netip.Prefix]uint16
	Routes     map[netip.Prefix]SelRoute
	Sources    map[Source]FD
	Neighbours []*Neighbour
	// Advertised is a map tracking the prefix and the time it will be advertised until
	Advertised map[netip.Prefix]Advertisement
}

func (*RouterState) GetNeighbour

func (s *RouterState) GetNeighbour(node NodeId) *Neighbour

func (*RouterState) GetSeqno

func (s *RouterState) GetSeqno(prefix netip.Prefix) uint16

func (*RouterState) SetSeqno

func (s *RouterState) SetSeqno(prefix netip.Prefix, seqno uint16)

func (*RouterState) StringRoutes

func (s *RouterState) StringRoutes() string

type RouterTunables added in v0.4.0

type RouterTunables struct {
	HopCost               uint32 // add a 5 microsecond hop cost to prevent loops on ultra-fast networks.
	LargeChangeThreshold  uint32 // 100 milliseconds change
	SeqnoRequestHopCount  uint8
	RouteUpdateDelay      time.Duration
	ProbeDelay            time.Duration
	ProbeRecoveryDelay    time.Duration
	ProbeDiscoveryDelay   time.Duration
	StarvationDelay       time.Duration
	SeqnoDedupTTL         time.Duration
	NeighbourIOFlushDelay time.Duration
	IPCDispatchTimeout    time.Duration
	SafeMTU               int

	// WindowSamples is the sliding window size
	WindowSamples     int
	OutlierPercentage float64
	// MinimumConfidenceWindow is the minimum number of samples before we lower the ping
	MinimumConfidenceWindow int

	GcDelay            time.Duration
	LinkDeadThreshold  time.Duration
	RouteExpiryTime    time.Duration
	LinkSwitchDeadband float64 // We will switch to a new feasible route if: metric(new) * LinkSwitchDeadband <= metric(old)

	// client configuration
	ClientKeepaliveInterval time.Duration
	ClientDeadThreshold     time.Duration

	// central updates
	CentralUpdateDelay time.Duration

	// healthcheck defaults
	HealthCheckDelay       time.Duration
	HealthCheckMaxFailures int

	EndpointResolveExpiry time.Duration
	EndpointResolveDelay  time.Duration

	MaxConfigSize int64
}

RouterTunables contains all timing and algorithm parameters for the router. These are set once at startup and should not be mutated after the Nylon instance starts.

func DefaultRouterTunables added in v0.4.0

func DefaultRouterTunables() RouterTunables

type SelRoute

type SelRoute struct {
	PubRoute
	Nh          NodeId    // next hop node
	ExpireAt    time.Time // when the route expires
	RetractedBy []NodeId
}

func (SelRoute) LogValue added in v0.4.0

func (r SelRoute) LogValue() slog.Value

func (SelRoute) String

func (r SelRoute) String() string

type Source

type Source struct {
	NodeId
	netip.Prefix
}

Source is a pair of a router-id and a prefix (Babel Section 2.7).

func (Source) LogValue added in v0.4.0

func (s Source) LogValue() slog.Value

func (Source) String

func (s Source) String() string

type StaticPrefixHealth added in v0.4.0

type StaticPrefixHealth struct {
	Prefix netip.Prefix `yaml:"prefix"`
	Metric uint32       `yaml:"metric,omitempty"` // the metric to advertise for this prefix
}

StaticPrefixHealth represents a static prefix configuration, always advertised with the same metric

func (*StaticPrefixHealth) GetPrefix added in v0.4.0

func (s *StaticPrefixHealth) GetPrefix() netip.Prefix

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL