server

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: BSD-3-Clause Imports: 17 Imported by: ? 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 server implements the TURN server of RFC 8656 with UDP relayed transport, reached over UDP, TCP or TLS, plus the STUN Binding answer of RFC 8489. Authentication is the long-term credential mechanism with NONCE expiry; the credential store is the Config.Auth hook.

Security defaults: the server never relays to or from loopback, 0.0.0.0/8, RFC 1918, 100.64/10, link-local (169.254.169.254 included), multicast, ULA, the IPv6 translator forms, IPv4-mapped forms of those, or its own addresses; it answers 403 Forbidden. Config.AllowPeers re-enables ranges (tests relay on 127.0.0.1 with it). Every table is bounded.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrProxyHeader = errors.New("server: malformed PROXY protocol header")
	ErrProxyFamily = errors.New("server: PROXY protocol family or transport not supported")
)

Errors of the header reader. Every one closes the connection.

View Source
var ErrClosed = errors.New("server: closed")

ErrClosed is returned by the Serve methods after Close.

Functions

func AppendProxyHeaderV2 added in v0.2.0

func AppendProxyHeaderV2(b []byte, src, dst netip.AddrPort) []byte

AppendProxyHeaderV2 appends a PROXY command header for a TCP connection from src to dst, for a proxy written in Go and for tests.

Types

type Config

type Config struct {
	// Realm is the long-term credential realm sent in 401 and 438 answers.
	Realm string
	// Auth returns the password of username. Wrap creds.Verify (or any store)
	// in this closure. An unknown user and a wrong password are answered
	// identically (401).
	Auth func(username string) (password string, ok bool)

	// AuthExisting, when set, returns the password of a username WITHOUT any
	// expiry check (creds.Keyring.AuthExisting). The server consults it only for
	// Refresh, CreatePermission and ChannelBind on an allocation of the same
	// 5-tuple that the same username created, and only while the allocation is
	// younger than MaxAllocationAge: a relayed call outlives the credential that
	// opened it, while a NEW allocation still needs an unexpired username (Auth).
	// MESSAGE-INTEGRITY is verified with the returned password as always. Nil
	// means an expired username ends its allocation at its next request.
	AuthExisting func(username string) (password string, ok bool)

	// Software is the SOFTWARE attribute value (default "go-turn").
	Software string

	// RelayIP is the address relayed sockets bind to; its family (IPv4 or
	// IPv6) is the only family relayed. RelayAdvertiseIP, if set, is the
	// address reported in XOR-RELAYED-ADDRESS (a NAT'd or floating address).
	RelayIP          netip.Addr
	RelayAdvertiseIP netip.Addr
	// RelayPortMin and RelayPortMax restrict the relayed UDP ports (both zero
	// means any ephemeral port).
	RelayPortMin, RelayPortMax uint16

	// AllowPeers re-enables relaying to and from the listed ranges even when
	// the default policy refuses them (it also overrides the own-address
	// refusal). Empty in production.
	AllowPeers []netip.Prefix
	// OwnAddrs lists extra addresses of this server that peers may not be
	// (interface addresses are discovered automatically).
	OwnAddrs []netip.Addr

	// Quotas and bounds. Zero means the default in parentheses.
	MaxAllocations        int           // total allocations (1000)
	MaxAllocationsPerUser int           // per USERNAME (10)
	DefaultLifetime       time.Duration // (10 min)
	MaxLifetime           time.Duration // cap on any lifetime (1 h)
	MaxAllocationAge      time.Duration // Refresh is refused, and an expired username no longer accepted, past this age (12 h)
	MaxBytesPerSecond     int           // per allocation, both directions; -1 disables (4 MiB/s)
	MaxPermissions        int           // per allocation (128)
	MaxChannels           int           // per allocation (128)
	NonceLifetime         time.Duration // (10 min)
	MaxConns              int           // concurrent TCP/TLS connections (1024)
	IdleTimeout           time.Duration // TCP/TLS idle limit once an allocation exists (10 min)
	HandshakeTimeout      time.Duration // TCP/TLS idle limit before any allocation (30 s)
	RelayBufSize          int           // largest relayed datagram (4096)

	// ProxyProtocolFrom lists the sources (a load balancer such as Caddy or
	// HAProxy) whose TCP and TLS connections must begin with a PROXY protocol
	// header (v2 or v1) naming the real client. A connection from a listed
	// source without a valid header is closed; a header from any other
	// source is never honoured (the connection is closed). Once honoured, the
	// header's address is the client address for XOR-MAPPED-ADDRESS, quotas
	// and logs. For ServeTLS the header precedes the ClientHello (TLS is
	// terminated here, not by the proxy). Empty means PROXY protocol is off.
	// It never applies to UDP.
	ProxyProtocolFrom []netip.Prefix

	// Logger receives debug and warning records (default: discard).
	Logger *slog.Logger
	// Observer, when set, is told about every finished control request (see
	// Observer). Nil is off.
	Observer Observer
	// Now replaces time.Now (tests).
	Now func() time.Time
}

