bgp

package
v0.0.0-...-77fc429 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	IPv4Unicast = Family(bgp.AFI_IP)<<16 | Family(bgp.SAFI_UNICAST)
	IPv6Unicast = Family(bgp.AFI_IP6)<<16 | Family(bgp.SAFI_UNICAST)
)
View Source
const (
	// DefaultLocalPreference is the default value of the local preference
	// for routes that do not specify one.
	DefaultLocalPreference uint32 = 100
)
View Source
const (

	// LevelUpdates is a log level between INFO and DEBUG, used for high volume
	// events associated with BGP UPDATE messages (announcements and withdrawals).
	LevelUpdates slog.Level = -2
)

Variables

View Source
var ErrDiscard = errors.New("discard")

ErrDiscard is returned by filters that have made an explicit decision to discard a path.

Functions

func Compare

func Compare(a, b Attributes) int

Compare decides which attributes represent the better route. It returns a negative number if a is better than b, a positive number if b is better than a, and zero if a and b are equally good. Better routes are identified by:

  • Local preference (higher values first)
  • AS path length (shorter paths first)
  • MED (lower values first)

func WatchBest

func WatchBest(t ...*Table) iter.Seq2[netip.Prefix, Attributes]

WatchBest returns an infinite iterator that yields the best route for each network in each table. The disappearance of a route is signaled with a zero value Attributes.

func WatchBestMultiPath

func WatchBestMultiPath(t ...*Table) iter.Seq2[netip.Prefix, []Attributes]

WatchBestMultiPath returns an infinite iterator that yields the best multipath routes for each network in each table. A multipath route is comprised of a set of routes on which the Compare function returns zero. The disappearance of a route is signaled with an empty slice of Attributes.

Types

type Attributes

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

Attributes is the information associated with a route. Attributes are comparable and may be used as keys in a map.

func (*Attributes) ClearLocalPref

func (a *Attributes) ClearLocalPref()

ClearLocalPref clears the local preference. See the documentation for the LocalPref method to see how this is used.

func (*Attributes) ClearMED

func (a *Attributes) ClearMED()

ClearMED clears the multi exit discriminator. See the documentation for the MED method to see how this is used.

func (Attributes) Communities

func (a Attributes) Communities() map[Community]bool

Communities returns the BGP communities as defined by https://datatracker.ietf.org/doc/html/rfc1997.

func (Attributes) ExtendedCommunities

func (a Attributes) ExtendedCommunities() map[ExtendedCommunity]bool

ExtendedCommunities returns the BGP communities as defined by https://datatracker.ietf.org/doc/html/rfc4360.

NOTE: This is experimental. See the ExtendedCommunity type for details.

func (Attributes) First

func (a Attributes) First() uint32

First returns the first AS in the path (corresponding to the nexthop).

func (Attributes) LargeCommunities

func (a Attributes) LargeCommunities() map[LargeCommunity]bool

LargeCommunities returns the BGP large communities as defined by https://datatracker.ietf.org/doc/html/rfc8092

func (Attributes) LocalPref

func (a Attributes) LocalPref() (uint32, bool)

LocalPref returns the local preference, a priority for the route that is considered prior to the AS path length. Higher values are more preferred. If absent, a default value of 100 is returned and the boolean will be false. The local preference is used in best path computations and may be set by an import filter, but is not imported from or exported to peers (eBGP semantics).

func (Attributes) MED

func (a Attributes) MED() (uint32, bool)

MED returns the multi exit discriminator, which specifies a priority that is used to break a tie between two routes with the same AS path length and same first AS in the path. Lower values are more preferred. The default is zero. MED is imported from peers if they provide it, and cleared by the default export filter (eBGP semantics).

func (Attributes) Nexthop

func (a Attributes) Nexthop() netip.Addr

Nexthop returns the IP neighbor where packets traversing the route should be sent. It's commonly equal to the peer address, but can differ e.g. if the peer is a route server.

func (Attributes) Origin

func (a Attributes) Origin() uint32

Origin returns the ASN originating the route.

func (Attributes) Path

func (a Attributes) Path() []uint32

Path returns AS path. The first element is the nexthop and the last element is the route's origin.

func (Attributes) PathContains

func (a Attributes) PathContains(asn uint32) bool

PathContains checks whether an AS is present in the path.

func (*Attributes) PathLen

func (a *Attributes) PathLen() int

PathLen returns the length of the AS path.

func (Attributes) Peer

func (a Attributes) Peer() netip.Addr

Peer returns the BGP peer from which the route was received.

func (*Attributes) Prepend

func (a *Attributes) Prepend(asns ...uint32)

Prepend inserts ASNs to the beginning of the path.

func (*Attributes) SetCommunities

func (a *Attributes) SetCommunities(cs map[Community]bool)

SetCommunities sets the BGP communities as defined by https://datatracker.ietf.org/doc/html/rfc1997.

func (*Attributes) SetExtendedCommunities

func (a *Attributes) SetExtendedCommunities(cs map[ExtendedCommunity]bool)

SetExtendedCommunities sets the BGP communities as defined by https://datatracker.ietf.org/doc/html/rfc4360.

