signal

package
v1.0.13 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: AGPL-3.0 Imports: 53 Imported by: 0 modules, 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

Overview

Package signal is RemoHop's rendezvous service: the server behind `remohop signal` and the client hosts and dialling peers use to talk to it.

The server does three things and nothing else:

  • it gives every host identity key a stable 9-digit ID,
  • it knows which hosts are online (a host is online while its QUIC connection to the server is open) and what public address each connection comes from,
  • on request it introduces a client to a host: both get the other's candidate addresses and a shared random nonce for hole punching.

It never carries session traffic, and it is not trusted: a session is authenticated end to end by the PAKE in internal/auth, bound to the TLS connection between the peers. The worst a hostile rendezvous server can do is refuse service or introduce a client to the wrong machine, which then fails that handshake.

Wire protocol

QUIC with ALPN "remohop-signal/1". Peers connect from the UDP socket they will use for the P2P session, which is how the server learns the reflexive address of exactly that socket. Each request is its own bidirectional stream carrying length-prefixed JSON messages of at most maxMsg bytes:

register (host → server)
  → {t:"register", v:1, key}
  ← {ok, challenge}
  → {sig}                   Ed25519 over label ‖ challenge ‖ TLS exporter
  ← {ok, id, you, alt_port, ws?}

connect (client → server)
  → {t:"connect", v:1, id, candidates, nat}
  ← {ok, nonce, peer:{reflexive, local, nat, via}, you, alt_port, ws?}

offer (server → host, on a stream the server opens)
  → {t:"offer", nonce, peer:{reflexive, local, nat, via}}
  ← {ok, candidates, nat}

relay (client → server, after a punch has failed, or at once when
either peer is bridged; only if the server was started with relaying
on)
  → {t:"relay", v:1, nonce [, key, proof]}   the nonce of the introduction;
                                     key and proof (Ed25519 over label ‖
                                     nonce ‖ TLS exporter) only from a
                                     device that wants its account tier
  ← {ok, relay_port}
and, in between, server → host on a stream the server opens:
  → {t:"relay", nonce, relay_port}
  ← {ok}

presence (client → server)
  → {t:"presence", v:1, ids:[...]}     at most 64 IDs
  ← {ok, presence:["online"|"offline"|"unknown"|"rate_limited", ...]}
Each ID costs what a connect request for it would and reveals the
same: the per-source and per-network connect budgets are charged per
ID, and answers other than "online" draw on the global budget for
such answers. When a budget runs out, the remaining IDs are answered
"rate_limited". No host is contacted.

outcome (client → server, after a connection attempt; see outcome.go)
  → {t:"outcome", v:1, outcome:{path, ms, nat, peer_nat}}
  ← {ok}
Older servers answer bad_request. The server keeps only aggregate
counts, nothing per report.

account (client → server; only if the server was started with
--accounts, see accounts.go for the operations)
  → {t:"account", v:1, op, ...}
  ← {ok, account:{...}}     at most maxAccountMsg bytes

x-NAME (client → server; request types that code built on the server
registers, see extend.go)
  → {t:"x-NAME", v:1, key?, proof?}
  → {ext: PAYLOAD}          at most MaxExtMsg bytes
  ← {ok, ext: REPLY}        at most MaxExtMsg bytes

via is "ws" for a peer that reaches the server through its websocket
bridge (see ws.go): its addresses are placeholders, and the two
peers go straight to the relay instead of punching.

A peer whose nat is "symmetric" may end its candidates with a port
prediction: two addresses on its observed address (nat.Prediction.Hint),
which the receiving peer reads back (nat.ReadHint). To the server they
are candidates like any other; it needs to know nothing about them.

ws is the URL of the server's websocket bridge, if its operator announces one (`remohop signal --ws-url`): a peer that has none configured remembers it for the day UDP to the server is blocked (bridge.go).

Failures are {ok:false, code, error, retry_after_ms}. "you" is the requester's own reflexive address; alt_port is the UDP port of the server's NAT-probe (reflect) service, see internal/nat. The main port answers reflect requests as well (they are not QUIC packets), which is how a peer measures its NAT while the QUIC handshake is still under way and before any introduction is asked for.

Index

Constants

View Source
const (
	AccountNew     = "new"
	AccountPending = "pending"
	AccountMember  = "member"
)

Account states.

View Source
const (
	BridgeAnnounced = "announced"
	BridgeGuessed   = "guessed"
)

How a bridge that was not configured was found (Options.WSFound).

View Source
const (
	// ExtPrefix starts every extension request type, so that none can
	// collide with a type the server itself has or will have.
	ExtPrefix = "x-"
	// MaxExtMsg bounds an extension payload and its reply.
	MaxExtMsg = 1 << 20
)
View Source
const (
	PathLAN       = "lan"       // a LAN or other private address
	PathDirect    = "direct"    // the host's public address, nothing to punch
	PathPunched   = "punched"   // a hole-punched public address
	PathMapped    = "mapped"    // a port the host's router forwards (internal/portmap)
	PathPredicted = "predicted" // a port predicted for a symmetric NAT (nat.Prediction)
	PathRelayed   = "relayed"   // the server's relay
	PathBridged   = "bridged"   // the relay, reached through the websocket bridge
	PathFailed    = "failed"    // no path: the attempt gave up
	// PathUpgraded reports a relayed session that moved to a direct path
	// later on (internal/dial); MS is how long after the session started.
	PathUpgraded = "upgraded"
)

