clientcore

package
v0.0.0-...-d9d1ba7 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: GPL-3.0 Imports: 35 Imported by: 3 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

broflake.go defines mid-layer abstractions for constructing and describing a Broflake instance

ipc.go defines structures and functionality for communication between client system components

producer.go defines standard producer behavior over WebRTC, including the discovery process, signaling, connection establishment, connection error detection, and reset. See: https://docs.google.com/spreadsheets/d/1qM1gwPRtTKTFfZZ0e51R7AdS6qkPlKMuJX3D3vmpG_U/edit#gid=471342300

protocol.go provides primitives for defining client protocol behavior

routing.go defines upstream and downstream router components

ui.go defines a standard interface for UI status bindings across build platforms

ui_default_impl.go implements the UI interface (see ui.go) for non-wasm build targets

user.go provides a facility for proxying user-generated bytestreams - ie, streams which originate from a process running on the user's computer (like a web browser) or streams which are generated as part of the user's Lantern control plane activity. We can operationalize a user stream in a WorkerFSM just like we do an RTCPeerConnection or a websocket.Conn, such that bytestreams from the user can be neatly managed alongside bytestreams from remote peers in their consumer table. In other words: we treat the user's web browser just like any connected consumer.

Index

Constants

View Source
const (
	ChunkIPC msgType = iota
	PathAssertionIPC
	ConsumerInfoIPC
	ConnectivityCheckIPC
	ExitBytesIPC
)
View Source
const (
	NoRoute        = workerID(-1)
	BroadcastRoute = workerID(-2)
)
View Source
const (
	STUNPreflightOK        = common.PreflightOK
	STUNPreflightNoReply   = common.PreflightNoReply
	STUNPreflightNoSocket  = common.PreflightNoSocket
	STUNPreflightNoServers = common.PreflightNoServers
)

STUN preflight outcomes; see common's Preflight* for what each means.

Variables

View Source
var ErrNoConnectedPath = errors.New("unbounded: no connected WebRTC path")

ErrNoConnectedPath is returned by a rooms-only consumer's QUICLayer.DialContext, and so by its SOCKS5Dialer, while it has gone WebRTCOptions.ConsumerNoPathGrace without a connected WebRTC slot: with no path to the egress, a dial would only wait for one.

Functions

func CreateHTTPTransport

func CreateHTTPTransport(c ReliableStreamLayer) *http.Transport

func DefaultSTUNBatchFunc

func DefaultSTUNBatchFunc(size uint32) (batch []string, err error)

func DownstreamUIHandler

func DownstreamUIHandler(ctx context.Context, ui UIImpl, netstated, tag string) func(msg IPCMsg)

func NewBroflake

func NewBroflake(bfOpt *BroflakeOptions, rtcOpt *WebRTCOptions, egOpt *EgressOptions) (bfconn *BroflakeConn, ui *UIImpl, err error)

func NewConsumerRouter

func NewConsumerRouter(bus *ipcChan, table *WorkerTable) *consumerRouter

func NewIpcObserver

func NewIpcObserver(bufferSz int, onTx, onRx func(IPCMsg)) *ipcObserver

func NewProducerJITRouter

func NewProducerJITRouter(bus *ipcChan, table *WorkerTable) *producerJITRouter

func NewProducerPoolRouter

func NewProducerPoolRouter(bus *ipcChan, table *WorkerTable) *producerPoolRouter

func NewProducerSerialRouter

func NewProducerSerialRouter(bus *ipcChan, table *WorkerTable, cTableSize int) *producerSerialRouter

func NewProducerUserStream

func NewProducerUserStream(wg *sync.WaitGroup) (*BroflakeConn, *WorkerFSM)

func UpstreamUIHandler

func UpstreamUIHandler(ctx context.Context, ui UIImpl, netstated, tag string) func(msg IPCMsg)

UpstreamUIHandler handles the bus's upstream traffic. A direct exit session's downstream bytes reach it too, and go to OnDownstreamChunk without counting toward a DownstreamUIHandler's throughput: uiHandlers pairs the two so that they do.

Types

type BroflakeConn

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

func (BroflakeConn) Close

