ice

package module
v5.0.0-rc.9 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 43 Imported by: 3

README


Pion ICE

A Go implementation of ICE

Pion ICE join us on Discord Follow us on Bluesky
GitHub Workflow Status Go Reference Coverage Status Go Report Card


Roadmap

The library is used as a part of our WebRTC implementation. Please refer to that roadmap to track our major milestones.

Community

Pion has an active community on the Discord.

Follow the Pion Bluesky or Pion Twitter for project updates and important WebRTC news.

We are always looking to support your projects. Please reach out if you have something to build! If you need commercial support or don't want to use public methods you can contact us at team@pion.ly

Contributing

Check out the contributing wiki to join the group of amazing people making this project possible

License

MIT License - see LICENSE for full text

Documentation

Overview

Package ice implements the Interactive Connectivity Establishment (ICE) protocol defined in rfc5245.

Package ice ...

Package ice implements the Interactive Connectivity Establishment (ICE) protocol defined in rfc5245.

Index

Constants

View Source
const (

	// ComponentRTP indicates that the candidate is used for RTP.
	ComponentRTP uint16 = 1
	// ComponentRTCP indicates that the candidate is used for RTCP.
	ComponentRTCP
)
View Source
const (
	// DefaultNominationAttribute represents the default STUN Nomination attribute.
	// This is a custom attribute for ICE renomination support.
	// This value can be overridden via WithNominationAttribute.
	DefaultNominationAttribute stun.AttrType = 0xC001 // matching libwebrtc.
)

Default STUN Nomination attribute type for ICE renomination. Following the specification draft-thatcher-ice-renomination-01.

Variables

View Source
var (
	// ErrPort indicates malformed port is provided.
	ErrPort = errors.New("invalid port")

	// ErrLocalUfragInsufficientBits indicates local username fragment insufficient bits are provided.
	// Have to be at least 4 ice-chars, carrying the 24 bits of randomness RFC 8445 §5.3 requires.
	ErrLocalUfragInsufficientBits = errors.New(
		"local username fragment must be at least 4 ice-chars for 24 bits of randomness",
	)

	// ErrLocalPwdInsufficientBits indicates local password insufficient bits are provided.
	// Have to be at least 22 ice-chars, carrying the 128 bits of randomness RFC 8445 §5.3 requires.
	ErrLocalPwdInsufficientBits = errors.New(
		"local password must be at least 22 ice-chars for 128 bits of randomness",
	)

	// ErrProtoType indicates an unsupported transport type was provided.
	ErrProtoType = errors.New("invalid transport protocol type")

	// ErrClosed indicates the agent is closed.
	ErrClosed = taskloop.ErrClosed

	// ErrNoCandidatePairs indicates agent does not have a valid candidate pair.
	ErrNoCandidatePairs = errors.New("no candidate pairs available")

	// ErrCanceledByCaller indicates agent connection was canceled by the caller.
	ErrCanceledByCaller = errors.New("connecting canceled by caller")

	// ErrMultipleStart indicates agent was started twice.
	ErrMultipleStart = errors.New("attempted to start agent twice")

	// ErrRemoteUfragEmpty indicates agent was started with an empty remote ufrag.
	ErrRemoteUfragEmpty = errors.New("remote ufrag is empty")

	// ErrRemotePwdEmpty indicates agent was started with an empty remote pwd.
	ErrRemotePwdEmpty = errors.New("remote pwd is empty")

	// ErrNoOnCandidateHandler indicates agent was started without OnCandidate.
	ErrNoOnCandidateHandler = errors.New("no OnCandidate provided")

	// ErrInvalidURL indicates a nil STUN/TURN URL.
	ErrInvalidURL = errors.New("invalid nil STUN/TURN URL")

	// ErrUsernameEmpty indicates agent was give TURN URL with an empty Username.
	ErrUsernameEmpty = errors.New("username is empty")

	// ErrPasswordEmpty indicates agent was give TURN URL with an empty Password.
	ErrPasswordEmpty = errors.New("password is empty")

	// ErrAddressParseFailed indicates we were unable to parse a candidate address.
	ErrAddressParseFailed = errors.New("failed to parse address")

	// ErrLiteUsingNonHostCandidates indicates non host candidates were selected for a lite agent.
	ErrLiteUsingNonHostCandidates = errors.New("lite agents must only use host candidates")

	// ErrUselessURLsProvided indicates that one or more URL was provided to the agent but no host
	// candidate required them.
	ErrUselessURLsProvided = errors.New("agent does not need URL with selected candidate types")

	// ErrUnsupportedAddressRewriteCandidateType indicates an unsupported rewrite candidate type.
	ErrUnsupportedAddressRewriteCandidateType = errors.New("unsupported address rewrite candidate type")

	// ErrInvalidAddressRewriteMapping indicates an invalid address rewrite mapping.
	ErrInvalidAddressRewriteMapping = errors.New("invalid address rewrite mapping")

	// ErrMulticastDNSWithAddressRewrite indicates that mDNS gathering conflicts with host address rewriting.
	ErrMulticastDNSWithAddressRewrite = errors.New("mDNS gathering cannot be used with address rewrite for host candidate")

	// ErrIneffectiveAddressRewriteHost indicates that host rewriting was requested with host candidates disabled.
	ErrIneffectiveAddressRewriteHost = errors.New("address rewrite for host candidate ineffective")

	// ErrIneffectiveAddressRewriteSrflx indicates that srflx rewriting was requested with srflx candidates disabled.
	ErrIneffectiveAddressRewriteSrflx = errors.New("address rewrite for srflx candidate ineffective")

	// ErrInvalidMulticastDNSHostName indicates an invalid MulticastDNSHostName.
	ErrInvalidMulticastDNSHostName = errors.New(
		"invalid mDNS HostName, must end with .local and can only contain a single '.'",
	)

	// ErrRunCanceled indicates a run operation was canceled by its individual done.
	ErrRunCanceled = errors.New("run was canceled by done")

	// ErrUnknownCandidateTyp indicates that a candidate had a unknown type value.
	ErrUnknownCandidateTyp = errors.New("unknown candidate typ")

	// ErrDetermineNetworkType indicates that the NetworkType was not able to be parsed.
	ErrDetermineNetworkType = errors.New("unable to determine networkType")

	// ErrOnlyControllingAgentCanRenominate indicates that only controlling agent can renominate.
	ErrOnlyControllingAgentCanRenominate = errors.New("only controlling agent can renominate")

	// ErrRenominationNotEnabled indicates that renomination is not enabled.
	ErrRenominationNotEnabled = errors.New("renomination is not enabled")

	// ErrCandidatePairNotFound indicates that candidate pair was not found.
	ErrCandidatePairNotFound = errors.New("candidate pair not found")

	// ErrCandidatePairNotSucceeded indicates that candidate pair is not in succeeded state.
	ErrCandidatePairNotSucceeded = errors.New("candidate pair not in succeeded state")

	// ErrInvalidNominationAttribute indicates an invalid nomination attribute type was provided.
	ErrInvalidNominationAttribute = errors.New("invalid nomination attribute type")

	// ErrInvalidNominationValueGenerator indicates a nil nomination value generator was provided.
	ErrInvalidNominationValueGenerator = errors.New("nomination value generator cannot be nil")
)
View Source
var ErrGetTransportAddress = errors.New("failed to get local transport address")

ErrGetTransportAddress can't convert net.Addr to underlying type (UDPAddr or TCPAddr).

Functions

func GeneratePwd

func GeneratePwd() (string, error)

GeneratePwd generates a cryptographically random ICE password.

func GenerateUFrag

func GenerateUFrag() (string, error)

GenerateUFrag generates a cryptographically random ICE username fragment.

Types

type AddrPortReaderWriter

type AddrPortReaderWriter interface {
	ReadFromAddrPort(b []byte) (int, netip.AddrPort, error)
	WriteToAddrPort(b []byte, addr netip.AddrPort) (int, error)
}

AddrPortReaderWriter is an optional net.PacketConn capability that avoids allocating net.Addr values. Its methods must have the same packet-oriented semantics as net.PacketConn.ReadFrom and net.PacketConn.WriteTo, except that addresses are represented by netip.AddrPort. Custom UDP and framed TCP connections may implement it to opt in to the allocation-free path.

type AddressRewriteMode

type AddressRewriteMode int

AddressRewriteMode controls whether a rule replaces or appends candidates.

const (
	AddressRewriteReplace AddressRewriteMode
	AddressRewriteAppend
)

type AddressRewriteRule

type AddressRewriteRule struct {
	// External are the 1:1 external addresses to advertise for this rule. At
	// least one valid IP address or FQDN is required.
	External []string
	// Local optionally pins this rule to a specific local address. When set,
	// external IPs map to that address regardless of IP family. When empty,
	// External acts as a catch-all for the family implied by the local scope
	// (CIDR when set, otherwise the external IP family).
	Local string
	// Iface is the optional interface name to limit the rule to, empty = any.
	Iface string
	// CIDR is the optional CIDR to limit the rule to, empty = any.
	CIDR string
	// AsCandidateType is the candidate type to publish as for this rule. Defaults to host
	// when unspecified. Supported values: host, server reflexive, relay.
	AsCandidateType CandidateType
	// Mode controls whether we replace the original candidate or append extra
	// candidates.
	//
	// If Mode is zero, the default is:
	//   - CandidateTypeHost           -> AddressRewriteReplace
	//   - CandidateTypeServerReflexive, CandidateTypeRelay -> AddressRewriteAppend
	Mode AddressRewriteMode
	// Networks is the optional networks to limit the rule to, nil/empty = all.
	Networks []NetworkType
	// OriginalPort and NewPort optionally rewrite a gathered candidate's
	// advertised port. Set OriginalPort to zero to rewrite every port. NewPort
	// must be non-zero unless both fields are zero, which leaves ports unchanged.
	OriginalPort int
	NewPort      int
}

AddressRewriteRule represents a rule for remapping candidate addresses.

type Agent

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

Agent represents the ICE agent.

func NewAgent

func NewAgent(opts ...AgentOption) (*Agent, error)

NewAgent creates a new Agent.

func (*Agent) Accept

func (a *Agent) Accept(ctx context.Context, remoteUfrag, remotePwd string) (*Conn, error)

Accept blocks until at least one ice candidate pair has successfully connected.

func (*Agent) AddRemoteCandidate

func (a *Agent) AddRemoteCandidate(cand Candidate) error

AddRemoteCandidate adds a new remote candidate.

func (*Agent) AddVirtualCandidate

func (a *Agent) AddVirtualCandidate(cand Candidate, candidateConn net.PacketConn) error

AddVirtualCandidate registers a virtual candidate as a local ICE candidate, using the supplied packet connection to send and receive packets.

func (*Agent) AwaitConnect

func (a *Agent) AwaitConnect(ctx context.Context) error

AwaitConnect waits until a pair is selected.

func (*Agent) Close

func (a *Agent) Close() error

Close cleans up the Agent.

func (*Agent) Dial

func (a *Agent) Dial(ctx context.Context, remoteUfrag, remotePwd string) (*Conn, error)

Dial blocks until at least one ice candidate pair has successfully connected.

func (*Agent) Gather

func (a *Agent) Gather(opts ...GatherOption) error

Gather asynchronously gathers candidates, restarting ICE only when the local credentials change. Call OnCandidate before Gather. Local credentials are available when Gather returns. Calling Gather again cancels the previous gather. If the credentials are unchanged, existing candidates and connectivity are preserved. The first pass sets local credentials, Later credential changes clear candidates and remote credentials and restart connectivity checks. Each pass signals completion with a nil candidate. Call Gather again to gather more candidates.