Outcome paths: how the session's connection reached the host.

View Source
const (
	EnvPanelPassword = "REMOHOP_PANEL_PASSWORD"
	EnvPanelCFTeam   = "REMOHOP_PANEL_CF_TEAM"
	EnvPanelCFAUD    = "REMOHOP_PANEL_CF_AUD"
	EnvPanelCFEmails = "REMOHOP_PANEL_CF_EMAILS"
)

Environment variables of the panel; secrets never go on a command line.

View Source
const (
	// ALPN identifies the rendezvous protocol in the QUIC handshake.
	ALPN = "remohop-signal/1"
	// DefaultPort is the rendezvous server's UDP port; the NAT-probe
	// service listens on the next one by default.
	DefaultPort = 21116

	// MaxRetryAfter bounds the wait a rendezvous server can ask of us. A
	// server (or someone impersonating it) that names a longer one is cut
	// down to this; otherwise a single forged reply could keep a host
	// away from its rendezvous server indefinitely.
	MaxRetryAfter = 10 * time.Minute
)
View Source
const (
	CodeUnknownID   = "unknown_id"   // no host has ever registered this ID
	CodeOffline     = "offline"      // the ID exists but its host is not connected
	CodeNoAnswer    = "no_answer"    // the host is connected but did not answer the offer
	CodeDeclined    = "declined"     // the host refused the offer
	CodeRateLimited = "rate_limited" // slow down; see RetryAfter
	CodeFull        = "full"         // the server will not allocate more IDs
	CodeBadRequest  = "bad_request"
	CodeNoRelay     = "no_relay" // relaying is not offered, or the host refuses it
	// CodeIdentityInUse: another machine keeps registering with the same
	// identity key (a cloned disk image, a copied configuration
	// directory); this one waits RetryAfter. Hosts before 1.0.1 log the
	// message and retry with their own backoff (up to a minute).
	CodeIdentityInUse = "identity_in_use"

	// Account failures.
	CodeNoAccounts  = "no_accounts"   // the server does not offer accounts
	CodeNotAllowed  = "not_allowed"   // the server does not take accounts for this address
	CodeBadCode     = "bad_code"      // wrong, expired or used-up login code
	CodeNotLoggedIn = "not_logged_in" // the session is unknown or was revoked
	CodeForbidden   = "forbidden"     // the device is not a member of the account
	CodeConflict    = "conflict"      // the account changed meanwhile; fetch and retry
)

Failure codes.

View Source
const (
	PresenceOnline  = "online"
	PresenceOffline = "offline" // the ID exists but its host is not connected
	PresenceUnknown = "unknown" // no host has this ID
	// PresenceLimited: the answer was not given because a rate limit was
	// reached; ask again later.
	PresenceLimited = "rate_limited"
)

Presence states, the same three a connect request can find out.

View Source
const (
	SettingAddr = "signal"
	SettingPin  = "signal-pin"
	// SettingRelay is whether this machine accepts a relayed connection
	// when no direct one is possible. REMOHOP_RELAY=0 overrides it to off.
	SettingRelay = "relay"
	// SettingNone records that the user chose to use no rendezvous server
	// (computers are reached by address), so that the desktop app and
	// quick support do not ask again.
	SettingNone = "signal-none"
)

Config keys.

View Source
const (
	// TransportAuto tries UDP and, if that gets no answer within
	// FallbackAfter and a websocket bridge is configured, the bridge.
	TransportAuto = "auto"
	TransportUDP  = "udp"
	TransportWS   = "ws"
)

Transports: how a peer reaches the rendezvous server.

View Source
const (
	SettingWS               = "signal-ws"
	SettingWSAccessID       = "signal-ws-access-id"
	SettingWSAccessSecretFn = "signal-ws-access-secret-file"
	SettingTransport        = "signal-transport"
)

Config keys for the websocket bridge.

View Source
const (
	// CodeIsHost: the address is a RemoHop host (`remohop host`), not a
	// rendezvous server. Users put a host's address into the rendezvous
	// setting by mistake; the host can be reached by that address directly.
	CodeIsHost = "signal_is_host"
	// CodeWrongProtocol: something answered QUIC at the address but speaks
	// neither the rendezvous nor the host protocol.
	CodeWrongProtocol = "signal_wrong_protocol"
)

Codes of a WrongServerError, as CodeOf returns them. They are stable: the web page and the apps translate them.

View Source
const (

	// CodeDigits is the length of a login code.
	CodeDigits = 8
)
View Source
const MaxOutcomeMS = int64(24 * time.Hour / time.Millisecond)

MaxOutcomeMS bounds Outcome.MS; longer times are not plausible for one attempt, or for an upgrade worth counting separately.

View Source
const MaxPresenceIDs = 64

MaxPresenceIDs bounds the IDs of one presence request.

View Source
const OfficialAddr = "signal.remohop.com"

OfficialAddr is the public rendezvous server that the desktop app's and quick support's first-run choice offers. Nothing uses it unless the user picks it: there is still no built-in default (DefaultAddr).

Variables

View Source
var (
	DefaultAddr string
	DefaultPin  string
)

DefaultAddr and DefaultPin are the rendezvous server (and optionally its key) used when neither a flag, the environment nor the config file names one. They are empty in source: RemoHop does not ship with a built-in server. A distribution that runs one sets them at build time (through internal/dial.DefaultSignal, see there).