func (c BroflakeConn) Close() error

func (BroflakeConn) LocalAddr

func (c BroflakeConn) LocalAddr() net.Addr

func (BroflakeConn) ReadFrom

func (c BroflakeConn) ReadFrom(p []byte) (n int, addr net.Addr, err error)

func (BroflakeConn) SetDeadline

func (c BroflakeConn) SetDeadline(t time.Time) error

func (BroflakeConn) SetReadDeadline

func (c BroflakeConn) SetReadDeadline(t time.Time) error

XXX: A note about deadlines: as of quic-go 0.34, the QUIC dialer didn't seem to care about read or write deadlines, and it was happy to use a net.PacketConn which didn't properly implement them. But when we bumped to quic-go 0.40, it emerged that the dialer wouldn't work unless we added support for read deadlines. Since there's still no evidence that the dialer cares about write deadlines, we haven't added support for those yet.

func (BroflakeConn) SetWriteDeadline

func (c BroflakeConn) SetWriteDeadline(t time.Time) error

func (BroflakeConn) WriteTo

func (c BroflakeConn) WriteTo(p []byte, addr net.Addr) (n int, err error)

type BroflakeEngine

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

func NewBroflakeEngine

func NewBroflakeEngine(cTable, pTable *WorkerTable, ui UI, wg *sync.WaitGroup, netstated, tag string) *BroflakeEngine

func (*BroflakeEngine) ConsumerConnected

func (b *BroflakeEngine) ConsumerConnected() (connected bool, since time.Time)

ConsumerConnected reports whether any of a consumer's (ClientType "desktop") WebRTC slots is connected, and since when that has been so: the time the first slot connected or the last one disconnected. Until a slot has first connected, since is zero, so a caller can tell a consumer still making its first connection from one that has lost its helper. A widget reports false and the zero time.

Connected means a slot's WebRTC data channel to a volunteer, or its direct exit session (see ConsumerSlot.DirectExit), is open, not that the QUIC connection over it, or the egress behind the volunteer, is reachable.

A rooms-only consumer's QUICLayer fails its streams and dials once it has gone WebRTCOptions.ConsumerNoPathGrace with no WebRTC data channel open (see ErrNoConnectedPath). A direct exit doesn't count there, since it carries no QUIC traffic.

func (*BroflakeEngine) ConsumerSlots

func (b *BroflakeEngine) ConsumerSlots() []ConsumerSlot

ConsumerSlots returns a consumer's (ClientType "desktop") WebRTC slots: for each, whether it is connected and, if so, the helper pairing it came through. nil for a widget.

type BroflakeOptions

type BroflakeOptions struct {
	ClientType             string
	CTableSize             int
	PTableSize             int
	BusBufferSz            int
	Netstated              string
	OnConnectionChangeFunc ConnectionChangeFunc
	// OnConnectionChangeInfoFunc, if non-nil, is called with each producer
	// connection change, after OnConnectionChangeFunc, with the whole
	// ConsumerInfo, including its pairing.
	OnConnectionChangeInfoFunc ConnectionChangeInfoFunc
	// OnConsumerSlotChangeFunc, if non-nil, is called when one of a
	// consumer's (ClientType "desktop") WebRTC slots connects or disconnects.
	// See also BroflakeEngine.ConsumerSlots.
	OnConsumerSlotChangeFunc ConsumerSlotChangeFunc
	// OnDownstreamChunkFunc receives bytes relayed from the egress to a consumer
	OnDownstreamChunkFunc ChunkFunc
	// OnUpstreamChunkFunc receives bytes relayed from a consumer to the egress
	OnUpstreamChunkFunc ChunkFunc
}

func NewDefaultBroflakeOptions

func NewDefaultBroflakeOptions() *BroflakeOptions

type ChunkFunc

type ChunkFunc func(size int, workerIdx int)

ChunkFunc is a callback for data relayed for a consumer. size is in bytes; workerIdx is the consumer's connection slot, matching the workerIdx passed to ConnectionChangeFunc. Downstream callbacks fire once per chunk on the data path, so implementations must be cheap and non-blocking (e.g. an atomic add); upstream callbacks are batched per slot at uiRefreshHz.