Config configures a Server. Realm, Auth and RelayIP are required.

type Observer added in v0.6.0

type Observer interface {
	Request(RequestInfo)
}

Observer is told about every finished TURN control request (Allocate, Refresh, CreatePermission, ChannelBind). It is never called per relayed packet: those are the Stats counters. A nil Observer costs nothing.

The record carries no address, username, nonce or credential, so an implementation can export it as it is.

type RequestInfo added in v0.6.0

type RequestInfo struct {
	// Method is "allocate", "refresh", "create_permission", "channel_bind" or
	// "other" (a method the server does not serve).
	Method string
	// Transport is "udp", "tcp" or "tls": how the client reached the server.
	Transport string
	// Code is the STUN error code of the answer (RFC 8489 section 14.8), or 0
	// for a success.
	Code int
	// Policy classes a 403 caused by the peer-address policy: "loopback",
	// "private", "link_local", "metadata", "cgnat", "multicast", "translator",
	// "own_address", "reserved" or "port_zero". A 443 is "family_mismatch".
	// Empty for every other answer.
	Policy string
	// Received is when the request was taken off the wire; End is when it was
	// answered.
	Received, End time.Time
}

RequestInfo describes one finished control request.

type Server

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

Server is a TURN server. Create it with New, hand it sockets with ServePacketConn, ServeListener and ServeTLS, stop it with Close.

func New

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

New validates cfg and returns a stopped-until-served Server.

func (*Server) Close

func (s *Server) Close() error

Close stops every listener, connection and allocation and waits for the goroutines to end.

func (*Server) ServeListener

func (s *Server) ServeListener(ln net.Listener) error

ServeListener serves STUN and TURN over TCP connections accepted from ln until it is closed. With Config.ProxyProtocolFrom set, connections from the listed sources must start with a PROXY protocol header.

func (*Server) ServePacketConn

func (s *Server) ServePacketConn(pc net.PacketConn) error

ServePacketConn serves STUN and TURN over the UDP socket pc until it is closed. It returns nil when pc is closed by Close.

func (*Server) ServeTLS

func (s *Server) ServeTLS(ln net.Listener, cfg *tls.Config) error

ServeTLS serves TURN over TLS (turns:) on ln with cfg. With Config.ProxyProtocolFrom set, a PROXY protocol header from a listed source is read before the TLS handshake (it precedes the ClientHello).

func (*Server) Stats

func (s *Server) Stats() Stats

Stats returns the current counters.

func (*Server) Usage added in v0.6.0

func (s *Server) Usage() Usage

Usage returns the live permissions and channel bindings.

type Stats

type Stats struct {
	Allocations     int    // live allocations
	Allocated       uint64 // allocations ever created
	PacketsToPeer   uint64 // client to peer datagrams relayed
	PacketsToClient uint64 // peer to client datagrams relayed
	Dropped         uint64 // datagrams dropped (no permission, rate cap, bad frame)
	ChannelBinds    uint64 // successful ChannelBind requests
	BytesToPeer     uint64 // payload bytes of the datagrams counted in PacketsToPeer
	BytesToClient   uint64 // payload bytes of the datagrams counted in PacketsToClient
}

Stats is a snapshot of the server counters.

type Usage added in v0.6.0

type Usage struct {
	Permissions, Channels int
}

Usage is the live permissions and channel bindings, summed over every allocation. It walks the allocations, so call it at a slow rate (a metrics scrape), not per packet.

Jump to

Keyboard shortcuts

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