bridge

package
v0.35.6 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: GPL-3.0 Imports: 56 Imported by: 1 module, 0 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

Index

Constants

View Source
const RemoteUpdateMinVersion = legacy.RemoteUpdateMinVersion

RemoteUpdateMinVersion is the oldest npc release that acts on update requests.

Variables

View Source
var (
	// ErrClientOffline is returned by RequestClientUpdate for a client that
	// has no connected npc.
	ErrClientOffline = errors.New("client is offline")
	// ErrUpdateUnsupported is returned by RequestClientUpdate when no
	// connected npc of the client acts on update requests.
	ErrUpdateUnsupported = fmt.Errorf("client version does not support remote update, npc %s or newer is required", RemoteUpdateMinVersion)
)
View Source
var ErrClosed = errors.New("bridge closed")

ErrClosed is returned by StartTunnel on a bridge that is closed.

Functions

func CoreRecord added in v0.35.1

func CoreRecord(c *model.Client) (coreapi.ClientRecord, bool)

CoreRecord is what the new protocol entry knows of client c; ok is false for a client it does not admit.

Types

type Bridge

type Bridge struct {
	VirtualMixListener *netx.ChanListener
	OpenHost           chan *model.Host
	OpenTask           chan *model.Tunnel
	CloseTask          chan *model.Tunnel
	CloseClient        chan int

	VirtualWssListener *netx.ChanListener

	Client *sync.Map

	VirtualWsListener  *netx.ChanListener
	VirtualTlsListener *netx.ChanListener

	VirtualTcpListener *netx.ChanListener
	// contains filtered or unexported fields
}

func NewTunnel

func NewTunnel(store Store, runList *sync.Map, opts Options) *Bridge

NewTunnel returns a bridge of the entries in store; runList holds the running tunnels. Changes of the stored entries are reported to it through EntriesChanged.

func (*Bridge) CarrierRoute added in v0.35.0

func (s *Bridge) CarrierRoute(target string, r *http.Request, next http.Handler) http.Handler

CarrierRoute returns the handler of r when a domain route to the bridge target gives it to the new protocol, nil when it stays on the route's usual way: bridge://ws and wss keep a WebSocket that is not marked as the new protocol's for the old protocol (§12), and tcp and tls take no HTTP. A request that is no carrier goes to next.

func (*Bridge) Cause added in v0.35.0

func (s *Bridge) Cause() error

Cause returns why the bridge closed: the failure of a listener, or lifecycle.ErrClosed after Close; nil while it is open.

func (*Bridge) CliProcess added in v0.33.7

func (s *Bridge) CliProcess(c *conn.Conn, tunnelType string)

func (*Bridge) ClientCanUpdate added in v0.35.0

func (s *Bridge) ClientCanUpdate(id int) bool

ClientCanUpdate reports whether at least one connected npc of client id can be updated; it reads what the bridge holds and queries nothing.

func (s *Bridge) ClientLink(id int) *model.ClientLink

ClientLink summarizes how the core sessions of client id are carried now: the carriers of their pipes and their record modes. It reads the sessions, so it follows pipes joining and leaving. nil when the client has no core session.

func (*Bridge) ClientShapingStats added in v0.35.0

func (s *Bridge) ClientShapingStats(id int) (st coreapi.ShapingStats, ok bool)

ClientShapingStats sums the shaping statistics of the core sessions of client id; ok is false when none is connected.

func (*Bridge) Close added in v0.35.0

func (s *Bridge) Close() error

Close stops the bridge: it drains the clients, closes the listeners and the connections still being served, stops P2P and returns once every goroutine the bridge started has returned.

func (*Bridge) CloseIfDisconnected added in v0.35.0

func (s *Bridge) CloseIfDisconnected(id int, cleanup func()) bool

CloseIfDisconnected runs cleanup, which removes what client id published, unless the client came back. A close signal is handled after the client left; by then it may have reconnected and published its entries again, which must stay. Publishing waits for cleanup, so entries published after the check are not removed either.

func (*Bridge) Connected added in v0.35.0

func (s *Bridge) Connected(id int) bool

Connected reports whether client id has a session.

func (*Bridge) DelClient

func (s *Bridge) DelClient(id int)

DelClient ends the session of client id on behalf of the manager (kick, disable, delete); its client_offline line says reason=deleted.

func (*Bridge) Done added in v0.35.0

func (s *Bridge) Done() <-chan struct{}

Done is closed when the bridge starts closing: by Close, or because one of its listeners failed.

func (*Bridge) Drain added in v0.35.3

func (s *Bridge) Drain()

