m

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 10, 2024 License: BSD-3-Clause Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AddressDigestAlg = BLAKE3
	AddressKeyToolID = "Ed25519"
)

Default Cryptography.

View Source
const (

	// BaseNet is the required prefix base for all addresses.
	// The used address space is fd00/8.
	// It is for unique local addresses that are self-assigned.
	BaseNet = 0xfd

	TypeMask      = 0b1000_0000 // 1 Bit
	ContinentMask = 0b0111_0000 // 3 Bits
	RegionMask    = 0b0000_1111 // 4 Bits

	// CountryBaseMask is the maximum mask used for country IDs.
	CountryBaseMask = 0b1111_0000 // 4 Bits (up to)

	// Further Prefix Bit Sizes.
	ContinentPrefixBits = 12
	RegionPrefixBits    = 16
)

Base Masks.

View Source
const (
	TypeRoutingAddress = 0b0000_0000
	TypePrivacyAddress = 0b1000_0000
)

Address Type Markers (1 Bit).

View Source
const (
	// Eurafria.
	ContinentSpecial = 0b000_0000
	ContinentEurope  = 0b001_0000 // EU
	// --.
	ContinentAfrica   = 0b010_0000 // AF
	ContinentWestAsia = 0b011_0000 // WA

	// Pacific.
	ContinentNorthAmerica = 0b100_0000 // NA
	ContinentSouthAmerica = 0b101_0000 // SA
	// --.
	ContinentOceania  = 0b110_0000 // OC
	ContinentEastAsia = 0b111_0000 // EA
)

Continent Markers (3 Bits).

View Source
const (
	// RoamingMarker may be used if the location is unknown or is expected to change.
	// Bad routing performance is expected.
	RoamingMarker = 0b0000_0000

	// OrganizationMarker designates an organizational network.
	OrganizationMarker = 0b0000_0001
	// OrganizationBits is the org ID length in bits that addresses of the same organisation should share.
	// A full Organization Prefix would then be /32.
	OrganizationBits = 16

	// AnycastMarker designates an anycast network.
	AnycastMarker = 0b0000_1110
	// AnycastBits is the anycast network ID length in bits that addresses of the same anycast network should share.
	// A full Anycast Prefix would then be /32.
	AnycastBits = 16

	// ExperimentsMarker is a address marker for testing.
	// May not be handled well by production routers.
	ExperimentsMarker = 0b0000_1111
)

Special "Region" Markers (4 Bits).

View Source
const (
	MaxRoutableSwitchLabel = 127   // Fits into 1 byte varint
	MaxPrivateSwitchLabel  = 16383 // Fits into 2 byte varint

	MinHopDelay = 5 // In milliseconds.
)

Max Switch Label Sizes.

Variables

View Source
var (
	// APIAddress is the address used to connect to the local API.
	// It is only accessible from the tun interface.
	APIAddress = netip.MustParseAddr("fd00::1")

	// ServiceAddress is the address used to connect to the public service API.
	// It is available both from the tun interface and the network.
	ServiceAddress = netip.MustParseAddr("fd00::2")

	// RouterAddress is the address used to send multicast messages to other routers.
	RouterAddress = netip.MustParseAddr("fd00::4")
)
View Source
var (
	RoutingAddressPrefix = MustPrefix([]byte{BaseNet, TypeRoutingAddress}, 9)
	PrivacyAddressPrefix = MustPrefix([]byte{BaseNet, TypePrivacyAddress}, 9)
)

Address Type Prefixes (1 Bit).

Special "Region" Prefixes.

View Source
var (
	ErrBufTooSmall = errors.New("varint: buf too small")
	ErrValueTooBig = errors.New("varint: value too big")
)

Switch Label Errors.

View Source
var BaseNetPrefix = MustPrefix([]byte{BaseNet}, 8)

BaseNetPrefix is the base prefix for all addresses.

View Source
var (
	ErrMaxTriesReached = errors.New("maximum tries to generate address reached")
)

Errors.

View Source
var ErrNotFound = errors.New("not found")

ErrNotFound is return when a country is not found.

Functions

func DigestToAddress

func DigestToAddress(digestAlg Hash, keyToolID string, pubKeyData []byte) (ip netip.Addr, err error)

DigestToAddress derives an IP address from the given parameters.

func GetCountryPrefix added in v0.1.0

func GetCountryPrefix(countryCode string) (prefix netip.Prefix, err error)

GetCountryPrefix returns a prefix with a country geo marker for the given country code. The US country code requires the US state code to appended, splitted by a dash.

func GetDataBlock