View Source
var (
	BridgeHeadStart = 300 * time.Millisecond
	MinUDPGrace     = time.Second
)

A network without UDP used to cost every first dial the whole of FallbackAfter: the bridge was tried only once UDP had been given up. Now the two overlap (DialOrBridge). UDP runs alone for BridgeHeadStart, long enough that a network where it works never opens a websocket; then the bridge is connected alongside. A bridge that is up while UDP is still silent shows that the server is there and UDP is what does not get through, and UDP then has until udpGrace is over: at least MinUDPGrace from the start, and longer on a slow network, which shows in how long the bridge itself took (a websocket through TCP and TLS needs three round trips or more, the UDP handshake one). The bridge is only second best, since a session through it is relayed for its whole life, so UDP keeps the benefit of the doubt for that long and no longer. Variables for tests.

View Source
var DefaultWS string

DefaultWS is the websocket bridge of the build-time default server (internal/dial.DefaultSignalWS); empty in source.

View Source
var ErrNoOutcomes = errors.New("signal: the server does not take connection outcomes")

ErrNoOutcomes is returned by ReportOutcome when the server does not take outcome reports.

View Source
var ErrNotConfigured = errors.New("no rendezvous server configured. Choose one:\n" + Choices("  ") +
	"For one command only, pass --signal HOST[:PORT] or set REMOHOP_SIGNAL.")

ErrNotConfigured is returned by Resolve when no rendezvous server is set. Its text lists the ways to go on, one per line.

View Source
var ErrPinMismatch = errors.New("the rendezvous server's key is not the pinned one")

ErrPinMismatch is in the error of a Dial whose server presented another key than Options.Pin.

View Source
var ErrRelayPortsFull = errors.New("every port of the relay port range is in use")

ErrRelayPortsFull is returned by a port-range listener when every port of the range is taken.

View Source
var FallbackAfter = 4 * time.Second

FallbackAfter is how long a UDP attempt may take at most before auto falls back to the websocket bridge. A rendezvous handshake normally completes in one or two round trips.

Functions

func AnnouncedBridge

func AnnouncedBridge(dir, server string) string

AnnouncedBridge is the bridge URL that server (as configured: HOST or HOST:PORT) announced when it was last reached over UDP, or "". dir is the configuration directory, or "" for what this process learned.

func Choices

func Choices(indent string) string

Choices lists, one per line and each line starting with indent, the ways to go on without a rendezvous server: the official one (which the desktop app and quick support offer; nothing uses it unless chosen), one's own, or none at all on the same network.

func CodeOf

func CodeOf(err error) string

CodeOf returns the failure code of a rendezvous error (one of the Code* constants, including CodeIsHost and CodeWrongProtocol), or "".

func Display

func Display(addr string, o Options) string

Display names the server for messages: addr, or the bridge when there is no UDP address.

func FormatCode

func FormatCode(code string) string

FormatCode shows a code the way it is mailed: "1234 5678".

func FormatID

func FormatID(id string) string

FormatID renders a 9-digit ID the way it is shown to people: "123 456 789".

func IsWrongServer

func IsWrongServer(err error) bool

IsWrongServer reports whether err says the rendezvous address is not a rendezvous server (so trying its websocket bridge or again is pointless).

func NormalizeCode

func NormalizeCode(s string) string

NormalizeCode strips the spaces and dashes people type into a code.

func PortRangeListener

func PortRangeListener(host string, r PortRange) func() (net.PacketConn, error)

PortRangeListener returns a RelayConfig.Listen that binds each relay socket to a free port of r on host ("" for all addresses), so that a firewall needs to open only that range. It starts at a random port of the range, so that the ports of finished sessions are not reused at once, and fails with ErrRelayPortsFull when all are taken.

func RegisterRelayPolicy

func RegisterRelayPolicy(p RelayPolicy)

RegisterRelayPolicy adds a relay policy. Call it from init().

func RegisterRequest

func RegisterRequest(t string, h ExtHandler)

RegisterRequest adds the request type t, which must start with ExtPrefix. Call it from init().

func RelayAllowed

func RelayAllowed(dir string) bool

RelayAllowed reports whether this machine accepts relayed connections: the "relay" setting in dir's config file (default on), unless REMOHOP_RELAY is set to 0, off, no or false.

func SetUDPBlocked

func SetUDPBlocked(dir, server string, locals []netip.Addr, blocked bool)

SetUDPBlocked records (or, with blocked false, forgets) that UDP to server did not get through from this network while the bridge did. Failures to write are ignored: a hint is only an optimisation.

func SplitAddr

func SplitAddr(addr string) (host, port string, err error)

SplitAddr parses a rendezvous server address, adding the default port when none is given.

func UDPBlocked

func UDPBlocked(dir, server string, locals []netip.Addr) bool

UDPBlocked reports whether a dial to server from a socket with these local addresses should go to the websocket bridge at once. dir is the configuration directory, or "" to remember in memory only.

Types

type AccountArgs

type AccountArgs struct {
	Name     string        // this device's name, to update what the server shows
	Platform string        // this device's platform, likewise
	Entry    *ledger.Entry // append
	Device   ed25519.PublicKey
}

AccountArgs are the arguments of AccountCall.

type AccountDevice

type AccountDevice struct {
	Key      ed25519.PublicKey
	ID       string // its 9-digit ID if it ever registered as a host here
	Name     string // what it last called itself
	Platform string
	Online   bool
	LastSeen time.Time // zero if never
}