Drain ends the sessions of every client with a close while their carriers still run, so npc redials at once instead of waiting out its resume timeout. The server calls it before it stops the carriers.

func (*Bridge) EntriesChanged added in v0.35.0

func (s *Bridge) EntriesChanged()

EntriesChanged has every node compare its health groups with the stored entries; the owner of the store calls it after tunnels or hosts changed. It returns promptly.

func (*Bridge) GetHealthFromClient

func (s *Bridge) GetHealthFromClient(id int, c *conn.Conn, client *Client, node *Node)

GetHealthFromClient reads the health reports of a signal connection until it ends. While it runs, a node that supports it also gets its health groups; a released npc gets none, and its reports of checks it configured itself, which have no group, are ignored.

func (*Bridge) GlobalSource added in v0.35.0

func (s *Bridge) GlobalSource() *acl.Source

GlobalSource returns the global source access lists, nil if there are none.

func (*Bridge) IPRegisterConn added in v0.35.0

func (s *Bridge) IPRegisterConn(ctx context.Context, remote string) (net.Conn, error)

IPRegisterConn connects a bridge://ipreg target to the registration page, with remote, the visitor, as the address it sees.

func (*Bridge) IsServer added in v0.30.4

func (s *Bridge) IsServer() bool

func (*Bridge) LinkCert added in v0.35.0

func (s *Bridge) LinkCert() *tls.Certificate

LinkCert is the certificate nps presents on the encrypted links.

func (*Bridge) MinClientVersion added in v0.35.0

func (s *Bridge) MinClientVersion() string

MinClientVersion is the oldest npc core version the bridge accepts.

func (*Bridge) PruneRoutes added in v0.35.0

func (s *Bridge) PruneRoutes(delTask, delHost func(id int))

PruneRoutes removes the routes of nodes that left their client, and with the last route of an entry the entry, through delTask or delHost.

func (s *Bridge) RelayedSecretLinks() int64

RelayedSecretLinks is how many links of secret tasks the bridge has relayed.

func (*Bridge) RequestClientUpdate added in v0.34.9

func (s *Bridge) RequestClientUpdate(id int) (int, error)

RequestClientUpdate asks every connected npc of client id that can be updated (see ClientCanUpdate) to update itself to the latest release. It returns how many were asked.

func (*Bridge) RevokeSecretGrants added in v0.35.0

func (s *Bridge) RevokeSecretGrants()

RevokeSecretGrants ends every grant: the server calls it when settings the policies were resolved under change.

func (*Bridge) RevokeSecretTunnel added in v0.35.0

func (s *Bridge) RevokeSecretTunnel(id int)

RevokeSecretTunnel ends the grants of task id: the server calls it when the task stops, restarts with changed settings or is deleted.

func (*Bridge) ServeRouteTLS added in v0.35.0

func (s *Bridge) ServeRouteTLS(tc *tls.Conn, head []byte, target string) bool

ServeRouteTLS takes a TLS connection a domain route to target ended, head being its first bytes, when they are the new protocol's byte stream; false leaves it to the route's usual way, as for the old protocol.

func (*Bridge) Session added in v0.35.0

func (s *Bridge) Session(clientId int) conn.ClientSession

Session returns the way to open links to client clientId.

func (*Bridge) SetFallback added in v0.35.0

func (s *Bridge) SetFallback(f Fallback)

SetFallback sets the target of carriers the new protocol does not take; nil removes it.

func (*Bridge) SetIPRegisterListener added in v0.35.0

func (s *Bridge) SetIPRegisterListener(l *netx.ChanListener)

SetIPRegisterListener sets the in-memory listener of the registration page that bridge://ipreg targets reach; nil takes it away.

func (*Bridge) SetTunnelLookup added in v0.35.0

func (s *Bridge) SetTunnelLookup(fn TunnelLookup)

SetTunnelLookup sets how the tunnels of tunnel:// targets are found.

func (*Bridge) SetWebListener added in v0.35.0

func (s *Bridge) SetWebListener(l *netx.ChanListener)

SetWebListener sets the in-memory listener of the web manager that bridge://web targets reach; nil takes it away.

func (*Bridge) StartP2P added in v0.34.8

func (s *Bridge) StartP2P(cfg P2PConfig) error

StartP2P starts the NAT observers and the coordinator. It must be called before the bridge serves clients; without it P2P requests are refused.

func (*Bridge) StartTunnel

func (s *Bridge) StartTunnel(t Transports) error

StartTunnel opens the listeners of the transports in t and serves them in the background. It returns the error of the first listener that cannot be opened; Close then closes the ones that were. A listener that fails later closes the bridge: Done is closed then and Cause tells which listener failed.

