kolo-transport abre conexiones de QUIC versión 1 (RFC 9000) sobre UDP, protegidas con TLS 1.3 (RFC 9001), con la recuperación de pérdidas y el control de congestión Reno de RFC 9002 y un controlador BBR opcional según Cardwell et al. Da a cada peer streams bidireccionales y unidireccionales, con límites estrictos de datos sin leer, de streams y de conexiones. La conexión va cifrada, pero el peer no se autentica: kolo-secure añade la identidad por encima, con claves de kolo-id.
Instalación
go get github.com/ciranda-dev/kolo-transportCompila sin cgo.
Inicio rápido
Un listener y un dialer en un mismo programa sobre 127.0.0.1. El dialer abre un stream y el listener le devuelve lo que recibe.
package main
import (
"context"
"fmt"
"io"
"log"
"time"
kolotransport "github.com/ciranda-dev/kolo-transport"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
l, err := kolotransport.Listen(ctx, "127.0.0.1:0", nil)
if err != nil {
log.Fatal(err)
}
defer l.Close()
go func() {
c, err := l.Accept(ctx)
if err != nil {
return
}
s, err := c.AcceptStream(ctx)
if err != nil {
return
}
io.Copy(s, s)
s.Close()
}()
c, err := kolotransport.Dial(ctx, l.Addr().String(), nil)
if err != nil {
log.Fatal(err)
}
defer c.Close()
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)
}Imprime hello kolo. s.Close() solo cierra el lado de envío, así que el
dialer todavía puede leer la respuesta.
Referencia de la API
La referencia de la API se genera a partir del código Go y está en inglés.
Package kolotransport carries multiplexed streams over one QUIC (RFC 9000) connection between two Kolo peers.
It does not authenticate the peer. Each Listener presents an ephemeral self-signed certificate and the dialer accepts any such certificate, so TLS 1.3 gives confidentiality and integrity against passive observers but no identity, and an active man in the middle is not detected. Identity must come from a higher layer, for example kolo-id signatures over ExportKey.
Experimental: the API may change before v1.0.0.
Constantes
const ALPN = "kolo/0"ALPN is the TLS application protocol both ends must offer.
const DefaultMaxConnReceiveWindow = 512 << 10DefaultMaxConnReceiveWindow is the default MaxConnReceiveWindow: 512 KiB.
const DefaultMaxGrownConnReceiveWindow = 8 << 20DefaultMaxGrownConnReceiveWindow is the default MaxGrownConnReceiveWindow: 8 MiB.
const DefaultMaxGrownMemory = 64 << 20DefaultMaxGrownMemory is the default MaxGrownMemory: 64 MiB.
const DefaultMaxGrownStreamReceiveWindow = 4 << 20DefaultMaxGrownStreamReceiveWindow is the default MaxGrownStreamReceiveWindow: 4 MiB.
const DefaultMaxMemory = 1 << 30DefaultMaxMemory is the default MaxMemory: 1 GiB of receive window.
const DefaultMaxStreamReceiveWindow = 256 << 10DefaultMaxStreamReceiveWindow is the default MaxStreamReceiveWindow: 256 KiB.
const MaxCode uint64 = 1<<62 - 1MaxCode is the largest error code QUIC can carry.
const MaxPacketSize = 1200MaxPacketSize is the largest non-QUIC datagram WritePacket sends and ReadPacket returns.
Variables
var (
// ErrInvalidConfig means a Config field is out of range.
ErrInvalidConfig = errors.New("kolotransport: invalid config")
// ErrInvalidArgument means a bad code, close message, ExportKey label, PacketConn, listen or dial address, packet or destination (see the README).
ErrInvalidArgument = errors.New("kolotransport: invalid argument")
// ErrClosed means this side closed the listener, connection or stream.
ErrClosed = errors.New("kolotransport: closed")
// ErrPeerClosed means the peer closed the connection or no longer has state for it.
ErrPeerClosed = errors.New("kolotransport: peer closed the connection")
// ErrRefused means the peer refused the connection, for example because its listener is full.
ErrRefused = errors.New("kolotransport: connection refused")
// ErrHandshake means the TLS or QUIC handshake failed.
ErrHandshake = errors.New("kolotransport: handshake failed")
// ErrTimeout means the handshake or idle timeout expired.
ErrTimeout = errors.New("kolotransport: timeout")
// ErrTransport means a QUIC transport error or another failure of the connection.
ErrTransport = errors.New("kolotransport: transport error")
// ErrStreamReset means the peer reset the stream or asked this side to stop sending.
ErrStreamReset = errors.New("kolotransport: stream reset by peer")
// ErrMaxDialed means Listener.Dial already has MaxDialed connections open.
ErrMaxDialed = errors.New("kolotransport: too many dialed connections")
// ErrStreamCanceled means this side canceled the stream.
ErrStreamCanceled = errors.New("kolotransport: stream canceled")
)Tipos
type Config
type Config struct {
// MaxConns caps the connections of a Listener, handshaking or open. Listener only. Default 100, from 1 to 10000.
MaxConns int
// MaxConnsPerIP caps them per source address, the one a connection started from. Listener only. Default 4 (or MaxConns if lower), at most MaxConns.
MaxConnsPerIP int
// MaxDialed caps the connections Listener.Dial has open, which MaxConns and MaxConnsPerIP do not count. Listener only. Default 32, from 1 to 10000.
MaxDialed int
// MaxIncomingStreams caps the concurrent streams the peer may open, bidirectional and unidirectional each. Default 16, from 1 to 1000.
MaxIncomingStreams int
// HandshakeTimeout bounds the whole handshake and the life of a Retry token. Default 10s, from 1s to 60s.
HandshakeTimeout time.Duration
// IdleTimeout closes a connection with no network activity. Default 30s, from 1s to 10m.
IdleTimeout time.Duration
// KeepAlivePeriod sends a PING after this long without receiving, so connections stay open, also those never accepted.
// Default 5s (or IdleTimeout/2 if lower), from 500ms to below IdleTimeout.
KeepAlivePeriod time.Duration
// MaxMemory must cover (MaxConns + MaxDialed) times MaxConnReceiveWindow (unread data, not heap), in bytes; the default leaves headroom and does not bound heap (see the README). Listener only. Default 1 GiB, from 64 MiB to 64 GiB.
MaxMemory int64
// AcceptFunc filters attempts by the source IP a connection starts from, never port or identity; false or a panic refuses.
// Listener only. Nil allows all.
AcceptFunc func(remote netip.AddrPort) bool
// MaxStreamReceiveWindow caps the unread data buffered per stream, in bytes, on Listen and Dial. Advanced. Default 256 KiB (or MaxConnReceiveWindow if lower), from 64 KiB to 16 MiB.
MaxStreamReceiveWindow int64
// MaxConnReceiveWindow caps the unread data buffered per connection, in bytes; a node that dials N peers can hold N times it. Advanced. Default 512 KiB, from 64 KiB to 64 MiB, at least MaxStreamReceiveWindow.
MaxConnReceiveWindow int64
// WindowGrowth lets Conn.AllowWindowGrowth raise the receive windows of a connection the application trusts, up to the Grown values below; every other connection keeps its initial windows. Default false: no window ever grows.
WindowGrowth bool
// MaxGrownStreamReceiveWindow is the largest stream window a trusted connection can reach, in bytes. WindowGrowth only. Default 4 MiB (or MaxStreamReceiveWindow if higher), from MaxStreamReceiveWindow to 16 MiB.
MaxGrownStreamReceiveWindow int64
// MaxGrownConnReceiveWindow is the largest connection window a trusted connection can reach, in bytes. WindowGrowth only. Default 8 MiB (or MaxConnReceiveWindow if higher), from MaxConnReceiveWindow and MaxGrownStreamReceiveWindow to 64 MiB.
MaxGrownConnReceiveWindow int64
// MaxGrownMemory is the connection window growth all trusted connections of a Listener share, in bytes (a dialed Conn has its own); growth stops when it is used up and returns when a connection ends. WindowGrowth only. Default 64 MiB, from 1 MiB to 64 GiB.
MaxGrownMemory int64
// Network selects the UDP network of the socket Listen opens. Listener only. Default "udp4", the only accepted value: IPv6 is refused.
Network string
// CongestionControl picks the controller that paces what this end sends: "reno" (the default), "cubic" or "bbr". "bbr" keeps a link full where random loss makes the others crawl, but takes the bandwidth of other flows and holds a standing queue (see the guide).
CongestionControl string
}Config sets the limits of a Listener or a dialed Conn. A zero field takes its default. Config is not comparable.
type Conn
type Conn struct {
// contains filtered or unexported fields
}Conn is a connection to one peer, carrying multiplexed streams.
func Dial
func Dial(ctx context.Context, addr string, cfg *Config) (*Conn, error)Dial connects to the listener at an IPv4 addr from a new udp4 socket (on loopback for a loopback addr), released when the connection ends.
func (Conn) AcceptStream
func (c *Conn) AcceptStream(ctx context.Context) (*Stream, error)AcceptStream waits for the next bidirectional stream opened by the peer.
func (Conn) AcceptUniStream
func (c *Conn) AcceptUniStream(ctx context.Context) (*ReceiveStream, error)AcceptUniStream waits for the next unidirectional stream opened by the peer.
func (Conn) AllowWindowGrowth
func (c *Conn) AllowWindowGrowth() boolAllowWindowGrowth marks the connection as trusted, so its receive windows can grow up to the MaxGrown values while MaxGrownMemory lasts. Call it once the peer is one the application authorized, such as after a handshake that proved its identity; a connection never marked keeps its initial windows. It reports whether growth is on for the connection: false when Config.WindowGrowth is off or the connection has ended. It is safe to call more than once.
func (Conn) Close
func (c *Conn) Close() errorClose closes the connection with code 0.
func (Conn) CloseWithError
func (c *Conn) CloseWithError(code uint64, msg string) errorCloseWithError closes the connection, sending code and msg to the peer. An invalid code or msg (see ErrInvalidArgument) still closes the connection, with code 0 and no message.
func (Conn) Context
func (c *Conn) Context() context.ContextContext is canceled when the connection ends; its context.Cause is the error the connection's calls return.
func (Conn) ExportKey
func (c *Conn) ExportKey(label string) ([32]byte, error)ExportKey derives 32 bytes from the TLS session (RFC 9846 exporter); both ends get the same bytes only without a man in the middle. Use a unique non-empty label such as "kolo-<lib>/<purpose>/v0", and sign label, role and key together, never the key alone.
func (Conn) LocalAddr
func (c *Conn) LocalAddr() net.AddrLocalAddr returns the local UDP address.
func (Conn) OpenStream
func (c *Conn) OpenStream(ctx context.Context) (*Stream, error)OpenStream opens a bidirectional stream, waiting while the peer's stream limit is reached. The peer sees the stream only once data or a Close is sent on it.
func (Conn) OpenUniStream
func (c *Conn) OpenUniStream(ctx context.Context) (*SendStream, error)OpenUniStream opens a unidirectional stream, waiting while the peer's stream limit is reached.
func (Conn) RemoteAddr
func (c *Conn) RemoteAddr() net.AddrRemoteAddr returns the peer's UDP address.
func (Conn) Stats
func (c *Conn) Stats() ConnStatsStats returns a snapshot of the connection's statistics. It is cheap, does not wait on a network read and is safe from any goroutine. The fields are read one by one, not atomically, so a moving value can disagree with its neighbours. After the connection has ended it returns the zero ConnStats.
type ConnStats
type ConnStats struct {
// SmoothedRTT is the exponentially weighted moving average of the round-trip time samples (RFC 9002, section 5.3).
// It is 0 until the current path has a sample, which a new connection has once its handshake completes.
SmoothedRTT time.Duration
// MinRTT is the lowest round-trip time seen on the current path, which is close to the propagation delay.
MinRTT time.Duration
// LatestRTT is the last round-trip time sample on the current path.
LatestRTT time.Duration
// RTTVariation is the mean deviation of the samples from SmoothedRTT (the RTTVAR of RFC 9002), a measure of jitter.
RTTVariation time.Duration
// BytesSent counts every byte sent, including packets later declared lost and retransmitted data.
BytesSent uint64
// BytesReceived counts every byte received, including duplicates and packets that could not be processed.
BytesReceived uint64
// PacketsSent counts every packet sent, including packets later declared lost.
PacketsSent uint64
// PacketsReceived counts every packet received, including duplicates and packets that could not be processed.
PacketsReceived uint64
// PacketsLost counts the packets of this end the peer did not acknowledge in time, and each congestion signal of ECN
// (a peer that marks packets can raise it without any loss, as the built-in sender counts it too). A packet that arrives
// late after it was declared lost still counts, so PacketsLost over PacketsSent is an upper bound of the loss rate.
PacketsLost uint64
// BytesLost is the size in bytes of the packets counted in PacketsLost.
BytesLost uint64
// CongestionWindow is how many bytes this end may have in flight, as set by the congestion controller.
// A transfer is limited by the congestion window when BytesInFlight stays near it.
CongestionWindow uint64
// BytesInFlight is how many bytes of packets this end sent that the peer has not yet acknowledged and this end has not declared lost.
BytesInFlight uint64
// CongestionController is the name of the controller sending on this connection: "reno", "cubic" or "bbr".
CongestionController string
// BandwidthEstimate is the bottleneck bandwidth the controller measured, in bytes per second: the highest delivery
// rate of the last ten round trips. Only "bbr" measures it; it is 0 for "reno" and "cubic" and before the first sample.
BandwidthEstimate uint64
// MaxDatagramSize is the largest UDP payload in bytes this end sends on the current path. It starts at the
// initial size and grows as path MTU discovery succeeds.
MaxDatagramSize uint64
// PathChanges counts how often the connection moved to a new network path, for example when the peer's NAT gave it a new port.
// The RTT fields, the congestion window and BandwidthEstimate start over on a new path.
PathChanges uint64
}ConnStats is a snapshot of what a connection measured about its network path and its own traffic. Byte counts are QUIC packet bytes: they include QUIC headers and retransmissions, not UDP or IP headers.
type Error
type Error struct {
Err error
Code uint64
}Error is a connection or stream error with its numeric code; Unwrap returns one of the sentinels.
func (Error) Error
func (e *Error) Error() stringError returns the sentinel text and the code.
func (Error) Unwrap
func (e *Error) Unwrap() errorUnwrap returns the sentinel.
type Listener
type Listener struct {
// contains filtered or unexported fields
}Listener accepts connections on one UDP socket and can dial from it.
func Listen
func Listen(ctx context.Context, addr string, cfg *Config) (*Listener, error)Listen opens a UDP socket on addr, such as "127.0.0.1:0", and accepts connections on it.
func ListenConn
func ListenConn(ctx context.Context, pc net.PacketConn, cfg *Config) (*Listener, error)ListenConn is Listen on pc, which the Listener owns and closes, also when ListenConn fails (see the README). quic-go may set the socket's buffer sizes and DF bit.
func (Listener) Accept
func (l *Listener) Accept(ctx context.Context) (*Conn, error)Accept waits for the next connection whose handshake has completed. Up to 32 that are never accepted stay open until Close.
func (Listener) Addr
func (l *Listener) Addr() net.AddrAddr returns the local address of the listener.
func (Listener) Close
func (l *Listener) Close() errorClose refuses new connections, closes every connection of the listener with code 0, then the socket. It is safe to call more than once.
func (Listener) Dial
func (l *Listener) Dial(ctx context.Context, addr netip.AddrPort) (*Conn, error)Dial connects to addr from the listener's socket, with the listener's Config; MaxDialed bounds these connections.
func (Listener) ReadPacket
func (l *Listener) ReadPacket(ctx context.Context, b []byte) (int, netip.AddrPort, error)ReadPacket waits for the next non-QUIC datagram of at most MaxPacketSize bytes; the sender may be spoofed (see the README). A b shorter than the datagram gets its first len(b) bytes and the rest is dropped without an error; the count is the bytes copied.
func (Listener) WritePacket
func (l *Listener) WritePacket(b []byte, to netip.AddrPort) errorWritePacket sends b as one non-QUIC datagram from the listener's socket, blocking as long as its WriteTo does; b[0]&0xC0 must be 0.
type ReceiveStream
type ReceiveStream struct {
// contains filtered or unexported fields
}ReceiveStream is the receiving end of a unidirectional stream.
func (ReceiveStream) CancelRead
func (s *ReceiveStream) CancelRead(code uint64) errorCancelRead asks the peer to stop sending, with code (0 and ErrInvalidArgument if above MaxCode).
func (ReceiveStream) Read
func (s *ReceiveStream) Read(p []byte) (int, error)Read reads data from the peer; it returns io.EOF after the peer closed the stream.
func (ReceiveStream) SetReadDeadline
func (s *ReceiveStream) SetReadDeadline(t time.Time) errorSetReadDeadline sets the read deadline; an expired deadline returns os.ErrDeadlineExceeded.
type SendStream
type SendStream struct {
// contains filtered or unexported fields
}SendStream is the sending end of a unidirectional stream.
func (SendStream) CancelWrite
func (s *SendStream) CancelWrite(code uint64) errorCancelWrite abandons the stream with code (0 and ErrInvalidArgument if above MaxCode).
func (SendStream) Close
func (s *SendStream) Close() errorClose ends the stream.
func (SendStream) SetWriteDeadline
func (s *SendStream) SetWriteDeadline(t time.Time) errorSetWriteDeadline sets the write deadline; an expired deadline returns os.ErrDeadlineExceeded.
func (SendStream) Write
func (s *SendStream) Write(p []byte) (int, error)Write writes data to the peer, blocking while flow control is exhausted.
type Stream
type Stream struct {
// contains filtered or unexported fields
}Stream is a bidirectional stream. Read and Write may be used from different goroutines.
func (Stream) CancelRead
func (s *Stream) CancelRead(code uint64) errorCancelRead asks the peer to stop sending, with code (0 and ErrInvalidArgument if above MaxCode).
func (Stream) CancelWrite
func (s *Stream) CancelWrite(code uint64) errorCancelWrite abandons the send side with code (0 and ErrInvalidArgument if above MaxCode).
func (Stream) Close
func (s *Stream) Close() errorClose ends the send side; the receive side stays open.
func (Stream) Read
func (s *Stream) Read(p []byte) (int, error)Read reads data from the peer; it returns io.EOF after the peer closed its send side.
func (Stream) SetDeadline
func (s *Stream) SetDeadline(t time.Time) errorSetDeadline sets the read and write deadlines; an expired deadline returns os.ErrDeadlineExceeded.
func (Stream) SetReadDeadline
func (s *Stream) SetReadDeadline(t time.Time) errorSetReadDeadline sets the read deadline.
func (Stream) SetWriteDeadline
func (s *Stream) SetWriteDeadline(t time.Time) errorSetWriteDeadline sets the write deadline.
func (Stream) Write
func (s *Stream) Write(p []byte) (int, error)Write writes data to the peer, blocking while flow control is exhausted.
Conviene saber
Límites
v0.1.x solo funciona con IPv4. Los sockets son udp4. Una dirección IPv6,
incluida la forma v4-mapped ::ffff:a.b.c.d, se rechaza con
ErrInvalidArgument, y un Network distinto de "udp4", con
ErrInvalidConfig. Un nombre de host sin dirección IPv4 no se resuelve.
Campos de Config (nil o cero significa el valor por defecto; fuera de rango
es ErrInvalidConfig):
MaxConns: 100 conexiones por listener, en handshake o abiertas, de 1 a 10000. Por encima, se rechazan los intentos nuevos y el dialer recibeErrRefused.MaxConnsPerIP: 4 por dirección de origen (oMaxConnssi es menor), de 1 aMaxConns. Por encima, se rechazan los intentos desde esa dirección.MaxDialed: 32 conexiones abiertas desdeListener.Dial, de 1 a 10000. Por encima,Listener.DialdevuelveErrMaxDialed. No cuentan paraMaxConnsni paraMaxConnsPerIP.MaxIncomingStreams: 16 streams simultáneos que el peer puede abrir por conexión, bidireccionales y unidireccionales por separado, de 1 a 1000. Por encima, elOpenStreamdel peer espera.HandshakeTimeout: 10s, de 1s a 60s. También es la vida de un token Retry, así que un peer cuyo tiempo de ida y vuelta pase de más o menos la mitad no puede conectarse.IdleTimeout: 30s, de 1s a 10m. El tiempo de inactividad de cada lado es min(su propioIdleTimeout, max(elIdleTimeoutdel peer, 5s)), así que por debajo de 5s los dos lados pueden agotar el tiempo en momentos distintos.KeepAlivePeriod: 5s (oIdleTimeout/2 si es menor), desde 500ms hasta justo por debajo deIdleTimeout. El keep-alive siempre está activo.MaxStreamReceiveWindow: 256 KiB de datos sin leer por stream, de 64 KiB a 16 MiB.MaxConnReceiveWindow: 512 KiB de datos sin leer por conexión, de 64 KiB a 64 MiB, y como mínimoMaxStreamReceiveWindow.MaxMemory: 1 GiB, de 64 MiB a 64 GiB.Listencomprueba (MaxConns+MaxDialed) ×MaxConnReceiveWindow≤MaxMemoryy, si no se cumple, devuelveErrInvalidConfig. Los valores por defecto necesitan 66 MiB. Comprueba los datos sin leer, no el heap.CongestionControl:"reno"(por defecto),"cubic"o"bbr". Cualquier otro valor esErrInvalidConfig. Mira "Control de congestión" más abajo.WindowGrowth: desactivado por defecto. Activado,Conn.AllowWindowGrowthdeja que las ventanas de recepción de una conexión crezcan hastaMaxGrownStreamReceiveWindow(4 MiB, deMaxStreamReceiveWindowa 16 MiB) yMaxGrownConnReceiveWindow(8 MiB, deMaxConnReceiveWindowa 64 MiB), dentro deMaxGrownMemory(64 MiB, de 1 MiB a 64 GiB, compartido por las conexiones de unListener). Las tres opcionesMaxGrownnecesitanWindowGrowth.
Valores fijos:
- Cola de aceptación: 32 conexiones con el handshake hecho que esperan a
Accept. Por encima, se rechazan las conexiones nuevas. Llama aAcceptincluso en un listener que solo uses para conectarte. - Datagramas que no son QUIC:
MaxPacketSizees de 1200 bytes.WritePacketrechaza conErrInvalidArgumentuno más grande, vacío o con aspecto de QUIC (b[0]&0xC0 != 0), yReadPacketdescarta uno más grande. La cola guarda 32 datagramas (unos 45 KiB) y descarta el resto, así que léelos enseguida. CloseWithError: el código es como máximoMaxCode(2^62-1) y el mensaje como máximo 256 bytes. Fuera de rango, la conexión se cierra igualmente, con código 0, y la llamada devuelveErrInvalidArgument.CancelReadyCancelWritetratan igual un código por encima deMaxCode.ExportKeydevuelve 32 bytes y necesita una etiqueta no vacía.- Los tokens NEW_TOKEN caducan a cualquier edad, incluso dentro de un mismo
tic del reloj o tras un retroceso del reloj de pared (
MaxTokenAgees la duración más pequeña), así que cada intento nuevo pasa por Retry. Listener.Closecierra al cabo de 1s unPacketConnque ignora los plazos de lectura.- Con
ListenConn, la conn debe transportar datagramas de al menos 1280 bytes; lo que pase de 1452 bytes se trunca.
MaxMemory no acota el heap. Según las mediciones del README, con frames de
1 byte cada byte sin leer cuesta unos 176 bytes de heap, y cada byte leído en
un stream que sigue abierto retiene unos 96. El peor caso por conexión es:
2 × MaxIncomingStreams × MaxStreamReceiveWindow × 96
+ MaxConnReceiveWindow × 176Con los valores por defecto son unos 856 MiB por conexión. Para acotar el
heap, baja MaxConns, MaxIncomingStreams o las ventanas, define
GOMEMLIMIT, lee los streams enseguida y ciérralos en los dos sentidos cuando
termines.
Transferencias más rápidas para peers de confianza
Un stream mueve como mucho ventana / tiempo de ida y vuelta: con la ventana por defecto de 256 KiB por stream, unos 21 Mbit/s a 100 ms. Las ventanas son pequeñas porque un peer hostil puede hacer que una aplicación retenga hasta 176 bytes de heap por cada byte sin leer, así que empiezan pequeñas en toda conexión y solo crecen en una que la aplicación ha marcado como de confianza, dentro de un presupuesto que comparten todas.
cfg := &kolotransport.Config{WindowGrowth: true}
l, err := kolotransport.Listen(ctx, "127.0.0.1:0", cfg)
// ...
conn, err := l.Accept(ctx)
// The application learns who the peer is, for example from a handshake that
// proved its key, and decides it is one it wants to serve fast:
if peerIsAuthorized(conn) {
conn.AllowWindowGrowth()
}- kolo-transport nunca llega a saber quién es un peer, así que no puede
decidirlo. La aplicación llama a
Conn.AllowWindowGrowthcuando su propia capa ha autenticado al peer y su política lo admite. Devuelve false cuandoWindowGrowthestá desactivado, que es el valor por defecto y no cambia nada, o cuando la conexión ha terminado. - El crecimiento es el autoajuste de la ventana de recepción que tiene la pila QUIC: una
ventana se duplica mientras la aplicación la lee más rápido que unos pocos
tiempos de ida y vuelta, hasta
MaxGrownStreamReceiveWindow(4 MiB, hasta 16 MiB) yMaxGrownConnReceiveWindow(8 MiB, hasta 64 MiB). Nunca se encoge. MaxGrownMemory(64 MiB, de 1 MiB a 64 GiB) es el crecimiento que pueden retener juntas todas las conexiones marcadas de unListener, las deListener.Dialincluidas. Un paso de crecimiento se rechaza cuando el presupuesto no alcanza, y el presupuesto vuelve cuando la conexión termina.Listentambién comprueba queMaxMemorycubra las ventanas iniciales más ese crecimiento.- Cuando actives el crecimiento en un socket público, mantén
MaxConnReceiveWindowigual aMaxStreamReceiveWindow: la pila QUIC no deja que la aplicación rechace el crecimiento de la ventana de un stream, solo el de la conexión, así que con valores iguales una conexión que nadie marcó se queda en su ventana inicial, como sin crecimiento.
Medido con 100 Mbit/s en cada sentido y un stream leído tan rápido como llega, una conexión marcada leyó a la velocidad del enlace, 12,24 MB/s, con 20 ms, 50 ms y 100 ms de ida y vuelta, frente a 10,10, 4,43 y 2,01 MB/s con las ventanas fijas.
Control de congestión
Config.CongestionControl elige el controlador que marca el ritmo de lo que
envía este extremo: "reno", el valor por defecto,
"cubic" o "bbr". Reno reduce a la mitad su ventana con cada paquete
perdido, así que en un camino que además pierde paquetes al azar, como puede
hacer un enlace móvil, un stream sobre 20 Mbit/s con un 1 por ciento de
pérdida y 120 ms de ida y vuelta lee a 1,4 a 1,8 Mbit/s. BBR estima en cambio
la velocidad del enlace y no frena por pérdidas aisladas.
cfg := &kolotransport.Config{CongestionControl: "bbr"}
conn, err := kolotransport.Dial(ctx, addr, cfg)- Cada extremo marca el ritmo de su propio envío, así que actívalo en el
extremo que envía los datos, o en los dos para una transferencia que va en
ambos sentidos. Se aplica a toda conexión que crea el
Config(Dial,Listener.Accept,Listener.Dial), y una conexión conserva su controlador cuando un NAT da un puerto nuevo a quien marca. Cualquier otro valor esErrInvalidConfig. - Medido sobre un enlace simulado de 20 Mbit/s en cada sentido, 60 ms de retardo
en cada sentido y un 1 por ciento de pérdida al azar en cada sentido, con
ventanas de 8 MiB: un stream lee a 1,83 Mbit/s con Reno y a 18,86 Mbit/s con
BBR.
"cubic"no ayuda en ese camino, porque retrocede con cada pérdida como Reno. Los caminos medidos solo tienen pérdida aleatoria independiente, no las ráfagas, los reordenamientos ni los limitadores de una red real. - BBR solo es tan rápido como la ventana de recepción: con las ventanas por
defecto un stream mueve como mucho ventana / tiempo de ida y vuelta, así que
úsalo junto con ventanas mayores o con
WindowGrowth. - Mantén las llamadas y el medio en directo en
"reno". BBR mantiene una cola fija en el cuello de botella (unos 100 ms, 150 ms con un router con bufferbloat en las mediciones) y quita ancho de banda a los flujos Reno que lo comparten: es para una transferencia que el usuario pidió y quiere rápida, no para tráfico de fondo. - Una conexión BBR guarda una muestra de 88 bytes por número de paquete entre
el paquete más antiguo que espera y el más nuevo que envió. El tramo tiene
un tope de 40000 números de paquete, así que un peer que nunca confirma no
puede hacerlo crecer: se descartan las muestras más antiguas, lo que solo
cuesta muestras de ancho de banda. El tope lo limita a 5,5 MiB por conexión
BBR.
"reno"y"cubic"no tienen esa estructura.
Estadísticas de la conexión
Conn.Stats() devuelve una instantánea ConnStats de lo que midió una
conexión. Es barata (unas pocas lecturas atómicas), nunca se bloquea por la
red, es segura desde cualquier goroutine y devuelve el valor cero una vez
terminada la conexión, así que léela antes de cerrar la conexión si quieres
las cifras finales. Cada campo se lee por separado, así que dos campos pueden
no coincidir en una muestra.
s := conn.Stats()
fmt.Printf("rtt %v (min %v) window %d in flight %d lost %d of %d packets via %s\n",
s.SmoothedRTT, s.MinRTT, s.CongestionWindow, s.BytesInFlight, s.PacketsLost, s.PacketsSent, s.CongestionController)SmoothedRTT,MinRTT,LatestRTTyRTTVariation: el tiempo de ida y vuelta del camino actual y su variación.BytesSent,BytesReceived,PacketsSentyPacketsReceived: paquetes QUIC durante toda la conexión, con retransmisiones y duplicados.PacketsLostyBytesLost: paquetes que envió este extremo y no se confirmaron a tiempo. Una señal de congestión ECN cuenta como un paquete perdido.CongestionWindowyBytesInFlight: lo que el controlador permite en vuelo y lo que está en vuelo ahora.CongestionController:"reno","cubic"o"bbr".BandwidthEstimate: el ancho de banda del cuello de botella que midió BBR, en bytes por segundo, 0 con los otros dos.MaxDatagramSize: la mayor carga UDP que envía este extremo en el camino actual, como mucho 1452 bytes.PathChanges: cuántas veces la conexión pasó a un camino nuevo; los campos de ida y vuelta, la ventana y la estimación empiezan de cero en un camino nuevo.
BytesInFlight cerca de CongestionWindow quiere decir que el controlador
limita la transferencia. Un SmoothedRTT muy por encima de MinRTT quiere
decir que hay una cola en el camino. BytesInFlight muy por debajo de
CongestionWindow con una transferencia lenta quiere decir que el límite no
es la red: la aplicación no escribe lo bastante rápido, o las ventanas de
recepción del peer están llenas.
Seguridad
AcceptFuncfiltra por IP de origen, no por identidad. Filtra por IP, nunca por puerto: un token Retry solo demuestra la IP y se puede reutilizar desde esa IP duranteHandshakeTimeout. Un peer puede mover su conexión a otra dirección después del handshake. SiAcceptFuncdevuelve false o entra en pánico, el intento se rechaza. Se ejecuta en la goroutine que atiende cada intento nuevo, así que mantenla rápida y sin bloqueos.- El remitente de
ReadPacketpuede estar suplantado. No marques hacia él ni le respondas con más bytes de los que envió hasta que demuestre que recibe en esa dirección.AcceptFuncno filtra los datagramas que no son QUIC, y estos no llevan ninguna protección. Dial,Listener.DialyWritePacketrechazan destinos con puerto 0, IPv6, no especificados, multicast,0.0.0.0/8y240.0.0.0/4. Se permiten las direcciones de loopback, privadas, link-local y de broadcast de subred, así que filtra cualquier dirección que te dé un peer antes de conectarte a ella o escribirle.- Los sockets que crean
ListenyDialtienenSO_BROADCASTdesactivado.ListenConnlo deja como está. - Los errores nunca incluyen texto del peer, solo un código numérico.
Límites conocidos
- Experimental. La API puede cambiar antes de v1.0.0.
- Los datagramas QUIC no se exponen en v0.1.x.
- kolo-transport lleva su propia copia de su implementación de QUIC, una
versión fijada más un parche: el gancho para un controlador de congestión y
los contadores que lee
Conn.Stats. Un script y un test comprueban que la copia es la versión fijada más ese parche y nada más. Una corrección de la implementación de QUIC solo llega a kolo-transport cuando se actualiza la copia. - El
Dialdel paquete no tiene tope de conexiones, así que un nodo que se conecta a N peers puede retener N ×MaxConnReceiveWindowde datos sin leer. - Sin acotar: el número de direcciones distintas (peers en más de
MaxConns/MaxConnsPerIPdirecciones todavía pueden llenarMaxConns), la CPU y el ancho de banda gastados por paquete, y el búfer de recepción UDP del sistema operativo. - Con
ListenConny una conn que no sea*net.UDPConn: sin ECN, sin GSO, sin lecturas por lotes y con el descubrimiento de MTU de ruta desactivado, así que los paquetes se quedan en 1280 bytes.
Errores
| Error | Mensaje |
|---|---|
ErrClosed | kolotransport: closed |
ErrHandshake | kolotransport: handshake failed |
ErrInvalidArgument | kolotransport: invalid argument |
ErrInvalidConfig | kolotransport: invalid config |
ErrMaxDialed | kolotransport: too many dialed connections |
ErrPeerClosed | kolotransport: peer closed the connection |
ErrRefused | kolotransport: connection refused |
ErrStreamCanceled | kolotransport: stream canceled |
ErrStreamReset | kolotransport: stream reset by peer |
ErrTimeout | kolotransport: timeout |
ErrTransport | kolotransport: transport error |
Comprueba los errores con errors.Is frente a los centinelas. Los errores con
código son un *Error; usa errors.As para leer Code, y su Unwrap
devuelve el centinela. context.Cause de Conn.Context da los mismos
errores.
Referencias
- RFC 9000, QUIC: A UDP-Based Multiplexed and Secure Transport (Proposed Standard, May 2021).
- Toma: QUIC versión 1, Retry en cada conexión nueva (8.1.2), primeros paquetes de 1200 bytes (14), semántica de streams y de códigos de error.
- No implementa: 0-RTT, reanudación de sesión, QUIC versión 2 (RFC 9369), datagramas no fiables (RFC 9221).
- RFC 9001, Using TLS to Secure QUIC (Proposed Standard, May 2021).
- Toma: el handshake TLS 1.3 dentro de QUIC, ALPN
kolo/0. - No implementa: tickets de sesión, early data.
- Toma: el handshake TLS 1.3 dentro de QUIC, ALPN
- RFC 9002, QUIC Loss Detection and Congestion Control (Proposed Standard, May 2021).
- Toma: la estimación del RTT (5.3), la detección de pérdidas y el controlador Reno (7), que es el predeterminado.
- No implementa: no se ha quitado nada.
- RFC 6582, The NewReno Modification to TCP's Fast Recovery Algorithm (Proposed Standard, April 2012).
- Toma: una reducción de ventana por episodio de pérdida.
- RFC 9438, CUBIC for Fast and Long-Distance Networks (Proposed Standard, August 2023).
- Toma: el controlador
"cubic", opcional. - No implementa: no se comprobó la conformidad con cada sección.
- Toma: el controlador
- Cardwell, Cheng, Gunn, Hassas Yeganeh and Jacobson, BBR: Congestion-Based Congestion Control, ACM Queue 14(5), 2016.
- Toma: el controlador
"bbr", opcional: estimaciones del ancho de banda del cuello de botella y del tiempo de ida y vuelta, y pacing. - No implementa: BBRv3 de draft-ietf-ccwg-bbr; la pérdida no es una señal.
- Toma: el controlador
- RFC 8899, Packetization Layer Path MTU Discovery for Datagram Transports (Proposed Standard, September 2020).
- Toma: el descubrimiento de la MTU de la ruta por encima de 1200 bytes.
- RFC 9846, The Transport Layer Security (TLS) Protocol Version 1.3, sección 7.5 (Proposed Standard, July 2026; obsoletes RFC 8446).
- Toma: el exportador en el que se apoya
Conn.ExportKey.
- Toma: el exportador en el que se apoya