AccountDevice is a member device as the server sees it.

type AccountJoinRequest

type AccountJoinRequest struct {
	Key      ed25519.PublicKey
	Name     string
	Platform string
	From     string // the address it logged in from
	At       time.Time
}

AccountJoinRequest is a device waiting to be approved.

type AccountReply

type AccountReply struct {
	// State is AccountNew, AccountPending or AccountMember.
	State     string
	AccountID []byte
	// Token is the session token, from AccountVerify only.
	Token   []byte
	Log     []ledger.Entry
	Devices []AccountDevice
	Pending []AccountJoinRequest
}

AccountReply is the server's answer to an account request. Nothing in it is trusted: the log must be verified (ledger.Verify) against the account ID the device holds, and the other fields are display data, already cleaned and bounded here.

type AccountsConfig

type AccountsConfig struct {
	// Mailer sends login codes. Required.
	Mailer Mailer
	// Domains and Emails are the addresses accounts may be made for: any
	// address in Domains, and the addresses in Emails. Open allows every
	// address. With none of the three no address is allowed.
	Domains []string
	Emails  []string
	Open    bool

	// MaxAccounts bounds the store. Default 100,000.
	MaxAccounts int
	// CodeTTL is how long a login code is valid. Default 10 min.
	CodeTTL time.Duration
	// MaxAttempts wrong codes burn the code and lock the address for
	// Lockout. Defaults 5 and 15 min.
	MaxAttempts int
	Lockout     time.Duration

	// Rate limits. Login-code requests: per source burst 5, one more a
	// minute; per address burst 3, one more every 5 min; in total (mails
	// sent) burst 100, one more every 3 s. Code checks per source: burst
	// 10, one more every 10 s. Other account requests per source: burst
	// 60, one more every 500 ms.
	StartBurst  int
	StartEvery  time.Duration
	EmailBurst  int
	EmailEvery  time.Duration
	MailBurst   int
	MailEvery   time.Duration
	VerifyBurst int
	VerifyEvery time.Duration
	OpBurst     int
	OpEvery     time.Duration

	// Now replaces the clock for code expiry and lockouts (tests).
	Now func() time.Time
}

AccountsConfig enables and bounds accounts. Zero fields take the defaults documented on each.

func (*AccountsConfig) Allowed

func (a *AccountsConfig) Allowed(email string) bool

Allowed reports whether accounts may be made for a normalised address.

type Answer

type Answer struct {
	// Decline, if not empty, refuses the offer with this reason.
	Decline string
	Local   []netip.AddrPort // the host's interface candidates right now
	NAT     nat.Type
}

Answer is the host's reply to an offer.

type Client

type Client struct {

	// OnRelay, set by a host before ServeOffers, is called when the server
	// has opened a relay for an earlier offer (identified by its nonce)
	// at the given address. Returning an error declines the relay.
	OnRelay func(nonce []byte, relay netip.AddrPort) error
	// contains filtered or unexported fields
}

Client is a connection to a rendezvous server, made from a peer's shared socket.

func Connect

func Connect(ctx context.Context, addr string, opts Options, newUDP func() (*nat.Socket, error), log *slog.Logger) (*Client, *nat.Socket, error)

Connect dials the rendezvous server as opts say: over UDP from a socket that newUDP opens and, when that is not possible or gets no answer and a bridge is configured or found, through the bridge (DialOrBridge). It returns the client and the socket it runs on; the caller closes both, the client first.

func Dial

func Dial(ctx context.Context, sock *nat.Socket, addr string, opts Options) (*Client, error)

Dial connects to the rendezvous server at addr ("host[:port]") from sock.

func DialBridge

func DialBridge(ctx context.Context, sock *nat.Socket, wc *wsdgram.Conn, opts Options) (*Client, error)

DialBridge connects to the rendezvous server through its websocket bridge, from sock, a socket made on wc.

func DialOrBridge

func DialOrBridge(ctx context.Context, sock *nat.Socket, addr string, opts Options, full time.Duration, bridge *wsdgram.Conn, log *slog.Logger) (*Client, *wsdgram.Conn, error)

DialOrBridge dials the rendezvous server over UDP from sock, as Dial does, for at most full, and where a bridge may be used (opts.UseWS) finds out alongside whether to go through it instead (see BridgeHeadStart). It returns exactly one of:

  • a client, over UDP;
  • a bridge that is connected, with the reason UDP was given up: the caller dials through it (DialBridge on a socket made on it) and owns it. It is bridge if one was passed in, else one made here;
  • an error: UDP failed and there is no bridge to go to. For a bridge that was only guessed (Options.WSFound) the error is UDP's own.

bridge, if not nil, is the caller's own bridge to use (a host keeps one for its life); it is connected but never closed here.

func (*Client) AccountCall

func (c *Client) AccountCall(ctx context.Context, id *auth.Identity, token []byte, op string, args AccountArgs) (*AccountReply, error)

AccountCall runs an authenticated account operation: "state", "devices", "append", "reject", "logout" or "delete".

func (*Client) AccountLogin

func (c *Client) AccountLogin(ctx context.Context, email string) error

AccountLogin asks the server to mail a login code to email.

func (*Client) AccountVerify

func (c *Client) AccountVerify(ctx context.Context, id *auth.Identity, email, code, name, platform string) (*AccountReply, error)