func GetDataBlock(data []byte) (n int, block []byte, err error)

GetDataBlock returns the varint-length-prefixes data block at the start of the given data slice. It returns how many bytes were read and a slice reference to the block.

func GetRandomPrivatePort

func GetRandomPrivatePort() (uint16, error)

GetRandomPrivatePort returns a random private port to use.

func GetUint16

func GetUint16(b []byte) uint16

GetUint16 returns a uint16 from the first two bytes of the given byte slice.

func GetUint32

func GetUint32(b []byte) uint32

GetUint32 returns a uint32 from the first four bytes of the given byte slice.

func GetUint64

func GetUint64(b []byte) uint64

GetUint64 returns a uint64 from the first eight bytes of the given byte slice.

func MakeBaseIP

func MakeBaseIP(prefix []byte) netip.Addr

MakeBaseIP creates an IP address from the given prefix bytes.

func MakePrefix

func MakePrefix(prefix []byte, bits int) (netip.Prefix, error)

MakePrefix creates an IP prefix from the given bytes and bit length.

func MustPrefix

func MustPrefix(prefix []byte, bits int) netip.Prefix

MustPrefix creates an IP prefix and panics if it fails.

func PutDataBlock

func PutDataBlock(dst []byte, src []byte) (n int, err error)

PutDataBlock encodes the src data to dst with a varint-length-prefix. It returns how many bytes were written.

func PutUint16

func PutUint16(dst []byte, src uint16)

PutUint16 writes the uint16 to the first two bytes of the given byte slice.

func PutUint32

func PutUint32(dst []byte, src uint32)

PutUint32 writes the uint32 to the first four bytes of the given byte slice.

func PutUint64

func PutUint64(dst []byte, src uint64)

PutUint64 writes the uint64 to the first eight bytes of the given byte slice.

func SafeString added in v0.4.0

func SafeString(s string) string

SafeString returns the given ascii string cleaned from potentially disruptive characters. The readability of the result is not great. It's not meant for general use, but to be able to print or log untrusted input with some safety.

func SortPeeringURLs

func SortPeeringURLs(urls []*PeeringURL)

SortPeeringURLs sorts the peering URls to emphasize certain protocols and get a stable representation.

func TransformToReturnBlock

func TransformToReturnBlock(block []byte)

TransformToReturnBlock transform the given block to a return block that takes the exact route it came from.

func VerifyAddressKey

func VerifyAddressKey(ip netip.Addr, digestAlg Hash, keyType string, pubKeyData []byte) error

VerifyAddressKey checks if the given IP address matches the digest of the given key type and data.

Types

type AddrDistance

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

AddrDistance holds the address distance between two IPv6s.

func IPDistance

func IPDistance(a, b netip.Addr) AddrDistance

IPDistance returns the IP distance of the given addresses.

func MaxAddrDistance added in v0.1.0

func MaxAddrDistance() AddrDistance

MaxAddrDistance return the maximum address distance.

func ZeroAddrDistance added in v0.1.0

func ZeroAddrDistance() AddrDistance

ZeroAddrDistance returns an address distance of zero.

func (AddrDistance) Compare

func (a AddrDistance) Compare(b AddrDistance) int

Compare returns an integer comparing two IP distances.

func (AddrDistance) IsZero

func (a AddrDistance) IsZero() bool

IsZero reports whether the IP distance is zero.

func (AddrDistance) Less

func (a AddrDistance) Less(b AddrDistance) bool

Less reports whether the IP distance (a) sorts before the given IP distance (b).

type Address

type Address struct {
	PublicAddress `cbor:"-" json:"-" yaml:"-"` // Prevent serializing.

	PrivateKey ed25519.PrivateKey `cbor:"-" json:"-" yaml:"-"` // Prevent serializing.
}

Address is an address with the associated private key.

func AddressFromStorage

func AddressFromStorage(s AddressStorage) (*Address, error)

AddressFromStorage loads and verifies an address from storage.

func GeneratePrivacyAddress

func GeneratePrivacyAddress(ctx context.Context) (*Address, int, error)

GeneratePrivacyAddress generates a new privacy address.

func GenerateRoutableAddress

func GenerateRoutableAddress(ctx context.Context, acceptablePrefixes []netip.Prefix) (*Address, int, error)

GenerateRoutableAddress generates a new routable address within the given acceptable prefixes.

func (*Address) Sign

func (addr *Address) Sign(data []byte) (sig []byte)

Sign signs the given data with the address private key.

func (*Address) SignWithContext