func (*Bridge) StopP2P added in v0.34.8

func (s *Bridge) StopP2P()

StopP2P closes the P2P service; running sessions end.

func (*Bridge) TunnelConn added in v0.35.0

func (s *Bridge) TunnelConn(id int, remote string) (net.Conn, error)

TunnelConn connects to the running tunnel id as remote.

func (*Bridge) VirtualServices added in v0.35.0

func (s *Bridge) VirtualServices() []VirtualService

VirtualServices lists what the sessions report now, one entry per service of a client, in a stable order: a restarted npc reports from a new session while its old one is suspended, and several npc of a key may offer the same service. Links are routed among them by service id.

func (*Bridge) WebServerConn added in v0.35.0

func (s *Bridge) WebServerConn(ctx context.Context, remote string) (net.Conn, error)

WebServerConn connects to the web server's in-memory listener as remote.

type Client

type Client struct {
	Id       int
	LastUUID string
	// contains filtered or unexported fields
}

func NewClient

func NewClient(id int, n *Node, mode SelectMode) *Client

NewClient returns client id with node n, choosing nodes by mode.

func (*Client) AddNode added in v0.30.6

func (c *Client) AddNode(n *Node)

func (*Client) CheckNode added in v0.30.6

func (c *Client) CheckNode() *Node

CheckNode returns the current node: in Primary mode the last node used while it is online, otherwise, as in every mode, the next online node chosen by the mode, which becomes the current one. Offline nodes are skipped; outside the grace windows they are removed. A node whose session is suspended is chosen only when no other is usable, and does not become the current one. CheckNode returns nil if no node is online.

func (*Client) Close added in v0.30.3

func (c *Client) Close() error

Close closes the client and every node of it.

func (*Client) GetNode added in v0.30.6

func (c *Client) GetNode() *Node

GetNode is CheckNode, except that the RoundRobin and Random modes choose a node for every call.

func (*Client) GetNodeByUUID added in v0.32.0

func (c *Client) GetNodeByUUID(uuid string) (*Node, bool)

func (*Client) InConnectGraceWindow added in v0.34.5

func (c *Client) InConnectGraceWindow(window time.Duration) bool

func (*Client) IsClosed added in v0.30.3

func (c *Client) IsClosed() bool

IsClosed reports whether Close was called; the node pool records it.

func (*Client) MarkConnectedNow added in v0.34.5

func (c *Client) MarkConnectedNow()

func (*Client) NodeCount added in v0.30.6

func (c *Client) NodeCount() int

func (*Client) RemoveOfflineNodes added in v0.31.1

func (c *Client) RemoveOfflineNodes(ignoreClientGrace bool) (removed int)

func (*Client) RemoveOfflineNodesExcept added in v0.34.5

func (c *Client) RemoveOfflineNodesExcept(keepUUID string, ignoreClientGrace bool) (removed int)

type Fallback added in v0.35.0

type Fallback interface {
	// ServeFallback serves c, every byte replayed; state is its TLS when
	// this process terminated it. It returns false, leaving c to the
	// caller, when it cannot take c.
	ServeFallback(c net.Conn, state *tls.ConnectionState) bool
	// FallbackCert returns the certificate for the TLS handshake of a
	// connection that asked for hello.ServerName, or nil, nil to present the
	// bridge's own.
	FallbackCert(hello *tls.ClientHelloInfo) (*tls.Certificate, error)
	// ServeHTTP3 serves qc as HTTP/3 through the domain proxy until it
	// ends. It returns false when there is no HTTP/3 engine.
	ServeHTTP3(qc *quic.Conn, wrap func(http.Handler) http.Handler) bool
}

Fallback is the target of the carriers the new protocol does not take (the domain proxy).

type IdleTimer added in v0.32.0

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

func NewIdleTimer added in v0.32.0

func NewIdleTimer(idle time.Duration, closeFn func()) *IdleTimer

func (*IdleTimer) Dec added in v0.32.0

func (it *IdleTimer) Dec()

func (*IdleTimer) Inc added in v0.32.0

func (it *IdleTimer) Inc()

func (*IdleTimer) Stop added in v0.32.0

func (it *IdleTimer) Stop()

type Node added in v0.30.6

type Node struct {
	Client  *Client
	UUID    string
	Version string
	BaseVer int
	// contains filtered or unexported fields
}

A Node is one npc process of a client. It joins with its signal connection, or with its tunnel, and is online once it has both (or, for a protocol whose signal travels on the tunnel, once the tunnel is up). After joining, and while it waits for a new tunnel (awaitTunnel), it is protected: an offline node is then skipped but kept. Outside protection an offline node is removed from its client and closed.