func (*Agent) GetCandidatePairsStats

func (a *Agent) GetCandidatePairsStats() []CandidatePairStats

GetCandidatePairsStats returns a list of candidate pair stats.

func (*Agent) GetGatheringState

func (a *Agent) GetGatheringState() (GatheringState, error)

GetGatheringState returns the current gathering state of the Agent.

func (*Agent) GetLocalCandidates

func (a *Agent) GetLocalCandidates() ([]Candidate, error)

GetLocalCandidates returns the local candidates.

func (*Agent) GetLocalCandidatesStats

func (a *Agent) GetLocalCandidatesStats() []CandidateStats

GetLocalCandidatesStats returns a list of local candidates stats.

func (*Agent) GetLocalUserCredentials

func (a *Agent) GetLocalUserCredentials() (frag string, pwd string, err error)

GetLocalUserCredentials returns the local user credentials.

func (*Agent) GetRemoteCandidates

func (a *Agent) GetRemoteCandidates() ([]Candidate, error)

GetRemoteCandidates returns the remote candidates.

func (*Agent) GetRemoteCandidatesStats

func (a *Agent) GetRemoteCandidatesStats() []CandidateStats

GetRemoteCandidatesStats returns a list of remote candidates stats.

func (*Agent) GetRemoteUserCredentials

func (a *Agent) GetRemoteUserCredentials() (frag string, pwd string, err error)

GetRemoteUserCredentials returns the remote user credentials.

func (*Agent) GetSelectedCandidatePair

func (a *Agent) GetSelectedCandidatePair() (*CandidatePair, error)

GetSelectedCandidatePair returns the selected pair or nil if there is none.

func (*Agent) GetSelectedCandidatePairStats

func (a *Agent) GetSelectedCandidatePairStats() (CandidatePairStats, bool)

GetSelectedCandidatePairStats returns a candidate pair stats for selected candidate pair. Returns false if there is no selected pair.

func (*Agent) GracefulClose

func (a *Agent) GracefulClose() error

GracefulClose cleans up the Agent and waits for any goroutines it started to complete. This is only safe to call outside of Agent callbacks or if in a callback, in its own goroutine.

func (*Agent) OnCandidate

func (a *Agent) OnCandidate(f func(Candidate)) error

OnCandidate sets a handler that is fired when new candidates gathered. When the gathering process complete the last candidate is nil.

func (*Agent) OnConnectionStateChange

func (a *Agent) OnConnectionStateChange(f func(ConnectionState)) error

OnConnectionStateChange sets a handler that is fired when the connection state changes.

func (*Agent) OnSelectedCandidatePairChange

func (a *Agent) OnSelectedCandidatePairChange(f func(Candidate, Candidate)) error

OnSelectedCandidatePairChange sets a handler that is fired when the final candidate. pair is selected.

func (*Agent) Piggyback

func (a *Agent) Piggyback(datagrams [][]byte, _ net.Addr) bool

Piggyback stores the datagrams of one DTLS flight, to be picked in a round-robin fashion. Returns `true` if the flight is to be consumed.

func (*Agent) RenominateCandidate

func (a *Agent) RenominateCandidate(local, remote Candidate) error

RenominateCandidate allows the controlling ICE agent to nominate a new candidate pair. This implements the continuous renomination feature from draft-thatcher-ice-renomination-01. It returns once the request is queued; a later call replaces any unsent request. The agent loop looks up the pair and sends the request, logging errors (including a missing candidate pair) instead of returning them to the caller.

func (*Agent) ReportDTLSPacket

func (a *Agent) ReportDTLSPacket(packet []byte)

func (*Agent) SetDTLSCallback

func (a *Agent) SetDTLSCallback(cb func(packet []byte, rAddr net.Addr))

SetDTLSCallback sets the callback for DTLS packets. Setting this callback initializes state of the piggybacking state machine to "tentative", i.e. expecting embedded packets.

func (*Agent) SetDTLSFailed

func (a *Agent) SetDTLSFailed()

SetDTLSFailed disables piggybacking after the DTLS handshake failed.

func (*Agent) SetDTLSHandshakeComplete

func (a *Agent) SetDTLSHandshakeComplete(isClient bool, version protocol.Version)

SetDTLSHandshakeComplete signals that the local DTLS handshake completed and carries the negotiated DTLS role and version.

func (*Agent) SetRemoteCredentials

func (a *Agent) SetRemoteCredentials(remoteUfrag, remotePwd string) error

SetRemoteCredentials sets the credentials of the remote agent.

func (*Agent) SetRemoteICELite

func (a *Agent) SetRemoteICELite(lite bool) error

SetRemoteICELite sets whether signaling indicated that the remote agent uses ICE-lite. Call this before starting connectivity checks. Remote agents are assumed to use full ICE by default.

func (*Agent) StartAccept

func (a *Agent) StartAccept(remoteUfrag, remotePwd string) (*Conn, error)

StartAccept sets the agent up for connecting to the remote agent, acting as the controlled agent and returns immediately.

func (*Agent) StartDial

func (a *Agent) StartDial(remoteUfrag, remotePwd string) (*Conn, error)

StartDial sets the agent up for connecting to the remote agent, acting as the controlling agent and returns immediately.

type AgentOption

type AgentOption interface {
	// contains filtered or unexported methods
}

AgentOption configures an Agent during NewAgent.

func WithAddressRewriteRules

func WithAddressRewriteRules(rules ...AddressRewriteRule) AgentOption

WithAddressRewriteRules appends the provided address rewrite (1:1) rules to the agent's existing configuration. Each `AddressRewriteRule` can limit the mapping to a specific interface (`Iface`), local address (`Local`), CIDR block (`CIDR`), or subset of network types (`Networks`), allowing fine-grained control over which local addresses are replaced with the supplied external IPs or FQDNs. Use `Mode` to control whether a rule replaces the original candidate (default for host) or appends additional candidates (default for other types).

Rules are evaluated in the order they are added; for each candidate type + local address, explicit `Local` matches win immediately. Otherwise, the most specific catch-all is chosen (iface+CIDR > iface-only > CIDR-only > global), with declaration order breaking ties at the same specificity. `Iface` (when set) must also match. This lets you layer specificity (e.g., iface+CIDR, then iface-only, then global) while still keeping rule order meaningful. Overlapping rules in the same scope are logged as warnings.

func WithAutomaticRenomination

func WithAutomaticRenomination(interval time.Duration) AgentOption

WithAutomaticRenomination enables automatic renomination of candidate pairs when better pairs become available after initial connection establishment. This feature requires renomination to be enabled and both agents to support it.

When enabled, the controlling agent will periodically evaluate candidate pairs and renominate if a significantly better pair is found (e.g., switching from relay to direct connection, or when RTT improves significantly).

The interval parameter specifies the minimum time to wait after connection before considering automatic renomination. If set to 0, it defaults to 3 seconds.

Example:

agent, err := NewAgent(
	WithRenomination(DefaultNominationValueGenerator()),
	WithAutomaticRenomination(3*time.Second),
)

func WithBindingRequestHandler

func WithBindingRequestHandler(
	handler func(m *stun.Message, local, remote Candidate, pair *CandidatePair) bool,
) AgentOption

WithBindingRequestHandler sets a handler to allow applications to perform logic on incoming STUN Binding Requests. This was implemented to allow users to:

  • Log incoming Binding Requests for debugging
  • Implement draft-thatcher-ice-renomination
  • Implement custom CandidatePair switching logic

Example:

handler := func(m *stun.Message, local, remote Candidate, pair *CandidatePair) bool {
	log.Printf("Binding request from %s to %s", remote.Address(), local.Address())
	return true // Accept the request
}
agent, err := NewAgent(WithBindingRequestHandler(handler))

func WithCheckInterval

func WithCheckInterval(interval time.Duration) AgentOption

WithCheckInterval sets how often the agent runs connectivity checks while connecting.

func WithDisableActiveTCP

func WithDisableActiveTCP() AgentOption

WithDisableActiveTCP disables Active TCP candidates. When TCP is enabled, Active TCP candidates will be created when a new passive TCP remote candidate is added unless this option is used.

Example:

agent, err := NewAgent(WithDisableActiveTCP())

func WithDisconnectedTimeout

func WithDisconnectedTimeout(timeout time.Duration) AgentOption

WithDisconnectedTimeout sets the duration before the agent transitions to disconnected state. A timeout of 0 disables the transition.

func WithEnableUseCandidateCheckPriority

func WithEnableUseCandidateCheckPriority() AgentOption

WithEnableUseCandidateCheckPriority enables checking for equal or higher priority when switching selected candidate pair if the peer requests USE-CANDIDATE and agent is a lite agent. This is disabled by default, i.e. when peer requests USE-CANDIDATE, the selected pair will be switched to that irrespective of relative priority between current selected pair and priority of the pair being switched to.

Example:

agent, err := NewAgent(WithEnableUseCandidateCheckPriority())

func WithFailedTimeout

func WithFailedTimeout(timeout time.Duration) AgentOption

WithFailedTimeout sets the duration before the agent transitions to failed state after disconnected. A timeout of 0 disables the transition.

func WithHostAcceptanceMinWait

func WithHostAcceptanceMinWait(wait time.Duration) AgentOption

WithHostAcceptanceMinWait sets the minimum wait before selecting host candidates.

func WithICELite

func WithICELite(lite bool) AgentOption

WithICELite configures whether the agent operates in lite mode. Lite agents do not perform connectivity checks and only provide host candidates.

func WithIPFilter

func WithIPFilter(filter func(IPFilterInfo) bool) AgentOption

WithIPFilter sets a filter for local IP addresses used during candidate gathering. Returning false prevents use of the IP for the specified candidate type. The same IP can be allowed for STUN/TURN client binding while being excluded from host candidates by checking IPFilterInfo.CandidateType. For example, this excludes private IPs from host candidates while allowing all local IPs for STUN/TURN client binding:

WithIPFilter(func(info IPFilterInfo) bool {
	if info.CandidateType == CandidateTypeHost {
		return !info.IP.IsPrivate()
	}
	return true
})

func WithIncludeLoopback

func WithIncludeLoopback() AgentOption

WithIncludeLoopback includes loopback addresses in the candidate list. By default, loopback addresses are excluded.

Example:

agent, err := NewAgent(WithIncludeLoopback())

func WithInsecureSkipVerify

func WithInsecureSkipVerify(insecureSkipVerify bool) AgentOption

WithInsecureSkipVerify controls whether TURN TLS and DTLS connections skip certificate verification. By default, certificates are verified.

func WithInterfaceFilter

func WithInterfaceFilter(filter func(string) bool) AgentOption

WithInterfaceFilter sets a filter function to whitelist or blacklist network interfaces for ICE candidate gathering.

The filter function receives the interface name and should return true to keep the interface, or false to exclude it.

Example:

// Only use interfaces starting with "eth"
agent, err := NewAgent(
	WithInterfaceFilter(func(interfaceName string) bool {
		return len(interfaceName) >= 3 && interfaceName[:3] == "eth"
	}),
)

func WithKeepaliveInterval

func WithKeepaliveInterval(interval time.Duration) AgentOption

WithKeepaliveInterval sets how often ICE keepalive packets are sent. An interval of 0 disables extra keepalives. Full ICE agents still send consent freshness requests at the default interval (2 seconds), regardless of traffic.