type ConnectionChangeFunc

type ConnectionChangeFunc func(state int, workerIdx int, addr net.IP)

ConnectionChangeFunc is a callback for consumer connection state changes. state: 1 = connected, -1 = disconnected. When state == 1 (connected), addr is the IPv4 or IPv6 address of the new consumer. When state == -1 (disconnected), addr may be nil and should not be assumed to be non-nil.

type ConnectionChangeInfoFunc

type ConnectionChangeInfoFunc func(state int, workerIdx int, info common.ConsumerInfo)

ConnectionChangeInfoFunc is ConnectionChangeFunc with the whole ConsumerInfo in place of its address. state and workerIdx are as for ConnectionChangeFunc. When state == 1, info.Addr is the consumer's address, and info.Pairing is the helper pairing the consumer came through, or "" for a pool consumer or one whose pairing couldn't be attributed (see common.ConsumerInfo.Pairing). When state == -1, info is zero. info.Pairing must never be logged.

type ConsumerSlot

type ConsumerSlot struct {
	WorkerIdx int
	Connected bool
	// Pairing is the helper pairing of the room genesis a connected slot
	// answered, or "" for a pool producer, or when Freddie predates pairing
	// attribution. Never log it.
	Pairing string
	// DirectExit is whether a connected slot is a direct exit session, which carries no QUIC
	// traffic (see WebRTCOptions.OnExitPath).
	DirectExit bool
}

ConsumerSlot is one of a consumer's WebRTC connection slots.

type ConsumerSlotChangeFunc

type ConsumerSlotChangeFunc func(state int, workerIdx int, pairing string)

ConsumerSlotChangeFunc is a callback for a consumer's own WebRTC connection slots. state: 1 = connected, -1 = disconnected. workerIdx is the slot. When state == 1, pairing is the helper pairing of the room genesis the slot answered, or "" for a pool producer, or when Freddie predates pairing attribution. When state == -1, pairing is "". It is called on the slot's own goroutine, so it must be cheap and must not block. pairing must never be logged.

type EgressOptions

type EgressOptions struct {
	Addr           string
	Endpoint       string
	ConnectTimeout time.Duration
	ErrorBackoff   time.Duration
	// HTTPClient makes the WebSocket handshake to the egress; nil uses
	// http.DefaultClient. A widget running inside a VPN's own process can't
	// resolve the egress through the system resolver, which points into the
	// tunnel its sockets bypass, so it passes a client that dials around it.
	// Its Timeout must be zero: ConnectTimeout bounds the dial.
	HTTPClient *http.Client
}

func NewDefaultEgressOptions

func NewDefaultEgressOptions() *EgressOptions

type ExitOptions

type ExitOptions struct {
	// Ready reports whether the producer can exit a session of this kind now. While it can exit a
	// kind that a consumer reaching a genesis could get, the genesis offers an obfuscated direct
	// exit (see common.GenesisMsg.DirectExitObfs). An offer for a kind it can't exit is dropped.
	Ready func(personal bool) bool
	// Params mints a session's credentials: the SHA-256 pin of the exit certificate's public key,
	// and a password for this session alone. ok is false when the producer can no longer exit a
	// session of this kind.
	Params func(personal bool) (certPin, password string, ok bool)
	// Serve serves one session on conn, which carries only that session's consumer, with the
	// policy for its kind, obfuscated with Salamander keyed from password. It runs on its own goroutine and must return once ctx ends or conn's
	// reads fail.
	Serve func(ctx context.Context, conn net.PacketConn, password string, personal bool)
	// OnSession, if set, is called as each session connects, with whether it is a direct exit
	// or relays to the egress server as before.
	OnSession func(directExit bool)
}

ExitOptions let a producer carry sessions over ICE alone and exit their traffic itself, instead of relaying it to the egress server. A browser widget, which can't dial destinations, leaves them nil. Ready, Params and OnSession run on the signaling path, so they must be cheap and must not block.