NOTE: This is experimental. See the ExtendedCommunity type for details.

func (*Attributes) SetLargeCommunities

func (a *Attributes) SetLargeCommunities(cs map[LargeCommunity]bool)

SetLargeCommunities sets the BGP communities as defined by https://datatracker.ietf.org/doc/html/rfc8092

func (*Attributes) SetLocalPref

func (a *Attributes) SetLocalPref(v uint32)

SetLocalPref sets the local preference. See the documentation for the LocalPref method to see how this is used.

func (*Attributes) SetMED

func (a *Attributes) SetMED(v uint32)

SetMED sets the multi exit discriminator. See the documentation for the MED method to see how this is used.

func (*Attributes) SetNexthop

func (a *Attributes) SetNexthop(nh netip.Addr)

SetNexthop sets IP neighbor where packets traversing the route should be sent.

func (*Attributes) SetPath

func (a *Attributes) SetPath(asns []uint32)

SetPath replaces the AS path. The first element is the nexthop and the last element is the route's origin.

func (*Attributes) SetPeer

func (a *Attributes) SetPeer(peer netip.Addr)

SetPeer sets the BGP peer from which the route was received.

func (Attributes) String

func (a Attributes) String() string

String returns a human readable representation of a few key attributes.

type Community

type Community struct {
	Origin uint16
	Value  uint16
}

Community is a BGP community as defined in https://datatracker.ietf.org/doc/html/rfc1997.

func NewCommunity

func NewCommunity(c uint32) Community

NewCommunity creates a community from its numeric representation.

func ParseCommunity

func ParseCommunity(c string) (Community, error)

ParseCommunity parses a community from a string like "64512:1".

func (Community) String

func (c Community) String() string

String converts a community to a colon separated string like "64512:1".

func (Community) Uint32

func (c Community) Uint32() uint32

Uint32 converts a community to its numeric representation.

type ExtendedCommunity

type ExtendedCommunity uint64

ExtendedCommunity is a BGP Extended Community as defined in https://datatracker.ietf.org/doc/html/rfc4360.

NOTE: Support for extended communities is experimental and subject to change. Extended communities are not widely used on the internet and several details of this implementation were determined empirically from a handful of routes. If you need this and are able to contribute either code or expertise, please open an issue on GitHub.

func (ExtendedCommunity) String

func (c ExtendedCommunity) String() string

String returns a human-readable string. The format is subject to change.

type Family

type Family uint32

func FamilyFor

func FamilyFor(a netip.Addr) Family

func NewFamily

func NewFamily(afi uint16, safi uint8) Family

func (Family) Split

func (f Family) Split() (uint16, uint8)

func (Family) String

func (f Family) String() string

type Filter

type Filter func(nlri netip.Prefix, attrs Attributes) (Attributes, error)

A Filter is a function that runs on import or export of a route.

If a filter returns success, it must also return a valid Attributes, possibly modifying the provided one. An example modification is an export filter changing the nexthop to the local host.

A filter may return ErrDiscard to terminate the evaluation of the filter chain and prevent the path from being imported or exported.

type LargeCommunity

type LargeCommunity struct {
	ASN, Data1, Data2 uint32
}

LargeCommunity is a BGP large community as defined in https://datatracker.ietf.org/doc/html/rfc8092

func ParseLargeCommunity

func ParseLargeCommunity(c string) (LargeCommunity, error)

ParseLargeCommunity parses a large community from a string like "64512:1:2".

func (LargeCommunity) LessThan

func (a LargeCommunity) LessThan(b LargeCommunity) bool

LessThan returns whether a sorts ahead of b.

func (LargeCommunity) String

func (c LargeCommunity) String() string

String converts a community to a colon separated string like "64512:1:2".

type Peer

type Peer struct {
	// Addr is the address of the peer. This is required.
	Addr netip.Addr
	// Port is the port on which the peer listens.
	// If not set, port 179 is assumed.
	Port int
	// Passive inhibits dialing the peer. The local server will still
	// listen for incomming connections from the peer.
	Passive bool

	// LocalAddr is the local address.
	LocalAddr netip.Addr

	// ASN is the expected ASN of the peer.
	// If present, it will be verified upon connection establishment and the
	// default import filter will only accept routes with a matching first AS.
	ASN uint32

	// Import stores the network reachability information received from the peer.
	//
	// You must initialize this to contain a non-nil table for each route family
	// that you want to accept from the peer, prior to adding the peer to a
	// server. The map must not be manipulated after adding the peer, but network
	// paths may be added and removed from a table at any time.
	//
	// Tables may be safely shared across multiple peers or by import and export
	// use cases.
	Import map[Family]*Table

	// Export stores the network reachability information to be announced to the
	// peer. See the documentation on Import for usage details.
	Export map[Family]*Table

	// ImportFilter decides whether to import a route into the import table and
	// optionally modifies it. If not provided, the DefaultImportFilter method
	// is used.
	ImportFilter Filter

	// ExportFilter decides whether to export a route to the peer and optionally
	// modifies it. If not provided, the DefaultExportFilter method is used.
	//
	// Filter decisions are cached. To force a reevaluation, call ResetExportCache
	// after any filter policy changes.
	ExportFilter Filter

	// Timers holds optional parameters to control the hold time and keepalive of
	// the BGP session.
	Timers *Timers

	// DialerControl is called after creating the network connection but
	// before actually dialing. See https://pkg.go.dev/net#Dialer.Control
	// for background. To configure TCP MD5 authentication, set it to
	// tcpmd5.DialerControl("password").
	DialerControl func(network, address string, c syscall.RawConn) error

	// ConfigureListener is called for each of the server's listeners upon
	// adding the peer. To configure TCP MD5 authentication, set it to
	// tcpmd5.ConfigureListener("2001:db8::1234", "password"), making
	// sure that the IP address matches the one in Addr.
	ConfigureListener func(l net.Listener) error
	// contains filtered or unexported fields
}