func WithLoggerFactory

func WithLoggerFactory(loggerFactory logging.LoggerFactory) AgentOption

WithLoggerFactory sets the logger factory for the agent.

Example:

import "github.com/pion/logging"

loggerFactory := logging.NewDefaultLoggerFactory()
loggerFactory.DefaultLogLevel = logging.LogLevelDebug
agent, err := NewAgent(WithLoggerFactory(loggerFactory))

func WithMaxBindingRequests

func WithMaxBindingRequests(limit uint16) AgentOption

WithMaxBindingRequests sets the maximum number of binding requests before considering a pair failed.

func WithMulticastDNSHostName

func WithMulticastDNSHostName(hostName string) AgentOption

WithMulticastDNSHostName sets the mDNS host name used by the agent.

func WithMulticastDNSMode

func WithMulticastDNSMode(mode MulticastDNSMode) AgentOption

WithMulticastDNSMode configures mDNS behavior for the agent.

func WithNet

func WithNet(net transport.Net) AgentOption

WithNet sets the underlying network implementation for the agent.

func WithNominationAttribute

func WithNominationAttribute(attrType uint16) AgentOption

WithNominationAttribute sets the STUN attribute type to use for ICE renomination. The default value is 0xC001. This can be configured until the attribute is officially assigned by IANA for draft-thatcher-ice-renomination.

This option returns an error if the provided attribute type is invalid. Currently, validation ensures the attribute is not 0x0000 (reserved). Additional validation may be added in the future.

func WithPortRange

func WithPortRange(portMin, portMax uint16) AgentOption

WithPortRange sets the UDP port range for host candidates. It returns ErrPort if portMax is less than portMin.

func WithPrflxAcceptanceMinWait

func WithPrflxAcceptanceMinWait(wait time.Duration) AgentOption

WithPrflxAcceptanceMinWait sets the minimum wait before selecting prflx candidates.

func WithProxyDialer

func WithProxyDialer(dialer proxy.Dialer) AgentOption

WithProxyDialer sets the proxy dialer used for TURN over TCP/TLS/DTLS connections.

func WithRelayAcceptanceMinWait

func WithRelayAcceptanceMinWait(wait time.Duration) AgentOption

WithRelayAcceptanceMinWait sets the minimum wait before selecting relay candidates.

func WithRemoteIPFilter

func WithRemoteIPFilter(filter func(net.IP) bool) AgentOption

WithRemoteIPFilter sets a filter for remote candidate IP addresses. Candidates for which this function returns false are ignored.

func WithRenomination

func WithRenomination(generator NominationValueGenerator) AgentOption

WithRenomination enables ICE renomination as described in draft-thatcher-ice-renomination-01. When enabled, the controlling agent can renominate candidate pairs multiple times and the controlled agent follows "last nomination wins" rule.

The generator parameter specifies how nomination values are generated. Each value must be greater than every value previously returned for the agent. Use DefaultNominationValueGenerator() for a simple incrementing counter, or provide a custom generator for more complex scenarios.

Example:

agent, err := NewAgent(WithRenomination(DefaultNominationValueGenerator()))

func WithSTUNGatherTimeout

func WithSTUNGatherTimeout(timeout time.Duration) AgentOption

WithSTUNGatherTimeout sets the STUN gather timeout.

func WithSrflxAcceptanceMinWait

func WithSrflxAcceptanceMinWait(wait time.Duration) AgentOption

WithSrflxAcceptanceMinWait sets the minimum wait before selecting srflx candidates.

func WithTCPMux

func WithTCPMux(tcpMux TCPMux) AgentOption

WithTCPMux sets the TCP mux for ICE TCP multiplexing.

func WithTCPPriorityOffset

func WithTCPPriorityOffset(offset uint16) AgentOption

WithTCPPriorityOffset sets a number which is subtracted from the default (UDP) candidate type preference for host, srflx and prfx candidate types. It helps to configure relative preference of UDP candidates against TCP ones. Relay candidates for TCP and UDP are always 0 and not affected by this setting. When not set, defaultTCPPriorityOffset (27) is used.

Example:

agent, err := NewAgent(WithTCPPriorityOffset(50))

func WithUDPMux

func WithUDPMux(udpMux UDPMux) AgentOption

WithUDPMux sets the UDP mux used for multiplexing host candidates.

func WithUDPMuxSrflx

func WithUDPMuxSrflx(udpMuxSrflx UniversalUDPMux) AgentOption

WithUDPMuxSrflx sets the UDP mux for server reflexive candidates.

type AllConnsGetter

type AllConnsGetter interface {
	GetAllConns(ufrag string, isIPv6 bool, localIP net.IP) ([]net.PacketConn, error)
}

AllConnsGetter allows multiple fixed TCP ports to be used, each of which is multiplexed like TCPMux. AllConnsGetter also acts as a TCPMux, in which case it will return a single connection for one of the ports.

type AttrControl

type AttrControl struct {
	Role       Role
	Tiebreaker uint64
}

AttrControl is helper that wraps ICE-{CONTROLLED,CONTROLLING}.

func (AttrControl) AddTo

func (c AttrControl) AddTo(m *stun.Message) error

AddTo adds ICE-CONTROLLED or ICE-CONTROLLING attribute depending on Role.

func (*AttrControl) GetFrom

func (c *AttrControl) GetFrom(m *stun.Message) error

GetFrom decodes Role and Tiebreaker value from message.

type AttrControlled

type AttrControlled uint64

AttrControlled represents ICE-CONTROLLED attribute.

func (AttrControlled) AddTo

func (c AttrControlled) AddTo(m *stun.Message) error

AddTo adds ICE-CONTROLLED to message.

func (*AttrControlled) GetFrom

func (c *AttrControlled) GetFrom(m *stun.Message) error

GetFrom decodes ICE-CONTROLLED from message.

type AttrControlling

type AttrControlling uint64

AttrControlling represents ICE-CONTROLLING attribute.

func (AttrControlling) AddTo

func (c AttrControlling) AddTo(m *stun.Message) error

AddTo adds ICE-CONTROLLING to message.

func (*AttrControlling) GetFrom

func (c *AttrControlling) GetFrom(m *stun.Message) error

GetFrom decodes ICE-CONTROLLING from message.

type Candidate

type Candidate interface {
	// An arbitrary string used in the freezing algorithm to
	// group similar candidates.  It is the same for two candidates that
	// have the same type, base IP address, protocol (UDP, TCP, etc.),
	// and STUN or TURN server.
	Foundation() string

	// ID is a unique identifier for just this candidate
	// Unlike the foundation this is different for each candidate
	ID() string

	// A component is a piece of a data stream.
	// An example is one for RTP, and one for RTCP
	Component() uint16
	SetComponent(uint16)

	// The last time this candidate received traffic
	LastReceived() time.Time

	// The last time this candidate sent traffic
	LastSent() time.Time

	NetworkType() NetworkType
	Address() string
	Port() int

	Priority() uint32

	// Extensions returns a copy of all extension attributes associated with the ICECandidate.
	// In the order of insertion, *(key value).
	// Extension attributes are defined in RFC 5245, Section 15.1:
	// https://datatracker.ietf.org/doc/html/rfc5245#section-15.1
	//.
	Extensions() []CandidateExtension
	// SetExtensions replaces all extensions with a validated copy.
	// It preserves order and duplicates and leaves the candidate unchanged on error.
	SetExtensions([]CandidateExtension) error
	// GetExtension returns the value of the extension attribute associated with the ICECandidate.
	// Extension attributes are defined in RFC 5245, Section 15.1:
	// https://datatracker.ietf.org/doc/html/rfc5245#section-15.1
	//.
	GetExtension(key string) (value CandidateExtension, ok bool)
	// AddExtension adds an extension attribute to the ICECandidate.
	// If an extension with the same key already exists, the first is overwritten.
	// Extension attributes are defined in RFC 5245, Section 15.1:
	AddExtension(extension CandidateExtension) error
	// RemoveExtension removes the first extension attribute with the given key.
	// Extension attributes are defined in RFC 5245, Section 15.1:
	RemoveExtension(key string) (ok bool)

	String() string
	Type() CandidateType

	// TCPType returns the TCP mode extension, or TCPTypeUnspecified if absent or unrecognized.
	TCPType() TCPType

	// Equal compares the transport address (including TCP type) and candidate type.
	// Use DeepEqual to also compare extensions.
	Equal(other Candidate) bool

	// DeepEqual same as Equal, But it also compares the candidate extensions.
	DeepEqual(other Candidate) bool

	Marshal() string
	// contains filtered or unexported methods
}

Candidate represents an ICE candidate.

func UnmarshalCandidate

func UnmarshalCandidate(raw string) (Candidate, error)

UnmarshalCandidate Parses a candidate from a string https://datatracker.ietf.org/doc/html/rfc5245#section-15.1

type CandidateExtension

type CandidateExtension struct {
	Key   string
	Value string
}

CandidateExtension represents a single candidate extension as defined in https://tools.ietf.org/html/rfc5245#section-15.1 .

type CandidateHost

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

CandidateHost is a candidate of type host.

func NewCandidateHost

func NewCandidateHost(config *CandidateHostConfig) (*CandidateHost, error)

NewCandidateHost creates a new host candidate.

func (*CandidateHost) AddExtension

func (c *CandidateHost) AddExtension(ext CandidateExtension) error

func (*CandidateHost) Address

func (c *CandidateHost) Address() string

Address returns Candidate Address.

func (*CandidateHost) Component

func (c *CandidateHost) Component() uint16

Component returns candidate component.

func (*CandidateHost) Deadline

func (c *CandidateHost) Deadline() (deadline time.Time, ok bool)

Deadline implements context.Context.

func (*CandidateHost) DeepEqual

func (c *CandidateHost) DeepEqual(other Candidate) bool

DeepEqual is same as Equal but also compares the extensions.

func (*CandidateHost) Done

func (c *CandidateHost) Done() <-chan struct{}

Done implements context.Context.

func (*CandidateHost) Equal

func (c *CandidateHost) Equal(other Candidate) bool

Equal is used to compare two candidateBases.

func (*CandidateHost) Err

func (c *CandidateHost) Err() error

Err implements context.Context.

func (*CandidateHost) Extensions

func (c *CandidateHost) Extensions() []CandidateExtension

func (*CandidateHost) Foundation

func (c *CandidateHost) Foundation() string

func (*CandidateHost) GetExtension

func (c *CandidateHost) GetExtension(key string) (CandidateExtension, bool)

func (*CandidateHost) ID

func (c *CandidateHost) ID() string

ID returns Candidate ID.

func (*CandidateHost) LastReceived

func (c *CandidateHost) LastReceived() time.Time

LastReceived returns a time.Time indicating the last time this candidate was received.

func (*CandidateHost) LastSent

func (c *CandidateHost) LastSent() time.Time

LastSent returns a time.Time indicating the last time this candidate was sent.

func (*CandidateHost) LocalPreference

func (c *CandidateHost) LocalPreference() uint16

LocalPreference returns the local preference for this candidate.

func (*CandidateHost) Marshal

func (c *CandidateHost) Marshal() string

Marshal returns the string representation of the ICECandidate.

func (*CandidateHost) NetworkType

func (c *CandidateHost) NetworkType() NetworkType

NetworkType returns candidate NetworkType.

func (*CandidateHost) Port

func (c *CandidateHost) Port() int

Port returns Candidate Port.

func (*CandidateHost) Priority

func (c *CandidateHost) Priority() uint32