Each session is personal or pool, by the offer that opens it. A personal session's offer carries, on the envelope Freddie built for it, the pairing of one of the producer's own unexpired volunteer tickets: Freddie stamps it only for a consumer (a friend) that got the genesis through that pairing's room and is admitted to the room as it offers. Every other session is a pool session, as is every session through a Freddie that predates stamping. The embedder decides what each kind may reach, and the consumer learns its session's kind (ExitPath.Personal).

The exit is obfuscated: Serve, and the embedder's consumer side that takes each ExitPath, must both run Hysteria2 with Salamander keyed from the session password. broflake only carries the signal (common.GenesisMsg.DirectExitObfs) and the password; the key derivation lives with the embedder (lantern-box). Peers that predate obfuscation never pair with these exits: they relay.

type ExitPath

type ExitPath struct {
	Conn     net.PacketConn
	CertPin  string
	Password string
	Relayed  bool
	// Personal says whether the producer serves this session under its personal policy, with no
	// allowlist, rather than the pool's (see ExitOptions). A consumer must send a pool session
	// only what the pool policy admits.
	Personal bool
}

ExitPath is a consumer's connected direct exit session (see common.GenesisMsg.DirectExitObfs). Conn reaches the producer's exit, which takes only the certificate CertPin pins and the session's Password, and is obfuscated with Salamander keyed from Password (see ExitOptions). Conn's addresses are placeholders, the same for every session, not either side's: its peer is always the producer. Relayed says whether ICE chose a TURN relay. Closing Conn ends the session, and once the session ends, Conn's reads fail. Never logged: it carries the session's credentials.

type FSMstate

type FSMstate func(ctx context.Context, com *ipcChan, input []interface{}) (int, []interface{})

FSMstate encapsulates logic for one state in a WorkerFSM. An FSMstate must return an int corresponding to the next state and a list of any inputs to propagate to the next state. TODO: a state's number simply corresponds to its index in WorkerFSM.state, but we perform no sanity checking of state indices.

type IPCMsg

type IPCMsg struct {
	IpcType msgType
	Data    interface{}
	Wid     workerID
}

type QUICLayer

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

func NewQUICLayer

func NewQUICLayer(bfconn *BroflakeConn, tlsConfig *tls.Config) (*QUICLayer, error)

func (*QUICLayer) Close

func (c *QUICLayer) Close()

Close a QUICLayer which was previously opened via a call to DialAndMaintainQUICConnection.

func (*QUICLayer) DialContext

func (c *QUICLayer) DialContext(ctx context.Context) (net.Conn, error)

func (*QUICLayer) ListenAndMaintainQUICConnection

func (c *QUICLayer) ListenAndMaintainQUICConnection()

type ReliableStreamLayer

type ReliableStreamLayer interface {
	DialContext(ctx context.Context) (net.Conn, error)
}

type SOCKS5Dialer

type SOCKS5Dialer func(ctx context.Context, network, addr string) (net.Conn, error)

func CreateSOCKS5Dialer

func CreateSOCKS5Dialer(c ReliableStreamLayer) SOCKS5Dialer

type STUNCache

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

STUNCache implements the operations which support our strategy for evading STUN server blocking in-country. That is: populate the cache with the largest set of currently known STUN servers and shuffle it; select a cohort of the first N servers in the list to use in parallel; if any of those servers work, continue using that cohort; if all of those servers fail, delete the cohort from the list; when the list is empty, repeat the steps.

type STUNPreflightResult

type STUNPreflightResult struct {
	// Outcome is one of the STUNPreflight* values.
	Outcome string
	// Servers is how many STUN servers the preflight asked.
	Servers int
	// Elapsed is how long the preflight took.
	Elapsed time.Duration
	// Cause, for STUNPreflightNoSocket, is why the socket failed: one of common's
	// PreflightCause* values.
	Cause string
}

STUNPreflightResult is how a producer's STUN preflight went, reported to WebRTCOptions.OnSTUNPreflight.

type TableRouter

type TableRouter interface {
	Init(ctx context.Context)
	// contains filtered or unexported methods
}

A tableRouter is a multiplexer/demultiplexer which functions as the interface to a WorkerTable, abstracting the complexity of connecting a WorkerTable of arbitrary size to the message bus. An upstream tableRouter, in managing a WorkerTable consisting of workers which handle egress traffic, decides how to best utilize those connections (ie, in serial, in parallel, 1:1, multipath, etc.)