func (addr *Address) SignWithContext(data, context []byte) (sig []byte, err error)

SignWithContext signs the given data and context with the address private key.

func (*Address) Store

func (addr *Address) Store() AddressStorage

Store returns the address in a storable format.

type AddressStorage

type AddressStorage struct {
	IP         string `json:"ip,omitempty"      yaml:"ip,omitempty"`
	Hash       string `json:"hash,omitempty"    yaml:"hash,omitempty"`
	Type       string `json:"type,omitempty"    yaml:"type,omitempty"`
	PublicKey  string `json:"public,omitempty"  yaml:"public,omitempty"`
	PrivateKey string `json:"private,omitempty" yaml:"private,omitempty"`
}

AddressStorage is an address in a storable format.

type AddressType

type AddressType uint8

AddressType represents an address type.

const (
	TypeInvalid AddressType = iota
	TypeReserved
	TypePrivacy
	TypeGeoMarked
	TypeRoaming
	TypeOrganization
	TypeAnycast
	TypeExperiment
	TypeInternal
)

Address Types.

func GetAddressType

func GetAddressType(ip netip.Addr) AddressType

GetAddressType returns the address type of the IP.

func (AddressType) RoutingPrefixLength

func (at AddressType) RoutingPrefixLength() int

RoutingPrefixLength returns the base routing prefix length of the address type.

func (AddressType) String

func (at AddressType) String() string

type CountryGeoMarking added in v0.1.0

type CountryGeoMarking struct {
	ContinentCode string
	RegionCode    string

	CountryMarker     uint8
	CountryMarkerBits uint8
}

CountryGeoMarking defines the geo marker for a country.

func (CountryGeoMarking) BaseIP added in v0.1.0

func (cgm CountryGeoMarking) BaseIP() netip.Addr

BaseIP returns the base IP of the country marker.

func (CountryGeoMarking) Prefix added in v0.1.0

func (cgm CountryGeoMarking) Prefix() (netip.Prefix, error)

Prefix returns the prefix of the country marker.

type CountryMarkerLookup added in v0.1.0

type CountryMarkerLookup struct {
	BaseIP    netip.Addr
	Prefix    netip.Prefix
	Continent string
	Region    string
	Country   string
}

CountryMarkerLookup holds country geo marker information.

func LookupCountryMarker added in v0.1.0

func LookupCountryMarker(ip netip.Addr) (*CountryMarkerLookup, error)

LookupCountryMarker return the country geo marker information of the given IP.

type Hash

type Hash string

Hash is a hash algorithm.

const (
	// SHA2.
	SHA2_224     Hash = "SHA2_224"
	SHA2_256     Hash = "SHA2_256"
	SHA2_384     Hash = "SHA2_384"
	SHA2_512     Hash = "SHA2_512"
	SHA2_512_224 Hash = "SHA2_512_224"
	SHA2_512_256 Hash = "SHA2_512_256"

	// SHA3.
	SHA3_224 Hash = "SHA3_224"
	SHA3_256 Hash = "SHA3_256"
	SHA3_384 Hash = "SHA3_384"
	SHA3_512 Hash = "SHA3_512"

	// BLAKE2.
	BLAKE2s_256 Hash = "BLAKE2s_256"
	BLAKE2b_256 Hash = "BLAKE2b_256"
	BLAKE2b_384 Hash = "BLAKE2b_384"
	BLAKE2b_512 Hash = "BLAKE2b_512"

	// BLAKE3.
	BLAKE3 Hash = "BLAKE3"
)

Hashes

func (Hash) Digest

func (h Hash) Digest(data []byte) []byte

Digest calculate and returns the hash sum over the given data.

func (Hash) IsValid

func (h Hash) IsValid() bool

IsValid returns whether the hash is known.

func (Hash) New

func (h Hash) New() hash.Hash

New returns a new hash.Hash.

type PeeringURL

type PeeringURL struct {
	Protocol string
	Domain   string
	Port     uint16
	Path     string
	Option   string
}

PeeringURL represents a peering point that others can connect to.

func ParsePeeringURL

func ParsePeeringURL(definition string) (*PeeringURL, error)

ParsePeeringURL parses a peering URL.

func ParsePeeringURLs

func ParsePeeringURLs(definitions []string) (urls []*PeeringURL, errs []error)

ParsePeeringURLs returns a list of parsed peering URLs and errors from parsing.

func (*PeeringURL) FormatWith

func (p *PeeringURL) FormatWith(host string) string

FormatWith formats the peering URL with the given host.

func (*PeeringURL) String

func (p *PeeringURL) String() string

