package relay import ( "encoding/binary" "errors" "fmt" "math/rand/v2" "net" "sort" "strconv" "sync" "time" "github.com/pion/logging" "github.com/pion/stun/v3" "github.com/pion/turn/v4" ) // Realm is the TURN realm every credential is minted and verified under. const Realm = "carlos" // pendingLife is how long a socket or an admission may sit unclaimed // before tick reclaims it. Both are consumed within one request in the // normal path; this only catches an allocation that failed after pion had // already asked us for a socket. const pendingLife = 30 * time.Second // authMemory is how long the last parsed username for a typed source is // kept once that source has no allocation, so a client that authenticates // and never allocates cannot grow the map without bound. const authMemory = 10 * time.Minute const ( // maxRefusalIdentities and maxLoggedRefusals bound the two maps an // unauthenticated client can otherwise grow: pion calls AuthHandler // with the raw username before it checks MESSAGE-INTEGRITY, so every // counter keyed on something the caller chose is remote memory. Only // identities in the authority record get their own row; everything // else shares the zero identity, and these caps are the backstop. maxRefusalIdentities = 4096 maxLoggedRefusals = 4096 // refusalLogEvery is how often one identity's one refusal reason may // put a line in the log. refusalLogEvery = time.Minute // minLastAuthEntries is the floor under Limits.BoxLive*2 for how many // typed sources may hold a remembered username at once. minLastAuthEntries = 256 ) var errTCPAllocUnsupported = errors.New("relay: TCP relay allocations are not supported") // ServerConfig is everything the relay needs from its process: where to // listen, what to advertise, and the four live views (masters, authority, // lease, limits) it reads on every request. type ServerConfig struct { Region string RelayIP net.IP // the EIP advertised to clients UDP, TCP string // listen addresses, e.g. ":3478"; empty disables MinPort, MaxPort uint16 // 49152, 65535 DenyCIDRs []*net.IPNet // from CARLOS_RELAY_DENY_CIDRS, on top of the built-in private ranges ExtraAllow []*net.IPNet // peer ranges allowed despite the built-in list; empty in production Masters func() *Masters Authority func() *Authority Lease func(now time.Time) bool Limits Limits Now func() time.Time Log func(string, ...any) // Meter is the byte meter (Task 7); nil disables metering. It is an // interface so this file does not depend on the meter's shape. Meter interface { Add(id Identity, in, out, rejected int64) } } // Server is the relay: a pion TURN server whose every socket we own, so // that an allocation can be ended, attributed and bounded from outside // pion, which exposes no way to do any of it. type Server struct { cfg ServerConfig now func() time.Time log func(string, ...any) adm *Admission box *Bucket ports *portSet deny []*net.IPNet allow []*net.IPNet local []net.IP // our listeners' own addresses, when not wildcard maxLastAuth int turn *turn.Server udp net.PacketConn tcp net.Listener listeners []string mu sync.Mutex seq int64 pending map[int]pendingConn // relay port -> socket awaiting OnAllocationCreated lastAuth map[string]authRec // typed source -> the username it last authenticated with admits map[string]admitRec // typed source -> an admission not yet owned by an allocation bound map[string]*Binding // typed source -> the identity it is bound to allocs map[string]*allocEntry // typed source -> its live allocation owners map[*relayConn]*allocEntry // socket -> what closing it must undo byPort map[int]*relayConn // relay port -> its socket, however far the allocation got refusals map[Identity]map[string]int logged map[logKey]time.Time shedding map[Identity]bool } type logKey struct { id Identity reason string } type allocEntry struct { conn *relayConn id Identity key string // the typed source this allocation was created for seq int64 timer *time.Timer flow *flow } type pendingConn struct { conn *relayConn flow *flow at time.Time } // flow is one allocation's peer-to-client accounting. pion's allocation // reads a peer packet and then either forwards it to the client or drops // it for want of a permission, both on the allocation's own goroutine, so // a packet that is still unforwarded when the next one arrives (or when // the socket closes) is a packet that was dropped. That is what spec §3 // counts as `rejected`, and it is never charged to a budget. type flow struct { mu sync.Mutex awaiting int64 // size of the peer packet read and not yet forwarded } // read records a peer packet and returns the bytes of the previous one if // it was never forwarded. func (f *flow) read(n int) int64 { f.mu.Lock() defer f.mu.Unlock() dropped := f.awaiting f.awaiting = int64(n) return dropped } // forwarded clears the packet the listener has just written to the client. func (f *flow) forwarded() { f.mu.Lock() f.awaiting = 0 f.mu.Unlock() } // flush is the last packet's verdict when the socket closes. func (f *flow) flush() int64 { f.mu.Lock() defer f.mu.Unlock() dropped := f.awaiting f.awaiting = 0 return dropped } // readCounter is the relay socket's peer-ingress leg. It sits under // relayConn so that relayConn keeps counting only what it forwards. type readCounter struct { net.PacketConn f *flow onDrop func(int64) } func (r *readCounter) ReadFrom(p []byte) (int, net.Addr, error) { n, addr, err := r.PacketConn.ReadFrom(p) if n > 0 { if dropped := r.f.read(n); dropped > 0 && r.onDrop != nil { r.onDrop(dropped) } } return n, addr, err } type authRec struct { u Username at time.Time } type admitRec struct { id Identity at time.Time } // builtinDeny is the peer policy every relay carries whatever the operator // configures: loopback, link-local (the IMDS address included), RFC 1918, // unique-local and carrier-grade NAT space; "this network" (0.0.0.0/8, which // Linux delivers to the local host, not only the unspecified address), the // IETF protocol-assignment block (192.0.0.0/24) and the benchmarking range // (198.18.0.0/15), none of which is a public peer (discussion #220). // // IPv6 forms that carry an IPv4 address — NAT64 (64:ff9b::/96) and 6to4 // (2002::/16) — are not listed: they are judged by the address they embed // (see embeddedV4), so a NAT64 gateway cannot be used to reach 10.0.0.1 and // a public address behind either one still works. var builtinDeny = mustCIDRs( "127.0.0.0/8", "::1/128", "169.254.0.0/16", "fe80::/10", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7", "100.64.0.0/10", "0.0.0.0/8", "192.0.0.0/24", "198.18.0.0/15", ) // Prefixes whose addresses embed an IPv4 address: the NAT64 well-known // prefix carries it in the last 32 bits (RFC 6052), 6to4 in bits 16-47 // (RFC 3056). var ( nat64Prefix = mustCIDRs("64:ff9b::/96")[0] sixToFour = mustCIDRs("2002::/16")[0] ) // embeddedV4 returns the IPv4 address a NAT64 or 6to4 peer stands for, or // nil for any other address. An IPv4-mapped address (::ffff:a.b.c.d) needs // no help: net.IPNet.Contains already matches it against the IPv4 ranges. func embeddedV4(ip net.IP) net.IP { ip16 := ip.To16() if ip16 == nil || ip.To4() != nil { return nil } switch { case nat64Prefix.Contains(ip16): return net.IPv4(ip16[12], ip16[13], ip16[14], ip16[15]) case sixToFour.Contains(ip16): return net.IPv4(ip16[2], ip16[3], ip16[4], ip16[5]) } return nil } func mustCIDRs(ss ...string) []*net.IPNet { out := make([]*net.IPNet, 0, len(ss)) for _, s := range ss { _, n, err := net.ParseCIDR(s) if err != nil { panic("relay: bad built-in CIDR " + s + ": " + err.Error()) } out = append(out, n) } return out } func NewServer(cfg ServerConfig) (*Server, error) { if cfg.Now == nil { cfg.Now = time.Now } if cfg.Log == nil { cfg.Log = func(string, ...any) {} } if cfg.MinPort == 0 { cfg.MinPort = 49152 } if cfg.MaxPort == 0 { cfg.MaxPort = 65535 } switch { case cfg.RelayIP == nil: return nil, errors.New("relay: RelayIP is required") case cfg.MinPort > cfg.MaxPort: return nil, fmt.Errorf("relay: port range %d-%d is empty", cfg.MinPort, cfg.MaxPort) case cfg.Masters == nil || cfg.Authority == nil || cfg.Lease == nil: return nil, errors.New("relay: Masters, Authority and Lease are required") case cfg.UDP == "" && cfg.TCP == "": return nil, errors.New("relay: no listener configured") } maxLastAuth := cfg.Limits.BoxLive * 2 if maxLastAuth < minLastAuthEntries { maxLastAuth = minLastAuthEntries } s := &Server{ cfg: cfg, now: cfg.Now, log: cfg.Log, adm: NewAdmission(cfg.Limits, cfg.Now), box: NewBucket(cfg.Limits.BoxBitsPerSec, cfg.Now), ports: &portSet{m: map[int]bool{}}, deny: append(append([]*net.IPNet{}, builtinDeny...), cfg.DenyCIDRs...), allow: append([]*net.IPNet{}, cfg.ExtraAllow...), maxLastAuth: maxLastAuth, pending: map[int]pendingConn{}, lastAuth: map[string]authRec{}, admits: map[string]admitRec{}, bound: map[string]*Binding{}, allocs: map[string]*allocEntry{}, owners: map[*relayConn]*allocEntry{}, byPort: map[int]*relayConn{}, refusals: map[Identity]map[string]int{}, logged: map[logKey]time.Time{}, shedding: map[Identity]bool{}, } var packets []turn.PacketConnConfig var listeners []turn.ListenerConfig if cfg.UDP != "" { pc, err := net.ListenPacket("udp", cfg.UDP) if err != nil { return nil, fmt.Errorf("relay: listen udp %s: %w", cfg.UDP, err) } s.udp = pc s.noteLocal(pc.LocalAddr()) s.listeners = append(s.listeners, "udp:"+portOf(pc.LocalAddr())) packets = append(packets, turn.PacketConnConfig{ PacketConn: &listenerConn{PacketConn: pc, s: s}, RelayAddressGenerator: s, PermissionHandler: s.permit, }) } if cfg.TCP != "" { l, err := net.Listen("tcp", cfg.TCP) if err != nil { if s.udp != nil { s.udp.Close() } return nil, fmt.Errorf("relay: listen tcp %s: %w", cfg.TCP, err) } s.tcp = l s.noteLocal(l.Addr()) s.listeners = append(s.listeners, "tcp:"+portOf(l.Addr())) listeners = append(listeners, turn.ListenerConfig{ Listener: &countingListener{Listener: l, s: s}, RelayAddressGenerator: s, PermissionHandler: s.permit, }) } ts, err := turn.NewServer(turn.ServerConfig{ Realm: Realm, AuthHandler: s.auth, QuotaHandler: s.quota, EventHandler: turn.EventHandler{OnAllocationCreated: s.created}, PacketConnConfigs: packets, ListenerConfigs: listeners, LoggerFactory: logging.NewDefaultLoggerFactory(), }) if err != nil { if s.udp != nil { s.udp.Close() } if s.tcp != nil { s.tcp.Close() } return nil, fmt.Errorf("relay: pion server: %w", err) } s.turn = ts return s, nil } func (s *Server) noteLocal(a net.Addr) { var ip net.IP switch v := a.(type) { case *net.UDPAddr: ip = v.IP case *net.TCPAddr: ip = v.IP } if ip != nil && !ip.IsUnspecified() { s.local = append(s.local, ip) } } func portOf(a net.Addr) string { switch v := a.(type) { case *net.UDPAddr: return strconv.Itoa(v.Port) case *net.TCPAddr: return strconv.Itoa(v.Port) } _, p, err := net.SplitHostPort(a.String()) if err != nil { return a.String() } return p } // Listeners names the transports that are up, e.g. ["udp:3478","tcp:3478"], // for the heartbeat. func (s *Server) Listeners() []string { return append([]string{}, s.listeners...) } // UDPAddr is the UDP listener's bound address, or nil if UDP is disabled. func (s *Server) UDPAddr() net.Addr { if s.udp == nil { return nil } return s.udp.LocalAddr() } // Live is the number of allocations the relay is carrying. func (s *Server) Live() int { s.mu.Lock() defer s.mu.Unlock() return len(s.allocs) } // LiveByIdentity is Live broken down per app, for the meter's `allocs` // gauge (spec §3, "Metering"). The Meter the server holds is narrowed to // Add, deliberately — the server counts bytes as it forwards them and knows // nothing about sample boundaries — so the gauge is the serve loop's job to // set, and this is where it reads it from. func (s *Server) LiveByIdentity() map[Identity]int { s.mu.Lock() defer s.mu.Unlock() out := make(map[Identity]int, len(s.allocs)) for _, e := range s.allocs { out[e.id]++ } return out } // Seed replays metered bytes into the rolling-hour windows, so a restart // resumes its budgets from the metrics objects it wrote. func (s *Server) Seed(id Identity, at time.Time, n int64) { s.adm.Seed(id, at, n) } // Close ends every allocation and stops listening. func (s *Server) Close() error { s.EndAll("server closing") s.mu.Lock() pending := make([]*relayConn, 0, len(s.pending)) for _, p := range s.pending { pending = append(pending, p.conn) } s.mu.Unlock() for _, c := range pending { c.Close() } if s.turn == nil { return nil } return s.turn.Close() } // EndAll ends every allocation: a lease lapse, or shutdown. func (s *Server) EndAll(reason string) { s.EndWhere(func(*Binding) bool { return true }, reason) } // EndWhere ends every allocation whose binding matches: a disable, an // incarnation change, this region leaving an app's list, a byte budget, a // retired master. The predicate is called on a copy of the binding, off // the server's lock. func (s *Server) EndWhere(match func(*Binding) bool, reason string) { type candidate struct { conn *relayConn b Binding } s.mu.Lock() cands := make([]candidate, 0, len(s.allocs)) for _, e := range s.allocs { cands = append(cands, candidate{conn: e.conn, b: *e.conn.b}) } s.mu.Unlock() n := 0 for _, c := range cands { b := c.b if match(&b) { c.conn.Close() n++ } } if n > 0 { s.log("relay: ended %d allocation(s): %s", n, reason) } } // ShedOldest ends the n oldest allocations, for memory pressure. func (s *Server) ShedOldest(n int) { if n <= 0 { return } s.mu.Lock() entries := make([]*allocEntry, 0, len(s.allocs)) for _, e := range s.allocs { entries = append(entries, e) } s.mu.Unlock() sort.Slice(entries, func(i, j int) bool { return entries[i].seq < entries[j].seq }) if n > len(entries) { n = len(entries) } for _, e := range entries[:n] { e.conn.Close() } if n > 0 { s.log("relay: shed %d oldest allocation(s)", n) } } // tick is the sweep: it ends allocations whose credential has expired // (belt for the per-allocation timers), whose master has retired, whose app // or account is over budget, and every allocation at all if the serving // lease has lapsed. It also reclaims sockets and admissions that a failed // allocation left behind. func (s *Server) tick() { now := s.now() masters := s.cfg.Masters() leaseDead := !s.cfg.Lease(now) type victim struct { conn *relayConn reason string } var victims []victim var stale []*relayConn // A masters file that failed to reload leaves masters nil; that is a // reason to keep serving on the keys we have, not to end anything. retired := func(kid string) bool { if masters == nil || kid == "" { return false } _, ok := masters.Lookup(kid, now) return !ok } s.mu.Lock() for _, e := range s.allocs { b := e.conn.b switch { case leaseDead: victims = append(victims, victim{e.conn, "serving lease lapsed"}) case !b.Expiry.IsZero() && !b.Expiry.After(now): victims = append(victims, victim{e.conn, "credential expired"}) case retired(b.Kid): victims = append(victims, victim{e.conn, "master " + b.Kid + " retired"}) case s.adm.OverBudget(e.id, now): victims = append(victims, victim{e.conn, "byte budget"}) } } for port, p := range s.pending { if now.Sub(p.at) > pendingLife { delete(s.pending, port) stale = append(stale, p.conn) } } var lapsed []Identity for key, a := range s.admits { if now.Sub(a.at) > pendingLife { delete(s.admits, key) lapsed = append(lapsed, a.id) } } for key, a := range s.lastAuth { if _, live := s.allocs[key]; !live && now.Sub(a.at) > authMemory { delete(s.lastAuth, key) } } // Refusal counters live only for apps the authority still names; the // zero identity is the shared bucket for everything else and stays. for id := range s.refusals { if id == (Identity{}) { continue } if _, ok := s.cfg.Authority().Lookup(id.Account, id.App); !ok { delete(s.refusals, id) } } for k, at := range s.logged { if now.Sub(at) >= refusalLogEvery { delete(s.logged, k) } } s.mu.Unlock() for _, id := range lapsed { s.adm.Release(id) } for _, c := range stale { c.Close() } for _, v := range victims { s.log("relay: ending allocation for %s/%s: %s", v.conn.b.ID.Account, v.conn.b.ID.App, v.reason) v.conn.Close() } } // --- turn.RelayAddressGenerator ------------------------------------------ func (s *Server) Validate() error { if s.cfg.RelayIP == nil { return errors.New("relay: RelayIP is required") } if s.cfg.MinPort > s.cfg.MaxPort { return fmt.Errorf("relay: port range %d-%d is empty", s.cfg.MinPort, s.cfg.MaxPort) } return nil } // AllocatePacketConn binds one allocation's relay socket in the configured // port range and hands pion our wrapper for it: the wrapper is how the // allocation is ended, metered and bounded. The advertised address is the // EIP, which is not an address on the box, so the socket itself binds the // wildcard. func (s *Server) AllocatePacketConn(network string, requestedPort int) (net.PacketConn, net.Addr, error) { if network == "" { network = "udp4" } lo, hi := int(s.cfg.MinPort), int(s.cfg.MaxPort) span := hi - lo + 1 tries := span if tries > 64 { tries = 64 } ports := make([]int, 0, tries+1) if requestedPort >= lo && requestedPort <= hi { ports = append(ports, requestedPort) } start := rand.IntN(span) for i := 0; i < tries; i++ { ports = append(ports, lo+(start+i)%span) } for _, port := range ports { if s.ports.has(port) { continue } pc, err := net.ListenPacket(network, net.JoinHostPort("", strconv.Itoa(port))) if err != nil { continue } bucket := NewBucket(s.cfg.Limits.AllocBitsPerSec, s.now) f := &flow{} var c *relayConn // The socket counts peer ingress under the wrapper, so a peer // packet pion drops for want of a permission is still seen. counted := &readCounter{PacketConn: pc, f: f, onDrop: func(n int64) { s.countRejected(c.b.ID, n) }} c = newRelayConn(counted, &Binding{}, s.cfg.RelayIP, s.ports, bucket, s.box, s.countIn, s.countGated, func(rc *relayConn) { s.release(port, rc) }) s.ports.add(port) s.mu.Lock() s.pending[port] = pendingConn{conn: c, flow: f, at: s.now()} s.byPort[port] = c s.mu.Unlock() return c, &net.UDPAddr{IP: s.cfg.RelayIP, Port: port}, nil } return nil, nil, fmt.Errorf("relay: no free port in %d-%d", lo, hi) } // AllocateConn would be a TCP relay allocation (RFC 6062), which we do not // offer: a TURN client may reach us over TCP, but every relayed leg is UDP. func (s *Server) AllocateConn(string, int) (net.Conn, net.Addr, error) { return nil, nil, errTCPAllocUnsupported } // --- pion handlers ------------------------------------------------------- // auth is pion's AuthHandler: called on every authenticated request, and // the whole of spec §4's verification. It returns the key pion checks // MESSAGE-INTEGRITY against, so a wrong credential fails inside pion and // never reaches here. func (s *Server) auth(username, realm string, src net.Addr) ([]byte, bool) { now := s.now() u, err := ParseUsername(username) if err != nil { return s.refused(Identity{}, "bad shape", "relay: auth refused from %s: %v", src, err) } id := Identity{Account: u.Account, App: u.App} if !u.Expiry.After(now) || u.Expiry.After(now.Add(MaxCredentialLife)) { return s.refused(id, "expired", "relay: auth refused for %s/%s: expiry %s outside (now, now+%s]", id.Account, id.App, u.Expiry.UTC().Format(time.RFC3339), MaxCredentialLife) } s.mu.Lock() bound, isBound := s.bound[typedSrc(src)] s.mu.Unlock() if isBound && (bound.ID != id || bound.Incarnation != u.Incarnation) { return s.refused(id, "bound elsewhere", "relay: auth refused for %s/%s: source %s is bound to %s/%s", id.Account, id.App, typedSrc(src), bound.ID.Account, bound.ID.App) } app, ok := s.cfg.Authority().Lookup(u.Account, u.App) switch { case !ok: return s.refused(id, "unknown app", "relay: auth refused for %s/%s: not in the authority record", id.Account, id.App) case app.Incarnation != u.Incarnation: return s.refused(id, "wrong incarnation", "relay: auth refused for %s/%s: incarnation %s, record has %s", id.Account, id.App, u.Incarnation, app.Incarnation) case !contains(app.Regions, s.cfg.Region): return s.refused(id, "wrong region", "relay: auth refused for %s/%s: region %s not in %v", id.Account, id.App, s.cfg.Region, app.Regions) } masters := s.cfg.Masters() if masters == nil { return s.refused(id, "unknown kid", "relay: auth refused for %s/%s: no masters loaded", id.Account, id.App) } master, ok := masters.Lookup(u.Kid, now) if !ok { return s.refused(id, "unknown kid", "relay: auth refused for %s/%s: kid %s is unknown or retired", id.Account, id.App, u.Kid) } key := DeriveKey(master.Key, u.Account, u.App, u.Incarnation) s.rememberAuth(typedSrc(src), u, now) return turn.GenerateAuthKey(username, realm, Credential(key, username)), true } // rememberAuth stores the username a source last authenticated with, for // the allocation event that follows. pion verifies MESSAGE-INTEGRITY only // after the handler returns, so this map is written for sources that have // not proved anything yet: tick ages entries out, and this caps them at // twice the box's live-allocation limit, dropping the oldest quarter when // it fills. func (s *Server) rememberAuth(key string, u Username, now time.Time) { s.mu.Lock() defer s.mu.Unlock() if _, known := s.lastAuth[key]; !known && len(s.lastAuth) >= s.maxLastAuth { type aged struct { key string at time.Time } all := make([]aged, 0, len(s.lastAuth)) for k, r := range s.lastAuth { all = append(all, aged{k, r.at}) } sort.Slice(all, func(i, j int) bool { return all[i].at.Before(all[j].at) }) drop := len(all) / 4 if drop == 0 { drop = 1 } for _, a := range all[:drop] { delete(s.lastAuth, a.key) } } s.lastAuth[key] = authRec{u: u, at: now} } // quota is pion's QuotaHandler, called on Allocate only: a refusal answers // 486. The lease comes first, because a relay whose authority read is // stale must take nothing new on. func (s *Server) quota(username, _ string, src net.Addr) bool { now := s.now() if !s.cfg.Lease(now) { s.log("relay: allocation refused: serving lease has lapsed") return false } u, err := ParseUsername(username) if err != nil { return false // auth would already have refused this } id := Identity{Account: u.Account, App: u.App} ok, reason := s.adm.Admit(id) if !ok { s.countRefusal(id, reason) s.log("relay: allocation refused for %s/%s: %s", id.Account, id.App, reason) return false } key := typedSrc(src) s.mu.Lock() old, had := s.admits[key] s.admits[key] = admitRec{id: id, at: now} s.mu.Unlock() if had { // A previous attempt from this source was admitted and never // became an allocation; it owns no socket, so release it here. s.adm.Release(old.id) } return true } // created is pion's OnAllocationCreated, called with the relay address // before pion starts reading from the socket. It is where the wrapper we // handed out earlier learns whose allocation it is. func (s *Server) created(src, _ net.Addr, _, _, _ string, relayAddr net.Addr, _ int) { ua, ok := relayAddr.(*net.UDPAddr) if !ok { s.log("relay: allocation created with a non-UDP relay address %v", relayAddr) return } key := typedSrc(src) now := s.now() s.mu.Lock() p, havePending := s.pending[ua.Port] if !havePending { // The sweep already reclaimed this socket, or it was never ours. // Either way pion now owns an allocation no deadline of ours can // end, so end it here by closing the socket it reads from. orphan := s.byPort[ua.Port] s.mu.Unlock() if orphan != nil { s.log("relay: allocation created on port %d after its socket was reclaimed: ending it", ua.Port) orphan.Close() } else { s.log("relay: allocation created on port %d with no socket of ours", ua.Port) } return } delete(s.pending, ua.Port) rec, haveAuth := s.lastAuth[key] if !haveAuth { s.mu.Unlock() s.log("relay: allocation created for %s with no authenticated username", key) p.conn.Close() return } c := p.conn c.b.ID = Identity{Account: rec.u.Account, App: rec.u.App} c.b.Expiry = rec.u.Expiry c.b.Kid = rec.u.Kid c.b.Incarnation = rec.u.Incarnation c.b.Src = key s.seq++ e := &allocEntry{conn: c, id: c.b.ID, key: key, seq: s.seq, flow: p.flow} s.allocs[key] = e s.owners[c] = e s.bound[key] = c.b delete(s.admits, key) expiry := rec.u.Expiry s.mu.Unlock() // The credential's own deadline. Set outside the lock: a timer whose // deadline has already passed fires on the spot, and closing takes the // lock we would still be holding. t := time.AfterFunc(expiry.Sub(now), func() { c.Close() }) s.mu.Lock() if cur, ok := s.allocs[key]; ok && cur == e { e.timer = t } else { t.Stop() } s.mu.Unlock() s.log("relay: allocation for %s/%s on %s from %s until %s", c.b.ID.Account, c.b.ID.App, relayAddr, key, expiry.UTC().Format(time.RFC3339)) } // release is the wrapped socket's onClose, whoever closed it: pion on a // read error, a timer, tick, EndWhere. Its state is keyed on this socket, // not on the typed source, so a replacement allocation bound for the same // source while this one was closing (pion removes an allocation from its // manager before closing it) keeps its binding and this one still gives // its admission back. func (s *Server) release(port int, c *relayConn) { s.ports.remove(port) var id Identity var release bool var last int64 s.mu.Lock() if p, ok := s.pending[port]; ok && p.conn == c { delete(s.pending, port) last = p.flow.flush() } if cur, ok := s.byPort[port]; ok && cur == c { delete(s.byPort, port) } if e, ok := s.owners[c]; ok { last = e.flow.flush() delete(s.owners, c) if e.timer != nil { e.timer.Stop() } if cur, ok := s.allocs[e.key]; ok && cur == e { delete(s.allocs, e.key) } if b, ok := s.bound[e.key]; ok && b == c.b { delete(s.bound, e.key) } id, release = e.id, true } s.mu.Unlock() if release { s.adm.Release(id) } if last > 0 { // The last peer packet was read and never forwarded. s.countRejected(c.b.ID, last) } } // permit is pion's PermissionHandler: it sees only a peer IP, so the port // half of the EIP rule lives in relayConn.WriteTo. func (s *Server) permit(client net.Addr, peer net.IP) bool { deny := func(why string) bool { s.mu.Lock() b, ok := s.bound[typedSrc(client)] var id Identity if ok { id = b.ID } s.mu.Unlock() s.countRefusal(id, "peer denied") s.log("relay: permission refused for %s to %s: %s", client, peer, why) return false } if peer == nil { return deny("unspecified address") } // Our own EIP is allowed: two clients that both relay here hold relay // candidates on it and must reach each other. if s.cfg.RelayIP != nil && peer.Equal(s.cfg.RelayIP) { return true } if why := s.peerRefusal(peer); why != "" { return deny(why) } // A NAT64 or 6to4 address is a route to the IPv4 address inside it, so // that address has to pass too. if v4 := embeddedV4(peer); v4 != nil { if why := s.peerRefusal(v4); why != "" { return deny(why + " (embedded in " + peer.String() + ")") } } return true } // peerRefusal is permit's verdict on one address, "" when it may be reached. func (s *Server) peerRefusal(peer net.IP) string { switch { case peer.IsUnspecified(): return "unspecified address" case peer.IsMulticast(): return "multicast address" } // ExtraAllow is the operator's (and the test fixture's) way to permit // a range the built-in list denies. Empty on a real box. for _, n := range s.allow { if n.Contains(peer) { return "" } } for _, n := range s.deny { if n.Contains(peer) { return "denied range " + n.String() } } for _, ip := range s.local { if peer.Equal(ip) { return "the relay's own address" } } return "" } // --- metering ------------------------------------------------------------ // countIn is the client-to-peer leg, counted at the relay socket after // pion forwarded it. func (s *Server) countIn(id Identity, n int) { if s.cfg.Meter != nil { s.cfg.Meter.Add(id, int64(n), 0, 0) } if s.adm.AddBytes(id, int64(n)) { s.overBudget(id) } } // countOut is the peer-to-client leg, counted at the listener socket and // attributed through the owner binding. func (s *Server) countOut(id Identity, n int) { if s.cfg.Meter != nil { s.cfg.Meter.Add(id, 0, int64(n), 0) } if s.adm.AddBytes(id, int64(n)) { s.overBudget(id) } } // countRejected is spec §3's `rejected`: peer bytes that reached a relay // socket and were dropped for want of a permission. Metered, never charged // to a budget. func (s *Server) countRejected(id Identity, n int64) { if s.cfg.Meter != nil { s.cfg.Meter.Add(id, 0, 0, n) } } // countGated is the other kind of drop: a client packet aimed at our own // EIP on a port that is not a live allocation. It is a policy refusal, not // a meter line, so it is counted per app and goes no further. func (s *Server) countGated(id Identity, _ int) { s.countRefusal(id, "gated") } // overBudget ends an app's allocations once its rolling-hour budget is // crossed, because a budget that only stops new allocations bounds nothing. // It runs off the forwarding path, once per identity at a time. func (s *Server) overBudget(id Identity) { s.mu.Lock() if s.shedding[id] { s.mu.Unlock() return } s.shedding[id] = true s.mu.Unlock() go func() { s.EndWhere(func(b *Binding) bool { return b.ID == id }, "byte budget") s.mu.Lock() delete(s.shedding, id) s.mu.Unlock() }() } // attrib is which identity a refusal may be counted against. pion hands // the AuthHandler whatever username arrived, before any integrity check, // so an unauthenticated sender picks the account and app strings. Only an // app the authority record actually names gets a row of its own; every // other refusal shares the zero identity. func (s *Server) attrib(id Identity) Identity { if id.Account == "" || id.App == "" { return Identity{} } if _, ok := s.cfg.Authority().Lookup(id.Account, id.App); !ok { return Identity{} } return id } func (s *Server) countRefusal(id Identity, reason string) { id = s.attrib(id) s.mu.Lock() m := s.refusals[id] if m == nil && len(s.refusals) >= maxRefusalIdentities { id = Identity{} m = s.refusals[id] } if m == nil { m = map[string]int{} s.refusals[id] = m } m[reason]++ s.mu.Unlock() } // mayLog rate-limits one identity's one refusal reason to a line a minute, // so a flood of refusals cannot be turned into a flood of log. func (s *Server) mayLog(id Identity, reason string) bool { k := logKey{id: s.attrib(id), reason: reason} now := s.now() s.mu.Lock() defer s.mu.Unlock() if at, ok := s.logged[k]; ok { if now.Sub(at) < refusalLogEvery { return false } } else if len(s.logged) >= maxLoggedRefusals { return false } s.logged[k] = now return true } // refused counts a refusal against the app and logs why. Its return values // are the AuthHandler's, so a refusal is one line at the call site. func (s *Server) refused(id Identity, reason, format string, args ...any) ([]byte, bool) { s.countRefusal(id, reason) if s.mayLog(id, reason) { s.log(format, args...) } return nil, false } func (s *Server) refusalCount(id Identity, reason string) int { s.mu.Lock() defer s.mu.Unlock() return s.refusals[id][reason] } func (s *Server) refusalIdentities() int { s.mu.Lock() defer s.mu.Unlock() return len(s.refusals) } // entryFor is the owner binding lookup the out leg is attributed through. func (s *Server) entryFor(key string) *allocEntry { s.mu.Lock() defer s.mu.Unlock() return s.allocs[key] } // --- listener wrappers --------------------------------------------------- // listenerConn wraps the UDP listener pion answers clients on. It mirrors // relayConn without the EIP gate: everything written here goes to a client // that asked us for it, so the only questions are whose bytes they are and // whether the buckets still have room. type listenerConn struct { net.PacketConn s *Server } func (c *listenerConn) WriteTo(p []byte, addr net.Addr) (int, error) { // A TURN response is the client asking us something, not relayed // media: bucketing it would drop Refresh responses at the app's rate // cap and end calls for a reason spec §3 does not list, and metering // it would bill the client for its own signalling. if !relayedPayload(p) { return c.PacketConn.WriteTo(p, addr) } e := c.s.entryFor(typedSrc(addr)) if e != nil { // Peek both, then spend both: a box refusal must not leave the // app's bucket debited (see relayConn.WriteTo). if e.conn.appBucket != nil && !e.conn.appBucket.Peek(len(p)) { return len(p), nil } if c.s.box != nil && !c.s.box.Peek(len(p)) { return len(p), nil } if e.conn.appBucket != nil { e.conn.appBucket.Spend(len(p)) } if c.s.box != nil { c.s.box.Spend(len(p)) } } n, err := c.PacketConn.WriteTo(p, addr) if n > 0 && e != nil { e.flow.forwarded() c.s.countOut(e.id, n) } return n, err } // relayedPayload reports whether a packet bound for a client carries peer // media rather than TURN signalling: a ChannelData message (first two bits // 0b01, so 0x40 to 0x7f) or a Data indication. func relayedPayload(p []byte) bool { if len(p) == 0 { return false } if p[0]&0xc0 == 0x40 { return true } if !stun.IsMessage(p) { return false } var t stun.MessageType t.ReadValue(binary.BigEndian.Uint16(p[0:2])) return t.Method == stun.MethodData && t.Class == stun.ClassIndication } // countingListener wraps the TCP listener so the out leg is metered for // TCP clients too. A TCP stream cannot have bytes dropped out of it the // way a datagram can, so the buckets are spent but never enforced here. type countingListener struct { net.Listener s *Server } func (l *countingListener) Accept() (net.Conn, error) { c, err := l.Listener.Accept() if err != nil { return nil, err } return &countingConn{Conn: c, s: l.s, key: typedSrc(c.RemoteAddr())}, nil } type countingConn struct { net.Conn s *Server key string } func (c *countingConn) Write(p []byte) (int, error) { payload := relayedPayload(p) n, err := c.Conn.Write(p) if n > 0 && payload { if e := c.s.entryFor(c.key); e != nil { if e.conn.appBucket != nil { e.conn.appBucket.Spend(n) } if c.s.box != nil { c.s.box.Spend(n) } e.flow.forwarded() c.s.countOut(e.id, n) } } return n, err } func contains(ss []string, s string) bool { for _, x := range ss { if x == s { return true } } return false }