A Peer is a BGP neighbor.

func (*Peer) DefaultExportFilter

func (p *Peer) DefaultExportFilter(prefix netip.Prefix, attrs Attributes) (Attributes, error)

DefaultExportFilter is the default filter when no ExportFilter is provided. It implements the policy:

  • Discard routes with the "no export" well known community
  • Prepend the local ASN to the AS path
  • Change the nexthop to the local IP of the peering session
  • Clear the MED (multi exit discriminator)

func (*Peer) DefaultImportFilter

func (p *Peer) DefaultImportFilter(nlri netip.Prefix, attrs Attributes) (Attributes, error)

DefaultImportFilter is the default filter when no ImportFilter is provided. It discards routes if the AS path:

  • Contains the local ASN
  • Has a first AS not matching p.ASN (but if p.ASN==0, accept any first AS)

func (*Peer) ResetExportCache

func (p *Peer) ResetExportCache()

ResetExportCache clears any cached decisions made by the export filter. This may be called to reevaluate previously announced (or suppressed) routes if the filter policy has changed.

type Server

type Server struct {
	// Hostname is the server's short name. If present, it will be announced to
	// peers via the FQDN capability.
	Hostname string
	// Domainname is the server's domain. If present, it will be announced to
	// peers via the FQDN capability.
	Domainname string
	// RouterID is a unique identifier for this router within its AS. You must
	// populate this with a 32-bit number formatted as an IPv4 address.
	RouterID string
	// ASN is the autonomous system number. This is required.
	ASN uint32
	// CreatePeer is called when an incomming connection doesn't match any
	// predefined peer. If this function is non-nil and returns a non-error, the
	// connection will be accepted using the dynamically created peer. Dynamic
	// peers are destroyed when their TCP connection is closed.
	CreatePeer func(localAddr, remoteAddr netip.Addr, conn net.Conn) (*Peer, error)
	// Logger is an optional structured logger.
	// For simple use-cases, set it to slog.Default().
	Logger *slog.Logger
	// contains filtered or unexported fields
}

Server is a BGP server.

func (*Server) AddPeer

func (s *Server) AddPeer(p *Peer) error

AddPeer adds a peer.

Peers that are added to a non-running server will be held idle until Serve is called. Peers that are added after the first call to Serve will immediately have their state machine start running.

func (*Server) Close

func (s *Server) Close() error

Close terminates the server and closes all listeners. It does not wait for peering connections to be closed; to do that call Shutdown instead.

func (*Server) RemovePeer

func (s *Server) RemovePeer(peer netip.Addr) error

RemovePeer removes a peer.

func (*Server) Serve

func (s *Server) Serve(l net.Listener) error

Serve runs the BGP protocol. A listener is optional, and multiple listeners can be provided by calling Serve concurrently in several goroutines. All concurrent calls to Serve block until a single call to Shutdown or Close is made.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown terminates the server and closes all listeners. It waits for all peering connections to be closed before returning.

type Table

type Table struct {
	// Compare decides which attributes represent the better route.
	// If nil, the package level Compare function is used.
	Compare func(a, b Attributes) int
	// contains filtered or unexported fields
}

A Table is a set of networks that each have a distinct NLRI.

func (*Table) AddPath

func (t *Table) AddPath(nlri netip.Prefix, a Attributes)

AddPath adds a path to the given network. It replaces any previously added path from the same peer.

func (*Table) AllRoutes

func (t *Table) AllRoutes() iter.Seq2[netip.Prefix, Attributes]

AllRoutes returns an iterator that yields all the routes for every network.

func (*Table) RemovePath

func (t *Table) RemovePath(nlri netip.Prefix, peer netip.Addr)

RemovePath removes the path that goes via the specified peer. It is safe to call even if no path from the peer is present.

func (*Table) Routes

func (t *Table) Routes(nlri netip.Prefix) iter.Seq[Attributes]

Routes returns an iterator that yields all the routes for one network.

type Timers

type Timers struct {
	HoldTime          time.Duration
	KeepAliveInterval time.Duration
	KeepAliveFuzz     time.Duration
}

func (*Timers) NextKeepAlive

func (t *Timers) NextKeepAlive() time.Duration

Jump to

Keyboard shortcuts

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