AccountVerify proves the login code and binds id's key to the account. The reply carries the session token.

func (*Client) Bridged

func (c *Client) Bridged() bool

Bridged reports whether the connection runs over the server's websocket bridge, so that only the relay can reach the other peer.

func (*Client) Close

func (c *Client) Close() error

Close ends the connection; a registered host goes offline.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, id string, local []netip.AddrPort, natType nat.Type) (*Introduction, error)

Connect asks the server to introduce us to the host with the given ID. local are our own interface candidates and natType our NAT measurement, both passed on to the host. Failures reported by the server are *Error.

func (*Client) Done

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

Done is closed when the connection has ended.

func (*Client) Err

func (c *Client) Err() error

Err reports why the connection ended.

func (*Client) Ext

func (c *Client) Ext(ctx context.Context, t string, id *auth.Identity, payload any) (json.RawMessage, error)

Ext sends the extension request t with payload and returns the reply's body. With id, the request carries id's key and a proof for this connection; without, it is anonymous.

func (*Client) NATType

func (c *Client) NATType() nat.Type

NATType returns the socket's NAT type as measured against this server while connecting, waiting at most natGrace after Dial returned for the measurement to finish. The result is also on the socket (nat.Socket.NATType).

func (*Client) Presence

func (c *Client) Presence(ctx context.Context, ids []string) (map[string]string, error)

Presence asks the server which of ids are online. The result maps each ID to one of the Presence* states.

func (*Client) Register

func (c *Client) Register(ctx context.Context, id *auth.Identity) (*Registration, error)

Register proves possession of id's key and puts the host online under the ID the server keeps for that key. The host stays online until the connection ends.

func (*Client) Relay

func (c *Client) Relay(ctx context.Context, nonce []byte) (netip.AddrPort, error)

Relay asks the server to relay the session of an introduction whose punch failed. It returns the relay's address once the host has attached to it; the caller attaches with nat.Socket.BindRelay and dials the host there.

func (*Client) RelayAs

func (c *Client) RelayAs(ctx context.Context, nonce []byte, id *auth.Identity) (netip.AddrPort, error)

RelayAs is Relay with proof that the request comes from the holder of id, which the server needs to apply a better tier for devices of an account on it. A nil id asks anonymously; the server then never learns this machine's identity key.

func (*Client) ReportOutcome

func (c *Client) ReportOutcome(ctx context.Context, o Outcome) error

ReportOutcome tells the server how a connection attempt ended. It is best effort: callers should not wait on it for long (bound ctx) and may ignore its error. ErrNoOutcomes means the server does not take reports.

func (*Client) ServeOffers

func (c *Client) ServeOffers(ctx context.Context, handle func(Offer) Answer) error

ServeOffers handles introductions for a registered host, calling handle for each, until the connection ends or ctx is cancelled; it returns the reason. handle must be quick: the client is waiting for the answer.

func (*Client) ServerKey

func (c *Client) ServerKey() ed25519.PublicKey

ServerKey is the public key the server presented.

type Config

type Config struct {
	// DataDir holds the server's TLS key and the ID journal.
	DataDir string
	// Logger receives operational events; nil discards them.
	Logger *slog.Logger
	Limits Limits
	// Ext limits extension requests (see extend.go).
	Ext ExtLimits
	// Relay, if not nil, makes the server offer to relay sessions whose
	// peers could not connect directly. Off by default: it is the one
	// thing here that costs an operator real bandwidth.
	Relay *RelayConfig
	// Accounts, if not nil, offers accounts (see accounts.go). Off by
	// default.
	Accounts *AccountsConfig
	// WSURL, if set, is the public URL of the server's websocket bridge
	// (wsdgram.Advertised), announced to every peer that registers or
	// asks for an introduction, so that peers find the bridge without
	// being configured for it (bridge.go).
	WSURL string
}

Config configures a Server.

type Error

type Error struct {
	Code       string
	Message    string
	RetryAfter time.Duration
}

Error is a failure reported by the rendezvous server.

func (*Error) Error

func (e *Error) Error() string

type ExtError

type ExtError struct {
	Code, Msg  string
	RetryAfter time.Duration
}

ExtError is an error a handler returns to give the client a code.

func (*ExtError) Error

func (e *ExtError) Error() string

type ExtHandler

type ExtHandler func(ctx context.Context, s *Server, r ExtRequest) (any, error)

ExtHandler answers an extension request: its reply (marshalled as JSON) or an error. It runs on the request's stream, within requestTimeout.

type ExtLimits

type ExtLimits struct {
	// Burst and RefillPerSecond describe the per-source token bucket.
	// Defaults 20 and 5.
	Burst           int
	RefillPerSecond int
	// MaxConcurrent caps extension requests being served at once, over
	// all sources. Default 64.
	MaxConcurrent int
	// PerSourceConcurrent caps those of one source. Default 4.
	PerSourceConcurrent int
}

ExtLimits are the limits on extension requests. Zero fields take the defaults documented on each; tests lower them.

type ExtRequest

type ExtRequest struct {
	Type   string
	Source netip.Addr        // the client's address
	Key    ed25519.PublicKey // proven on this connection, or nil
	// Payload is the request's body, as the client sent it.
	Payload json.RawMessage
}

ExtRequest is one extension request as its handler sees it.

type Introduction