type UI

type UI interface {
	Init(bf *BroflakeEngine)

	Start()

	Stop()

	Debug()

	OnReady()

	OnStartup()

	OnDownstreamChunk(size int, workerIdx int)

	OnDownstreamThroughput(bytesPerSec int)

	OnUpstreamChunk(size int, workerIdx int)

	OnConsumerConnectionChange(state int, workerIdx int, addr net.IP)
}

type UIImpl

type UIImpl struct {
	UI
	BroflakeEngine             *BroflakeEngine
	OnConnectionChangeFunc     ConnectionChangeFunc
	OnConnectionChangeInfoFunc ConnectionChangeInfoFunc
	OnDownstreamChunkFunc      ChunkFunc
	OnUpstreamChunkFunc        ChunkFunc
}

func (UIImpl) Debug

func (ui UIImpl) Debug()

func (*UIImpl) Init

func (ui *UIImpl) Init(bf *BroflakeEngine)

func (UIImpl) OnConsumerConnectionChange

func (ui UIImpl) OnConsumerConnectionChange(state int, workerIdx int, addr net.IP)

func (UIImpl) OnDownstreamChunk

func (ui UIImpl) OnDownstreamChunk(size int, workerIdx int)

func (UIImpl) OnDownstreamThroughput

func (ui UIImpl) OnDownstreamThroughput(bytesPerSec int)

func (UIImpl) OnReady

func (ui UIImpl) OnReady()

func (UIImpl) OnStartup

func (ui UIImpl) OnStartup()

func (UIImpl) OnUpstreamChunk

func (ui UIImpl) OnUpstreamChunk(size int, workerIdx int)

func (UIImpl) Start

func (ui UIImpl) Start()

func (UIImpl) Stop

func (ui UIImpl) Stop()

type WebRTCOptions