String returns the definition form of the peering URL.

type PublicAddress

type PublicAddress struct {
	IP        netip.Addr        `cbor:"i,omitempty" json:"ip,omitempty"   yaml:"ip,omitempty"`
	Hash      Hash              `cbor:"h,omitempty" json:"hash,omitempty" yaml:"hash,omitempty"`
	Type      string            `cbor:"t,omitempty" json:"type,omitempty" yaml:"type,omitempty"`
	PublicKey ed25519.PublicKey `cbor:"k,omitempty" json:"key,omitempty"  yaml:"key,omitempty"`
}

PublicAddress is the public part of an address in a shareable form.

func (*PublicAddress) VerifyAddress

func (addr *PublicAddress) VerifyAddress() error

VerifyAddress check if the address is a mycoria IP and calls VerifyAddressKey.

func (*PublicAddress) VerifySig

func (addr *PublicAddress) VerifySig(data, sig []byte) (ok bool)

VerifySig verifies the given data and signature.

func (*PublicAddress) VerifySigWithContext

func (addr *PublicAddress) VerifySigWithContext(data, sig, context []byte) error

VerifySigWithContext verifies the given data and signature.

type RoutablePrefix

type RoutablePrefix struct {
	// BasePrefix is the prefix for which these settings should apply.
	BasePrefix netip.Prefix

	// RoutingBits is the length of the bitmask with which to create the routing
	// prefix for the table entry.
	RoutingBits int

	// EntryTTL is the entry TTL for entries in this prefix.
	EntryTTL time.Duration

	// EntriesPerPrefix defines how many routing entries to keep per
	// identical routing prefix.
	EntriesPerPrefix int
}

RoutablePrefix configures how routing entries of a defined base prefix should be handled.

func GetRoutablePrefixesFor

func GetRoutablePrefixesFor(myIP netip.Addr, myPrefix netip.Prefix) []RoutablePrefix

GetRoutablePrefixesFor returns the routable prefix for the given own IP as well as the own prefix.

type RouteSource

type RouteSource uint8

RouteSource is the source of a route.

const (
	// Source not known or not defined.
	RouteSourceUnknown RouteSource = iota

	// Directly connected.
	// Entries are never auto-cleared.
	RouteSourcePeer

	// Route to other network that was learned through gossip.
	// Entries are automatically removed after expiry or when abundant.
	RouteSourceGossip

	// Discovered by active probing (for own use).
	// Entries are automatically removed after expiry.
	RouteSourceDiscovered
)

Route Sources.

func (RouteSource) String

func (s RouteSource) String() string

type RouterInfo

type RouterInfo struct {
	Version string `cbor:"v,omitempty" json:"version,omitempty" yaml:"version,omitempty"`

	Listeners []string `cbor:"l,omitempty" json:"listeners,omitempty" yaml:"listeners,omitempty"`
	IANA      []string `cbor:"i,omitempty" json:"iana,omitempty"      yaml:"iana,omitempty"`

	PublicServices []RouterService `cbor:"srv,omitempty" json:"publicServices,omitempty" yaml:"publicServices,omitempty"`
}

RouterInfo holds information about a router.

type RouterService

type RouterService struct {
	Name        string `cbor:"n,omitempty"   json:"name,omitempty"        yaml:"name,omitempty"`
	Description string `cbor:"d,omitempty"   json:"description,omitempty" yaml:"description,omitempty"`
	Domain      string `cbor:"dns,omitempty" json:"domain,omitempty"      yaml:"domain,omitempty"`
	URL         string `cbor:"url,omitempty" json:"url,omitempty"         yaml:"url,omitempty"`
}

RouterService describes a service offered by a router.

type RoutingTable

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

RoutingTable is a routing table.

func NewRoutingTable

func NewRoutingTable(cfg RoutingTableConfig) *RoutingTable

NewRoutingTable returns a new routing table with the given config.

func (*RoutingTable) AddRoute

func (rt *RoutingTable) AddRoute(entry RoutingTableEntry) (added bool, err error)

AddRoute adds the given route to the routing table.

func (*RoutingTable) Clean

func (rt *RoutingTable) Clean()

Clean cleans the routing table from unneeded entries: - Removes expired routes. - Removes excess routes of identical routing prefixes.

func (*RoutingTable) Format

func (rt *RoutingTable) Format() string

Format formats the routing table for printing it. Warning: Acquires a write lock!

func (*RoutingTable) LookupNearest

func (rt *RoutingTable) LookupNearest(dst netip.Addr) (rte *RoutingTableEntry, isDestination bool)