type Introduction struct {
	Nonce     []byte         // shared with the host, for punch probes
	Peer      Peer           // the host
	Reflexive netip.AddrPort // our own public address as the server sees it
	Alt       netip.AddrPort // the server's NAT-probe address; invalid if it has none
	// RelayOffered says the server would relay this session if asked.
	RelayOffered bool
}

Introduction is the result of a successful connect request.

type Limits

type Limits struct {
	// MaxConns and MaxConnsPerSource bound open QUIC connections.
	// Defaults 50000 and 64 (the per-source bound has to leave room for
	// many hosts behind one carrier-grade NAT address).
	MaxConns          int
	MaxConnsPerSource int
	// MaxConnsPerNet bounds those of one network (an IPv6 /48), so that the
	// many /64s of one customer cannot fill the table. Default 256. (For
	// IPv4 the network is the address, so MaxConnsPerSource applies.)
	MaxConnsPerNet int
	// Register*: registrations per source. Defaults: burst 10, one more
	// every 6 s.
	RegisterBurst int
	RegisterEvery time.Duration

	// New IDs are the only thing a stranger can make the server keep, so
	// allocating one draws on three budgets. Per source: burst 5, one
	// more every 10 min. Per network: burst 20, one more every 2 min.
	// Globally: burst 500, one more every IDExpiry/MaxIDs (7.8 s with the
	// defaults). The global rate is chosen so that IDs which are never
	// used again expire as fast as they can be created: the table cannot
	// be filled for good that way, whatever the number of addresses.
	NewIDBurst       int
	NewIDEvery       time.Duration
	NewIDNetBurst    int
	NewIDNetEvery    time.Duration
	NewIDGlobalBurst int
	NewIDGlobalEvery time.Duration
	// MaxIDs caps the ID table. Default 1,000,000.
	MaxIDs int
	// IDExpiry is how long an ID is kept for a host that does not
	// register. Default 90 days.
	IDExpiry time.Duration

	// Connect*: connect requests per source and per network. This limits
	// use of the server to make hosts emit probe packets, while leaving
	// room for scripts and agents that run many short commands, each of
	// which is one request. Defaults: burst 60 and one more every 500 ms
	// per source; burst 240 and one more every 125 ms per network.
	ConnectBurst    int
	ConnectEvery    time.Duration
	ConnectNetBurst int
	ConnectNetEvery time.Duration
	// Miss*: connect requests, from anyone, for IDs that are unknown or
	// offline. This is what limits finding out which IDs exist by trying
	// them. Default: burst 1000, one more every 50 ms; at 20 misses a
	// second, sweeping the 900 million possible IDs takes all the
	// world's addresses together more than a year. When the budget is
	// spent such requests are answered "rate limited" instead of
	// "unknown" or "offline"; requests for hosts that are online are not
	// affected.
	MissBurst int
	MissEvery time.Duration
	// Offer*: offers delivered to one host, whoever asks. Defaults: burst
	// 40, one more every 250 ms. A host punches for about 13 s per offer
	// that leads nowhere and runs at most 128 punches at once, so even a
	// sustained flood of requests for one ID (from many sources) leaves
	// the host room to answer real clients.
	OfferBurst int
	OfferEvery time.Duration
	// ClientLifetime is how long a connection that has not registered may
	// stay open; a dialling peer needs a few seconds. Default 60 s.
	ClientLifetime time.Duration
}

Limits are the server's abuse controls. Zero fields take the defaults documented on each; tests shrink them.

Limits apply at three widths, because addresses are not equally scarce. A "source" is an IPv4 address or an IPv6 /64, the least any one host has. A "network" is an IPv6 /48, what a single customer is routinely given and which holds 65536 sources (for IPv4 the network is the address itself). And some budgets are global, so that no number of networks can exhaust what they protect.

type LogMailer

type LogMailer struct{ Log *slog.Logger }

LogMailer "sends" codes to a log. It is for development only: anyone who can read the log can log in to any account.

func (LogMailer) SendCode

func (m LogMailer) SendCode(_ context.Context, to, code string) error

SendCode implements Mailer.

type Mailer

type Mailer interface {
	SendCode(ctx context.Context, to, code string) error
}

Mailer delivers login codes.

type Offer

type Offer struct {
	Nonce []byte
	Peer  Peer // the client
}

Offer is an introduction delivered to a host: a client wants to connect.

type Options

type Options struct {
	// Pin, if set, is the rendezvous server's public key (as printed by
	// `remohop signal`); the connection fails if the server presents another.
	//
	// Leaving it empty accepts any server key, and that is a deliberate
	// default rather than a shortcut: nothing a rendezvous server tells us
	// is trusted. The peer it introduces us to must still pass the PAKE,
	// which is bound to the TLS connection between the two peers, so an
	// impostor server (or someone intercepting the way to the real one)
	// can deny service or learn which ID we asked for, but cannot read or
	// alter a session, nor obtain anything to test password guesses
	// against. Pinning only removes those two nuisances; a web-PKI
	// certificate would add nothing on top and would make self-hosting
	// harder.
	Pin string

	// WS is the URL of the server's websocket bridge (signal-ws), for
	// networks that let only HTTP(S) out; empty if none is configured.
	// WSHeader holds extra headers for it (Cloudflare Access tokens).
	WS       string
	WSHeader map[string][]string
	// Transport says how to reach the server: TransportAuto (UDP, and the
	// bridge if UDP does not get through), TransportUDP or TransportWS.
	// Empty means auto.
	Transport string

	// WSFound says how WS was found when it was not configured:
	// BridgeAnnounced or BridgeGuessed (bridge.go); empty for a configured
	// one. A guessed bridge may well not exist, which is then no error of
	// its own.
	WSFound string

	// HintDir is the configuration directory where Connect remembers that
	// UDP to the server is blocked from the current network (see
	// UDPBlocked), and Dial the bridge the server announces; empty
	// remembers in memory only.
	HintDir string
}