type WebRTCOptions struct {
	DiscoverySrv      string
	Endpoint          string
	GenesisAddr       string
	NATFailTimeout    time.Duration
	STUNBatch         func(size uint32) (batch []string, err error)
	STUNBatchSize     uint32
	Tag               string
	HTTPClient        *http.Client
	Patience          time.Duration
	ErrorBackoff      time.Duration
	ConsumerSessionID string
	// ConsumerCountry is an optional ISO-3166-1 alpha-2 country the consumer
	// discloses so the egress can attribute traffic to the region it is actually
	// serving. Consumer-side only, like ConsumerSessionID above.
	//
	// Empty is a valid and complete choice: it emits the same 3-element subprotocol
	// list as every release before this one, so a consumer that declines is
	// byte-identical on the wire to one that predates the field.
	//
	// Note this travels consumer -> donor -> egress, so the donor can read it. That
	// discloses nothing the donor does not already have: producer.go extracts the
	// consumer's public address from the remote ICE candidates and the widget
	// geolocates it for the UI globe. The marginal disclosure is to the *egress*,
	// which otherwise cannot know.
	//
	// A consumer also declares it to Freddie when subscribing to the genesis stream, so Freddie
	// can steer genesis messages from producers who target that country (see TargetCountries).
	ConsumerCountry string
	// TargetCountries optionally lists ISO-3166-1 alpha-2 countries whose consumers this
	// *producer* prefers to serve. Freddie delivers this producer's genesis messages only to
	// waiting consumers from these countries when there are any, and to everyone otherwise, so a
	// targeting producer is never left idle. Empty means no preference, which is byte-identical on
	// the wire to releases before this field existed. Producer-side only.
	//
	// Set it before NewBroflake; to change it on a running instance use SetTargetCountries, which
	// takes effect from each worker's next genesis message.
	TargetCountries []string
	// RoomTickets optionally lists helper pairing tickets (see
	// common/helperticket) for pairings this client belongs to. A producer
	// sends its volunteer tickets with every genesis message, and Freddie
	// offers that genesis to the consumers waiting in those pairings' rooms
	// before anyone else. A consumer sends its inviter tickets when it
	// subscribes, and Freddie puts it in those rooms. Freddie verifies every
	// ticket and ignores invalid ones. Empty is byte-identical on the wire to
	// releases before this field.
	//
	// Set it before NewBroflake; on a running instance use SetRoomTickets,
	// which takes effect from each worker's next genesis message or
	// subscribe. RoomTicketSource, when set, takes precedence.
	RoomTickets []string
	// RoomTicketSource, if non-nil, is called for the current tickets at each
	// genesis message and each subscribe instead of reading RoomTickets. It
	// runs on the signaling path, so it must be cheap and must not block. Set
	// it before NewBroflake.
	RoomTicketSource func() []string
	// RoomsOnly, on a producer, tells Freddie to offer its genesis messages
	// to the consumers in its rooms and nobody else. The zero value serves
	// everyone, as every release before rooms did, and sends nothing new on
	// the wire. A Freddie that predates rooms refuses a rooms-only
	// producer's genesis messages rather than broadcast them (see
	// common.SignalSendToGenesisRooms), so it is offered to nobody there.
	// On a running instance use SetServePool.
	RoomsOnly bool
	// ConsumerRoomsOnly, on a consumer, makes it answer only genesis messages
	// Freddie delivered through one of its rooms (see RoomTickets), so it
	// connects only through its own helpers and never through a stranger.
	// Without room tickets it doesn't subscribe, since nothing it would answer
	// can reach it, but waits for them.
	// Pool genesis messages are ignored, and repeated failures with room
	// helpers never fall back to the pool. Without a room helper online the
	// consumer has no connection at all. The zero value answers everyone, as
	// every release before it did. It changes nothing on the wire. Set it
	// before NewBroflake.
	ConsumerRoomsOnly bool
	// ConsumerNoPathGrace is how long a rooms-only consumer (see
	// ConsumerRoomsOnly) may go without a connected WebRTC slot before its
	// QUICLayer fails fast: the streams open on its QUIC connection are
	// reset, and its dials fail at once with ErrNoConnectedPath, until a slot
	// connects again. Without it a stream sent into a dead path waits on the
	// QUIC connection, which outlives the path by up to MaxIdleTimeout. Zero
	// means defaultConsumerNoPathGrace, and a negative value turns the guard
	// off. A pool consumer has no guard: the pool soon offers it another
	// volunteer. Set it before NewBroflake.
	ConsumerNoPathGrace time.Duration
	// Net is the transport pion opens its UDP sockets on, for both the
	// consumer and the producer. nil uses the host's network stack. Browser
	// (wasm) builds ignore it: the WebRTC stack there is the browser's.
	Net transport.Net
	// ICEUDPMux, if set on a native build, carries the consumer's or
	// producer's host-candidate WebRTC traffic on one UDP socket, which a node
	// can map on its router so the other side reaches it directly. pion tells
	// sessions apart by ICE username, so every slot, consumer or producer,
	// can share one. Server-reflexive candidates from STUN still use sockets
	// of their own. Build it on Net, or traffic through it escapes Net. The
	// caller owns it and closes it once the widget has stopped. Browser builds
	// ignore it.
	ICEUDPMux ice.UDPMux
	// ICEUDPMuxExternalIP is the IPv4 address ICEUDPMux's port is reachable at
	// from outside, through a router mapping that keeps the port. The peer
	// adds it as a host candidate on that port, alongside its usual
	// candidates, and STUN becomes best-effort: if the STUN list or the STUN
	// check fails, the peer still connects on the mapped address. A mapping
	// that doesn't work costs only a candidate that never answers. Ignored
	// without ICEUDPMux.
	ICEUDPMuxExternalIP string
	// CovertDTLS configures DTLS ClientHello fingerprint-resistance on the
	// producer/widget side. See common/covertdtls and net4people/bbs#603
	// for background. The zero value disables the feature.
	CovertDTLS covertdtls.Config
	// Tuning overrides pion's ICE, DTLS and SCTP defaults on native builds.
	// The zero value keeps every default.
	Tuning WebRTCTuning
	// Exit, on a producer, lets it exit sessions itself (see ExitOptions). Nil, the default and
	// always in a browser widget, relays every session to the egress server as before. Set it
	// before NewBroflake.
	Exit *ExitOptions
	// OnExitPath, on a consumer, takes each direct exit session as it connects (see ExitPath). It
	// runs on the worker's goroutine and must not block. While it is nil, the consumer answers
	// every genesis with an SDP offer, as before. Set it before NewBroflake.
	OnExitPath func(ExitPath)
	// TakeExit, if set, is asked before each direct exit the consumer could take. While it reports
	// false, the consumer answers every genesis with an SDP offer, as if OnExitPath were nil, so an
	// embedder can fall back after direct exits keep failing. It runs on the signaling path, so it
	// must be cheap and must not block.
	TakeExit func() bool
	// ConnectGrace is the least time left for DTLS and the data channel to open once ICE connects,
	// extending NATFailTimeout when ICE connects near its end.
	ConnectGrace time.Duration
	// OnSTUNPreflight, if set, is called with each producer STUN preflight's result, on the
	// producer worker's goroutine, so it must not block.
	OnSTUNPreflight func(STUNPreflightResult)
	// VPNStatus, if set, returns the embedding app's VPN state, which a producer reports to Freddie
	// with its STUN preflights. Freddie counts radiance's vpn.VPNStatus values and no others.
	VPNStatus func() string
	// VolunteerKind, on a producer, is one of common's VolunteerKind* values, which it reports on
	// every genesis so Freddie can count each kind's connect rate. Empty sends nothing.
	VolunteerKind string
	// VolunteerMapped, on a producer, says its WebRTC traffic runs through a port mapped on its
	// router and verified from outside. It is reported with VolunteerKind.
	VolunteerMapped bool
	// VolunteerSocket, on a producer, sends its genesis and answer messages to Freddie over one
	// WebSocket that all its workers share, rather than as a POST each (see
	// common.VolunteerSocketEndpoint), and POSTs whenever the socket can't be had. Its rooms-only
	// geneses also ask Freddie to hold them for their rooms' next consumer (see common.HoldField).
	// The zero value POSTs, as every release before it did.
	VolunteerSocket bool
}

