A kolo-relay permite que dois peers se conectem quando nenhum dos dois consegue alcançar o outro, por exemplo quando os dois estão atrás de NAT simétrico ou CGNAT, ou atrás de um firewall que só deixa o tráfego sair. Um peer reserva uma vaga em um relay com um endereço alcançável; outro peer pede ao relay a chave desse peer, e o relay une os dois e copia os bytes entre eles, com alocações, durações e cotas baseadas no TURN (RFC 8656). Os dois peers rodam uma conexão comum da kolo-secure de ponta a ponta, então o relay repassa um texto cifrado que não consegue ler. Como a política relay do WebRTC, o relay fica desligado a não ser que a aplicação o ligue: ele nunca procura relays, nunca tenta um caminho direto primeiro e nunca recorre sozinho a um relay. Veja Relay.
Direto, ou por um relay
O relay nunca é uma alternativa silenciosa: quem escolhe é o seu app, pelo endereço e pela chave dele.
- Quando existe um caminho direto, os peers se conectam diretamente e nenhum relay participa.
- O alvo se conecta ao relay com kolo-secure e envia Reserve. O relay mantém a reserva por até uma hora.
- O iniciador se conecta ao relay e envia Connect com a chave do alvo.
- O relay avisa o alvo com Incoming e a chave do iniciador. O alvo aceita ou recusa, e o relay responde OK.
- O relay junta os dois streams. Dentro deles os peers abrem a própria conexão kolo-secure, de ponta a ponta, e o alvo confere que é o iniciador anunciado.
- O relay não consegue ler os pacotes. Ele fica sabendo as duas chaves, os dois endereços, quando a sessão começa e termina, e o tamanho e o ritmo dos pacotes. Cada sessão tem limites: 1 hora, 1 GiB em cada sentido, 60 segundos parada.
Instalação
go get github.com/ciranda-dev/kolo-relayCompila sem cgo.
Início rápido
Este programa inicia um relay no loopback, reserva uma vaga para um peer e se conecta a ele a partir de outro peer, através do relay.
package main
import (
"context"
"fmt"
"io"
"log"
"time"
koloid "github.com/ciranda-dev/kolo-id"
kolorelay "github.com/ciranda-dev/kolo-relay"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
relayID, err := koloid.Generate()
if err != nil {
log.Fatal(err)
}
targetID, err := koloid.Generate()
if err != nil {
log.Fatal(err)
}
dialerID, err := koloid.Generate()
if err != nil {
log.Fatal(err)
}
relay, err := kolorelay.Listen(ctx, "127.0.0.1:0", relayID, nil)
if err != nil {
log.Fatal(err)
}
defer relay.Close()
addr, key := relay.Addr().String(), relayID.PublicKey()
res, err := kolorelay.Reserve(ctx, addr, key, targetID, nil)
if err != nil {
log.Fatal(err)
}
defer res.Close()
go func() {
c, err := res.Accept(ctx)
if err != nil {
return
}
s, err := c.AcceptStream(ctx)
if err != nil {
return
}
io.Copy(s, s)
s.Close()
}()
c, err := kolorelay.Dial(ctx, addr, key, dialerID, targetID.PublicKey(), nil)
if err != nil {
log.Fatal(err)
}
defer c.Close()
fmt.Printf("connected to %x through relay %x\n", c.RemotePublicKey()[:4], c.RelayPublicKey()[:4])
s, err := c.OpenStream(ctx)
if err != nil {
log.Fatal(err)
}
if _, err := s.Write([]byte("hello kolo")); err != nil {
log.Fatal(err)
}
s.Close()
reply, err := io.ReadAll(s)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", reply)
}O programa imprime os primeiros bytes da chave do alvo e da chave do relay, e depois hello kolo devolvido pelo alvo. Em uma implantação real, o relay roda em um host com endereço público e carrega a sua identidade com koloid.Load; os peers obtêm o endereço e a chave dele pela sua própria configuração, e um alvo informa aos outros, por meio da aplicação, em qual relay fez a reserva.
Referência da API
A referência da API é gerada a partir do código Go e está em inglês.
Package kolorelay lets two Kolo peers that cannot reach each other connect through a relay they chose.
The peers run a kolo-secure connection end to end; its packets travel inside streams of each peer's own connection to the relay, so the relay forwards ciphertext of a session it is not part of. Using a relay is always an explicit choice of the application.
Experimental: the API may change before v1.0.0.
Variáveis
var (
// ErrInvalidConfig means a Config or ServerConfig field is out of range, or a kolo-transport Network in it is not "udp4".
ErrInvalidConfig = errors.New("kolorelay: invalid config")
// ErrInvalidArgument means a nil or zero identity, an IPv6 address (v4-mapped included),
// or a target key that is not 32 bytes or is the local or the relay's key.
ErrInvalidArgument = errors.New("kolorelay: invalid argument")
// ErrClosed means the Server or Reservation is closed.
ErrClosed = errors.New("kolorelay: closed")
// ErrProtocol means a relay message was malformed, truncated, too large or unexpected.
ErrProtocol = wire.ErrProtocol
// ErrUnsupportedVersion means the other side speaks another kolo-relay version.
ErrUnsupportedVersion = wire.ErrUnsupportedVersion
// ErrUnavailable means the target cannot be reached through the relay: no reservation,
// MaxSessionsPerTarget sessions, or the relay or the target refused.
ErrUnavailable = errors.New("kolorelay: target unavailable through the relay")
// ErrNotAllowed means the relay does not let this key reserve.
ErrNotAllowed = errors.New("kolorelay: not allowed by the relay")
// ErrLimit means MaxReservations, MaxSessions or MaxSessionsPerPeer was reached; trying later may work.
ErrLimit = limits.ErrLimit
// ErrReservationEnded means the reservation ended: its lifetime passed, the key reserved again,
// the relay closed, or the connection was lost.
ErrReservationEnded = errors.New("kolorelay: reservation ended")
)Tipos
type Config
type Config struct {
// Relay configures the connection to the relay. Nil means kolo-secure's defaults with a 5s keep-alive; a non-nil value is used as given.
Relay *kolosecure.Config
// Peer configures the end-to-end connection. Nil means the defaults; kolorelay sets the listener-only transport fields.
Peer *kolosecure.Config
// ControlTimeout bounds each exchange with the relay and the wait for a relayed peer's handshake.
// Default 20s, 5s above the relay's default ConnectTimeout; from 1s to 60s.
ControlTimeout time.Duration
// MaxPending caps the incoming sessions not yet returned by Accept. Default 16, from 1 to 256.
MaxPending int
// SendQueue is how many packets a session queues before it drops the oldest. Default 512, from 8 to 1024.
SendQueue int
// AllowFunc says whether an initiator may reach this reservation. Nil allows every key; a panic refuses.
AllowFunc func(initiator ed25519.PublicKey) bool
}Config sets the limits of a peer that reserves on a relay or dials through one. A zero field takes its default.
type Conn
type Conn struct {
// contains filtered or unexported fields
}Conn is a connection to a peer through a relay; the peer proved RemotePublicKey end to end, and the relay only sees ciphertext.
func Dial
func Dial(ctx context.Context, relayAddr string, relayKey ed25519.PublicKey, id *koloid.Identity, target ed25519.PublicKey, cfg *Config) (*Conn, error)Dial connects to target through the relay at relayAddr, whose key is relayKey, and returns once target has proved its key end to end. The relay must hold a reservation for target. Nothing is tried directly: the connection always goes through the relay.
func (Conn) AcceptStream
func (c *Conn) AcceptStream(ctx context.Context) (*kolotransport.Stream, error)AcceptStream waits for the next bidirectional stream opened by the peer.
func (Conn) AcceptUniStream
func (c *Conn) AcceptUniStream(ctx context.Context) (*kolotransport.ReceiveStream, error)AcceptUniStream waits for the next unidirectional stream opened by the peer.
func (Conn) Close
func (c *Conn) Close() errorClose closes the connection with code 0 and releases its resources.
func (Conn) CloseWithError
func (c *Conn) CloseWithError(code uint64, msg string) errorCloseWithError closes the connection, sending code and msg to the peer, as kolosecure.Conn.CloseWithError.
func (Conn) Context
func (c *Conn) Context() context.ContextContext is canceled when the connection ends, also when the relay ends the session; its context.Cause is a kolo-transport error.
func (Conn) OpenStream
func (c *Conn) OpenStream(ctx context.Context) (*kolotransport.Stream, error)OpenStream opens a bidirectional stream, as kolosecure.Conn.OpenStream.
func (Conn) OpenUniStream
func (c *Conn) OpenUniStream(ctx context.Context) (*kolotransport.SendStream, error)OpenUniStream opens a unidirectional stream, as kolosecure.Conn.OpenUniStream.
func (Conn) RelayAddr
func (c *Conn) RelayAddr() net.AddrRelayAddr returns the UDP address of the relay this connection goes through.
func (Conn) RelayPublicKey
func (c *Conn) RelayPublicKey() ed25519.PublicKeyRelayPublicKey returns a copy of the key of the relay this connection goes through.
func (Conn) RemotePublicKey
func (c *Conn) RemotePublicKey() ed25519.PublicKeyRemotePublicKey returns a copy of the peer's kolo-id public key, proved end to end.
func (Conn) Stats
func (c *Conn) Stats() kolotransport.ConnStatsStats returns the transport statistics of the end-to-end connection, which crosses the relay: its round trip time is the whole path. It is the zero value after the connection has ended.
type Reservation
type Reservation struct {
// contains filtered or unexported fields
}Reservation makes this peer reachable through one relay and receives the connections other peers make to it there.
func Reserve
func Reserve(ctx context.Context, relayAddr string, relayKey ed25519.PublicKey, id *koloid.Identity, cfg *Config) (*Reservation, error)Reserve asks the relay at relayAddr, whose key is relayKey, to make id reachable there until the relay ends the reservation or Close.
func (Reservation) Accept
func (r *Reservation) Accept(ctx context.Context) (*Conn, error)Accept waits for the next peer that connected through the relay and proved its key end to end. After the relay ends the reservation it returns an error wrapping ErrReservationEnded; connections already returned keep working.
func (Reservation) Close
func (r *Reservation) Close() errorClose ends the reservation and closes its connection to the relay, with every connection Accept returned. It is safe to call more than once.
type Server
type Server struct {
// contains filtered or unexported fields
}Server is a relay: peers reserve on it, and it joins other peers to them, copying bytes it cannot read.
func Listen
func Listen(ctx context.Context, addr string, id *koloid.Identity, cfg *ServerConfig) (*Server, error)Listen starts a relay on addr, such as "127.0.0.1:0", authenticated as id. Clients must know id's public key.
func (Server) Addr
func (s *Server) Addr() net.AddrAddr returns the relay's local UDP address.
func (Server) Close
func (s *Server) Close() errorClose ends every session and reservation, closes every connection and waits for them. It is safe to call more than once.
type ServerConfig
type ServerConfig struct {
// Secure configures the relay's listener. Nil means the relay defaults in the README; a non-nil value is used as given.
Secure *kolosecure.Config
// MaxReservations caps the reserved keys. Default 64, from 1 to 100000.
MaxReservations int
// MaxSessions caps the sessions being set up or open. Default 16, from 1 to 10000.
MaxSessions int
// MaxSessionsPerPeer caps the sessions one key has started. Default 4 or MaxSessions if lower, at most MaxSessions.
MaxSessionsPerPeer int
// MaxSessionsPerTarget caps the sessions to one reserved key; beyond it the relay answers Unavailable.
// Default 8 or MaxSessions if lower, at most MaxSessions.
MaxSessionsPerTarget int
// ReservationLifetime ends a reservation; the peer must reserve again. Default 1h, from 1s to 24h.
ReservationLifetime time.Duration
// MaxSessionDuration ends a session. Default 1h, from 1s to 24h.
MaxSessionDuration time.Duration
// MaxSessionBytes ends a session once this many bytes went one way. Default 1 GiB, from 64 KiB to 1 TiB.
MaxSessionBytes int64
// SessionIdleTimeout ends a session with no byte either way. Default 60s, from 1s to 10m.
// Keep-alive is always on, so it ends a session between live peers only if it is not above their KeepAlivePeriod (5s by default).
SessionIdleTimeout time.Duration
// ConnectTimeout bounds how long the target may take to accept a session. Default 15s, from 1s to 60s.
// Default clients wait 20s for the answer, so above about 15s they need a longer ControlTimeout.
ConnectTimeout time.Duration
// ControlTimeout bounds how long a client may take to send its first message. Default 15s, from 1s to 60s.
ControlTimeout time.Duration
// RateBytes is the read rate per client connection, in bytes per second. Default 1 MiB, from 16 KiB to 1 GiB.
RateBytes int64
// RateBurst is the most a client connection may send at once above RateBytes. Default 256 KiB, from 16 KiB to 64 MiB.
RateBurst int64
// FlushInterval is the shortest time between two writes of less than a full buffer in one direction of a session.
// Default 1ms, from 100µs to 100ms.
FlushInterval time.Duration
// AllowReserve says whether a key may reserve. Nil allows every key, which Listen reports with a warning; a panic refuses.
AllowReserve func(key ed25519.PublicKey) bool
// AllowConnect says whether from may reach to. Nil allows every pair; a panic refuses.
// It must be fast: Server.Close waits for calls in progress.
AllowConnect func(from, to ed25519.PublicKey) bool
// Logger receives the warning Listen logs when AllowReserve is nil. Nil means slog.Default().
Logger *slog.Logger
}ServerConfig sets the limits of a relay. A zero field takes its default.
Bom saber
Conn.Stats retorna as estatísticas da kolo-transport da conexão de ponta a ponta que atravessa o relay: o tempo de ida e volta do caminho todo, as perdas, a janela de congestionamento e o controlador. É o valor zero depois que a conexão termina.
Limites
Os padrões servem para um teste em um host com cerca de 8 GiB e deixam o relay aberto a qualquer chave. Antes de expor um relay, defina AllowReserve e dimensione MaxConns, as janelas de recepção e MaxSessions para o seu host; a página de limites do repositório tem a receita para um host de 300 MiB.
- Só IPv4. Um endereço IPv6 passado para
Listen,ReserveouDial, incluindo o v4-mapped, éErrInvalidArgumentantes de qualquer envio. UmNetworkda kolo-transport diferente de"udp4"emConfigouServerConfigéErrInvalidConfig. ServerConfig(um campo zerado assume o padrão; fora da faixa éErrInvalidConfig):MaxReservations: 64, de 1 a 100000. Acima disso,ReserverecebeErrLimit.MaxSessions(sendo montadas ou abertas): 16, de 1 a 10000. Acima disso,ErrLimit.MaxSessionsPerPeer(iniciadas por uma mesma chave): 4, ouMaxSessions, se for menor. Acima disso,ErrLimit.MaxSessionsPerTarget(para uma mesma chave reservada): 8, ouMaxSessions, se for menor. Acima disso,ErrUnavailable.ReservationLifetime: 1h, de 1s a 24h. Depois disso a reserva termina e o peer precisa reservar de novo; as sessões que ela já carrega continuam.MaxSessionDuration: 1h, de 1s a 24h.MaxSessionBytes(em cada sentido): 1 GiB, de 64 KiB a 1 TiB. Passam exatamente essa quantidade de bytes, e então a sessão inteira termina.SessionIdleTimeout(nenhum byte em nenhum sentido): 60s, de 1s a 10m. O keep-alive está sempre ligado (5s por padrão), então uma sessão entre dois peers ativos não chega a um timeout acima doKeepAlivePerioddeles.ConnectTimeout(o alvo aceita uma sessão): 15s, de 1s a 60s. Acima de cerca de 15s, os clientes precisam de umControlTimeoutmaior que o padrão de 20s.ControlTimeout(primeira mensagem do cliente): 15s, de 1s a 60s.RateBytes(lidos de cada conexão de cliente, por segundo): 1 MiB, de 16 KiB a 1 GiB.RateBurst: 256 KiB, de 16 KiB a 64 MiB.FlushInterval: 1ms, de 100µs a 100ms.Logger: nil quer dizerslog.Default(). Recebe o único aviso de um relay aberto.
- Com
Securenil, o relay escuta comMaxConns128,MaxConnsPerIP4,MaxDialed1,MaxIncomingStreams2,MaxStreamReceiveWindow64 KiB eMaxConnReceiveWindow256 KiB. UmSecurenão nil é usado do jeito que vier, sem esses valores. - Cada sessão precisa da sua própria conexão de cliente, então um mesmo endereço de origem mantém no máximo
MaxConnsPerIPsessões. Config(paraReserveeDial; um campo zerado assume o padrão; fora da faixa éErrInvalidConfig):Relay: nil quer dizer os padrões da kolo-secure com umKeepAlivePeriodde 5s.ControlTimeout(cada troca com o relay): 20s, de 1s a 60s. Um relay que não responde a tempo gera um erro que envolveos.ErrDeadlineExceeded.MaxPending(sessões ainda não retornadas porAccept): 16, de 1 a 256.SendQueue(pacotes na fila por sessão): 512, de 8 a 1024. Quando a fila está cheia, o pacote mais antigo é descartado, como no UDP.
- Um
HandshakeTimeoutzerado emPeervale 10s. Um alvo espera no máximoControlTimeoutmais os dois timeouts de handshake (40s com os padrões) por um peer anunciado e depois libera a vaga. - Tamanhos fixos: uma mensagem de controle tem no máximo 64 bytes, um frame de pacote no máximo 1452 bytes, e o buffer de cópia do relay tem 64 KiB por sentido. Os pacotes internos ficam em 1280 bytes, porque a descoberta de MTU do caminho fica desligada no caminho via relay.
Reservation.CloseeConn.Closepodem levar cerca de 2s: o último pacote tem no máximo 1s para sair, e depois o outro lado tem no máximo 1s para encerrar o seu stream. Quando o relay encerra uma sessão, oConnde cada lado fecha em cerca de 1s.Server.Closedá a cada iniciador até 1s para fechar a sua conexão e depois encerra todas as reservas.- Vazão com os padrões: a janela de stream de 64 KiB limita uma sessão a 64 KiB por ida e volta em cada sentido,
RateByteslimita cada conexão de cliente a 1 MiB/s, e a saída do relay é no máximo 2 ×MaxSessions×RateBytes, 32 MiB/s. Só existem testes em loopback. - Memória: o pior caso de heap ativo do relay com os padrões é de cerca de 7,3 GiB (7506,8 MiB). Defina
GOMEMLIMITum pouco acima do limite da sua configuração, por exemploGOMEMLIMIT=8500MiBcom os padrões. Em um host pequeno, reduzaMaxSessionse os limites do listener por meio deSecure, e refaça a conta com a fórmula do README. Uma conexão cuja ponta escolheuCongestionControl: "bbr"acrescenta até 5,5 MiB de amostras do BBR, um termo que a fórmula omite; o listener do próprio relay usa Reno, a não ser que oSecuredele diga outra coisa.
Segurança
- O relay não é uma ponta TLS da conexão entre os peers. Ele não consegue ler nem alterar os pacotes internos, e não consegue se passar por nenhum dos dois peers. Ele sempre pode descartar, atrasar ou encerrar esses pacotes.
- O relay fica sabendo as duas chaves de cada sessão, os endereços dos dois clientes, quais chaves têm reservas, quando as sessões começam e terminam, e os tamanhos e o ritmo dos pacotes internos.
- O relay nunca abre conexão com ninguém e só une dois dos seus próprios clientes autenticados, em direção a uma chave que fez reserva, então ele não é um proxy aberto.
- Só quem tem uma chave pode reservá-la. Uma reserva mais nova da mesma chave substitui a mais antiga.
Dialsó retorna depois quetargetprovou a sua chave de ponta a ponta. Um alvo que recebe um peer cuja chave provada não é a que o relay anunciou fecha essa conexão com o código 1 e nunca a retorna.- Uma chave de cliente ou de destino que não tem 32 bytes encerra a conexão com o código 1.
- Um pânico em
AllowReserve,AllowConnectouAllowFuncrecusa.AllowConnectprecisa ser rápido:Server.Closeespera as chamadas em andamento. ErrUnavailableé, de propósito, uma única resposta para várias causas. Uma chave ainda consegue descobrir a sua própria decisão deAllowConnecte se um alvo está reservado, mas nada sobre outras chaves.- Nenhum erro carrega algo que o peer ou o relay enviou, a não ser códigos numéricos.
Limites conhecidos
Acceptnão reserva de novo depois que o relay encerra uma reserva. ChameClosedepois queAcceptfalhar e entãoReservede novo.Connnão temRemoteAddr: o único endereço no caminho é o do relay (RelayAddr).- Cada pacote é criptografado duas vezes e passa por dois controles de fluxo (até o relay e de ponta a ponta), e os dois limitam a vazão. A vazão em redes reais não foi medida.
- O relay é experimental. A API pode mudar antes da v1.0.0.
Erros
| Erro | Mensagem |
|---|---|
ErrClosed | kolorelay: closed |
ErrInvalidArgument | kolorelay: invalid argument |
ErrInvalidConfig | kolorelay: invalid config |
ErrLimit | kolorelay: relay limit reached |
ErrNotAllowed | kolorelay: not allowed by the relay |
ErrProtocol | kolorelay: invalid message |
ErrReservationEnded | kolorelay: reservation ended |
ErrUnavailable | kolorelay: target unavailable through the relay |
ErrUnsupportedVersion | kolorelay: unsupported protocol version |
Teste os erros com errors.Is. O erro de Accept depois que o relay encerra uma reserva envolve tanto ErrReservationEnded quanto o erro da kolo-transport com o código do relay (2 validade esgotada, 3 substituída, 4 relay fechando). Os erros da kolo-secure e da kolo-transport passam adiante, por exemplo kolosecure.ErrUnexpectedPeer quando o relay não tem relayKey.
Referências
- RFC 8656, TURN: Relay Extensions to STUN (Proposed Standard, February 2020).
- Usa: as alocações, suas durações e as cotas.
- Não implementa: o formato de mensagens do TURN e do STUN.
- RFC 8445, ICE: A Protocol for NAT Traversal (Proposed Standard, July 2018).
- Usa: o caminho por relay como último recurso.
- Não implementa: a coleta de candidatos e as verificações de conectividade.
- RFC 8827, WebRTC Security Architecture (Proposed Standard, January 2021).
- Usa: o modelo de segurança do WebRTC para relays.
- WebRTC: Real-Time Communication in Browsers (W3C Recommendation, 13 March 2025).
- Usa: a ideia do
iceTransportPolicy: a aplicação decide se um relay é usado.
- Usa: a ideia do
- RFC 9000, QUIC: A UDP-Based Multiplexed and Secure Transport (Proposed Standard, May 2021).
- Usa: o QUIC, por meio da kolo-transport.