Options configures Dial.

func Resolve

func Resolve(override string) (addr string, opts Options, err error)

Resolve picks the rendezvous server to use: override (the --signal flag or REMOHOP_SIGNAL) if set, else the config file, else the build-time default. A pin is returned only together with the address it was configured for, and likewise the websocket bridge (signal-ws), unless REMOHOP_SIGNAL_WS names one. A config file with a bridge but no address gives addr "" and a bridge-only Options.

func (Options) NewBridge

func (o Options) NewBridge(log *slog.Logger) (*wsdgram.Conn, error)

NewBridge prepares the client end of the websocket bridge (it connects on first use), through the proxy the environment, the proxy setting or the system's settings name for it (internal/sysproxy).

func (Options) UDPWait

func (o Options) UDPWait(full time.Duration) time.Duration

UDPWait is how long a UDP attempt may take, out of full: FallbackAfter when the bridge is the fallback.

func (Options) UseUDP

func (o Options) UseUDP() bool

UseUDP reports whether UDP is to be tried.

func (Options) UseWS

func (o Options) UseWS() bool

UseWS reports whether the websocket bridge is to be used, at once or as the fallback.

type Outcome

type Outcome struct {
	Path string `json:"path"`
	// MS is the time from the client's connect request to a working
	// session (or to giving up), in milliseconds; for PathUpgraded, the
	// time from the session's start to the move.
	MS int64 `json:"ms"`
	// NAT and PeerNAT are the NAT types of the client and the host as
	// they were exchanged in the introduction (nat.Type values).
	NAT     string `json:"nat,omitempty"`
	PeerNAT string `json:"peer_nat,omitempty"`
}

Outcome is one connection attempt's result, as a client reports it.

func (Outcome) Valid

func (o Outcome) Valid() bool

Valid reports whether o is well formed: a known path, a plausible time, and known NAT types (or none).

type PanelConfig

type PanelConfig struct {
	Listen   string
	Password string
	// Cloudflare Access: the team domain, the application's AUD tag and
	// the allowed emails (empty: any the Access policy lets in).
	CFTeam   string
	CFAUD    string
	CFEmails []string
	// CFCertsURL replaces https://TEAM/cdn-cgi/access/certs (tests).
	CFCertsURL string

	// What the overview says about the server's other sockets.
	UDP, Alt, WS, RelayPorts string
}

PanelConfig configures the web panel.

type Peer

type Peer struct {
	Reflexive netip.AddrPort   // public address of the peer's socket, observed by the server
	Local     []netip.AddrPort // interface addresses the peer reported itself
	NAT       nat.Type         // the peer's own NAT measurement
	// Bridged: the peer reaches the server through its websocket bridge;
	// it has no address to punch and only the relay reaches it.
	Bridged bool
	// Prediction, when valid, says how the peer's symmetric NAT hands out
	// ports (see nat.Prediction), always on the Reflexive address. It
	// travels as a hint at the end of the peer's self-reported candidates
	// (nat.Prediction.Hint), which is taken out of Local.
	Prediction nat.Prediction
}

Peer is one side's reachability as relayed by the server.

func (Peer) Candidates

func (p Peer) Candidates() []netip.AddrPort

Candidates lists every address worth probing: the reflexive one, which the server vouches for, then the self-reported local ones.

type PortRange

type PortRange struct{ Lo, Hi int }

PortRange is an inclusive range of UDP ports.

func ParsePortRange

func ParsePortRange(s string) (PortRange, error)

ParsePortRange parses "LO-HI" (or a single port).

func (PortRange) Size

func (r PortRange) Size() int

Size is the number of ports in the range.

func (PortRange) String

func (r PortRange) String() string

type Registration

type Registration struct {
	ID        string         // the host's 9-digit ID
	Reflexive netip.AddrPort // the socket's public address as the server sees it
	Alt       netip.AddrPort // the server's NAT-probe address; invalid if it has none
}

Registration is what the server tells a registered host.

type RelayConfig

type RelayConfig struct {
	// Listen opens the UDP socket for one relayed session. The default
	// binds an ephemeral port on all interfaces; the ports must be
	// reachable from the peers.
	Listen func() (net.PacketConn, error)
	// MaxSessions bounds concurrent relayed sessions. Default 64.
	MaxSessions int
	// Rate is each session's budget in bytes per second, both directions
	// together. Default 1,000,000 (8 Mbit/s).
	Rate int
	// TotalRate is the budget of all sessions together. Default
	// 5,000,000 (40 Mbit/s).
	TotalRate int
	// Idle ends a session that passes no traffic. Default 30 s.
	Idle time.Duration

	// Access control and budget; see relaypolicy.go.
	//
	// PerSource bounds concurrent relayed sessions per source address
	// (IPv4 address or IPv6 /64), counting both peers. 0: unlimited.
	PerSource int
	// AccountRate is the per-session rate when either peer is a verified
	// member of an account on this server. Default: Rate.
	AccountRate int
	// ForAccounts relays only sessions with such a peer.
	ForAccounts bool
	// DenyFile names a deny list (addresses, networks, identity keys),
	// re-read when it changes; empty for none.
	DenyFile string
	// MonthlyBytes is the relay budget per calendar month (UTC); 0 is
	// unlimited. From 80% anonymous sessions get half their rate, from
	// 100% they are refused, from 110% all are.
	MonthlyBytes int64
	// Now is the clock for the budget; default time.Now.
	Now func() time.Time
}