func NewDefaultWebRTCOptions

func NewDefaultWebRTCOptions() *WebRTCOptions

func (*WebRTCOptions) CurrentRoomTickets

func (o *WebRTCOptions) CurrentRoomTickets() []string

CurrentRoomTickets returns the tickets the next genesis message or subscribe will carry: RoomTicketSource's if it is set, else RoomTickets.

func (*WebRTCOptions) ServesPool

func (o *WebRTCOptions) ServesPool() bool

ServesPool reports whether a producer's genesis messages may go to consumers outside its rooms.

func (*WebRTCOptions) SetRoomTickets

func (o *WebRTCOptions) SetRoomTickets(tickets []string)

SetRoomTickets replaces RoomTickets on a live instance. Malformed tickets are dropped. Tickets expire after 15 minutes, so the caller renews them; each worker picks up the change with its next genesis message or subscribe.

func (*WebRTCOptions) SetServePool

func (o *WebRTCOptions) SetServePool(serve bool)

SetServePool sets whether a producer's genesis messages may go to consumers outside its rooms. Each producer worker picks up the change with its next genesis message; established connections are unaffected.

func (*WebRTCOptions) SetTargetCountries

func (o *WebRTCOptions) SetTargetCountries(countries []string)

SetTargetCountries replaces TargetCountries on a live instance. Invalid codes are dropped. Each producer worker picks up the change with its next genesis message; established connections are unaffected.

type WebRTCTuning