Priority computes the priority for this ICE Candidate See: https://www.rfc-editor.org/rfc/rfc8445#section-5.1.2.1

func (*CandidateHost) RemoveExtension

func (c *CandidateHost) RemoveExtension(key string) bool

func (*CandidateHost) SetComponent

func (c *CandidateHost) SetComponent(component uint16)

func (*CandidateHost) SetExtensions

func (c *CandidateHost) SetExtensions(extensions []CandidateExtension) error

SetExtensions replaces all extensions, preserving order and duplicates. It copies the input and leaves the candidate unchanged if validation fails.

func (*CandidateHost) String

func (c *CandidateHost) String() string

String makes the candidateBase printable.

func (*CandidateHost) TCPType

func (c *CandidateHost) TCPType() TCPType

func (*CandidateHost) Type

func (c *CandidateHost) Type() CandidateType

Type returns candidate type.

func (*CandidateHost) TypePreference

func (c *CandidateHost) TypePreference() uint16

TypePreference returns the type preference for this candidate.

func (*CandidateHost) Value

func (c *CandidateHost) Value(any) any

Value implements context.Context.

type CandidateHostConfig

type CandidateHostConfig struct {
	CandidateID       string
	Network           string
	Address           string
	Port              int
	Component         uint16
	Priority          uint32
	Foundation        string
	Extensions        []CandidateExtension
	IsLocationTracked bool
}

CandidateHostConfig is the config required to create a new CandidateHost.

type CandidatePair

type CandidatePair struct {
	Remote Candidate
	Local  Candidate
	// contains filtered or unexported fields
}

CandidatePair is a combination of a local and remote candidate.

func (*CandidatePair) BytesReceived

func (p *CandidatePair) BytesReceived() uint64

BytesReceived returns total application bytes received on this pair.

func (*CandidatePair) BytesSent

func (p *CandidatePair) BytesSent() uint64

BytesSent returns total application bytes sent on this pair.

func (*CandidatePair) CurrentRoundTripTime

func (p *CandidatePair) CurrentRoundTripTime() float64

CurrentRoundTripTime returns the current round trip time in seconds https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-currentroundtriptime

func (*CandidatePair) FirstRequestReceivedAt

func (p *CandidatePair) FirstRequestReceivedAt() time.Time

FirstRequestReceivedAt returns the timestamp of the first connectivity check received.

func (*CandidatePair) FirstRequestSentAt

func (p *CandidatePair) FirstRequestSentAt() time.Time

FirstRequestSentAt returns the timestamp of the first connectivity check sent.

func (*CandidatePair) FirstResponseReceivedAt

func (p *CandidatePair) FirstResponseReceivedAt() time.Time

FirstResponseReceivedAt returns the timestamp of the first connectivity response received.

func (*CandidatePair) ID

func (p *CandidatePair) ID() uint64

ID returns the unique identifier for this candidate pair.

func (*CandidatePair) LastPacketReceivedAt

func (p *CandidatePair) LastPacketReceivedAt() time.Time

LastPacketReceivedAt returns the timestamp of the last application packet received.

func (*CandidatePair) LastPacketSentAt

func (p *CandidatePair) LastPacketSentAt() time.Time

LastPacketSentAt returns the timestamp of the last application packet sent.

func (*CandidatePair) LastRequestReceivedAt

func (p *CandidatePair) LastRequestReceivedAt() time.Time

LastRequestReceivedAt returns the timestamp of the last connectivity check received.

func (*CandidatePair) LastRequestSentAt

func (p *CandidatePair) LastRequestSentAt() time.Time

LastRequestSentAt returns the timestamp of the last connectivity check sent.

func (*CandidatePair) LastResponseReceivedAt

func (p *CandidatePair) LastResponseReceivedAt() time.Time

LastResponseReceivedAt returns the timestamp of the last connectivity response received.

func (*CandidatePair) PacketsReceived

func (p *CandidatePair) PacketsReceived() uint64

PacketsReceived returns total application (non-STUN) packets received on this pair.

func (*CandidatePair) PacketsSent

func (p *CandidatePair) PacketsSent() uint64

PacketsSent returns total application (non-STUN) packets sent on this pair.

func (*CandidatePair) RequestsReceived

func (p *CandidatePair) RequestsReceived() uint64

RequestsReceived returns the total number of connectivity checks received https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-requestsreceived

func (*CandidatePair) RequestsSent

func (p *CandidatePair) RequestsSent() uint64

RequestsSent returns the total number of connectivity checks sent https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-requestssent

func (*CandidatePair) ResponsesReceived

func (p *CandidatePair) ResponsesReceived() uint64

ResponsesReceived returns the total number of connectivity responses received https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-responsesreceived

func (*CandidatePair) ResponsesSent

func (p *CandidatePair) ResponsesSent() uint64

ResponsesSent returns the total number of connectivity responses sent https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-responsessent

func (*CandidatePair) String

func (p *CandidatePair) String() string

func (*CandidatePair) TotalRoundTripTime

func (p *CandidatePair) TotalRoundTripTime() float64

TotalRoundTripTime returns the current round trip time in seconds https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-totalroundtriptime

func (*CandidatePair) UpdatePacketReceived

func (p *CandidatePair) UpdatePacketReceived(n int)

UpdatePacketReceived increments packet/byte counters and updates timestamp for a received application packet.

func (*CandidatePair) UpdatePacketSent

func (p *CandidatePair) UpdatePacketSent(n int)

UpdatePacketSent increments packet/byte counters and updates timestamp for a sent application packet.

func (*CandidatePair) UpdateRequestReceived

func (p *CandidatePair) UpdateRequestReceived()

UpdateRequestReceived increments the number of requests received and updates the timestamp.

func (*CandidatePair) UpdateRequestSent

func (p *CandidatePair) UpdateRequestSent()

UpdateRequestSent increments the number of requests sent and updates the timestamp.

func (*CandidatePair) UpdateResponseSent

func (p *CandidatePair) UpdateResponseSent()

UpdateResponseSent increments the number of responses sent.

func (*CandidatePair) UpdateRoundTripTime

func (p *CandidatePair) UpdateRoundTripTime(rtt time.Duration)

UpdateRoundTripTime sets the current round time of this pair and accumulates total round trip time and responses received.

func (*CandidatePair) Write

func (p *CandidatePair) Write(b []byte) (int, error)

type CandidatePairInfo

type CandidatePairInfo struct {
	// ID is the unique identifier for this candidate pair.
	// Use this with Conn.WriteToPair() to write to this pair.
	ID uint64

	// LocalCandidateType is the type of the local candidate (host, srflx, prflx, relay).
	LocalCandidateType CandidateType

	// RemoteCandidateType is the type of the remote candidate (host, srflx, prflx, relay).
	RemoteCandidateType CandidateType

	// State is the current state of the candidate pair.
	State CandidatePairState

	// Nominated indicates whether this pair has been nominated.
	Nominated bool

	// CurrentRoundTripTime is the latest RTT measurement.
	CurrentRoundTripTime time.Duration

	// RenominationQuality is a score indicating the pair's quality (higher is better).
	// Considers candidate types (host > srflx > relay), measured RTT, and stability.
	RenominationQuality float64
}

CandidatePairInfo is a snapshot of a candidate pair's state. Use the ID with Conn.WriteToPair() to write to this specific pair.

type CandidatePairState

type CandidatePairState int

CandidatePairState represent the ICE candidate pair state.

const (
	// CandidatePairStateWaiting means a check has not been performed for
	// this pair.
	CandidatePairStateWaiting CandidatePairState = iota + 1

	// CandidatePairStateInProgress means a check has been sent for this pair,
	// but the transaction is in progress.
	CandidatePairStateInProgress

	// CandidatePairStateFailed means a check for this pair was already done
	// and failed, either never producing any response or producing an unrecoverable
	// failure response.
	CandidatePairStateFailed

	// CandidatePairStateSucceeded means a check for this pair was already
	// done and produced a successful result.
	CandidatePairStateSucceeded
)

func (CandidatePairState) String

func (c CandidatePairState) String() string

type CandidatePairStats

type CandidatePairStats struct {
	// Timestamp is the timestamp associated with this object.
	Timestamp time.Time

	// LocalCandidateID is the ID of the local candidate
	LocalCandidateID string

	// RemoteCandidateID is the ID of the remote candidate
	RemoteCandidateID string

	// State represents the state of the checklist for the local and remote
	// candidates in a pair.
	State CandidatePairState

	// Nominated is true when this valid pair that should be used for media
	// if it is the highest-priority one amongst those whose nominated flag is set
	Nominated bool

	// PacketsSent represents the total number of packets sent on this candidate pair.
	PacketsSent uint64

	// PacketsReceived represents the total number of packets received on this candidate pair.
	PacketsReceived uint64

	// BytesSent represents the total number of payload bytes sent on this candidate pair
	// not including headers or padding.
	BytesSent uint64

	// BytesReceived represents the total number of payload bytes received on this candidate pair
	// not including headers or padding.
	BytesReceived uint64

	// LastPacketSentTimestamp represents the timestamp at which the last packet was
	// sent on this particular candidate pair, excluding STUN packets.
	LastPacketSentTimestamp time.Time

	// LastPacketReceivedTimestamp represents the timestamp at which the last packet
	// was received on this particular candidate pair, excluding STUN packets.
	LastPacketReceivedTimestamp time.Time

	// FirstRequestTimestamp represents the timestamp at which the first STUN request
	// was sent on this particular candidate pair.
	FirstRequestTimestamp time.Time

	// LastRequestTimestamp represents the timestamp at which the last STUN request
	// was sent on this particular candidate pair. The average interval between two
	// consecutive connectivity checks sent can be calculated with
	// (LastRequestTimestamp - FirstRequestTimestamp) / RequestsSent.
	LastRequestTimestamp time.Time

	// FirstResponseTimestamp represents the timestamp at which the first STUN response
	// was received on this particular candidate pair.
	FirstResponseTimestamp time.Time

	// LastResponseTimestamp represents the timestamp at which the last STUN response
	// was received on this particular candidate pair.
	LastResponseTimestamp time.Time

	// FirstRequestReceivedTimestamp represents the timestamp at which the first
	// connectivity check request was received.
	FirstRequestReceivedTimestamp time.Time

	// LastRequestReceivedTimestamp represents the timestamp at which the last
	// connectivity check request was received.
	LastRequestReceivedTimestamp time.Time

	// TotalRoundTripTime represents the sum of all round trip time measurements
	// in seconds since the beginning of the session, based on STUN connectivity
	// check responses (ResponsesReceived), including those that reply to requests
	// that are sent in order to verify consent. The average round trip time can
	// be computed from TotalRoundTripTime by dividing it by ResponsesReceived.
	TotalRoundTripTime float64

	// CurrentRoundTripTime represents the latest round trip time measured in seconds,
	// computed from both STUN connectivity checks, including those that are sent
	// for consent verification.
	CurrentRoundTripTime float64

	// AvailableOutgoingBitrate is calculated by the underlying congestion control
	// by combining the available bitrate for all the outgoing RTP streams using
	// this candidate pair. The bitrate measurement does not count the size of the
	// IP or other transport layers like TCP or UDP. It is similar to the TIAS defined
	// in RFC 3890, i.e., it is measured in bits per second and the bitrate is calculated
	// over a 1 second window.
	AvailableOutgoingBitrate float64

	// AvailableIncomingBitrate is calculated by the underlying congestion control
	// by combining the available bitrate for all the incoming RTP streams using
	// this candidate pair. The bitrate measurement does not count the size of the
	// IP or other transport layers like TCP or UDP. It is similar to the TIAS defined
	// in  RFC 3890, i.e., it is measured in bits per second and the bitrate is
	// calculated over a 1 second window.
	AvailableIncomingBitrate float64

	// CircuitBreakerTriggerCount represents the number of times the circuit breaker
	// is triggered for this particular 5-tuple, ceasing transmission.
	CircuitBreakerTriggerCount uint32

	// RequestsReceived represents the total number of connectivity check requests
	// received (including retransmissions). It is impossible for the receiver to
	// tell whether the request was sent in order to check connectivity or check
	// consent, so all connectivity checks requests are counted here.
	RequestsReceived uint64

	// RequestsSent represents the total number of connectivity check requests
	// sent (not including retransmissions).
	RequestsSent uint64

	// ResponsesReceived represents the total number of connectivity check responses received.
	ResponsesReceived uint64

	// ResponsesSent represents the total number of connectivity check responses sent.
	// Since we cannot distinguish connectivity check requests and consent requests,
	// all responses are counted.
	ResponsesSent uint64

	// RetransmissionsReceived represents the total number of connectivity check
	// request retransmissions received.
	RetransmissionsReceived uint64

	// RetransmissionsSent represents the total number of connectivity check
	// request retransmissions sent.
	RetransmissionsSent uint64

	// ConsentRequestsSent represents the total number of consent requests sent.
	ConsentRequestsSent uint64

	// ConsentExpiredTimestamp represents the timestamp at which the latest valid
	// STUN binding response expired.
	ConsentExpiredTimestamp time.Time
}