func NewLocalNode added in v0.35.0

func NewLocalNode(uuid, version string) *Node

NewLocalNode returns the node of the client that nps runs itself, which speaks the latest protocol.

func NewNode added in v0.30.6

func NewNode(uuid, vs string, bv int) *Node

func (*Node) AddCore added in v0.35.0

func (n *Node) AddCore(cs coreapi.Session)

AddCore makes cs the node's session on the core protocol.

func (*Node) AddNode added in v0.30.6

func (n *Node) AddNode(node *Node)

func (*Node) AddSignal added in v0.30.6

func (n *Node) AddSignal(signal *conn.Conn)

func (*Node) AddTunnel added in v0.30.6

func (n *Node) AddTunnel(tunnel legacy.Carrier)

func (*Node) Caps added in v0.35.0

func (n *Node) Caps() legacy.Caps

Caps returns what the node's npc speaks.

func (*Node) Close added in v0.30.6

func (n *Node) Close() error

func (*Node) CloseIfCoreCurrent added in v0.35.0

func (n *Node) CloseIfCoreCurrent(cs coreapi.Session) bool

CloseIfCoreCurrent is CloseIfSignalCurrent for a core protocol session.

func (*Node) CloseIfSignalCurrent added in v0.34.8

func (n *Node) CloseIfSignalCurrent(signal *conn.Conn) bool

CloseIfSignalCurrent closes the node only while signal is still its signal connection, so that an outdated connection exiting cannot tear down a node that has been taken over by a newer connection with the same UUID.

func (*Node) CloseIfTunnelCurrent added in v0.34.8

func (n *Node) CloseIfTunnelCurrent(tunnel legacy.Carrier) bool

CloseIfTunnelCurrent is CloseIfSignalCurrent for the tunnel.

func (*Node) GetSignal added in v0.30.6

func (n *Node) GetSignal() *conn.Conn

func (*Node) GetTunnel added in v0.30.6

func (n *Node) GetTunnel() legacy.Carrier

func (*Node) InJoinGraceWindow added in v0.34.5

func (n *Node) InJoinGraceWindow(window time.Duration) bool

func (*Node) IsOffline added in v0.30.6

func (n *Node) IsOffline() bool

func (*Node) IsOnline added in v0.30.6

func (n *Node) IsOnline() bool

func (*Node) IsTunnelClosed added in v0.32.0

func (n *Node) IsTunnelClosed() bool

func (*Node) Retry added in v0.31.1

func (n *Node) Retry() bool

type Options added in v0.35.0

type Options struct {
	// DisconnectTime is how long, in seconds, a silent client tunnel lives.
	DisconnectTime int
	// SecureMode refuses the handshakes of npc versions that predate
	// secure mode.
	SecureMode bool
	// SelectMode is how a client with several nodes picks the node of a
	// new link.
	SelectMode SelectMode
	// Cert is the certificate of the TLS, WSS and P2P listeners and of the
	// encrypted links; npc pins it by the fingerprint the handshake sends.
	Cert tls.Certificate
	// NewUUID makes the server UUID a handshake sends; nil means a random
	// one (crypt.GetUUID).
	NewUUID func() string
	// AllowedPorts are the ports the tunnels npc publishes may listen on;
	// the zero value allows every port.
	AllowedPorts ports.Allowed
	// CoreEntry is the new protocol on the bridge ports.
	CoreEntry coreapi.Entry
	// MaxNodeServices bounds the virtual services one session may report: 0
	// is defaultMaxNodeServices, negative no limit.
	MaxNodeServices int
	// LatestVersion returns the latest release as last known, or "" when
	// unknown; it must not wait for the network. The npc running an older
	// version can be updated. Nil, or unknown, compares with the server's
	// own version.
	LatestVersion func() string
}

Options are the settings a bridge is built with.

type P2PConfig added in v0.34.8

type P2PConfig struct {
	// BasePort is the first of the observers' three UDP ports; they listen
	// on 0.0.0.0 and, when the host allows it, on ::. 0 lets the kernel
	// choose.
	BasePort int
	// IP is p2p_ip: the addresses (IPs or host names, comma separated)
	// announced to the clients; 0.0.0.0 and :: detect the host's IPv4 and
	// IPv6 address.
	IP          string
	STUNServers []string          // host:port of public STUN servers handed to the clients; empty: none
	Timeouts    protocol.Timeouts // zero fields take the library defaults
	// PortMapping enables the clients' port mapping methods.
	PortMapping protocol.PortMappingPolicy
}