LookupNearest returns the best matching table entry for the given destination.

func (*RoutingTable) LookupPossiblePaths

func (rt *RoutingTable) LookupPossiblePaths(dst netip.Addr, maxMatches int, maxDistance AddrDistance, distinctNextHop bool, avoid []netip.Addr) []*RoutingTableEntry

LookupPossiblePaths looks the best possible entires for the given destination.

func (*RoutingTable) RemoveDisconnected added in v0.4.0

func (rt *RoutingTable) RemoveDisconnected(router netip.Addr, disconnected []netip.Addr) (removed int)

RemoveDisconnected removes all routes with the given disconnected peerings. If disconnected is empty, all routes including the router are removed.

func (*RoutingTable) RemoveNextHop

func (rt *RoutingTable) RemoveNextHop(ip netip.Addr) (removed int)

RemoveNextHop removes all routes with the given next hop IP from the routing table.

type RoutingTableConfig

type RoutingTableConfig struct {
	// RoutablePrefixes defines for which prefixes routes should be held and in
	// what detail. This only applies to entries sourced from gossip.
	RoutablePrefixes []RoutablePrefix

	// RouterIP is ip address of router of the routing table.
	RouterIP netip.Addr
}

RoutingTableConfig holds the configuration for a routing table.

type RoutingTableEntry

type RoutingTableEntry struct {
	DstIP         netip.Addr
	RoutingPrefix netip.Prefix

	NextHop netip.Addr
	Path    SwitchPath

	Source  RouteSource
	Expires time.Time
}

RoutingTableEntry represents an entry in the routing table. All fields must be treated as constants.

func (*RoutingTableEntry) RouteEquals added in v0.3.0

func (a *RoutingTableEntry) RouteEquals(b *RoutingTableEntry) bool

RouteEquals returns whether the routes match.

type SwitchHop

type SwitchHop struct {
	Router       netip.Addr  `json:"router,omitempty"       yaml:"router,omitempty"`
	Delay        uint16      `json:"delay,omitempty"        yaml:"delay,omitempty"` // In milliseconds.
	ForwardLabel SwitchLabel `json:"forwardLabel,omitempty" yaml:"forwardLabel,omitempty"`
	ReturnLabel  SwitchLabel `json:"returnLabel,omitempty"  yaml:"returnLabel,omitempty"`
}

SwitchHop descibes a single hop in a path.

type SwitchLabel

type SwitchLabel uint16

SwitchLabel is used to identify an interface on a router.

func DeriveSwitchLabelFromIP

func DeriveSwitchLabelFromIP(ip netip.Addr) (label SwitchLabel, ok bool)

DeriveSwitchLabelFromIP derives a switch label from the given IP and reports whether it was able to do so.

func GetRandomSwitchLabel

func GetRandomSwitchLabel(forRoutableAddress bool) (label SwitchLabel, ok bool)

GetRandomSwitchLabel generate a random switch label.

func NextRotateSwitchBlock

func NextRotateSwitchBlock(block []byte, returnLabel SwitchLabel) (nextHop SwitchLabel, err error)

NextRotateSwitchBlock extracts the next switch label and rotates the block so it can be reversed by the destination.

func (SwitchLabel) EncodedSize

func (sl SwitchLabel) EncodedSize() int

EncodedSize returns the number of bytes needed to encode the switch label.

type SwitchPath

type SwitchPath struct {
	Hops         []SwitchHop `json:"hops,omitempty"         yaml:"hops,omitempty"`
	ForwardBlock []byte      `json:"forwardBlock,omitempty" yaml:"forwardBlock,omitempty"`
	ReturnBlock  []byte      `json:"returnBlock,omitempty"  yaml:"returnBlock,omitempty"`

	TotalDelay uint16 `json:"totalDelay,omitempty" yaml:"totalDelay,omitempty"` // In milliseconds.
	TotalHops  uint8  `json:"totalHops,omitempty"  yaml:"totalHops,omitempty"`
}

SwitchPath describes a path through the network using switch labels.

func (*SwitchPath) BuildBlocks

func (sp *SwitchPath) BuildBlocks() error

BuildBlocks builds the forward and return switch label blocks from the path.

func (*SwitchPath) CalculateBlockSize

func (sp *SwitchPath) CalculateBlockSize() (int, error)

CalculateBlockSize calculates the maximum needed block size in the whole path.

func (*SwitchPath) CalculateTotals

func (sp *SwitchPath) CalculateTotals()

CalculateTotals calculates the total values of the switch path.

Jump to

Keyboard shortcuts

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