CandidatePairStats contains ICE candidate pair statistics.

type CandidatePeerReflexive

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

CandidatePeerReflexive ...

func NewCandidatePeerReflexive

func NewCandidatePeerReflexive(config *CandidatePeerReflexiveConfig) (*CandidatePeerReflexive, error)

NewCandidatePeerReflexive creates a new peer reflective candidate.

func (*CandidatePeerReflexive) AddExtension

func (c *CandidatePeerReflexive) AddExtension(ext CandidateExtension) error

func (*CandidatePeerReflexive) Address

func (c *CandidatePeerReflexive) Address() string

Address returns Candidate Address.

func (*CandidatePeerReflexive) Component

func (c *CandidatePeerReflexive) Component() uint16

Component returns candidate component.

func (*CandidatePeerReflexive) Deadline

func (c *CandidatePeerReflexive) Deadline() (deadline time.Time, ok bool)

Deadline implements context.Context.

func (*CandidatePeerReflexive) DeepEqual

func (c *CandidatePeerReflexive) DeepEqual(other Candidate) bool

DeepEqual is same as Equal but also compares the extensions.

func (*CandidatePeerReflexive) Done

func (c *CandidatePeerReflexive) Done() <-chan struct{}

Done implements context.Context.

func (*CandidatePeerReflexive) Equal

func (c *CandidatePeerReflexive) Equal(other Candidate) bool

Equal is used to compare two candidateBases.

func (*CandidatePeerReflexive) Err

func (c *CandidatePeerReflexive) Err() error

Err implements context.Context.

func (*CandidatePeerReflexive) Extensions

func (c *CandidatePeerReflexive) Extensions() []CandidateExtension

func (*CandidatePeerReflexive) Foundation

func (c *CandidatePeerReflexive) Foundation() string

func (*CandidatePeerReflexive) GetExtension

func (c *CandidatePeerReflexive) GetExtension(key string) (CandidateExtension, bool)

func (*CandidatePeerReflexive) ID

func (c *CandidatePeerReflexive) ID() string

ID returns Candidate ID.

func (*CandidatePeerReflexive) LastReceived

func (c *CandidatePeerReflexive) LastReceived() time.Time

LastReceived returns a time.Time indicating the last time this candidate was received.

func (*CandidatePeerReflexive) LastSent

func (c *CandidatePeerReflexive) LastSent() time.Time

LastSent returns a time.Time indicating the last time this candidate was sent.

func (*CandidatePeerReflexive) LocalPreference

func (c *CandidatePeerReflexive) LocalPreference() uint16

LocalPreference returns the local preference for this candidate.

func (*CandidatePeerReflexive) Marshal

func (c *CandidatePeerReflexive) Marshal() string

Marshal returns the string representation of the ICECandidate.

func (*CandidatePeerReflexive) NetworkType

func (c *CandidatePeerReflexive) NetworkType() NetworkType

NetworkType returns candidate NetworkType.

func (*CandidatePeerReflexive) Port

func (c *CandidatePeerReflexive) Port() int

Port returns Candidate Port.

func (*CandidatePeerReflexive) Priority

func (c *CandidatePeerReflexive) Priority() uint32

Priority computes the priority for this ICE Candidate See: https://www.rfc-editor.org/rfc/rfc8445#section-5.1.2.1

func (*CandidatePeerReflexive) RemoveExtension

func (c *CandidatePeerReflexive) RemoveExtension(key string) bool

func (*CandidatePeerReflexive) SetComponent

func (c *CandidatePeerReflexive) SetComponent(component uint16)

func (*CandidatePeerReflexive) SetExtensions

func (c *CandidatePeerReflexive) SetExtensions(extensions []CandidateExtension) error

SetExtensions replaces all extensions, preserving order and duplicates. It copies the input and leaves the candidate unchanged if validation fails.

func (*CandidatePeerReflexive) String

func (c *CandidatePeerReflexive) String() string

String makes the candidateBase printable.

func (*CandidatePeerReflexive) TCPType

func (c *CandidatePeerReflexive) TCPType() TCPType

func (*CandidatePeerReflexive) Type

func (c *CandidatePeerReflexive) Type() CandidateType

Type returns candidate type.

func (*CandidatePeerReflexive) TypePreference

func (c *CandidatePeerReflexive) TypePreference() uint16

TypePreference returns the type preference for this candidate.

func (*CandidatePeerReflexive) Value

func (c *CandidatePeerReflexive) Value(any) any

Value implements context.Context.

type CandidatePeerReflexiveConfig

type CandidatePeerReflexiveConfig struct {
	CandidateID string
	Network     string
	Address     string
	Port        int
	Component   uint16
	Priority    uint32
	Foundation  string
	// Extensions contains candidate attributes.
	Extensions []CandidateExtension
}

CandidatePeerReflexiveConfig is the config required to create a new CandidatePeerReflexive.

type CandidateRelay

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

CandidateRelay ...

func NewCandidateRelay

func NewCandidateRelay(config *CandidateRelayConfig) (*CandidateRelay, error)

NewCandidateRelay creates a new relay candidate.

func (*CandidateRelay) AddExtension

func (c *CandidateRelay) AddExtension(ext CandidateExtension) error

func (*CandidateRelay) Address

func (c *CandidateRelay) Address() string

Address returns Candidate Address.

func (*CandidateRelay) Component

func (c *CandidateRelay) Component() uint16

Component returns candidate component.

func (*CandidateRelay) Deadline

func (c *CandidateRelay) Deadline() (deadline time.Time, ok bool)

Deadline implements context.Context.

func (*CandidateRelay) DeepEqual

func (c *CandidateRelay) DeepEqual(other Candidate) bool

DeepEqual is same as Equal but also compares the extensions.

func (*CandidateRelay) Done

func (c *CandidateRelay) Done() <-chan struct{}

Done implements context.Context.

func (*CandidateRelay) Equal

func (c *CandidateRelay) Equal(other Candidate) bool

Equal is used to compare two candidateBases.

func (*CandidateRelay) Err

func (c *CandidateRelay) Err() error

Err implements context.Context.

func (*CandidateRelay) Extensions

func (c *CandidateRelay) Extensions() []CandidateExtension

func (*CandidateRelay) Foundation

func (c *CandidateRelay) Foundation() string

func (*CandidateRelay) GetExtension

func (c *CandidateRelay) GetExtension(key string) (CandidateExtension, bool)

func (*CandidateRelay) ID

func (c *CandidateRelay) ID() string

ID returns Candidate ID.

func (*CandidateRelay) LastReceived

func (c *CandidateRelay) LastReceived() time.Time

LastReceived returns a time.Time indicating the last time this candidate was received.

func (*CandidateRelay) LastSent

func (c *CandidateRelay) LastSent() time.Time

LastSent returns a time.Time indicating the last time this candidate was sent.

func (*CandidateRelay) LocalPreference

func (c *CandidateRelay) LocalPreference() uint16

LocalPreference returns the local preference for this candidate.

func (*CandidateRelay) Marshal

func (c *CandidateRelay) Marshal() string

Marshal returns the string representation of the ICECandidate.

func (*CandidateRelay) NetworkType

func (c *CandidateRelay) NetworkType() NetworkType

NetworkType returns candidate NetworkType.

func (*CandidateRelay) Port

func (c *CandidateRelay) Port() int

Port returns Candidate Port.

func (*CandidateRelay) Priority

func (c *CandidateRelay) Priority() uint32

Priority computes the priority for this ICE Candidate See: https://www.rfc-editor.org/rfc/rfc8445#section-5.1.2.1

func (*CandidateRelay) RelayProtocol

func (c *CandidateRelay) RelayProtocol() string

RelayProtocol returns the protocol used between the endpoint and the relay server.

func (*CandidateRelay) RemoveExtension

func (c *CandidateRelay) RemoveExtension(key string) bool

func (*CandidateRelay) SetComponent

func (c *CandidateRelay) SetComponent(component uint16)

func (*CandidateRelay) SetExtensions

func (c *CandidateRelay) SetExtensions(extensions []CandidateExtension) error

SetExtensions replaces all extensions, preserving order and duplicates. It copies the input and leaves the candidate unchanged if validation fails.

func (*CandidateRelay) String

func (c *CandidateRelay) String() string

String makes the candidateBase printable.

func (*CandidateRelay) TCPType

func (c *CandidateRelay) TCPType() TCPType

func (*CandidateRelay) Type

func (c *CandidateRelay) Type() CandidateType

Type returns candidate type.

func (*CandidateRelay) TypePreference

func (c *CandidateRelay) TypePreference() uint16

TypePreference returns the type preference for this candidate.

func (*CandidateRelay) Value

func (c *CandidateRelay) Value(any) any

Value implements context.Context.

type CandidateRelayConfig

type CandidateRelayConfig struct {
	CandidateID   string
	Network       string
	Address       string
	Port          int
	Component     uint16
	Priority      uint32
	Foundation    string
	RelayProtocol string
	OnClose       func() error
	// Extensions contains candidate attributes.
	Extensions []CandidateExtension
}

CandidateRelayConfig is the config required to create a new CandidateRelay.

type CandidateServerReflexive

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

CandidateServerReflexive ...

func NewCandidateServerReflexive

func NewCandidateServerReflexive(config *CandidateServerReflexiveConfig) (*CandidateServerReflexive, error)

NewCandidateServerReflexive creates a new server reflective candidate.

func (*CandidateServerReflexive) AddExtension

func (c *CandidateServerReflexive) AddExtension(ext CandidateExtension) error

func (*CandidateServerReflexive) Address

func (c *CandidateServerReflexive) Address() string

Address returns Candidate Address.

func (*CandidateServerReflexive) Component

func (c *CandidateServerReflexive) Component() uint16

Component returns candidate component.

func (*CandidateServerReflexive) Deadline

func (c *CandidateServerReflexive) Deadline() (deadline time.Time, ok bool)

