Documentation
¶
Overview ¶
Package vnet provides a virtual network layer for pion
Index ¶
- Constants
- Variables
- type Chunk
- type ChunkFilter
- type DelayFilter
- type DuplicationFilter
- type DuplicationOption
- func WithDuplicationBurstDuration(duration time.Duration) DuplicationOption
- func WithDuplicationBurstMultiplier(multiplier float64) DuplicationOption
- func WithDuplicationBurstProbability(prob float64) DuplicationOption
- func WithDuplicationExtraDelay(minDelay, maxDelay time.Duration) DuplicationOption
- func WithDuplicationImmediate() DuplicationOption
- func WithDuplicationProbability(prob float64) DuplicationOption
- func WithDuplicationSeed(seed int64) DuplicationOption
- type EndpointDependencyType
- type LossFilter
- type LossFilterHandler
- type LossFilterOption
- type NATMode
- type NATType
- type NIC
- type Net
- func (v *Net) CreateDialer(d *net.Dialer) transport.Dialer
- func (v *Net) Dial(network string, address string) (net.Conn, error)
- func (v *Net) DialTCP(string, *net.TCPAddr, *net.TCPAddr) (transport.TCPConn, error)
- func (v *Net) DialUDP(network string, locAddr, remAddr *net.UDPAddr) (transport.UDPConn, error)
- func (v *Net) InterfaceByIndex(index int) (*transport.Interface, error)
- func (v *Net) InterfaceByName(ifName string) (*transport.Interface, error)
- func (v *Net) Interfaces() ([]*transport.Interface, error)
- func (v *Net) ListenPacket(network string, address string) (net.PacketConn, error)
- func (v *Net) ListenTCP(string, *net.TCPAddr) (transport.TCPListener, error)
- func (v *Net) ListenUDP(network string, locAddr *net.UDPAddr) (transport.UDPConn, error)
- func (v *Net) ResolveIPAddr(_, address string) (*net.IPAddr, error)
- func (v *Net) ResolveTCPAddr(network, address string) (*net.TCPAddr, error)
- func (v *Net) ResolveUDPAddr(network, address string) (*net.UDPAddr, error)
- type NetConfig
- type Router
- func (r *Router) AddChildRouter(router *Router) error
- func (r *Router) AddChunkFilter(filter ChunkFilter)
- func (r *Router) AddHost(hostName string, ipAddr string) error
- func (r *Router) AddNet(nic NIC) error
- func (r *Router) AddRouter(router *Router) error
- func (r *Router) Start() error
- func (r *Router) Stop() error
- type RouterConfig
- type TBFOption
- type TokenBucketFilter
- type UDPConn
- func (c *UDPConn) Close() error
- func (c *UDPConn) LocalAddr() net.Addr
- func (c *UDPConn) Read(b []byte) (int, error)
- func (c *UDPConn) ReadFrom(p []byte) (n int, addr net.Addr, err error)
- func (c *UDPConn) ReadFromUDP(b []byte) (int, *net.UDPAddr, error)
- func (c *UDPConn) ReadMsgUDP([]byte, []byte) (n, oobn, flags int, addr *net.UDPAddr, err error)
- func (c *UDPConn) RemoteAddr() net.Addr
- func (c *UDPConn) SetDeadline(t time.Time) error
- func (c *UDPConn) SetReadBuffer(int) error
- func (c *UDPConn) SetReadDeadline(t time.Time) error
- func (c *UDPConn) SetWriteBuffer(int) error
- func (c *UDPConn) SetWriteDeadline(time.Time) error
- func (c *UDPConn) Write(b []byte) (int, error)
- func (c *UDPConn) WriteMsgUDP([]byte, []byte, *net.UDPAddr) (n, oobn int, err error)
- func (c *UDPConn) WriteTo(payload []byte, addr net.Addr) (n int, err error)
- func (c *UDPConn) WriteToUDP(b []byte, addr *net.UDPAddr) (int, error)
- type UDPProxy
Constants ¶
const ( // Bit is a single bit. Bit = 1 // KBit is a kilobit. KBit = 1000 * Bit // MBit is a Megabit. MBit = 1000 * KBit )
Variables ¶
var ( ErrInvalidChance = errors.New("chance must be between 0 and 100 inclusive") ErrInvalidShuffleBlockSize = errors.New("shuffleBlockSize must be greater than 0") )
Static errors for better error handling.
Functions ¶
This section is empty.
Types ¶
type Chunk ¶
type Chunk interface {
SourceAddr() net.Addr
DestinationAddr() net.Addr
UserData() []byte
Tag() string
Clone() Chunk
Network() string // returns "udp" or "tcp"
String() string
// contains filtered or unexported methods
}
Chunk represents a packet passed around in the vnet.
type ChunkFilter ¶
ChunkFilter is a handler users can add to filter chunks. If the filter returns false, the packet will be dropped.
type DelayFilter ¶
type DelayFilter struct {
NIC
// contains filtered or unexported fields
}
DelayFilter delays inbound packets by the given delay. Automatically starts processing when created and runs until Close() is called.
func NewDelayFilter ¶
func NewDelayFilter(nic NIC, delay time.Duration) (*DelayFilter, error)
NewDelayFilter creates and starts a new DelayFilter with the given nic and delay.
func (*DelayFilter) Close ¶ added in v3.0.8
func (f *DelayFilter) Close() error
Close stops the DelayFilter and waits for graceful shutdown.
func (*DelayFilter) Run ¶
func (f *DelayFilter) Run(_ context.Context)
Run is provided for backward compatibility. The DelayFilter now starts automatically when created, so this method is a no-op.
func (*DelayFilter) SetDelay ¶ added in v3.0.8
func (f *DelayFilter) SetDelay(newDelay time.Duration)
SetDelay atomically updates the delay.
type DuplicationFilter ¶ added in v3.1.0
type DuplicationFilter struct {
// contains filtered or unexported fields
}
DuplicationFilter duplicates chunks that traverse a router according to the supplied configuration. When chaining with other filters, register duplication ahead of loss or latency filters to better emulate how duplicates typically occur before drop or jitter on real networks.
Note: Call Close() to cancel pending delayed duplicates and prevent goroutine leaks when shutting down. Routers do not automatically close registered duplication filters so applications should wire Close() into their lifecycle (e.g., along with Router.Stop()). The filter is safe for concurrent use by multiple goroutines.
Note: Duplicates re-enter the router and may be reordered relative to the original if other filters add jitter. Configure minExtraDelay appropriately to maintain ordering guarantees.
func NewDuplicationFilterWithOptions ¶ added in v3.1.0
func NewDuplicationFilterWithOptions(router *Router, opts ...DuplicationOption) (*DuplicationFilter, error)
NewDuplicationFilterWithOptions constructs a new DuplicationFilter bound to the provided router.
func (*DuplicationFilter) ChunkFilter ¶ added in v3.1.0
func (f *DuplicationFilter) ChunkFilter() ChunkFilter
ChunkFilter returns a ChunkFilter that can be registered with Router.AddChunkFilter.
func (*DuplicationFilter) Close ¶ added in v3.1.0
func (f *DuplicationFilter) Close() error
Close cancels all pending duplicate deliveries and prevents future duplications.
type DuplicationOption ¶ added in v3.1.0
type DuplicationOption func(*duplicationConfig) error
DuplicationOption configures a DuplicationFilter.
func WithDuplicationBurstDuration ¶ added in v3.1.0
func WithDuplicationBurstDuration(duration time.Duration) DuplicationOption
WithDuplicationBurstDuration configures how long burst mode stays active once triggered.
func WithDuplicationBurstMultiplier ¶ added in v3.1.0
func WithDuplicationBurstMultiplier(multiplier float64) DuplicationOption
WithDuplicationBurstMultiplier adjusts how aggressively probability increases during a burst window.
func WithDuplicationBurstProbability ¶ added in v3.1.0
func WithDuplicationBurstProbability(prob float64) DuplicationOption
WithDuplicationBurstProbability sets the probability that a burst window starts. Bursts are triggered probabilistically per packet when outside a burst window, creating time-based windows of elevated duplication. For deterministic burst cadences, seed the filter and control the burst timing externally.
func WithDuplicationExtraDelay ¶ added in v3.1.0
func WithDuplicationExtraDelay(minDelay, maxDelay time.Duration) DuplicationOption
WithDuplicationExtraDelay sets the range for additional delay applied to duplicates. The selected delay is uniform across the inclusive range [minDelay, maxDelay].
func WithDuplicationImmediate ¶ added in v3.1.0
func WithDuplicationImmediate() DuplicationOption
WithDuplicationImmediate is a convenience that configures duplicates to be delivered without any extra delay (equivalent to WithDuplicationExtraDelay(0, 0)).
func WithDuplicationProbability ¶ added in v3.1.0
func WithDuplicationProbability(prob float64) DuplicationOption
WithDuplicationProbability sets the base duplication probability.
func WithDuplicationSeed ¶ added in v3.1.0
func WithDuplicationSeed(seed int64) DuplicationOption
WithDuplicationSeed sets the random seed used by the duplication filter.
type EndpointDependencyType ¶
type EndpointDependencyType uint8
EndpointDependencyType defines a type of behavioral dependendency on the remote endpoint's IP address or port number. This is used for the two kinds of behaviors:
- Port mapping behavior
- Filtering behavior
See: https://tools.ietf.org/html/rfc4787
const ( // EndpointIndependent means the behavior is independent of the endpoint's address or port. EndpointIndependent EndpointDependencyType = iota // EndpointAddrDependent means the behavior is dependent on the endpoint's address. EndpointAddrDependent // EndpointAddrPortDependent means the behavior is dependent on the endpoint's address and port. EndpointAddrPortDependent )
type LossFilter ¶
type LossFilter struct {
NIC
LossFilterHandler
}
LossFilter is a wrapper around NICs, that drops some of the packets passed to onInboundChunk.
func NewLossFilter ¶
func NewLossFilter(nic NIC, chance int) (*LossFilter, error)
NewLossFilter creates a new LossFilter that drops every packet with a probability of chance/100 using the default random LossHandler. This maintains backward compatibility with the original API.
func NewLossFilterWithOptions ¶ added in v3.0.8
func NewLossFilterWithOptions(nic NIC, chance int, options ...LossFilterOption) (*LossFilter, error)
NewLossFilterWithOptions creates a new LossFilter that drops every packet with a probability of chance/100. You can provide custom options to override the default behavior. This follows the Pion options pattern for extensibility.
Option precedence: If WithLossHandler is provided, it takes precedence and any WithShuffleLossHandler option will be ignored.
func (*LossFilter) SetLossRate ¶ added in v3.0.8
func (f *LossFilter) SetLossRate(chance int, resetImmediately bool) error
SetLossRate sets the loss rate for the loss filter. The chance parameter is an integer out of 100. The resetImmediately parameter is a boolean that indicates whether to reset the loss rate immediately. If resetImmediately is true, the loss rate will be reset immediately. If resetImmediately is false, the loss rate will be reset after the next shuffle for shuffle-based handlers. Note that for random loss handlers (when shuffleBlockSize is 0), the loss rate will be reset immediately regardless of the resetImmediately parameter.
type LossFilterHandler ¶ added in v3.0.8
type LossFilterHandler interface {
// contains filtered or unexported methods
}
func NewRandomLossHandler
deprecated
added in
v3.0.8
func NewRandomLossHandler(chance int) (LossFilterHandler, error)
NewRandomLossHandler creates a new LossHandler with random packet dropping.
Deprecated: This function does not support seed-based deterministic behavior. For deterministic testing, use NewLossFilterWithOptions with WithLossSeed instead. This function will be removed in a future version.
func NewRandomShuffleLossHandler
deprecated
added in
v3.0.8
func NewRandomShuffleLossHandler(chance int, shuffleBlockSize int) (LossFilterHandler, error)
NewRandomShuffleLossHandler creates a new LossHandler with shuffle-based deterministic packet loss. The chance parameter is a percentage (0-100). For every shuffleBlockSize packets, it guarantees that the number of packets dropped equals round(shuffleBlockSize * chance / 100).
Deprecated: This function does not support seed-based deterministic behavior. For deterministic testing and reproducible shuffle patterns, use NewLossFilterWithOptions with WithShuffleLossHandler and WithLossSeed instead. This function will be removed in a future version.
type LossFilterOption ¶ added in v3.0.8
type LossFilterOption func(cfg *lossFilterConfig) error
LossFilterOption represents a configuration option for LossFilter creation.
func WithLossHandler ¶ added in v3.0.8
func WithLossHandler(handler LossFilterHandler) LossFilterOption
WithLossHandler sets a custom loss handler for the LossFilter. This option takes precedence over WithShuffleLossHandler if both are provided.
func WithLossSeed ¶ added in v3.1.0
func WithLossSeed(seed int64) LossFilterOption
WithLossSeed sets the random seed used by the loss filter for deterministic behavior. When a seed is provided (including seed==0), both random loss and shuffle-based loss will produce reproducible results. If no seed is provided (nil), the filter uses time-based seeding for non-deterministic behavior.
func WithShuffleLossHandler ¶ added in v3.0.8
func WithShuffleLossHandler(blockSize int) LossFilterOption
WithShuffleLossHandler configures the LossFilter to use deterministic shuffle-based packet loss with the specified block size. When set, for every blockSize packets, it guarantees that the number of packets dropped equals round(blockSize * chance / 100), where chance is a percentage (0-100).
type NATMode ¶
type NATMode uint8
NATMode defines basic behavior of the NAT.
const ( // NATModeNormal means the NAT behaves as a standard NAPT (RFC 2663). NATModeNormal NATMode = iota // NATModeNAT1To1 exhibits 1:1 DNAT where the external IP address is statically mapped to // a specific local IP address with port number is preserved always between them. // When this mode is selected, MappingBehavior, FilteringBehavior, PortPreservation and // MappingLifeTime of NATType are ignored. NATModeNAT1To1 )
type NATType ¶
type NATType struct {
Mode NATMode
MappingBehavior EndpointDependencyType
FilteringBehavior EndpointDependencyType
Hairpinning bool // Not implemented yet
PortPreservation bool // Not implemented yet
MappingLifeTime time.Duration
}
NATType has a set of parameters that define the behavior of NAT.
type NIC ¶
type NIC interface {
// contains filtered or unexported methods
}
NIC is a network interface controller that interfaces Router.
type Net ¶
type Net struct {
// contains filtered or unexported fields
}
Net represents a local network stack equivalent to a set of layers from NIC up to the transport (UDP / TCP) layer.
func NewNet ¶
NewNet creates an instance of a virtual network.
By design, it always have lo0 and eth0 interfaces. The lo0 has the address 127.0.0.1 assigned by default. IP address for eth0 will be assigned when this Net is added to a router.
func (*Net) CreateDialer ¶
CreateDialer creates an instance of vnet.Dialer.
func (*Net) InterfaceByIndex ¶
InterfaceByIndex returns the interface specified by index.
On Solaris, it returns one of the logical network interfaces sharing the logical data link; for more precision use InterfaceByName.
func (*Net) InterfaceByName ¶
InterfaceByName returns the interface specified by name.
func (*Net) Interfaces ¶
Interfaces returns a list of the system's network interfaces.
func (*Net) ListenPacket ¶
ListenPacket announces on the local network address.
func (*Net) ResolveIPAddr ¶
ResolveIPAddr returns an address of IP end point.
func (*Net) ResolveTCPAddr ¶
ResolveTCPAddr returns an address of TCP end point.
type NetConfig ¶
type NetConfig struct {
// StaticIPs is an array of static IP addresses to be assigned for this Net.
// If no static IP address is given, the router will automatically assign
// an IP address.
StaticIPs []string
// StaticIP is deprecated. Use StaticIPs.
StaticIP string
}
NetConfig is a bag of configuration parameters passed to NewNet().
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router ...
func (*Router) AddChildRouter ¶
AddChildRouter is like AddRouter, but does not add the child routers NIC to the parent. This has to be done manually by calling AddNet, which allows to use a wrapper around the subrouters NIC. AddNet MUST be called before AddChildRouter.
func (*Router) AddChunkFilter ¶
func (r *Router) AddChunkFilter(filter ChunkFilter)
AddChunkFilter adds a filter for chunks traversing this router. You may add more than one filter. The filters are called in the order of this method call. If a chunk is dropped by a filter, subsequent filter will not receive the chunk.
func (*Router) AddHost ¶
AddHost adds a mapping of hostname and an IP address to the local resolver.
type RouterConfig ¶
type RouterConfig struct {
// Name of router. If not specified, a unique name will be assigned.
Name string
// CIDR notation, like "192.0.2.0/24"
CIDR string
// StaticIPs is an array of static IP addresses to be assigned for this router.
// If no static IP address is given, the router will automatically assign
// an IP address.
// This will be ignored if this router is the root.
StaticIPs []string
// StaticIP is deprecated. Use StaticIPs.
StaticIP string
// Internal queue size
QueueSize int
// Effective only when this router has a parent router
NATType *NATType
// Minimum Delay
MinDelay time.Duration
// Max Jitter
MaxJitter time.Duration
// Logger factory
LoggerFactory logging.LoggerFactory
}
RouterConfig ...
type TBFOption ¶
type TBFOption func(*TokenBucketFilter) TBFOption
TBFOption is the option type to configure a TokenBucketFilter.
func TBFMaxBurst ¶
TBFMaxBurst sets the bucket size of the token bucket filter. This is the maximum size that can instantly leave the filter, if the bucket is full.
func TBFQueueSizeInBytes ¶
TBFQueueSizeInBytes sets the max number of bytes waiting in the queue. Can only be set in constructor before using the TBF.
type TokenBucketFilter ¶
type TokenBucketFilter struct {
NIC
// contains filtered or unexported fields
}
TokenBucketFilter implements a token bucket rate limit algorithm.
func NewTokenBucketFilter ¶
func NewTokenBucketFilter(n NIC, opts ...TBFOption) (*TokenBucketFilter, error)
NewTokenBucketFilter creates and starts a new TokenBucketFilter.
func (*TokenBucketFilter) Close ¶
func (t *TokenBucketFilter) Close() error
Close closes and stops the token bucket filter queue.
func (*TokenBucketFilter) Set ¶
func (t *TokenBucketFilter) Set(opts ...TBFOption) (previous TBFOption)
Set updates a setting on the token bucket filter.
type UDPConn ¶
type UDPConn struct {
// contains filtered or unexported fields
}
UDPConn is the implementation of the Conn and PacketConn interfaces for UDP network connections. compatible with net.PacketConn and net.Conn.
func (*UDPConn) Close ¶
Close closes the connection. Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
func (*UDPConn) Read ¶
Read reads data from the connection. Read can be made to time out and return an Error with Timeout() == true after a fixed time limit; see SetDeadline and SetReadDeadline.
func (*UDPConn) ReadFrom ¶
ReadFrom reads a packet from the connection, copying the payload into p. It returns the number of bytes copied into p and the return address that was on the packet. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Callers should always process the n > 0 bytes returned before considering the error err. ReadFrom can be made to time out and return an Error with Timeout() == true after a fixed time limit; see SetDeadline and SetReadDeadline.
func (*UDPConn) ReadFromUDP ¶
ReadFromUDP acts like ReadFrom but returns a UDPAddr.
func (*UDPConn) ReadMsgUDP ¶
ReadMsgUDP reads a message from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the message and the source address of the message.
The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.
func (*UDPConn) RemoteAddr ¶
RemoteAddr returns the remote network address.
func (*UDPConn) SetDeadline ¶
SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
A deadline is an absolute time after which I/O operations fail with a timeout (see type Error) instead of blocking. The deadline applies to all future and pending I/O, not just the immediately following call to ReadFrom or WriteTo. After a deadline has been exceeded, the connection can be refreshed by setting a deadline in the future.
An idle timeout can be implemented by repeatedly extending the deadline after successful ReadFrom or WriteTo calls.
A zero value for t means I/O operations will not time out.
func (*UDPConn) SetReadBuffer ¶
SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.
func (*UDPConn) SetReadDeadline ¶
SetReadDeadline sets the deadline for future ReadFrom calls and any currently-blocked ReadFrom call. A zero value for t means ReadFrom will not time out.
func (*UDPConn) SetWriteBuffer ¶
SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.
func (*UDPConn) SetWriteDeadline ¶
SetWriteDeadline sets the deadline for future WriteTo calls and any currently-blocked WriteTo call. Even if write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means WriteTo will not time out.
func (*UDPConn) Write ¶
Write writes data to the connection. Write can be made to time out and return an Error with Timeout() == true after a fixed time limit; see SetDeadline and SetWriteDeadline.
func (*UDPConn) WriteMsgUDP ¶
WriteMsgUDP writes a message to addr via c if c isn't connected, or to c's remote address if c is connected (in which case addr must be nil). The payload is copied from b and the associated out-of-band data is copied from oob. It returns the number of payload and out-of-band bytes written.
The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be used to manipulate IP-level socket options in oob.
type UDPProxy ¶
type UDPProxy struct {
// contains filtered or unexported fields
}
UDPProxy is a proxy between real server(net.UDPConn) and vnet.UDPConn.
High level design:
..............................................
: Virtual Network (vnet) :
: :
+-------+ * 1 +----+ +--------+ :
| :App |------------>|:Net|--o<-----|:Router | .............................
+-------+ +----+ | | : UDPProxy :
: | | +----+ +---------+ +---------+ +--------+
: | |--->o--|:Net|-->o-| vnet. |-->o-| net. |--->-| :Real |
: | | +----+ | UDPConn | | UDPConn | | Server |
: | | : +---------+ +---------+ +--------+
: | | ............................:
: +--------+ :
...............................................
func NewProxy ¶
NewProxy create a proxy, the router for this proxy belongs/bind to. If need to proxy for please create a new proxy for each router. For all addresses we proxy, we will create a vnet.Net in this router and proxy all packets.