RelayConfig bounds the relay service. Zero fields take the defaults documented on each.

type RelayPolicy

type RelayPolicy struct {
	Name string
	// Member reports whether a proven identity key gets the relay's member
	// tier, as members of an account on this server do (the account rate,
	// and a relay that --relay-for accounts keeps for members). Must be
	// quick.
	Member func(s *Server, key ed25519.PublicKey) bool
	// Ended is told about every relay session that ran, with the proven
	// keys of its client and host (nil when not proven) and the bytes it
	// carried, for metering. Must not block.
	Ended func(s *Server, client, host ed25519.PublicKey, bytes int64, d time.Duration)
}

RelayPolicy gives an extension a say in the relay. Both functions get the server (its DataDir, for an extension's own records).

type SMTPMailer

type SMTPMailer struct {
	Host     string
	Port     int
	User     string
	Password string
	From     string
	// Security is "starttls" (the default: plain connection upgraded with
	// STARTTLS, which must succeed), "tls" (TLS from the start, usually
	// port 465) or "none" (only for a relay on the same machine).
	Security string
}

SMTPMailer sends codes through an SMTP server.

func (*SMTPMailer) SendCode

func (m *SMTPMailer) SendCode(ctx context.Context, to, code string) error

SendCode implements Mailer.

type Server

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

Server is a rendezvous server.

func NewServer

func NewServer(cfg Config) (*Server, error)

func (*Server) AnnounceBridge

func (s *Server) AnnounceBridge(url string)

AnnounceBridge sets the bridge address announced to peers from now on, in place of Config.WSURL; "" announces none.

func (*Server) Close

func (s *Server) Close() error

Close releases the ID journal. Call it after Serve has returned.

func (*Server) DataDir

func (s *Server) DataDir() string

DataDir is the server's data directory (Config.DataDir), where an extension keeps its own files, in a subdirectory named after it.

func (*Server) Logger

func (s *Server) Logger() *slog.Logger

Logger is the server's logger.

func (*Server) PublicKey

func (s *Server) PublicKey() ed25519.PublicKey

PublicKey is the server's TLS identity, which clients may pin.

func (*Server) ReloadRelayDeny

func (s *Server) ReloadRelayDeny() error

ReloadRelayDeny re-reads the relay deny list now (on SIGHUP).

func (*Server) Serve

func (s *Server) Serve(ctx context.Context, main, alt net.PacketConn) error

Serve runs the rendezvous service on main and, if alt is not nil, the NAT-probe service on alt, until ctx is cancelled. It closes both connections before returning.

func (*Server) WSHandler

func (s *Server) WSHandler(cfg WSConfig) http.Handler

WSHandler returns the HTTP handler of the websocket bridge. It serves cfg.Path only and needs Serve to be running.

type WSConfig

type WSConfig struct {
	// Path is the one URL path served. Default wsdgram.DefaultPath.
	Path string
	// Target is the address the server's UDP sockets are reachable at
	// from this machine; bridge sockets are bound to it. Default
	// 127.0.0.1.
	Target netip.Addr
	// MaxConns bounds open WebSocket connections, MaxConnsPerSource those
	// from one source address. Defaults 512 and 32.
	MaxConns          int
	MaxConnsPerSource int
	// Rate is each connection's budget in bytes per second, both
	// directions together; TotalRate the budget of all of them. Defaults:
	// the relay's per-session and total rates plus 32 KB/s for
	// rendezvous traffic, or 32 KB/s and 1 MB/s without a relay.
	Rate      int
	TotalRate int
	// Idle closes a connection that has carried nothing for this long.
	// Default 2 min; peers send keep-alives every 10 s.
	Idle time.Duration
	// RealIPHeader names a request header holding the client's address,
	// set by a reverse proxy in front of the bridge (CF-Connecting-IP
	// behind a Cloudflare Tunnel, X-Forwarded-For behind most others; for
	// a list the last entry counts). Requests without it are refused.
	// Empty means the TCP peer's address, which behind a proxy is the
	// proxy's own, so all clients share one source's limits.
	RealIPHeader string
}

WSConfig configures the websocket bridge. Zero fields take the defaults documented on each.

type WrongServerError

type WrongServerError struct {
	Addr string
	// Host: the address accepted the RemoHop host protocol instead.
	Host bool
	Err  error
}

WrongServerError is Dial's error when the address answered but is not a rendezvous server: its TLS handshake refused the rendezvous protocol (QUIC CRYPTO_ERROR 0x178, "no application protocol").

func (*WrongServerError) Code

func (e *WrongServerError) Code() string

Code is CodeIsHost or CodeWrongProtocol.

func (*WrongServerError) Error

func (e *WrongServerError) Error() string

func (*WrongServerError) Unwrap

func (e *WrongServerError) Unwrap() error

Jump to

Keyboard shortcuts

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