Deadline implements context.Context.

func (*CandidateServerReflexive) DeepEqual

func (c *CandidateServerReflexive) DeepEqual(other Candidate) bool

DeepEqual is same as Equal but also compares the extensions.

func (*CandidateServerReflexive) Done

func (c *CandidateServerReflexive) Done() <-chan struct{}

Done implements context.Context.

func (*CandidateServerReflexive) Equal

func (c *CandidateServerReflexive) Equal(other Candidate) bool

Equal is used to compare two candidateBases.

func (*CandidateServerReflexive) Err

func (c *CandidateServerReflexive) Err() error

Err implements context.Context.

func (*CandidateServerReflexive) Extensions

func (c *CandidateServerReflexive) Extensions() []CandidateExtension

func (*CandidateServerReflexive) Foundation

func (c *CandidateServerReflexive) Foundation() string

func (*CandidateServerReflexive) GetExtension

func (c *CandidateServerReflexive) GetExtension(key string) (CandidateExtension, bool)

func (*CandidateServerReflexive) ID

func (c *CandidateServerReflexive) ID() string

ID returns Candidate ID.

func (*CandidateServerReflexive) LastReceived

func (c *CandidateServerReflexive) LastReceived() time.Time

LastReceived returns a time.Time indicating the last time this candidate was received.

func (*CandidateServerReflexive) LastSent

func (c *CandidateServerReflexive) LastSent() time.Time

LastSent returns a time.Time indicating the last time this candidate was sent.

func (*CandidateServerReflexive) LocalPreference

func (c *CandidateServerReflexive) LocalPreference() uint16

LocalPreference returns the local preference for this candidate.

func (*CandidateServerReflexive) Marshal

func (c *CandidateServerReflexive) Marshal() string

Marshal returns the string representation of the ICECandidate.

func (*CandidateServerReflexive) NetworkType

func (c *CandidateServerReflexive) NetworkType() NetworkType

NetworkType returns candidate NetworkType.

func (*CandidateServerReflexive) Port

func (c *CandidateServerReflexive) Port() int

Port returns Candidate Port.

func (*CandidateServerReflexive) Priority

func (c *CandidateServerReflexive) Priority() uint32

Priority computes the priority for this ICE Candidate See: https://www.rfc-editor.org/rfc/rfc8445#section-5.1.2.1

func (*CandidateServerReflexive) RemoveExtension

func (c *CandidateServerReflexive) RemoveExtension(key string) bool

func (*CandidateServerReflexive) SetComponent

func (c *CandidateServerReflexive) SetComponent(component uint16)

func (*CandidateServerReflexive) SetExtensions

func (c *CandidateServerReflexive) SetExtensions(extensions []CandidateExtension) error

SetExtensions replaces all extensions, preserving order and duplicates. It copies the input and leaves the candidate unchanged if validation fails.

func (*CandidateServerReflexive) String

func (c *CandidateServerReflexive) String() string

String makes the candidateBase printable.

func (*CandidateServerReflexive) TCPType

func (c *CandidateServerReflexive) TCPType() TCPType

func (*CandidateServerReflexive) Type

func (c *CandidateServerReflexive) Type() CandidateType

Type returns candidate type.

func (*CandidateServerReflexive) TypePreference

func (c *CandidateServerReflexive) TypePreference() uint16

TypePreference returns the type preference for this candidate.

func (*CandidateServerReflexive) Value

func (c *CandidateServerReflexive) Value(any) any

Value implements context.Context.

type CandidateServerReflexiveConfig

type CandidateServerReflexiveConfig struct {
	CandidateID string
	Network     string
	Address     string
	Port        int
	Component   uint16
	Priority    uint32
	Foundation  string
	// Extensions contains candidate attributes.
	Extensions []CandidateExtension
}

CandidateServerReflexiveConfig is the config required to create a new CandidateServerReflexive.

type CandidateStats

type CandidateStats struct {
	// Timestamp is the timestamp associated with this object.
	Timestamp time.Time

	// ID is the candidate ID
	ID string

	// NetworkType represents the type of network interface used by the base of a
	// local candidate (the address the ICE agent sends from). Only present for
	// local candidates; it's not possible to know what type of network interface
	// a remote candidate is using.
	//
	// Note:
	// This stat only tells you about the network interface used by the first "hop";
	// it's possible that a connection will be bottlenecked by another type of network.
	// For example, when using Wi-Fi tethering, the networkType of the relevant candidate
	// would be "wifi", even when the next hop is over a cellular connection.
	NetworkType NetworkType

	// IP is the IP address of the candidate, allowing for IPv4 addresses and
	// IPv6 addresses, but fully qualified domain names (FQDNs) are not allowed.
	IP string

	// Port is the port number of the candidate.
	Port int

	// CandidateType is the "Type" field of the ICECandidate.
	CandidateType CandidateType

	// Priority is the "Priority" field of the ICECandidate.
	Priority uint32

	// URL is the URL of the TURN or STUN server indicated in the that translated
	// this IP address. It is the URL address surfaced in an PeerConnectionICEEvent.
	URL string

	// RelayProtocol is the protocol used by the endpoint to communicate with the
	// TURN server. This is only present for local candidates. Valid values for
	// the TURN URL protocol is one of UDP, TCP, or TLS.
	RelayProtocol string

	// Deleted is true if the candidate has been deleted/freed. For host candidates,
	// this means that any network resources (typically a socket) associated with the
	// candidate have been released. For TURN candidates, this means the TURN allocation
	// is no longer active.
	//
	// Only defined for local candidates. For remote candidates, this property is not applicable.
	Deleted bool
}

CandidateStats contains ICE candidate statistics related to the ICETransport objects.

type CandidateType

type CandidateType byte

CandidateType represents the type of candidate.

const (
	CandidateTypeUnspecified CandidateType = iota
	CandidateTypeHost
	CandidateTypeServerReflexive
	CandidateTypePeerReflexive
	CandidateTypeRelay
)

CandidateType enum.

func (CandidateType) Preference

func (c CandidateType) Preference() uint16

Preference returns the preference weight of a CandidateType

4.1.2.2. Guidelines for Choosing Type and Local Preferences The RECOMMENDED values are 126 for host candidates, 100 for server reflexive candidates, 110 for peer reflexive candidates, and 0 for relayed candidates.

func (CandidateType) String

func (c CandidateType) String() string

String makes CandidateType printable.

type Conn

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

Conn represents the ICE connection. At the moment the lifetime of the Conn is equal to the Agent.

func (*Conn) BytesReceived

func (c *Conn) BytesReceived() uint64

BytesReceived returns the number of bytes received.

func (*Conn) BytesSent

func (c *Conn) BytesSent() uint64

BytesSent returns the number of bytes sent.

func (*Conn) Close

func (c *Conn) Close() error

Close implements the Conn Close method. It is used to close the connection. Any calls to Read and Write will be unblocked and return an error.

func (*Conn) GetCandidatePairsInfo

func (c *Conn) GetCandidatePairsInfo() []CandidatePairInfo

GetCandidatePairsInfo returns snapshot information for all candidate pairs. Use the returned ID with WriteToPair() to write to a specific pair.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local address of the current selected pair or nil if there is none.

func (*Conn) Read

func (c *Conn) Read(p []byte) (int, error)

Read implements the Conn Read method.

func (*Conn) ReadWithAttributes

func (c *Conn) ReadWithAttributes(p []byte, attrs packetio.Attributes) (int, packetio.Attributes, error)

ReadWithAttributes reads a packet and replaces attrs with its metadata.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote address of the current selected pair or nil if there is none.

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline sets both read and write deadlines on the underlying ICE connection.