P2PConfig configures the bridge's P2P service: the NAT observers and the coordinator that pairs a visitor with a provider.

type SelectMode added in v0.30.3

type SelectMode int32
const (
	Primary SelectMode = iota
	RoundRobin
	Random
)

func ParseSelectMode added in v0.35.0

func ParseSelectMode(v any) (SelectMode, error)

ParseSelectMode reads a select mode given by name or number. Anything else is an error, with Primary as the mode to fall back to.

func (SelectMode) String added in v0.35.0

func (m SelectMode) String() string

String names the mode.

type Store added in v0.35.0

type Store interface {
	// GetClient returns client id, or an error if there is none.
	GetClient(id int) (*model.Client, error)
	// IsPubClient reports whether id is the client of the public key.
	IsPubClient(id int) bool
	// GetClientIdByBlake2bVkey finds the client of a hashed verify key.
	GetClientIdByBlake2bVkey(digest string) (int, error)
	// GetIdByVerifyKey finds the client whose key hashFunc turns into
	// vKey, and records the address it connects from.
	GetIdByVerifyKey(vKey, addr, localAddr string, hashFunc func(string) string) (int, error)
	// NewClient stores c, assigning its id and verify key.
	NewClient(c *model.Client) error
	// ClientPresence reports that client id got or lost its session.
	ClientPresence(id int, c *model.Client, online bool)
	// GlobalDenied reports whether the global access lists deny addr.
	GlobalDenied(addr net.Addr, what string) bool
	// GetGlobal returns the global settings, nil if there are none.
	GetGlobal() *model.Glob

	RangeTunnels(fn func(*model.Tunnel) bool)
	RangeHosts(fn func(*model.Host) bool)
	// RangeClientTunnels and RangeClientHosts call fn for the entries of
	// client id alone, until fn returns false.
	RangeClientTunnels(id int, fn func(*model.Tunnel) bool)
	RangeClientHosts(id int, fn func(*model.Host) bool)
	NextTunnelID() int
	NextHostID() int

	// ClientTunnel finds the stored tunnel of c that matches t.
	ClientTunnel(c *model.Client, t *model.Tunnel) (*model.Tunnel, bool)
	NewTask(t *model.Tunnel) error
	DelTask(id int) error
	// ReserveTaskPassword checks that the password of t is free for it.
	ReserveTaskPassword(t *model.Tunnel) error
	// TunnelChanged reports that the stored t was changed in place.
	TunnelChanged(t *model.Tunnel)
	// GetTaskBySecretIndex finds the task whose password has index p
	// (crypt.SecretIndex).
	GetTaskBySecretIndex(p string) *model.Tunnel
	// GetTaskByLegacySecret finds the point-to-point task whose password
	// has the MD5 hex digest sum, as npc before 0.35 sends it.
	GetTaskByLegacySecret(sum []byte) *model.Tunnel
	// GetTaskByAccessID finds the task whose password has the access id
	// (coreapi.AccessID).
	GetTaskByAccessID(id []byte) *model.Tunnel

	// ClientHost finds the stored host of c that matches h.
	ClientHost(c *model.Client, h *model.Host) (*model.Host, bool)
	IsHostExist(h *model.Host) bool
	NewHost(h *model.Host) error
	// HostChanged reports that the stored h was changed in place.
	HostChanged(h *model.Host)
}

Store is what the bridge reads and changes of the stored clients, tunnels and hosts. The server passes its store; the bridge reaches no other.

type Transports added in v0.35.0

type Transports struct {
	TCP, TLS, WS, WSS, KCP, QUIC bool
}

Transports says which bridge transports listen on a port of their own; bridge:// targets reach the TCP, TLS, WS and WSS transports either way.

type TunnelDialer added in v0.35.0

type TunnelDialer interface {
	DialVirtual(remote string) (net.Conn, error)
	ServeVirtual(c net.Conn)
}

TunnelDialer is a running tunnel that bridge:// targets of its id reach.

type TunnelLookup added in v0.35.0

type TunnelLookup func(id int) (TunnelDialer, bool)

TunnelLookup finds the running tunnel of an id.

type VirtualService added in v0.35.0

type VirtualService struct {
	Client              int
	Kind, Name, Network string
	Target              string // what a tunnel's target names it with
}

VirtualService is a service a connected npc reports.

Directories

Path Synopsis
Package legacy is nps's one door to the wire protocol that released npc speak: it alone turns protocol messages into nps's own types.
Package legacy is nps's one door to the wire protocol that released npc speak: it alone turns protocol messages into nps's own types.

Jump to

Keyboard shortcuts

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