type WebRTCTuning struct {
	// ICEMaxBindingRequests caps the connectivity checks sent on a candidate pair before it is
	// marked failed. Unset, native peers check for their whole NATFailTimeout (see checkingFor)
	// rather than stopping at pion's default of 7.
	ICEMaxBindingRequests uint16
	// STUNGatherTimeout bounds how long gathering waits on each STUN server. pion's default is 5s,
	// so one unresponsive server in a batch delays every handshake by that much.
	STUNGatherTimeout time.Duration
	// ICEDisconnectedTimeout, ICEFailedTimeout and ICEKeepaliveInterval are pion's ICE liveness
	// timers: 5s, 25s and 2s by default. Setting any one sets all three, the rest at their defaults.
	ICEDisconnectedTimeout time.Duration
	ICEFailedTimeout       time.Duration
	ICEKeepaliveInterval   time.Duration
	// SrflxAcceptanceMinWait is how long the controlling agent waits before nominating a server
	// reflexive pair, which is the usual pair between a consumer and a volunteer. pion's default is
	// 500ms; zero can't express "don't wait", so use 1ms for that.
	SrflxAcceptanceMinWait time.Duration
	// DTLSRetransmitInterval is the initial DTLS handshake retransmission interval. pion's default
	// is 1s, doubling after each loss, so a few lost handshake packets use up most of
	// NATFailTimeout on a lossy path.
	DTLSRetransmitInterval time.Duration
	// SCTPRTOMax caps SCTP's retransmission timeout, which backs off on loss. pion's default is
	// 60s, long enough to stall a data channel after a burst of loss.
	SCTPRTOMax time.Duration
	// SCTPMaxReceiveBuffer is the SCTP receive buffer in bytes, which bounds a reliable channel's
	// window. pion's default is 1MiB.
	SCTPMaxReceiveBuffer uint32
	// DataChannelQueueTarget is the queuing delay a data channel's send buffer may hold above the
	// path's own before packets are dropped (see sendGate). Zero is defaultQueueTarget. It has no
	// effect in the browser widget, whose WebRTC stack reports no round trip, so its gate never
	// closes.
	DataChannelQueueTarget time.Duration
}

WebRTCTuning overrides pion's transport defaults on native consumers and producers, so they can be tuned from server config rather than by release. A zero field keeps pion's default, so the zero value changes nothing. A browser's WebRTC stack can't be tuned, so the widget ignores it.

func ParseWebRTCTuning

func ParseWebRTCTuning(opts map[string]string) (tuning WebRTCTuning, ignored []string)

ParseWebRTCTuning turns a server's tuning map into a WebRTCTuning. Keys it doesn't recognize are reported in ignored rather than rejected: the option is a map precisely so that a server can send knobs newer clients understand without breaking older ones, which is the whole point of tuning from config. A recognized key with a bad value is reported too and left at its default.

type WorkerFSM

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

WorkerFSM implements a Mealy machine: https://en.wikipedia.org/wiki/Mealy_machine A WorkerFSM independently manages the lifetime of a single connection slot. A client maintains two pools of WorkerFSMs - one for upstream channels and one for downstream channels.

func NewConsumerWebRTC

func NewConsumerWebRTC(options *WebRTCOptions, wg *sync.WaitGroup) *WorkerFSM

func NewEgressConsumerWebSocket

func NewEgressConsumerWebSocket(options *EgressOptions, wg *sync.WaitGroup) *WorkerFSM

func NewJITEgressConsumer

func NewJITEgressConsumer(options *EgressOptions, act *activation, wg *sync.WaitGroup) *WorkerFSM

func NewProducerWebRTC

func NewProducerWebRTC(options *WebRTCOptions, wg *sync.WaitGroup) *WorkerFSM

func NewWorkerFSM

func NewWorkerFSM(wg *sync.WaitGroup, states []FSMstate) *WorkerFSM

Construct a new WorkerFSM

func (*WorkerFSM) Start

func (fsm *WorkerFSM) Start()

Start this WorkerFSM

func (*WorkerFSM) Stop

func (fsm *WorkerFSM) Stop()

Stop this WorkerFSM (takes effect upon returning from the currently executing state)

type WorkerTable

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

WorkerTable ts the structure we use to represent the producer and consumer tables

func NewWorkerTable

func NewWorkerTable(list []WorkerFSM) *WorkerTable

Construct a new WorkerTable; len(list) corresponds to max concurrent connections for this table. By mixing WorkerFSMs, you can construct a table consisting of connections over different transports.

func (WorkerTable) Size

func (t WorkerTable) Size() int

func (WorkerTable) Start

func (t WorkerTable) Start()

Start all of this table's workers

func (WorkerTable) Stop

func (t WorkerTable) Stop()

Stop all of this table's workers

Jump to

Keyboard shortcuts

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