func (*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline on the packet buffer used for application data.

func (*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the write deadline on the currently selected local candidate connection. The deadline applies to the selected candidate pair and will affect all traffic over that pair.

func (*Conn) Write

func (c *Conn) Write(packet []byte) (int, error)

Write implements the Conn Write method.

func (*Conn) WriteToPair

func (c *Conn) WriteToPair(pairID uint64, packet []byte) (int, error)

WriteToPair writes packet to a specific candidate pair identified by its ID. Returns ErrCandidatePairNotFound if the pair ID is not found. Returns ErrCandidatePairNotSucceeded if the pair is not in Succeeded state. This is useful for sending packets over alternate paths even if they are not nominated.

type ConnectionState

type ConnectionState int

ConnectionState is an enum showing the state of a ICE Connection.

const (
	// ConnectionStateUnknown represents an unknown state.
	ConnectionStateUnknown ConnectionState = iota

	// ConnectionStateNew ICE agent is gathering addresses.
	ConnectionStateNew

	// ConnectionStateChecking ICE agent has been given local and remote candidates, and is attempting to find a match.
	ConnectionStateChecking

	// ConnectionStateConnected ICE agent has a pairing, but is still checking other pairs.
	ConnectionStateConnected

	// ConnectionStateCompleted ICE agent has finished.
	ConnectionStateCompleted

	// ConnectionStateFailed ICE agent never could successfully connect.
	ConnectionStateFailed

	// ConnectionStateDisconnected ICE agent connected successfully, but has entered a failed state.
	ConnectionStateDisconnected

	// ConnectionStateClosed ICE agent has finished and is no longer handling requests.
	ConnectionStateClosed
)

List of supported States.

func (ConnectionState) String

func (c ConnectionState) String() string

type DTLSInSTUNAckAttribute

type DTLSInSTUNAckAttribute []uint32

DTLSInSTUNAckAttribute is a STUN attribute for acknowledging the receipt of DTLS packets (embedded in STUN or without embedding).

func (DTLSInSTUNAckAttribute) AddTo

AddTo adds DTLS-in-STUN-ACK attribute to message.

func (*DTLSInSTUNAckAttribute) GetFrom

func (a *DTLSInSTUNAckAttribute) GetFrom(m *stun.Message) error

GetFrom decodes DTLS-in-STUN-ACK attribute from message.

type DTLSInSTUNAttribute

type DTLSInSTUNAttribute []byte

DTLSInSTUNAttribute is a STUN attribute for carrying DTLS embedded in STUN.

func (DTLSInSTUNAttribute) AddTo

func (d DTLSInSTUNAttribute) AddTo(m *stun.Message) error

AddTo adds DTLS-in-STUN attribute to message.

func (*DTLSInSTUNAttribute) GetFrom

func (d *DTLSInSTUNAttribute) GetFrom(m *stun.Message) error

GetFrom decodes DTLS-in-STUN attribute from message.

type ECN

type ECN uint8

ECN is the two-bit Explicit Congestion Notification codepoint in an IP header.

func ECNFromAttributes

func ECNFromAttributes(attrs packetio.Attributes) (ECN, bool)

ECNFromAttributes returns the received packet's ECN codepoint.

type GatherOption

type GatherOption interface {
	// contains filtered or unexported methods
}

GatherOption configures a gathering pass.

func WithCandidateTypes

func WithCandidateTypes(candidateTypes []CandidateType) GatherOption

WithCandidateTypes sets the enabled candidate types for gathering. By default, host, server reflexive, and relay candidates are enabled.

Example:

err := agent.Gather(
	WithCandidateTypes([]CandidateType{CandidateTypeHost, CandidateTypeServerReflexive}),
)

func WithLocalCredentials

func WithLocalCredentials(ufrag, pwd string) GatherOption

WithLocalCredentials sets the local ICE username fragment and password for gathering. Gather calls without this option reuse the existing credentials. Changing either credential on a subsequent Gather starts a new ICE generation and restarts ICE. Each empty string generates a fresh value.

func WithNetworkTypes

func WithNetworkTypes(networkTypes []NetworkType) GatherOption

WithNetworkTypes sets the enabled candidate network types for candidate gathering. This controls the network types exposed in ICE candidates and used for pairing. Use WithTURNTransportProtocols to control the local TURN client-to-server transport. By default, all network types are enabled.

Example:

err := agent.Gather(
	WithNetworkTypes([]NetworkType{NetworkTypeUDP4, NetworkTypeUDP6}),
)

func WithTURNTransportProtocols

func WithTURNTransportProtocols(protocols []NetworkType) GatherOption

WithTURNTransportProtocols restricts protocols used for this gathering pass when connecting to TURN servers (TURN client <-> TURN server transport).

This is independent from WithNetworkTypes, which controls ICE candidate network types announced to the peer. Supported values are NetworkTypeUDP4/UDP6 and NetworkTypeTCP4/TCP6.

func WithURLs

func WithURLs(urls []*stun.URI) GatherOption

WithURLs sets the STUN/TURN server URLs used for this gathering pass.

type GatheringState

type GatheringState int

GatheringState describes the state of the candidate gathering process.

const (
	// GatheringStateUnknown represents an unknown state.
	GatheringStateUnknown GatheringState = iota

	// GatheringStateNew indicates candidate gathering is not yet started.
	GatheringStateNew

	// GatheringStateGathering indicates candidate gathering is ongoing.
	GatheringStateGathering

	// GatheringStateComplete indicates candidate gathering has been completed.
	GatheringStateComplete
)

func (GatheringState) String

func (t GatheringState) String() string

type IPFilterInfo

type IPFilterInfo struct {
	IP net.IP
	// CandidateType identifies how IP will be used: CandidateTypeHost for a host
	// candidate, CandidateTypeServerReflexive for a STUN client bind address, or
	// CandidateTypeRelay for a TURN client bind address.
	CandidateType CandidateType
}

IPFilterInfo describes a local IP considered for candidate gathering. IP is the local bind address (not the public address returned by STUN or TURN).

type MultiTCPMuxDefault

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

MultiTCPMuxDefault implements both TCPMux and AllConnsGetter, allowing users to pass multiple TCPMux instances to the ICE agent configuration.

func NewMultiTCPMuxDefault

func NewMultiTCPMuxDefault(muxes ...TCPMux) *MultiTCPMuxDefault

NewMultiTCPMuxDefault creates an instance of MultiTCPMuxDefault that uses the provided TCPMux instances.

func (*MultiTCPMuxDefault) Close

func (m *MultiTCPMuxDefault) Close() error

Close the multi mux, no further connections could be created.

func (*MultiTCPMuxDefault) GetAllConns

func (m *MultiTCPMuxDefault) GetAllConns(ufrag string, isIPv6 bool, local net.IP) ([]net.PacketConn, error)

GetAllConns returns a PacketConn for each underlying TCPMux.

func (*MultiTCPMuxDefault) GetConnByUfrag

func (m *MultiTCPMuxDefault) GetConnByUfrag(ufrag string, isIPv6 bool, local net.IP) (net.PacketConn, error)

GetConnByUfrag returns a PacketConn given the connection's ufrag, network and local address creates the connection if an existing one can't be found. This, unlike GetAllConns, will only return a single PacketConn from the first mux that was passed in to NewMultiTCPMuxDefault.

func (*MultiTCPMuxDefault) RemoveConnByUfrag

func (m *MultiTCPMuxDefault) RemoveConnByUfrag(ufrag string)

RemoveConnByUfrag stops and removes the muxed packet connection from all underlying TCPMux instances.

type MultiUDPMuxDefault

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

MultiUDPMuxDefault implements both UDPMux and AllConnsGetter, allowing users to pass multiple UDPMux instances to the ICE agent configuration.

func NewMultiUDPMuxDefault

func NewMultiUDPMuxDefault(muxes ...UDPMux) *MultiUDPMuxDefault

NewMultiUDPMuxDefault creates an instance of MultiUDPMuxDefault that uses the provided UDPMux instances.

func NewMultiUDPMuxFromPort

func NewMultiUDPMuxFromPort(port int, opts ...UDPMuxFromPortOption) (*MultiUDPMuxDefault, error)

NewMultiUDPMuxFromPort creates an instance of MultiUDPMuxDefault that listen all interfaces on the provided port.

func (*MultiUDPMuxDefault) Close

func (m *MultiUDPMuxDefault) Close() error

Close the multi mux, no further connections could be created.

func (*MultiUDPMuxDefault) GetConn

func (m *MultiUDPMuxDefault) GetConn(ufrag string, addr net.Addr) (net.PacketConn, error)

GetConn returns a PacketConn given the connection's ufrag and network creates the connection if an existing one can't be found.

func (*MultiUDPMuxDefault) GetListenAddresses

func (m *MultiUDPMuxDefault) GetListenAddresses() []net.Addr

GetListenAddresses returns the list of addresses that this mux is listening on.

func (*MultiUDPMuxDefault) RemoveConnByUfrag

func (m *MultiUDPMuxDefault) RemoveConnByUfrag(ufrag string)

RemoveConnByUfrag stops and removes the muxed packet connection from all underlying UDPMux instances.

type MulticastDNSMode

type MulticastDNSMode byte

MulticastDNSMode represents the different Multicast modes ICE can run in.

const (
	// MulticastDNSModeDisabled means remote mDNS candidates will be discarded, and local host candidates will use IPs.
	MulticastDNSModeDisabled MulticastDNSMode = iota + 1

	// MulticastDNSModeQueryOnly means remote mDNS candidates will be accepted, and local host candidates will use IPs.
	MulticastDNSModeQueryOnly

	// MulticastDNSModeQueryAndGather means remote mDNS candidates will be accepted,
	// and local host candidates will use mDNS.
	MulticastDNSModeQueryAndGather
)

MulticastDNSMode enum.

type NetworkType

type NetworkType int

NetworkType represents the type of network.

const (
	// NetworkTypeUDP4 indicates UDP over IPv4.
	NetworkTypeUDP4 NetworkType = iota + 1

	// NetworkTypeUDP6 indicates UDP over IPv6.
	NetworkTypeUDP6

	// NetworkTypeTCP4 indicates TCP over IPv4.
	NetworkTypeTCP4

	// NetworkTypeTCP6 indicates TCP over IPv6.
	NetworkTypeTCP6
)

func (NetworkType) IsIPv4

func (t NetworkType) IsIPv4() bool

IsIPv4 returns whether the network type is IPv4 or not.

func (NetworkType) IsIPv6

func (t NetworkType) IsIPv6() bool

IsIPv6 returns whether the network type is IPv6 or not.

func (NetworkType) IsReliable

func (t NetworkType) IsReliable() bool

IsReliable returns true if the network is reliable.

func (NetworkType) IsTCP

func (t NetworkType) IsTCP() bool

IsTCP returns true when network is TCP4 or TCP6.

func (NetworkType) IsUDP

func (t NetworkType) IsUDP() bool

IsUDP returns true when network is UDP4 or UDP6.

func (NetworkType) NetworkShort

func (t NetworkType) NetworkShort() string

NetworkShort returns the short network description.

func (NetworkType) String

func (t NetworkType) String() string

type NominationAttribute

type NominationAttribute struct {
	Value uint32
}

NominationAttribute represents a STUN Nomination attribute.

func Nomination

func Nomination(value uint32) NominationAttribute

Nomination creates a new STUN nomination attribute.

func (NominationAttribute) AddTo

func (a NominationAttribute) AddTo(m *stun.Message) error

AddTo adds a Nomination attribute to a STUN message.

func (NominationAttribute) AddToWithType

func (a NominationAttribute) AddToWithType(m *stun.Message, attrType stun.AttrType) error

AddToWithType adds a Nomination attribute to a STUN message using a specific attribute type.

func (*NominationAttribute) GetFrom

func (a *NominationAttribute) GetFrom(m *stun.Message) error

GetFrom decodes a Nomination attribute from a STUN message.

func (*NominationAttribute) GetFromWithType

func (a *NominationAttribute) GetFromWithType(m *stun.Message, attrType stun.AttrType) error

GetFromWithType decodes a Nomination attribute from a STUN message using a specific attribute type.

func (NominationAttribute) String

func (a NominationAttribute) String() string

String returns string representation of the nomination attribute.

type NominationSetter

type NominationSetter struct {
	Value    uint32
	AttrType stun.AttrType
}

NominationSetter is a STUN setter for nomination attribute with configurable type.

func (NominationSetter) AddTo

func (n NominationSetter) AddTo(m *stun.Message) error

AddTo adds a Nomination attribute to a STUN message using the configured attribute type.

type NominationValueGenerator

type NominationValueGenerator func() uint32

NominationValueGenerator generates strictly increasing nomination values for renomination.

func DefaultNominationValueGenerator

func DefaultNominationValueGenerator() NominationValueGenerator

DefaultNominationValueGenerator returns a generator that starts at 1 and increments for each call. This provides a simple, monotonically increasing sequence suitable for renomination.

type Option

type Option interface {
	AgentOption
	GatherOption
}

Option can be used with both NewAgent and Gather.

type PriorityAttr

type PriorityAttr uint32

PriorityAttr represents PRIORITY attribute.

func (PriorityAttr) AddTo

func (p PriorityAttr) AddTo(m *stun.Message) error

AddTo adds PRIORITY attribute to message.

func (*PriorityAttr) GetFrom

func (p *PriorityAttr) GetFrom(m *stun.Message) error

GetFrom decodes PRIORITY attribute from message.

type Role

type Role byte

Role represents ICE agent role, which can be controlling or controlled.

const (
	Controlling Role = iota
	Controlled
)

Possible ICE agent roles.

func (Role) MarshalText

func (r Role) MarshalText() (text []byte, err error)

MarshalText implements TextMarshaler.

func (Role) String

func (r Role) String() string

func (*Role) UnmarshalText

func (r *Role) UnmarshalText(text []byte) error

UnmarshalText implements TextUnmarshaler.

type TCPMux

type TCPMux interface {
	io.Closer
	GetConnByUfrag(ufrag string, isIPv6 bool, local net.IP) (net.PacketConn, error)
	RemoveConnByUfrag(ufrag string)
}

TCPMux is allows grouping multiple TCP net.Conns and using them like UDP net.PacketConns. The main implementation of this is TCPMuxDefault, and this interface exists to allow mocking in tests.

type TCPMuxDefault

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

TCPMuxDefault muxes TCP net.Conns into net.PacketConns and groups them by Ufrag. It is a default implementation of TCPMux interface.

func NewTCPMuxDefault

func NewTCPMuxDefault(params TCPMuxParams) *TCPMuxDefault

NewTCPMuxDefault creates a new instance of TCPMuxDefault.

func (*TCPMuxDefault) Close

func (m *TCPMuxDefault) Close() error

Close closes the listener and waits for all goroutines to exit.

func (*TCPMuxDefault) GetConnByUfrag

func (m *TCPMuxDefault) GetConnByUfrag(ufrag string, isIPv6 bool, local net.IP) (net.PacketConn, error)

GetConnByUfrag retrieves an existing or creates a new net.PacketConn. The returned conn is a refcounted — repeat calls return connection with increased refcount, so the connection's Close method should be called for each GetConn call to avoid leaks.

func (*TCPMuxDefault) LocalAddr

func (m *TCPMuxDefault) LocalAddr() net.Addr

LocalAddr returns the listening address of this TCPMuxDefault.

func (*TCPMuxDefault) RemoveConnByUfrag

func (m *TCPMuxDefault) RemoveConnByUfrag(ufrag string)

RemoveConnByUfrag closes and removes a net.PacketConn by Ufrag.

type TCPMuxParams

type TCPMuxParams struct {
	Listener       net.Listener
	Logger         logging.LeveledLogger
	ReadBufferSize int

	// Maximum buffer size for write op. 0 means no write buffer, the write op will block until the whole packet is written
	// if the write buffer is full, the subsequent write packet will be dropped until it has enough space.
	// a default 4MB is recommended.
	WriteBufferSize int

	// A new established connection will be removed if the first STUN binding request is not received within this timeout,
	// avoiding the client with bad network or attacker to create a lot of empty connections.
	// Default 30s timeout will be used if not set.
	FirstStunBindTimeout time.Duration

	// TCPMux will create connection from STUN binding request with an unknown username, if
	// the connection is not used in the timeout, it will be removed to avoid resource leak / attack.
	// Default 30s timeout will be used if not set.
	AliveDurationForConnFromStun time.Duration
}

TCPMuxParams are parameters for TCPMux.

type TCPType

type TCPType int

TCPType is the type of ICE TCP candidate as described in https://tools.ietf.org/html/rfc6544#section-4.5

const (
	// TCPTypeUnspecified is the default value. For example UDP candidates do not
	// need this field.
	TCPTypeUnspecified TCPType = iota
	// TCPTypeActive is active TCP candidate, which initiates TCP connections.
	TCPTypeActive
	// TCPTypePassive is passive TCP candidate, only accepts TCP connections.
	TCPTypePassive
	// TCPTypeSimultaneousOpen is like active and passive at the same time.
	TCPTypeSimultaneousOpen
)

func NewTCPType

func NewTCPType(value string) TCPType

NewTCPType creates a new TCPType from string.

func (TCPType) String

func (t TCPType) String() string

type UDPMux

type UDPMux interface {
	io.Closer
	GetConn(ufrag string, addr net.Addr) (net.PacketConn, error)
	RemoveConnByUfrag(ufrag string)
	GetListenAddresses() []net.Addr
}

UDPMux allows multiple connections to go over a single UDP port.

type UDPMuxDefault

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

UDPMuxDefault is an implementation of the interface.

func NewUDPMuxDefault

func NewUDPMuxDefault(params UDPMuxParams) *UDPMuxDefault

NewUDPMuxDefault creates an implementation of UDPMux.

func (*UDPMuxDefault) Close

func (m *UDPMuxDefault) Close() error

Close the mux, no further connections could be created.

func (*UDPMuxDefault) GetConn

func (m *UDPMuxDefault) GetConn(ufrag string, addr net.Addr) (net.PacketConn, error)

GetConn returns a PacketConn given the connection's ufrag and network address. creates the connection if an existing one can't be found. The returned conn is a refcounted — repeat calls return connection with increased refcount, so the connection's Close method should be called for each GetConn call to avoid leaks.

func (*UDPMuxDefault) GetListenAddresses

func (m *UDPMuxDefault) GetListenAddresses() []net.Addr

GetListenAddresses returns the list of addresses that this mux is listening on.

func (*UDPMuxDefault) IsClosed

func (m *UDPMuxDefault) IsClosed() bool

IsClosed returns true if the mux had been closed.

func (*UDPMuxDefault) LocalAddr

func (m *UDPMuxDefault) LocalAddr() net.Addr

LocalAddr returns the listening address of this UDPMuxDefault.

func (*UDPMuxDefault) RemoveConnByUfrag

func (m *UDPMuxDefault) RemoveConnByUfrag(ufrag string)

RemoveConnByUfrag stops and removes the muxed packet connection.

type UDPMuxFromPortOption

type UDPMuxFromPortOption func(*multiUDPMuxFromPortParam)

UDPMuxFromPortOption provide options for NewMultiUDPMuxFromPort.

func UDPMuxFromPortWithIPFilter

func UDPMuxFromPortWithIPFilter(f func(ip net.IP) (keep bool)) UDPMuxFromPortOption

UDPMuxFromPortWithIPFilter set the filter to filter out IP addresses that should not be used.

func UDPMuxFromPortWithInterfaceFilter

func UDPMuxFromPortWithInterfaceFilter(f func(string) (keep bool)) UDPMuxFromPortOption

UDPMuxFromPortWithInterfaceFilter set the filter to filter out interfaces that should not be used.

func UDPMuxFromPortWithLogger

func UDPMuxFromPortWithLogger(logger logging.LeveledLogger) UDPMuxFromPortOption

UDPMuxFromPortWithLogger set the logger for the created UDPMux.

func UDPMuxFromPortWithLoopback

func UDPMuxFromPortWithLoopback() UDPMuxFromPortOption

UDPMuxFromPortWithLoopback set loopback interface should be included.

func UDPMuxFromPortWithNet

func UDPMuxFromPortWithNet(n transport.Net) UDPMuxFromPortOption

UDPMuxFromPortWithNet sets the network transport to use.

func UDPMuxFromPortWithNetworks

func UDPMuxFromPortWithNetworks(networks ...NetworkType) UDPMuxFromPortOption

UDPMuxFromPortWithNetworks set the networks that should be used. default is both IPv4 and IPv6.

func UDPMuxFromPortWithReadBufferSize

func UDPMuxFromPortWithReadBufferSize(size int) UDPMuxFromPortOption

UDPMuxFromPortWithReadBufferSize set the UDP connection read buffer size.

func UDPMuxFromPortWithWriteBufferSize

func UDPMuxFromPortWithWriteBufferSize(size int) UDPMuxFromPortOption

UDPMuxFromPortWithWriteBufferSize set the UDP connection write buffer size.

type UDPMuxParams

type UDPMuxParams struct {
	Logger logging.LeveledLogger
	// UDPConn may implement AddrPortReaderWriter to opt in to
	// allocation-free address handling. *net.UDPConn will be
	// automatically adapted to implement AddrPortReaderWriter.
	UDPConn net.PacketConn

	// Required for gathering local addresses
	// in case a un UDPConn is passed which does not
	// bind to a specific local address.
	Net transport.Net
	// OnUnhandledPacket is called synchronously when a packet cannot be routed
	// to a muxed connection. It must not block. The data slice is reused after
	// the callback returns and must be copied if it is retained.
	OnUnhandledPacket func(data []byte, addr netip.AddrPort)
}

UDPMuxParams are parameters for UDPMux.

type UniversalUDPMux

type UniversalUDPMux interface {
	UDPMux
	GetXORMappedAddr(stunAddr net.Addr, deadline time.Duration) (*stun.XORMappedAddress, error)
	GetRelayedAddr(turnAddr net.Addr, deadline time.Duration) (*net.Addr, error)
	GetConnForURL(ufrag string, url string, addr net.Addr) (net.PacketConn, error)
}

UniversalUDPMux allows multiple connections to go over a single UDP port for host, server reflexive and relayed candidates. Actual connection muxing is happening in the UDPMux.

type UniversalUDPMuxDefault

type UniversalUDPMuxDefault struct {
	*UDPMuxDefault
	// contains filtered or unexported fields
}

UniversalUDPMuxDefault handles STUN and TURN servers packets by wrapping the original UDPConn overriding ReadFrom. It the passes packets to the UDPMux that does the actual connection muxing.

func NewUniversalUDPMuxDefault

func NewUniversalUDPMuxDefault(params UniversalUDPMuxParams) *UniversalUDPMuxDefault

NewUniversalUDPMuxDefault creates an implementation of UniversalUDPMux embedding UDPMux.

func (*UniversalUDPMuxDefault) GetConnForURL

func (m *UniversalUDPMuxDefault) GetConnForURL(ufrag string, url string, addr net.Addr) (net.PacketConn, error)

GetConnForURL add uniques to the muxed connection by concatenating ufrag and URL (e.g. STUN URL) to be able to support multiple STUN/TURN servers and return a unique connection per server.

func (*UniversalUDPMuxDefault) GetRelayedAddr

func (m *UniversalUDPMuxDefault) GetRelayedAddr(net.Addr, time.Duration) (*net.Addr, error)

GetRelayedAddr creates relayed connection to the given TURN service and returns the relayed addr. Not implemented yet.

func (*UniversalUDPMuxDefault) GetXORMappedAddr

func (m *UniversalUDPMuxDefault) GetXORMappedAddr(
	serverAddr net.Addr,
	deadline time.Duration,
) (*stun.XORMappedAddress, error)

GetXORMappedAddr returns *stun.XORMappedAddress if already present for a given STUN server. Makes a STUN binding request to discover mapped address otherwise. Blocks until the stun.XORMappedAddress has been discovered or deadline. Method is safe for concurrent use.

func (*UniversalUDPMuxDefault) GetXORMappedAddrContext

func (m *UniversalUDPMuxDefault) GetXORMappedAddrContext(
	ctx context.Context,
	serverAddr net.Addr,
	deadline time.Duration,
) (*stun.XORMappedAddress, error)

type UniversalUDPMuxParams

type UniversalUDPMuxParams struct {
	Logger logging.LeveledLogger
	// UDPConn may implement AddrPortReaderWriter to opt in to allocation-free
	// address handling. *net.UDPConn will automatically be adapted to
	// implement AddrPortReaderWriter.
	UDPConn               net.PacketConn
	XORMappedAddrCacheTTL time.Duration
	Net                   transport.Net
}

UniversalUDPMuxParams are parameters for UniversalUDPMux server reflexive.

type UseCandidateAttr

type UseCandidateAttr struct{}

UseCandidateAttr represents USE-CANDIDATE attribute.

func UseCandidate

func UseCandidate() UseCandidateAttr

UseCandidate is shorthand for UseCandidateAttr.

func (UseCandidateAttr) AddTo

func (UseCandidateAttr) AddTo(m *stun.Message) error

AddTo adds USE-CANDIDATE attribute to message.

func (UseCandidateAttr) IsSet

func (UseCandidateAttr) IsSet(m *stun.Message) bool

IsSet returns true if USE-CANDIDATE attribute is set.

Directories

Path Synopsis
examples
automatic-renomination command
Package main demonstrates automatic renomination with real network interfaces.
Package main demonstrates automatic renomination with real network interfaces.
continual-gathering command
Package main demonstrates continual gathering using a transport network change detector.
Package main demonstrates continual gathering using a transport network change detector.
nat-rules command
Package main provides a simple CLI that prints the host and srflx addresses produced by different address rewrite (1:1) rule configurations.
Package main provides a simple CLI that prints the host and srflx addresses produced by different address rewrite (1:1) rule configurations.
ping-pong command
Package main implements a simple example demonstrating a Pion-to-Pion ICE connection
Package main implements a simple example demonstrating a Pion-to-Pion ICE connection
Package internal implements internal functionality for Pions ICE module
Package internal implements internal functionality for Pions ICE module
fakenet
Package fakenet contains fake network abstractions
Package fakenet contains fake network abstractions
netutil
Package netutil provides network-related helpers.
Package netutil provides network-related helpers.
stun
Package stun contains ICE specific STUN code
Package stun contains ICE specific STUN code
taskloop
Package taskloop implements a task loop to run tasks sequentially in a separate Goroutine.
Package taskloop implements a task loop to run tasks sequentially in a separate Goroutine.

Jump to

Keyboard shortcuts

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