quic

package module
v0.0.6-firefox.3 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 46 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

A QUIC implementation in pure Go

Documentation PkgGoDev Code Coverage Fuzzing Status

quic-go is an implementation of the QUIC protocol (RFC 9000, RFC 9001, RFC 9002) in Go. It has support for HTTP/3 (RFC 9114), including QPACK (RFC 9204) and HTTP Datagrams (RFC 9297).

In addition to these base RFCs, it also implements the following RFCs:

Support for WebTransport over HTTP/3 (draft-ietf-webtrans-http3) is implemented in webtransport-go.

Detailed documentation can be found on quic-go.net.

Projects using quic-go

Project Description Stars
AdGuardHome Free and open source, powerful network-wide ads & trackers blocking DNS server. GitHub Repo stars
algernon Small self-contained pure-Go web server with Lua, Markdown, HTTP/2, QUIC, Redis and PostgreSQL support GitHub Repo stars
caddy Fast, multi-platform web server with automatic HTTPS GitHub Repo stars
cloudflared A tunneling daemon that proxies traffic from the Cloudflare network to your origins GitHub Repo stars
frp A fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet GitHub Repo stars
go-libp2p libp2p implementation in Go, powering Kubo (IPFS) and Lotus (Filecoin), among others GitHub Repo stars
gost A simple security tunnel written in Go GitHub Repo stars
Hysteria A powerful, lightning fast and censorship resistant proxy GitHub Repo stars
Mercure An open, easy, fast, reliable and battery-efficient solution for real-time communications GitHub Repo stars
nodepass A secure, efficient TCP/UDP tunneling solution that delivers fast, reliable access across network restrictions using pre-established TCP/QUIC connections GitHub Repo stars
OONI Probe Next generation OONI Probe. Library and CLI tool. GitHub Repo stars
reverst Reverse Tunnels in Go over HTTP/3 and QUIC GitHub Repo stars
RoadRunner High-performance PHP application server, process manager written in Go and powered with plugins GitHub Repo stars
syncthing Open Source Continuous File Synchronization GitHub Repo stars
traefik The Cloud Native Application Proxy GitHub Repo stars
v2ray-core A platform for building proxies to bypass network restrictions GitHub Repo stars
YoMo Streaming Serverless Framework for Geo-distributed System GitHub Repo stars

If you'd like to see your project added to this list, please send us a PR.

Release Policy

quic-go always aims to support the latest two Go releases.

Contributing

We are always happy to welcome new contributors! We have a number of self-contained issues that are suitable for first-time contributors, they are tagged with help wanted. If you have any questions, please feel free to reach out by opening an issue or leaving a comment.

License

The code is licensed under the MIT license. The logo and brand assets are excluded from the MIT license. See assets/LICENSE.md for the full usage policy and details.

Documentation

Index

Constants

View Source
const (
	// NoError is the NO_ERROR transport error code.
	NoError = qerr.NoError
	// InternalError is the INTERNAL_ERROR transport error code.
	InternalError = qerr.InternalError
	// ConnectionRefused is the CONNECTION_REFUSED transport error code.
	ConnectionRefused = qerr.ConnectionRefused
	// FlowControlError is the FLOW_CONTROL_ERROR transport error code.
	FlowControlError = qerr.FlowControlError
	// StreamLimitError is the STREAM_LIMIT_ERROR transport error code.
	StreamLimitError = qerr.StreamLimitError
	// StreamStateError is the STREAM_STATE_ERROR transport error code.
	StreamStateError = qerr.StreamStateError
	// FinalSizeError is the FINAL_SIZE_ERROR transport error code.
	FinalSizeError = qerr.FinalSizeError
	// FrameEncodingError is the FRAME_ENCODING_ERROR transport error code.
	FrameEncodingError = qerr.FrameEncodingError
	// TransportParameterError is the TRANSPORT_PARAMETER_ERROR transport error code.
	TransportParameterError = qerr.TransportParameterError
	// ConnectionIDLimitError is the CONNECTION_ID_LIMIT_ERROR transport error code.
	ConnectionIDLimitError = qerr.ConnectionIDLimitError
	// ProtocolViolation is the PROTOCOL_VIOLATION transport error code.
	ProtocolViolation = qerr.ProtocolViolation
	// InvalidToken is the INVALID_TOKEN transport error code.
	InvalidToken = qerr.InvalidToken
	// ApplicationErrorErrorCode is the APPLICATION_ERROR transport error code.
	ApplicationErrorErrorCode = qerr.ApplicationErrorErrorCode
	// CryptoBufferExceeded is the CRYPTO_BUFFER_EXCEEDED transport error code.
	CryptoBufferExceeded = qerr.CryptoBufferExceeded
	// KeyUpdateError is the KEY_UPDATE_ERROR transport error code.
	KeyUpdateError = qerr.KeyUpdateError
	// AEADLimitReached is the AEAD_LIMIT_REACHED transport error code.
	AEADLimitReached = qerr.AEADLimitReached
	// NoViablePathError is the NO_VIABLE_PATH_ERROR transport error code.
	NoViablePathError = qerr.NoViablePathError
)
View Source
const (
	// Version1 is RFC 9000
	Version1 = protocol.Version1
	// Version2 is RFC 9369
	Version2 = protocol.Version2
)
View Source
const (
	DefaultUDPDatagramMinSize = 1200
)
View Source
const QTPGrease uint64 = 27

QTPGrease is the canonical ID QUIC fingerprinters use for every GREASE transport parameter (the reserved IDs are 31*N+27, of which 27 is the smallest). Pass it in QUICSpec.SuppressTransportParameters to drop GREASE parameters whatever ID they drew.

Variables

View Source
var (
	// ErrPathClosed is returned when trying to switch to a path that has been closed.
	ErrPathClosed = errors.New("path closed")
	// ErrPathNotValidated is returned when trying to use a path before path probing has completed.
	ErrPathNotValidated = errors.New("path not yet validated")
)
View Source
var (
	QUICFirefox_116  = QUICFirefox_116A                               // point to most-popular 8-byte DCID
	QUICFirefox_116A = QUICID{quicFirefox, "116", "31ea0e4ffd75b477"} // DCID.len = 8
	QUICFirefox_116B = QUICID{quicFirefox, "116", "d07d3c9152fbc5e0"} // DCID.len = 9
	QUICFirefox_116C = QUICID{quicFirefox, "116", "c74f87b2a9ccc006"} // DCID.len = 15

	QUICChrome_115      = QUICChrome_115_IPv4                               // IPv4 is still more popular
	QUICChrome_115_IPv4 = QUICID{quicChrome, "115", "beeb454235791d5c"}     // IPv4: UDP payload 20-byte longer than IPv6 due to padding
	QUICChrome_115_IPv6 = QUICID{quicChrome, "115_ip6", "beeb454235791d5c"} // IPv6

	QUICChrome_146      = QUICChrome_146_IPv4                               // IPv4 is still more popular
	QUICChrome_146_IPv4 = QUICID{quicChrome, "146", "a3c5e1f2b7d9048a"}     // IPv4: 2-datagram Initial (X25519MLKEM768 key share)
	QUICChrome_146_IPv6 = QUICID{quicChrome, "146_ip6", "c2d8f3a1e6b05794"} // IPv6

)
View Source
var Err0RTTRejected = errors.New("0-RTT rejected")

Err0RTTRejected is the returned from:

  • Open{Uni}Stream{Sync}
  • Accept{Uni}Stream
  • Stream.Read and Stream.Write

when the server rejects a 0-RTT connection attempt.

View Source
var ErrServerClosed = errServerClosed{}

ErrServerClosed is returned by the Listener or EarlyListener's Accept method after a call to Close.

View Source
var ErrTransportClosed = &errTransportClosed{}

ErrTransportClosed is returned by the Transport's Listen or Dial method after it was closed.

View Source
var QUICVersionContextKey = handshake.QUICVersionContextKey

QUICVersionContextKey can be used to find out the QUIC version of a TLS handshake from the context returned by tls.Config.ClientInfo.Context.

Functions

func ChromeRandomInitialRTT

func ChromeRandomInitialRTT() *tls.FakeQUICTransportParameter

ChromeRandomInitialRTT returns a FakeQUICTransportParameter for google_initial_rtt (0x3127). Chrome 146 includes this parameter with a random realistic RTT value in microseconds. The observed value in the reference pcap was 7740 µs; the range 1000–20000 µs covers typical network conditions. Value is encoded as a 2-byte QUIC varint (high bits = 0b01).

func IsGREASEQTPID

func IsGREASEQTPID(id uint64) bool

IsGREASEQTPID reports whether id is one of the reserved GREASE transport parameter IDs, i.e. 31*N+27 for some N >= 0. See RFC 9000 §18.1.

func ShuffleQUICTransportParameters

func ShuffleQUICTransportParameters(qtp *tls.QUICTransportParametersExtension) *tls.QUICTransportParametersExtension

ShuffleQUICTransportParameters permutes qtp's transport parameters uniformly at random, in place, returning qtp for chaining. Real Chrome randomizes the QTP wire order on every handshake, so a fixed order is a trivial discriminator signal.

Prefer QUICSpec.RandomizeTransportParameters over calling this directly: the spec field runs the same shuffle at connection setup, which re-randomizes every dial even when one spec value is reused, and it runs after SuppressTransportParameters so the shuffled set is exactly the wire set. Calling this from spec-construction code only randomizes as often as the spec is rebuilt.

Like SuppressQUICTransportParameters, this mutates qtp.TransportParameters and must run before uTLS marshals the extension, which caches its bytes on the first Len().

func ShuffleTLSExtensions

func ShuffleTLSExtensions(exts []tls.TLSExtension) []tls.TLSExtension

ShuffleTLSExtensions permutes exts uniformly at random, in place, and returns it. Every extension moves, including ones real clients keep pinned — GREASE, padding and pre_shared_key (which RFC 8446 requires last). For a Chrome-shaped ClientHello use utls.ShuffleChromeTLSExtensions instead, which holds those positions fixed.

func SuppressQUICTransportParameters

func SuppressQUICTransportParameters(qtp *tls.QUICTransportParametersExtension, suppress []uint64) *tls.QUICTransportParametersExtension

SuppressQUICTransportParameters removes from qtp every transport parameter whose ID is listed in suppress, returning qtp for chaining. A suppress entry of QTPGrease matches every GREASE ID, not just 27 — fingerprinters canonicalize them all to 27, so suppressing "27" has to mean "the GREASE parameter" to be useful.

This mutates qtp.TransportParameters in place and must therefore run before uTLS marshals the extension (it caches the result on the first Len() call). It is idempotent, so re-applying it to a reused spec is harmless.

func VariableLengthGREASEQTP

func VariableLengthGREASEQTP(maxLen int) *tls.GREASETransportParameter

VariableLengthGREASEQTP returns a GREASE transport parameter carrying a random number of random bytes, uniform over [0, maxLen). Chrome's GREASE parameter varies in length between handshakes, so a fixed length is itself a fingerprint.

Types

type ApplicationError

type ApplicationError = qerr.ApplicationError

ApplicationError is an application-defined error.

type ApplicationErrorCode

type ApplicationErrorCode = qerr.ApplicationErrorCode

ApplicationErrorCode is an QUIC application error code.

type ClientInfo

type ClientInfo struct {
	// RemoteAddr is the remote address on the Initial packet.
	// Unless AddrVerified is set, the address is not yet verified, and could be a spoofed IP address.
	RemoteAddr net.Addr
	// AddrVerified says if the remote address was verified using QUIC's Retry mechanism.
	// Note that the Retry mechanism costs one network roundtrip,
	// and is not performed unless Transport.MaxUnvalidatedHandshakes is surpassed.
	AddrVerified bool
}

ClientInfo contains information about an incoming connection attempt.

type ClientToken

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

A ClientToken is a token received by the client. It can be used to skip address validation on future connection attempts.

func NewClientToken

func NewClientToken(data []byte) *ClientToken

NewClientToken returns a ClientToken carrying the given bytes. It exists for TokenStore implementations outside this package that synthesize a token instead of replaying a server-issued one — e.g. to reproduce a target client's Initial token. ClientToken's fields are unexported, so without this such a store cannot produce a non-empty token at all. The bytes are copied. [UQUIC]

type Config

type Config struct {
	// GetConfigForClient is called for incoming connections.
	// If the error is not nil, the connection attempt is refused.
	GetConfigForClient func(info *ClientInfo) (*Config, error)
	// The QUIC versions that can be negotiated.
	// If not set, it uses all versions available.
	Versions []Version
	// HandshakeIdleTimeout is the idle timeout before completion of the handshake.
	// If we don't receive any packet from the peer within this time, the connection attempt is aborted.
	// Additionally, if the handshake doesn't complete in twice this time, the connection attempt is also aborted.
	// If this value is zero, the timeout is set to 5 seconds.
	HandshakeIdleTimeout time.Duration
	// MaxIdleTimeout is the maximum duration that may pass without any incoming network activity.
	// The actual value for the idle timeout is the minimum of this value and the peer's.
	// This value only applies after the handshake has completed.
	// If the timeout is exceeded, the connection is closed.
	// If this value is zero, the timeout is set to 30 seconds.
	MaxIdleTimeout time.Duration
	// The TokenStore stores tokens received from the server.
	// Tokens are used to skip address validation on future connection attempts.
	// The key used to store tokens is the ServerName from the tls.Config, if set
	// otherwise the token is associated with the server's IP address.
	TokenStore TokenStore
	// InitialStreamReceiveWindow is the initial size of the stream-level flow control window for receiving data.
	// If the application is consuming data quickly enough, the flow control auto-tuning algorithm
	// will increase the window up to MaxStreamReceiveWindow.
	// If this value is zero, it will default to 512 KB.
	// Values larger than the maximum varint (quicvarint.Max) will be clipped to that value.
	InitialStreamReceiveWindow uint64
	// MaxStreamReceiveWindow is the maximum stream-level flow control window for receiving data.
	// If this value is zero, it will default to 6 MB.
	// Values larger than the maximum varint (quicvarint.Max) will be clipped to that value.
	MaxStreamReceiveWindow uint64
	// InitialConnectionReceiveWindow is the initial size of the stream-level flow control window for receiving data.
	// If the application is consuming data quickly enough, the flow control auto-tuning algorithm
	// will increase the window up to MaxConnectionReceiveWindow.
	// If this value is zero, it will default to 512 KB.
	// Values larger than the maximum varint (quicvarint.Max) will be clipped to that value.
	InitialConnectionReceiveWindow uint64
	// MaxConnectionReceiveWindow is the connection-level flow control window for receiving data.
	// If this value is zero, it will default to 15 MB.
	// Values larger than the maximum varint (quicvarint.Max) will be clipped to that value.
	MaxConnectionReceiveWindow uint64
	// AllowConnectionWindowIncrease is called every time the connection flow controller attempts
	// to increase the connection flow control window.
	// If set, the caller can prevent an increase of the window. Typically, it would do so to
	// limit the memory usage.
	// To avoid deadlocks, it is not valid to call other functions on the connection or on streams
	// in this callback.
	AllowConnectionWindowIncrease func(conn *Conn, delta uint64) bool
	// MaxIncomingStreams is the maximum number of concurrent bidirectional streams that a peer is allowed to open.
	// If not set, it will default to 100.
	// If set to a negative value, it doesn't allow any bidirectional streams.
	// Values larger than 2^60 will be clipped to that value.
	MaxIncomingStreams int64
	// MaxIncomingUniStreams is the maximum number of concurrent unidirectional streams that a peer is allowed to open.
	// If not set, it will default to 100.
	// If set to a negative value, it doesn't allow any unidirectional streams.
	// Values larger than 2^60 will be clipped to that value.
	MaxIncomingUniStreams int64
	// KeepAlivePeriod defines whether this peer will periodically send a packet to keep the connection alive.
	// If set to 0, then no keep alive is sent. Otherwise, the keep alive is sent on that period (or at most
	// every half of MaxIdleTimeout, whichever is smaller).
	KeepAlivePeriod time.Duration
	// InitialPacketSize is the initial size (and the lower limit) for packets sent.
	// Under most circumstances, it is not necessary to manually set this value,
	// since path MTU discovery quickly finds the path's MTU.
	// If set too high, the path might not support packets of that size, leading to a timeout of the QUIC handshake.
	// Values below 1200 are invalid.
	InitialPacketSize uint16
	// DisablePathMTUDiscovery disables Path MTU Discovery (RFC 8899).
	// This allows the sending of QUIC packets that fully utilize the available MTU of the path.
	// Path MTU discovery is only available on systems that allow setting of the Don't Fragment (DF) bit.
	DisablePathMTUDiscovery bool
	// Allow0RTT allows the application to decide if a 0-RTT connection attempt should be accepted.
	// Only valid for the server.
	Allow0RTT bool
	// Enable QUIC datagram support (RFC 9221).
	EnableDatagrams bool
	// Enable QUIC Stream Resets with Partial Delivery.
	// See https://datatracker.ietf.org/doc/html/draft-ietf-quic-reliable-stream-reset-07.
	EnableStreamResetPartialDelivery bool

	Tracer func(ctx context.Context, isClient bool, connID ConnectionID) qlogwriter.Trace
}

Config contains all configuration data needed for a QUIC server or client.

func (*Config) Clone

func (c *Config) Clone() *Config

Clone clones a Config.

type Conn

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

A Conn is a QUIC connection between two peers. Calls to the connection (and to streams) can return the following types of errors:

func Dial

func Dial(ctx context.Context, c net.PacketConn, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)

Dial establishes a new QUIC connection to a server using a net.PacketConn. If the PacketConn satisfies the OOBCapablePacketConn interface (as a net.UDPConn does), ECN and packet info support will be enabled. In this case, ReadMsgUDP and WriteMsgUDP will be used instead of ReadFrom and WriteTo to read/write packets. The tls.Config must define an application protocol (using tls.Config.NextProtos).

This is a convenience function. More advanced use cases should instantiate a Transport, which offers configuration options for a more fine-grained control of the connection establishment, including reusing the underlying UDP socket for multiple QUIC connections.

func DialAddr

func DialAddr(ctx context.Context, addr string, tlsConf *tls.Config, conf *Config) (*Conn, error)

DialAddr establishes a new QUIC connection to a server. It resolves the address, and then creates a new UDP connection to dial the QUIC server. When the QUIC connection is closed, this UDP connection is closed. See Dial for more details.

func DialAddrEarly

func DialAddrEarly(ctx context.Context, addr string, tlsConf *tls.Config, conf *Config) (*Conn, error)

DialAddrEarly establishes a new 0-RTT QUIC connection to a server. See DialAddr for more details.

func DialEarly

func DialEarly(ctx context.Context, c net.PacketConn, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)

DialEarly establishes a new 0-RTT QUIC connection to a server using a net.PacketConn. See Dial for more details.

func (*Conn) AcceptStream

func (c *Conn) AcceptStream(ctx context.Context) (*Stream, error)

AcceptStream returns the next stream opened by the peer, blocking until one is available.

func (*Conn) AcceptUniStream

func (c *Conn) AcceptUniStream(ctx context.Context) (*ReceiveStream, error)

AcceptUniStream returns the next unidirectional stream opened by the peer, blocking until one is available.

func (*Conn) AddPath

func (c *Conn) AddPath(t *Transport) (*Path, error)

func (*Conn) CloseWithError

func (c *Conn) CloseWithError(code ApplicationErrorCode, desc string) error

CloseWithError closes the connection with an error. The error string will be sent to the peer.

func (*Conn) ConnectionState

func (c *Conn) ConnectionState() ConnectionState

ConnectionState returns basic details about the QUIC connection.

func (*Conn) ConnectionStats

func (c *Conn) ConnectionStats() ConnectionStats

func (*Conn) Context

func (c *Conn) Context() context.Context

Context returns a context that is cancelled when the connection is closed. The cancellation cause is set to the error that caused the connection to close.

func (*Conn) HandshakeComplete

func (c *Conn) HandshakeComplete() <-chan struct{}

HandshakeComplete blocks until the handshake completes (or fails). For the client, data sent before completion of the handshake is encrypted with 0-RTT keys. For the server, data sent before completion of the handshake is encrypted with 1-RTT keys, however the client's identity is only verified once the handshake completes.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local address of the QUIC connection.

func (*Conn) NextConnection

func (c *Conn) NextConnection(ctx context.Context) (*Conn, error)

NextConnection transitions a connection to be usable after a 0-RTT rejection. It waits for the handshake to complete and then enables the connection for normal use. This should be called when the server rejects 0-RTT and the application receives Err0RTTRejected errors.

Note that 0-RTT rejection invalidates all data sent in 0-RTT packets. It is the application's responsibility to handle this (for example by resending the data).

func (*Conn) OpenStream

func (c *Conn) OpenStream() (*Stream, error)

OpenStream opens a new bidirectional QUIC stream. There is no signaling to the peer about new streams: The peer can only accept the stream after data has been sent on the stream, or the stream has been reset or closed. When reaching the peer's stream limit, it is not possible to open a new stream until the peer raises the stream limit. In that case, a StreamLimitReachedError is returned.

func (*Conn) OpenStreamSync

func (c *Conn) OpenStreamSync(ctx context.Context) (*Stream, error)

OpenStreamSync opens a new bidirectional QUIC stream. It blocks until a new stream can be opened. There is no signaling to the peer about new streams: The peer can only accept the stream after data has been sent on the stream, or the stream has been reset or closed.

func (*Conn) OpenUniStream

func (c *Conn) OpenUniStream() (*SendStream, error)

OpenUniStream opens a new outgoing unidirectional QUIC stream. There is no signaling to the peer about new streams: The peer can only accept the stream after data has been sent on the stream, or the stream has been reset or closed. When reaching the peer's stream limit, it is not possible to open a new stream until the peer raises the stream limit. In that case, a StreamLimitReachedError is returned.

func (*Conn) OpenUniStreamSync

func (c *Conn) OpenUniStreamSync(ctx context.Context) (*SendStream, error)

OpenUniStreamSync opens a new outgoing unidirectional QUIC stream. It blocks until a new stream can be opened. There is no signaling to the peer about new streams: The peer can only accept the stream after data has been sent on the stream, or the stream has been reset or closed.

func (*Conn) QlogTrace

func (c *Conn) QlogTrace() qlogwriter.Trace

QlogTrace returns the qlog trace of the QUIC connection. It is nil if qlog is not enabled.

func (*Conn) ReceiveDatagram

func (c *Conn) ReceiveDatagram(ctx context.Context) ([]byte, error)

ReceiveDatagram gets a message received in a QUIC datagram, as specified in RFC 9221.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the remote address of the QUIC connection.

func (*Conn) SendDatagram

func (c *Conn) SendDatagram(p []byte) error

SendDatagram sends a message using a QUIC datagram, as specified in RFC 9221, if the peer enabled datagram support. There is no delivery guarantee for DATAGRAM frames, they are not retransmitted if lost. The payload of the datagram needs to fit into a single QUIC packet. In addition, a datagram may be dropped before being sent out if the available packet size suddenly decreases. If the payload is too large to be sent at the current time, a DatagramTooLargeError is returned.

type ConnectionID

type ConnectionID = protocol.ConnectionID

A ConnectionID is a QUIC Connection ID, as defined in RFC 9000. It is not able to handle QUIC Connection IDs longer than 20 bytes, as they are allowed by RFC 8999.

func ConnectionIDFromBytes

func ConnectionIDFromBytes(b []byte) ConnectionID

ConnectionIDFromBytes interprets b as a ConnectionID. It panics if b is longer than 20 bytes.

type ConnectionIDGenerator

type ConnectionIDGenerator interface {
	// GenerateConnectionID generates a new Connection ID.
	// Generated Connection IDs must be unique and observers should not be able to correlate two Connection IDs.
	GenerateConnectionID() (ConnectionID, error)

	// ConnectionIDLen returns the length of Connection IDs generated by this implementation.
	// Implementations must return constant-length Connection IDs with lengths between 0 and 20 bytes.
	// A length of 0 can only be used when an endpoint doesn't need to multiplex connections during migration.
	ConnectionIDLen() int
}

A ConnectionIDGenerator allows the application to take control over the generation of Connection IDs. Connection IDs generated by an implementation must be of constant length.

type ConnectionState

type ConnectionState struct {
	// TLS contains information about the TLS connection state, incl. the tls.ConnectionState.
	TLS tls.ConnectionState
	// SupportsDatagrams indicates support for QUIC datagrams (RFC 9221).
	SupportsDatagrams struct {
		// Remote is true if the peer advertised datagram support.
		// Local is true if datagram support was enabled via Config.EnableDatagrams.
		Remote, Local bool
	}
	// SupportsStreamResetPartialDelivery indicates support for QUIC Stream Resets with Partial Delivery.
	SupportsStreamResetPartialDelivery struct {
		// Remote is true if the peer advertised support.
		// Local is true if support was enabled via Config.EnableStreamResetPartialDelivery.
		Remote, Local bool
	}
	// Used0RTT says if 0-RTT resumption was used.
	Used0RTT bool
	// Version is the QUIC version of the QUIC connection.
	Version Version
	// GSO says if generic segmentation offload is used.
	GSO bool
}

ConnectionState records basic details about a QUIC connection.

type ConnectionStats

type ConnectionStats struct {
	// MinRTT is the estimate of the minimum RTT observed on the active network
	// path.
	MinRTT time.Duration
	// LatestRTT is the last RTT sample observed on the active network path.
	LatestRTT time.Duration
	// SmoothedRTT is an exponentially weighted moving average of an endpoint's
	// RTT samples. See https://www.rfc-editor.org/rfc/rfc9002#section-5.3
	SmoothedRTT time.Duration
	// MeanDeviation estimates the variation in the RTT samples using a mean
	// variation. See https://www.rfc-editor.org/rfc/rfc9002#section-5.3
	MeanDeviation time.Duration

	// BytesSent is the number of bytes sent on the underlying connection,
	// including retransmissions. Does not include UDP or any other outer
	// framing.
	BytesSent uint64
	// PacketsSent is the number of packets sent on the underlying connection,
	// including those that are determined to have been lost.
	PacketsSent uint64
	// BytesReceived is the number of total bytes received on the underlying
	// connection, including duplicate data for streams. Does not include UDP or
	// any other outer framing.
	BytesReceived uint64
	// PacketsReceived is the number of total packets received on the underlying
	// connection, including packets that were not processable.
	PacketsReceived uint64
	// BytesLost is the number of bytes lost on the underlying connection (does
	// not monotonically increase, because packets that are declared lost can
	// subsequently be received). Does not include UDP or any other outer
	// framing.
	BytesLost uint64
	// PacketsLost is the number of packets lost on the underlying connection
	// (does not monotonically increase, because packets that are declared lost
	// can subsequently be received).
	PacketsLost uint64
}

ConnectionStats contains statistics about the QUIC connection

type DatagramTooLargeError

type DatagramTooLargeError struct {
	MaxDatagramPayloadSize int64
}

DatagramTooLargeError is returned from Conn.SendDatagram if the payload is too large to be sent.

func (*DatagramTooLargeError) Error

func (e *DatagramTooLargeError) Error() string

func (*DatagramTooLargeError) Is

func (e *DatagramTooLargeError) Is(target error) bool

type EarlyListener

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

An EarlyListener listens for incoming QUIC connections, and returns them before the handshake completes. For connections that don't use 0-RTT, this allows the server to send 0.5-RTT data. This data is encrypted with forward-secure keys, however, the client's identity has not yet been verified. For connection using 0-RTT, this allows the server to accept and respond to streams that the client opened in the 0-RTT data it sent. Note that at this point during the handshake, the live-ness of the client has not yet been confirmed, and the 0-RTT data could have been replayed by an attacker.

func ListenAddrEarly

func ListenAddrEarly(addr string, tlsConf *tls.Config, config *Config) (*EarlyListener, error)

ListenAddrEarly works like ListenAddr, but it returns connections before the handshake completes.

func ListenEarly

func ListenEarly(conn net.PacketConn, tlsConf *tls.Config, config *Config) (*EarlyListener, error)

ListenEarly works like Listen, but it returns connections before the handshake completes.

func (*EarlyListener) Accept

func (l *EarlyListener) Accept(ctx context.Context) (*Conn, error)

Accept returns a new connections. It should be called in a loop.

func (*EarlyListener) Addr

func (l *EarlyListener) Addr() net.Addr

Addr returns the local network addr that the server is listening on.

func (*EarlyListener) Close

func (l *EarlyListener) Close() error

Close closes the listener. Accept will return ErrServerClosed as soon as all connections in the accept queue have been accepted. Early connections that are still in flight will be rejected with a CONNECTION_REFUSED error. Already established (accepted) connections will be unaffected.

type HandshakeTimeoutError

type HandshakeTimeoutError = qerr.HandshakeTimeoutError

HandshakeTimeoutError indicates that the connection timed out before completing the handshake.

type IdleTimeoutError

type IdleTimeoutError = qerr.IdleTimeoutError

IdleTimeoutError indicates that the connection timed out because it was inactive for too long.

type InitialDatagramBudget

type InitialDatagramBudget struct {
	// Plan is the InitialPacketPlan the spec pinned for this datagram, or the zero plan
	// if InitialPacketSpec.InitialPackets doesn't reach this far.
	Plan InitialPacketPlan

	// MaxFrameBytes is the largest frame payload this datagram can carry: its QUIC
	// packet size (Plan.PacketSize, or the path MTU when that is unset) minus the long
	// header and the AEAD tag. A longer payload cannot be sent and is rejected.
	MaxFrameBytes int
}

InitialDatagramBudget tells a QUICFlightFrameBuilder what one Initial datagram of the flight can hold. [UQUIC]

type InitialPacketPlan

type InitialPacketPlan struct {
	// CryptoLength caps the CRYPTO data bytes placed in this datagram, which fixes
	// the next datagram's CRYPTO offset (the split point). 0 = all remaining CRYPTO.
	CryptoLength int

	// PacketSize forces the exact serialized QUIC packet size (UDP payload bytes) by
	// padding the payload with PADDING frames. 0 = no exact-size padding. Must leave
	// room: the CRYPTO assigned to this datagram (+ header/AEAD) must not exceed it.
	PacketSize int
}

InitialPacketPlan pins, for one Initial datagram, how much of the CRYPTO stream it carries and the exact QUIC packet (UDP payload) size it is padded to. See InitialPacketSpec.InitialPackets. [UQUIC]

type InitialPacketSpec

type InitialPacketSpec struct {
	// SrcConnIDLength specifies how many bytes should the SrcConnID be
	SrcConnIDLength int

	// DestConnIDLength specifies how many bytes should the DestConnID be
	DestConnIDLength int

	// InitPacketNumberLength specifies how many bytes should the InitPacketNumber
	// be interpreted as. It is usually 1 or 2 bytes. If unset, UQUIC will use the
	// default algorithm to compute the length which is at least 2 bytes.
	//
	// Deprecated: Use InitPacketNumberLengths for per-packet control. This field is
	// ignored when InitPacketNumberLengths is non-empty.
	InitPacketNumberLength PacketNumberLen

	// InitPacketNumberLengths specifies the PN encoding length for each successive
	// Initial packet. Entry [0] applies to PN=InitPacketNumber, [1] to the next
	// Initial packet, etc. If the packet index exceeds the slice length, the last
	// entry repeats. Overrides InitPacketNumberLength when non-empty.
	//
	// Example (Chrome 146): []PacketNumberLen{1, 2} — 1-byte encoding for PN=1,
	// 2-byte encoding for PN=2.
	InitPacketNumberLengths []PacketNumberLen // [UQUIC]

	// InitPacketNumber is the packet number of the first Initial packet. Following
	// Initial packets, if any, will increment the Packet Number accordingly.
	InitPacketNumber uint64 // [UQUIC]

	// TokenStore is used to store and retrieve tokens. If set, will override the
	// one set in the Config.
	//
	// Use this when the token must be computed per connection rather than described
	// statically — ClientTokenLength and ClientTokenPrefix cover the common cases and
	// need no implementation. NewClientToken builds the *ClientToken to return from
	// Pop; ClientToken's fields are unexported, so a store outside this package
	// cannot construct one any other way.
	TokenStore TokenStore

	// If ClientTokenLength is set when TokenStore is not set, a dummy TokenStore
	// will be created to randomly generate tokens of the specified length for
	// Pop() calls with any key and silently drop any Put() calls.
	//
	// However, the tokens will not be stored anywhere and are expected to be
	// invalid since not assigned by the server.
	ClientTokenLength int

	// ClientTokenPrefix pins the leading bytes of the generated token; the rest stays
	// random and is regenerated per connection. A real token is a server-issued opaque
	// blob, but its first bytes are typically a fixed version/type prefix — Chrome's
	// tokens from Google servers are 70 bytes starting with 0x00 — so a token that is
	// random all the way to byte 0 is a trivial tell.
	//
	// The token is ClientTokenPrefix followed by random bytes, up to whichever of
	// ClientTokenLength and len(ClientTokenPrefix) is larger. The prefix is never
	// truncated, so putting the whole token here (with ClientTokenLength unset) sends
	// exactly those bytes on every connection:
	//
	//	ClientTokenPrefix: []byte{0x00}, ClientTokenLength: 70 // Chrome
	//
	// Setting only ClientTokenPrefix installs the dummy TokenStore just as
	// ClientTokenLength does; an explicit TokenStore still takes priority over both.
	// [UQUIC]
	ClientTokenPrefix []byte

	// FrameBuilder specifies how the frames should be encapsulated for each Initial
	// packet.
	//
	// If FrameBuilder implements QUICFrameBuilderEx, BuildForDatagram is called once
	// per Initial datagram with the datagram index and base CRYPTO stream offset,
	// enabling correct multi-datagram fingerprinting (e.g. Chrome 146 with two Initials).
	//
	// If nil, there will be only one single Crypto frame in the first Initial packet.
	FrameBuilder QUICFrameBuilder

	// InitialPackets, when non-empty, pins the per-datagram fragmentation of the
	// Initial flight: entry [i] controls the i-th Initial datagram. This lets a spec
	// reproduce a client whose Initials have specific CRYPTO split offsets and exact
	// wire sizes — e.g. Chrome's X25519MLKEM768 flight of two 1200-byte Initials with
	// the ClientHello split at CRYPTO offset 999:
	//
	//	[]InitialPacketPlan{{CryptoLength: 999, PacketSize: 1200}, {PacketSize: 1200}}
	//
	// If the datagram index exceeds the slice length, the last entry repeats. [UQUIC]
	InitialPackets []InitialPacketPlan
}

InitialPacketSpec describes everything about the QUIC Initial flight except the ClientHello itself: the long header's connection IDs, packet numbers and token, how the CRYPTO stream is cut into frames, and how those frames are spread across datagrams. It is the QUIC-header half of a QUICSpec.

The fields fall into three groups:

  • Long header: SrcConnIDLength, DestConnIDLength, InitPacketNumber, InitPacketNumberLengths, and the token (TokenStore / ClientTokenLength / ClientTokenPrefix).
  • Framing inside a packet: FrameBuilder.
  • Datagram layout of the flight: InitialPackets.

The zero value produces a default-shaped Initial: a single datagram carrying one CRYPTO frame, no token, and library-chosen connection ID lengths.

func (*InitialPacketSpec) UpdateConfig

func (ps *InitialPacketSpec) UpdateConfig(conf *Config)

UpdateConfig installs the spec's token source into conf, resolved by getTokenStore: an explicit TokenStore wins, otherwise ClientTokenLength/ClientTokenPrefix synthesize one. A spec that requests no token leaves conf.TokenStore untouched, so a caller's own store survives.

type Listener

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

A Listener listens for incoming QUIC connections. It returns connections once the handshake has completed.

func Listen

func Listen(conn net.PacketConn, tlsConf *tls.Config, config *Config) (*Listener, error)

Listen listens for QUIC connections on a given net.PacketConn. If the PacketConn satisfies the OOBCapablePacketConn interface (as a net.UDPConn does), ECN and packet info support will be enabled. In this case, ReadMsgUDP and WriteMsgUDP will be used instead of ReadFrom and WriteTo to read/write packets. A single net.PacketConn can only be used for a single call to Listen.

The tls.Config must not be nil and must contain a certificate configuration. Furthermore, it must define an application control (using [NextProtos]). The quic.Config may be nil, in that case the default values will be used.

This is a convenience function. More advanced use cases should instantiate a Transport, which offers configuration options for a more fine-grained control of the connection establishment, including reusing the underlying UDP socket for outgoing QUIC connections. When closing a listener created with Listen, all established QUIC connections will be closed immediately.

func ListenAddr

func ListenAddr(addr string, tlsConf *tls.Config, config *Config) (*Listener, error)

ListenAddr creates a QUIC server listening on a given address. See Listen for more details.

func (*Listener) Accept

func (l *Listener) Accept(ctx context.Context) (*Conn, error)

Accept returns new connections. It should be called in a loop.

func (*Listener) Addr

func (l *Listener) Addr() net.Addr

Addr returns the local network address that the server is listening on.

func (*Listener) Close

func (l *Listener) Close() error

Close closes the listener. Accept will return ErrServerClosed as soon as all connections in the accept queue have been accepted. QUIC handshakes that are still in flight will be rejected with a CONNECTION_REFUSED error. Already established (accepted) connections will be unaffected.

type OOBCapablePacketConn

type OOBCapablePacketConn interface {
	net.PacketConn
	SyscallConn() (syscall.RawConn, error)
	SetReadBuffer(int) error
	ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error)
	WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error)
}

OOBCapablePacketConn is a connection that allows the reading of ECN bits from the IP header. If the PacketConn passed to the Transport satisfies this interface, quic-go will use it. In this case, ReadMsgUDP() will be used instead of ReadFrom() to read packets.

type PacketNumberLen

type PacketNumberLen = protocol.PacketNumberLen
const (
	// PacketNumberLen1 is a packet number length of 1 byte
	PacketNumberLen1 PacketNumberLen = 1
	// PacketNumberLen2 is a packet number length of 2 bytes
	PacketNumberLen2 PacketNumberLen = 2
	// PacketNumberLen3 is a packet number length of 3 bytes
	PacketNumberLen3 PacketNumberLen = 3
	// PacketNumberLen4 is a packet number length of 4 bytes
	PacketNumberLen4 PacketNumberLen = 4
)

type Path

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

Path is a network path.

func (*Path) Close

func (p *Path) Close() error

Close abandons a path. It is not possible to close the path that’s currently active. After closing, it is not possible to probe this path again.

func (*Path) Probe

func (p *Path) Probe(ctx context.Context) error

func (*Path) Switch

func (p *Path) Switch() error

Switch switches the QUIC connection to this path. It immediately stops sending on the old path, and sends on this new path.

type QUICCryptoRange

type QUICCryptoRange struct {
	// Offset is the absolute offset of the first byte. A negative Offset counts back
	// from the end of the stream, so Offset: -365 is "the last 365 bytes". That is how
	// to pin "this datagram carries the tail of the ClientHello" without knowing the
	// ClientHello's exact length, which shifts whenever the TLS spec changes.
	Offset int

	// Length is the number of bytes. 0 means "to the end of the stream", and a negative
	// Length ends the range that many bytes before the end (-365 stops where a
	// {Offset: -365} tail range begins). Between the two, a flight can be described
	// entirely in offsets from the start and the end, and stays correct when the
	// ClientHello's length shifts.
	Length int
}

QUICCryptoRange is a byte range of the complete CRYPTO stream — the serialized ClientHello — addressed by absolute position rather than by position within whatever slice a single datagram was handed. [UQUIC]

type QUICFlightFrameBuilder

type QUICFlightFrameBuilder interface {
	QUICFrameBuilder

	// BuildFlight returns one frame payload per Initial datagram, in flight order.
	// budgets[i] describes datagram i; len(budgets) is what the spec asked for, but the
	// length of the returned slice decides how many Initial datagrams are actually sent.
	//
	// Every byte of cryptoData must be covered by a CRYPTO frame somewhere in the
	// returned payloads. A byte no datagram emits is never sent by anything else, and
	// the peer sees a ClientHello it can never reassemble; uQUIC rejects such a plan
	// instead of putting it on the wire.
	BuildFlight(cryptoData []byte, budgets []InitialDatagramBudget) (payloads [][]byte, err error)
}

QUICFlightFrameBuilder builds the frame payload of every Initial datagram in the flight at once, from the complete CRYPTO stream.

It exists because QUICFrameBuilderEx cannot describe a flight. BuildForDatagram is handed only the contiguous slice of the CRYPTO stream the packer popped for that one datagram, and slices are popped in stream order as the flight is packed, so no datagram can carry bytes from later in the ClientHello than its own slice. Real clients do exactly that: Chrome's Initial flight puts the TAIL of the ClientHello (its highest CRYPTO offsets) in the FIRST datagram and the middle of the ClientHello in later ones. With a ~2300-byte ClientHello and ~1150 bytes of Initial payload capacity, those tail bytes have not even been produced when datagram 0 is built.

BuildFlight closes that gap. It is called once, before any Initial packet of the flight is serialized, with the entire CRYPTO stream, and returns the exact frame payload of every Initial datagram. Any byte range may be placed in any datagram, in any order. uQUIC supplies only the long header, packet number, token, exact-size PADDING and AEAD.

QUICFlightFrames and QUICRandomFlightFrames implement this; a caller needing something neither expresses can implement it directly.

type QUICFlightFrames

type QUICFlightFrames struct {
	// Datagrams[i] is the ordered frame list of Initial datagram i. Must not be empty.
	Datagrams []QUICFrames
}

QUICFlightFrames is a declarative QUICFlightFrameBuilder that pins the exact frame layout of every Initial datagram in the flight.

Datagrams[i] is the wire-order frame list of Initial datagram i. It reuses QUICFrames, with one difference that is the whole point of a flight plan: a QUICFrameCrypto's Offset is an ABSOLUTE offset into the complete CRYPTO stream, not an offset into the slice this datagram happened to be handed. Offset and Length are read as a QUICCryptoRange, so both may be negative to address the stream from its end. QUICFramePing and QUICFramePadding behave exactly as they do elsewhere.

Chrome's three-datagram flight — tail first, then the head, then the middle:

QUICFlightFrames{Datagrams: []QUICFrames{
    {QUICFrameCrypto{Offset: -365}, QUICFrameCrypto{Offset: 0, Length: 62}},
    {QUICFrameCrypto{Offset: 62, Length: 1139}},
    {QUICFrameCrypto{Offset: 1201, Length: -365}}, // up to where the tail starts
}}

The layout is fixed, so every connection emits the same one. Real clients vary their fragmentation per connection; use QUICRandomFlightFrames when that variation is itself part of the fingerprint. [UQUIC]

func (*QUICFlightFrames) Build

func (f *QUICFlightFrames) Build(cryptoData []byte) ([]byte, error)

Build implements QUICFrameBuilder by building the first datagram's frames. It is the fallback used for Initial packets outside the planned flight (e.g. a PTO probe that retransmits CRYPTO after the flight is gone).

func (*QUICFlightFrames) BuildFlight

func (f *QUICFlightFrames) BuildFlight(cryptoData []byte, _ []InitialDatagramBudget) ([][]byte, error)

BuildFlight implements QUICFlightFrameBuilder.

type QUICFrame

type QUICFrame interface {
	// None crypto frames should return false for cryptoOK
	CryptoFrameInfo() (offset, length int, cryptoOK bool)

	// None crypto frames should return the byte representation of the frame.
	// Crypto frames' behavior is undefined and unused.
	Read() ([]byte, error)
}

QUICFrame is the interface for all QUIC frames to be included in the Initial Packet.

type QUICFrameBuilder

type QUICFrameBuilder interface {
	// Build ingests data from crypto frames without the crypto frame header
	// and returns the byte representation of all frames.
	Build(cryptoData []byte) (allFrames []byte, err error)
}

QUICFrameBuilder builds QUIC Initial packet frames from TLS crypto data.

type QUICFrameBuilderEx

type QUICFrameBuilderEx interface {
	QUICFrameBuilder
	BuildForDatagram(datagramIdx int, cryptoData []byte, baseOffset uint64) (allFrames []byte, err error)
}

QUICFrameBuilderEx extends QUICFrameBuilder with N-datagram support. BuildForDatagram is called once per Initial datagram by uPacketPacker:

  • datagramIdx: 0-based index of this datagram (0 = first Initial packet)
  • cryptoData: the CRYPTO bytes assigned to this datagram's slice of the crypto stream
  • baseOffset: absolute QUIC crypto stream offset of cryptoData[0]

Implementations must produce CRYPTO frame wire offsets = (local_offset + baseOffset). Existing single-datagram specs (Chrome 115, Firefox 116) implement QUICFrameBuilder only; uPacketPacker falls back to Build() when QUICFrameBuilderEx is not implemented.

A datagram can only re-cut the slice it is handed. Slices are popped from the CRYPTO stream in order as the flight is packed, so datagram i never sees a byte belonging to datagram i+1: with a ~2300-byte ClientHello and ~1150 bytes of Initial payload capacity, the tail of the ClientHello does not exist yet when the first datagram is built. Every byte handed to BuildForDatagram must also be emitted by it — bytes held back are never sent by anyone else, and the ClientHello arrives truncated. Use QUICFlightFrameBuilder for any layout that moves bytes between datagrams.

type QUICFrameCrypto

type QUICFrameCrypto struct {
	// Offset is used to specify the starting offset of the crypto frame,
	// relative to the start of the crypto data slice for this datagram.
	// Used when sending multiple crypto frames in a single packet.
	//
	// Multiple crypto frames in a single packet must not overlap and must
	// make up an entire crypto stream continuously.
	Offset int

	// Length is used to specify the length of the crypto frame.
	//
	// Must be set if it is NOT the last crypto frame in a packet.
	Length int
}

QUICFrameCrypto is used to specify the crypto frames containing the TLS ClientHello to be sent in the first Initial packet.

func (QUICFrameCrypto) CryptoFrameInfo

func (q QUICFrameCrypto) CryptoFrameInfo() (offset, length int, cryptoOK bool)

CryptoFrameInfo() implements the QUICFrame interface.

Crypto frames are later replaced by the crypto message using the information returned by this function.

func (QUICFrameCrypto) Read

func (q QUICFrameCrypto) Read() ([]byte, error)

Read() implements the QUICFrame interface.

Crypto frames are later replaced by the crypto message, so they are not Read()-able.

type QUICFramePadding

type QUICFramePadding struct {
	// Length is used to specify the length of the padding frame.
	Length int
}

QUICFramePadding is used to specify the padding frames to be sent in the first Initial packet.

func (QUICFramePadding) CryptoFrameInfo

func (q QUICFramePadding) CryptoFrameInfo() (offset, length int, cryptoOK bool)

CryptoFrameInfo() implements the QUICFrame interface.

func (QUICFramePadding) Read

func (q QUICFramePadding) Read() ([]byte, error)

Read() implements the QUICFrame interface.

Padding simply returns a slice of bytes of the specified length filled with 0.

type QUICFramePing

type QUICFramePing struct{}

QUICFramePing is used to specify the ping frames to be sent in the first Initial packet.

func (QUICFramePing) CryptoFrameInfo

func (q QUICFramePing) CryptoFrameInfo() (offset, length int, cryptoOK bool)

CryptoFrameInfo() implements the QUICFrame interface.

func (QUICFramePing) Read

func (q QUICFramePing) Read() ([]byte, error)

Read() implements the QUICFrame interface.

Ping simply returns a slice of bytes of size 1 with value 0x01(PING).

type QUICFrames

type QUICFrames []QUICFrame

QUICFrames is a slice of QUICFrame that implements QUICFrameBuilder and QUICFrameBuilderEx. It could be used to deterministically build QUIC Frames from crypto data.

func (QUICFrames) Build

func (qfs QUICFrames) Build(cryptoData []byte) (payload []byte, err error)

Build ingests data from crypto frames without the crypto frame header and returns the byte representation of all frames as specified in the slice. Equivalent to BuildForDatagram(0, cryptoData, 0).

func (QUICFrames) BuildForDatagram

func (qfs QUICFrames) BuildForDatagram(_ int, cryptoData []byte, baseOffset uint64) ([]byte, error)

BuildForDatagram implements QUICFrameBuilderEx. baseOffset is added to every CRYPTO frame wire offset, enabling correct absolute crypto stream positions for datagrams beyond the first.

func (QUICFrames) BuildFromFrames

func (qfs QUICFrames) BuildFromFrames(frames []byte) (payload []byte, err error)

BuildFromFrames ingests data from all input frames and returns the byte representation of all frames as specified in the slice.

type QUICID

type QUICID struct {
	Client string

	// Version specifies version of a mimicked clients (e.g. browsers).
	Version string

	// Fingerprint is a unique identifier for each different QUIC client/spec.
	Fingerprint string
}

QUICID names one built-in client fingerprint that QUICID2Spec can expand into a ready-made QUICSpec — the QUIC-layer analogue of uTLS's ClientHelloID. The package vars below (QUICChrome_146, QUICFirefox_116, …) are the available IDs; a client with several observed variants gets one ID per variant, with the unsuffixed name aliasing the most common one.

type QUICMultiDatagramFrames

type QUICMultiDatagramFrames struct {
	// PerDatagram specifies the frame randomization for each Initial datagram.
	// PerDatagram[0] is used for the first datagram, [1] for the second, etc.
	// If datagramIdx >= len(PerDatagram), the last entry is used (repeating pattern).
	// Must have at least one entry.
	PerDatagram []QUICRandomFrames
}

QUICMultiDatagramFrames implements QUICFrameBuilderEx with per-datagram configuration. It enables different PING/CRYPTO/PADDING distributions for each Initial datagram, which is useful for clients like Chrome 146 that send multiple Initial packets.

Each datagram still re-cuts only its own slice of the stream. To choose which part of the ClientHello a datagram carries — Chrome's cross-packet CRYPTO scatter, where the first datagram holds the tail — use a QUICFlightFrameBuilder instead.

func (*QUICMultiDatagramFrames) Build

func (m *QUICMultiDatagramFrames) Build(cryptoData []byte) ([]byte, error)

Build implements QUICFrameBuilder by using the first datagram's spec with baseOffset=0. This provides backward compatibility when QUICFrameBuilderEx is not used.

func (*QUICMultiDatagramFrames) BuildForDatagram

func (m *QUICMultiDatagramFrames) BuildForDatagram(datagramIdx int, cryptoData []byte, baseOffset uint64) ([]byte, error)

BuildForDatagram implements QUICFrameBuilderEx. It selects the QUICRandomFrames spec for datagramIdx (clamped to the last entry) and builds frames with the given baseOffset for correct absolute CRYPTO wire offsets.

type QUICRandomFlightDatagram

type QUICRandomFlightDatagram struct {
	// CryptoRanges are the absolute ranges of the CRYPTO stream this datagram carries.
	// Any range may go in any datagram — that freedom is the reason this type exists.
	// Across the whole flight the ranges must cover the entire stream, or uQUIC rejects
	// the plan rather than sending a ClientHello that can never be reassembled.
	CryptoRanges []QUICCryptoRange

	// Frames randomizes this datagram's framing. Each range in CryptoRanges is
	// independently cut into [MinCRYPTO, MaxCRYPTO) CRYPTO frames, [MinPING, MaxPING)
	// PING frames are added, the whole list is shuffled, and PADDING is appended to
	// reach Frames.Length (which, unlike InitialPacketPlan.PacketSize, can be scattered
	// through the packet rather than trailing it). The zero value emits exactly one
	// CRYPTO frame per range, in order, with no PING or PADDING.
	Frames QUICRandomFrames
}

QUICRandomFlightDatagram is one Initial datagram of a QUICRandomFlightFrames plan. [UQUIC]

type QUICRandomFlightFrames

type QUICRandomFlightFrames struct {
	// PerDatagram[i] describes Initial datagram i. Must not be empty.
	PerDatagram []QUICRandomFlightDatagram
}

QUICRandomFlightFrames is a QUICFlightFrameBuilder that assigns each Initial datagram an explicit set of absolute CRYPTO ranges — which is what a per-datagram builder cannot do — and then randomizes the framing *within* each datagram per connection, the way QUICRandomFrames does within a single packet.

This is the combination real clients show: which part of the ClientHello lands in which datagram is a fixed structural property of the client (Chrome always carries the tail in datagram 1), while the cut points, frame order and PADDING placement inside a datagram differ on every connection. A fingerprinter reads the first as a signature and the second as noise, so reproducing only the fixed half — the same fragmentation on every connection — is itself a tell.

QUICRandomFlightFrames{PerDatagram: []QUICRandomFlightDatagram{
    {   // datagram 1: the tail, then the head, scattered into 6-9 CRYPTO frames
        CryptoRanges: []QUICCryptoRange{{Offset: -365}, {Offset: 0, Length: 62}},
        Frames:       QUICRandomFrames{MinCRYPTO: 3, MaxCRYPTO: 5, MinPING: 1, MaxPING: 3},
    },
    {   // datagram 2: the contiguous middle
        CryptoRanges: []QUICCryptoRange{{Offset: 62, Length: 1139}},
        Frames:       QUICRandomFrames{MinCRYPTO: 1, MaxCRYPTO: 2},
    },
}}

[UQUIC]

func (*QUICRandomFlightFrames) Build

func (f *QUICRandomFlightFrames) Build(cryptoData []byte) ([]byte, error)

Build implements QUICFrameBuilder by laying out the first datagram against cryptoData as if it were the whole stream. Used for Initial packets outside the planned flight.

func (*QUICRandomFlightFrames) BuildFlight

func (f *QUICRandomFlightFrames) BuildFlight(cryptoData []byte, _ []InitialDatagramBudget) ([][]byte, error)

BuildFlight implements QUICFlightFrameBuilder.

type QUICRandomFrames

type QUICRandomFrames struct {
	// MinPING specifies the inclusive lower bound of the number of PING frames to be
	// included in the Initial Packet.
	MinPING uint8

	// MaxPING specifies the exclusive upper bound of the number of PING frames to be
	// included in the Initial Packet. It must be at least MinPING+1.
	MaxPING uint8

	// MinCRYPTO specifies the inclusive lower bound of the number of CRYPTO frames to
	// split the Crypto data into. It must be at least 1.
	MinCRYPTO uint8

	// MaxCRYPTO specifies the exclusive upper bound of the number of CRYPTO frames to
	// split the Crypto data into. It must be at least MinCRYPTO+1.
	MaxCRYPTO uint8

	// MinPADDING specifies the inclusive lower bound of the number of PADDING frames
	// to be included in the Initial Packet. It must be at least 1 if Length is not 0.
	MinPADDING uint8

	// MaxPADDING specifies the exclusive upper bound of the number of PADDING frames
	// to be included in the Initial Packet. It must be at least MinPADDING+1 if
	// Length is not 0.
	MaxPADDING uint8

	// Length specifies the total length of all frames including PADDING frames.
	// If the Length specified is already exceeded by the CRYPTO+PING frames, no
	// PADDING frames will be included.
	Length uint16 // 2 bytes, max 65535
}

QUICRandomFrames could be used to indeterministically build QUIC Frames from crypto data. A caller may specify how many PING and CRYPTO frames are expected to be included in the Initial Packet, as well as the total length plus PADDING frames in the end.

QUICRandomFrames implements both QUICFrameBuilder and QUICFrameBuilderEx. When used as a FrameBuilder for multi-datagram Initials, each datagram gets independently randomized fragmentation with correct absolute CRYPTO offsets.

func (*QUICRandomFrames) Build

func (qrf *QUICRandomFrames) Build(cryptoData []byte) (payload []byte, err error)

Build ingests data from crypto frames without the crypto frame header and returns the byte representation of all frames as specified in the slice. Equivalent to BuildForDatagram(0, cryptoData, 0).

func (*QUICRandomFrames) BuildForDatagram

func (qrf *QUICRandomFrames) BuildForDatagram(_ int, cryptoData []byte, baseOffset uint64) ([]byte, error)

BuildForDatagram implements QUICFrameBuilderEx. datagramIdx is available for future per-datagram configuration (currently ignored; all datagrams use the same randomization parameters). baseOffset is added to every CRYPTO frame wire offset for correct multi-datagram positioning.

type QUICSpec

type QUICSpec struct {
	// InitialPacketSpec specifies the QUIC Initial Packet, which includes Initial
	// Packet Headers and Frames.
	InitialPacketSpec InitialPacketSpec

	// ClientHelloSpec specifies the TLS ClientHello to be sent in the first Initial
	// Packet. It is implemented by the uTLS library and a valid ClientHelloSpec
	// for QUIC MUST include (utls).QUICTransportParametersExtension.
	ClientHelloSpec *tls.ClientHelloSpec

	// UDPDatagramMinSize specifies the minimum size of the UDP Datagram (UDP payload).
	// If the UDP Datagram is smaller than this size, zeros will be padded to the end
	// of the UDP Datagram until this size is reached.
	UDPDatagramMinSize int

	// RandomizeTransportParameters, when true, shuffles the QUIC transport parameters
	// (the ClientHelloSpec's QUICTransportParametersExtension list) into a uniformly
	// random permutation per connection, before they are serialized into the Initial
	// CRYPTO stream. This mirrors real Chrome, which randomizes the QTP wire order on
	// every handshake; without it the parameter order is fixed by the spec and becomes
	// a trivial discriminator signal. The shuffle reorders the extension's parameter
	// slice in place at connection-setup time (so a freshly built spec randomizes each
	// connection); it does not change which parameters or values are sent.
	RandomizeTransportParameters bool

	// SuppressTransportParameters lists QUIC transport parameter IDs to drop from the
	// ClientHelloSpec's QUICTransportParametersExtension before it is serialized into
	// the Initial CRYPTO stream. It lets a caller pin the exact on-wire parameter set
	// — most usefully by starting from a parrot (or any shared spec) and removing
	// parameters, instead of restating the whole list.
	//
	// An entry of QTPGrease (27) removes every GREASE-valued parameter (31*N+27), since
	// QUIC fingerprinters bucket all GREASE IDs into that one canonical ID; other
	// entries match the parameter ID exactly. Suppression runs before
	// RandomizeTransportParameters, so the shuffled set is exactly the wire set, and
	// the connection's own view of its parameters is populated from the filtered list.
	//
	// Suppressing a parameter the peer requires (e.g. initial_source_connection_id)
	// produces a ClientHello a conformant server will reject. That is allowed on
	// purpose — mimicry sometimes needs it — but it is the caller's responsibility.
	SuppressTransportParameters []uint64
}

QUICSpec is the complete description of the QUIC Initial flight a UTransport emits: the Initial packet's header and framing (InitialPacketSpec), the TLS ClientHello carried in its CRYPTO stream (ClientHelloSpec), and the datagram-level and transport-parameter knobs below. It is the QUIC-layer analogue of uTLS's ClientHelloSpec — everything a fingerprinter can observe about the flight should be reachable from here.

Assign one to UTransport.QUICSpec before dialing:

ut := &quic.UTransport{Transport: &quic.Transport{Conn: pc}, QUICSpec: spec}
conn, err := ut.Dial(ctx, addr, tlsConf, conf)

Fields that randomize per connection (RandomizeTransportParameters, a QUICRandomFrames FrameBuilder, ClientTokenPrefix's random tail) are re-drawn on every dial, so one spec value can serve many connections. Fields whose value is itself random — a GREASE transport parameter's ID, VariableLengthGREASEQTP's length — are drawn once when the spec is built, so build a fresh spec per connection if those must vary too.

func QUICID2Spec

func QUICID2Spec(id QUICID) (QUICSpec, error)

QUICID2Spec returns the QUICSpec that mimics the client named by id, or an error for an unknown ID. Each call builds a fresh spec, so per-spec random draws (GREASE parameter IDs and lengths, ChromeRandomInitialRTT) are re-drawn — call it per connection rather than caching one result if those values must vary.

The returned spec is a starting point, not a frozen artifact: mutate its fields, or set QUICSpec.SuppressTransportParameters, to derive a variant without restating the whole parameter list.

func (*QUICSpec) TransportParameterIDs

func (s *QUICSpec) TransportParameterIDs() []uint64

TransportParameterIDs returns the QUIC transport parameter IDs this spec will put on the wire, in the canonical form QUIC fingerprinters use: every GREASE ID (31*N+27) is folded to QTPGrease and the result is sorted ascending. SuppressTransportParameters is applied, so this is what a dial would actually send. It returns nil if the spec has no ClientHelloSpec or no QUICTransportParametersExtension.

Duplicates are deliberately kept, because they are the whole point: a spec listing both an explicit tls.FakeQUICTransportParameter{Id: 0x1b} and a GREASE parameter emits two distinct IDs on the wire, but a fingerprinter canonicalizes both to 27 and sees it twice. That collision is invisible in the spec source and otherwise only surfaces in a packet capture. Compare this slice against a target fingerprint's parameter ID list to catch it before dialing.

Calling this pins each GREASE parameter's ID, which is drawn randomly on first use, so a subsequent dial sends exactly the IDs reported here.

func (*QUICSpec) UpdateConfig

func (s *QUICSpec) UpdateConfig(config *Config)

UpdateConfig applies the spec's Config-level overrides to config — currently the TokenStore derived from InitialPacketSpec (see InitialPacketSpec.UpdateConfig). UTransport.dial calls this after populateConfig and before dialing; a spec field that has to reach the connection through Config must be wired in here, or it will be silently ignored no matter what the spec sets.

type ReceiveStream

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

A ReceiveStream is a unidirectional Receive Stream.

func (*ReceiveStream) CancelRead

func (s *ReceiveStream) CancelRead(errorCode StreamErrorCode)

CancelRead aborts receiving on this stream. It instructs the peer to stop transmitting stream data. Read will unblock immediately, and future Read calls will fail. When called multiple times or after reading the io.EOF it is a no-op.

func (*ReceiveStream) Peek

func (s *ReceiveStream) Peek(b []byte) (int, error)

Peek fills b with stream data, without consuming the stream data. It blocks until len(b) bytes are available, or an error occurs. It respects the stream deadline set by SetReadDeadline. If the stream ends before len(b) bytes are available, it returns the number of bytes peeked along with io.EOF.

func (*ReceiveStream) Read

func (s *ReceiveStream) Read(p []byte) (int, error)

Read reads data from the stream. Read can be made to time out using ReceiveStream.SetReadDeadline. If the stream was canceled, the error is a StreamError.

func (*ReceiveStream) SetReadDeadline

func (s *ReceiveStream) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future Read calls and any currently-blocked Read call. A zero value for t means Read will not time out.

func (*ReceiveStream) StreamID

func (s *ReceiveStream) StreamID() protocol.StreamID

StreamID returns the stream ID.

type SendStream

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

A SendStream is a unidirectional Send Stream.

func (*SendStream) CancelWrite

func (s *SendStream) CancelWrite(errorCode StreamErrorCode)

CancelWrite aborts sending on this stream. Data already written, but not yet delivered to the peer is not guaranteed to be delivered reliably. Write will unblock immediately, and future calls to Write will fail. When called multiple times it is a no-op. When called after Close, it aborts reliable delivery of outstanding stream data. Note that there is no guarantee if the peer will receive the FIN or the cancellation error first.

func (*SendStream) Close

func (s *SendStream) Close() error

Close closes the write-direction of the stream. Future calls to Write are not permitted after calling Close. It must not be called concurrently with Write. It must not be called after calling CancelWrite.

func (*SendStream) Context

func (s *SendStream) Context() context.Context

The Context is canceled as soon as the write-side of the stream is closed. This happens when Close() or CancelWrite() is called, or when the peer cancels the read-side of their stream. The cancellation cause is set to the error that caused the stream to close, or `context.Canceled` in case the stream is closed without error.

func (*SendStream) SetReliableBoundary

func (s *SendStream) SetReliableBoundary()

SetReliableBoundary marks the data written to this stream so far as reliable. It is valid to call this function multiple times, thereby increasing the reliable size. It only has an effect if the peer enabled support for the RESET_STREAM_AT extension, otherwise, it is a no-op.

func (*SendStream) SetWriteDeadline

func (s *SendStream) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for future Write calls and any currently-blocked Write call. Even if write times out, it may return n > 0, indicating that some data was successfully written. A zero value for t means Write will not time out.

func (*SendStream) StreamID

func (s *SendStream) StreamID() StreamID

StreamID returns the stream ID.

func (*SendStream) Write

func (s *SendStream) Write(p []byte) (int, error)

Write writes data to the stream. Write can be made to time out using SendStream.SetWriteDeadline. If the stream was canceled, the error is a StreamError.

type StatelessResetError

type StatelessResetError = qerr.StatelessResetError

StatelessResetError indicates a stateless reset was received. This can happen when the peer reboots, or when packets are misrouted. See section 10.3 of RFC 9000 for details.

type StatelessResetKey

type StatelessResetKey [32]byte

StatelessResetKey is a key used to derive stateless reset tokens.

type Stream

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

func (*Stream) CancelRead

func (s *Stream) CancelRead(errorCode StreamErrorCode)

CancelRead aborts receiving on this stream. See ReceiveStream.CancelRead for more details.

func (*Stream) CancelWrite

func (s *Stream) CancelWrite(errorCode StreamErrorCode)

CancelWrite aborts sending on this stream. See SendStream.CancelWrite for more details.

func (*Stream) Close

func (s *Stream) Close() error

Close closes the send-direction of the stream. It does not close the receive-direction of the stream.

func (*Stream) Context

func (s *Stream) Context() context.Context

The Context is canceled as soon as the write-side of the stream is closed. See SendStream.Context for more details.

func (*Stream) Peek

func (s *Stream) Peek(b []byte) (int, error)

Peek fills b with stream data, without consuming the stream data. It blocks until len(b) bytes are available, or an error occurs. It respects the stream deadline set by SetReadDeadline. If the stream ends before len(b) bytes are available, it returns the number of bytes peeked along with io.EOF.

func (*Stream) Read

func (s *Stream) Read(p []byte) (int, error)

Read reads data from the stream. Read can be made to time out using Stream.SetReadDeadline and Stream.SetDeadline. If the stream was canceled, the error is a StreamError.

func (*Stream) SetDeadline

func (s *Stream) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the stream. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

func (*Stream) SetReadDeadline

func (s *Stream) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future Read calls. See ReceiveStream.SetReadDeadline for more details.

func (*Stream) SetReliableBoundary

func (s *Stream) SetReliableBoundary()

SetReliableBoundary marks the data written to this stream so far as reliable. It is valid to call this function multiple times, thereby increasing the reliable size. It only has an effect if the peer enabled support for the RESET_STREAM_AT extension, otherwise, it is a no-op.

func (*Stream) SetWriteDeadline

func (s *Stream) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for future Write calls. See SendStream.SetWriteDeadline for more details.

func (*Stream) StreamID

func (s *Stream) StreamID() protocol.StreamID

StreamID returns the stream ID.

func (*Stream) Write

func (s *Stream) Write(p []byte) (int, error)

Write writes data to the stream. Write can be made to time out using Stream.SetWriteDeadline or Stream.SetDeadline. If the stream was canceled, the error is a StreamError.

type StreamError

type StreamError struct {
	StreamID  StreamID
	ErrorCode StreamErrorCode
	Remote    bool
}

A StreamError is used to signal stream cancellations. It is returned from the Read and Write methods of the ReceiveStream, SendStream and Stream.

func (*StreamError) Error

func (e *StreamError) Error() string

func (*StreamError) Is

func (e *StreamError) Is(target error) bool

type StreamErrorCode

type StreamErrorCode = qerr.StreamErrorCode

StreamErrorCode is a QUIC stream error code. The meaning of the value is defined by the application.

type StreamID

type StreamID = protocol.StreamID

The StreamID is the ID of a QUIC stream.

type StreamLimitReachedError

type StreamLimitReachedError struct{}

StreamLimitReachedError is returned from Conn.OpenStream and Conn.OpenUniStream when it is not possible to open a new stream because the number of opens streams reached the peer's stream limit.

func (StreamLimitReachedError) Error

func (e StreamLimitReachedError) Error() string

type TokenGeneratorKey

type TokenGeneratorKey = handshake.TokenProtectorKey

TokenGeneratorKey is a key used to encrypt session resumption tokens.

type TokenStore

type TokenStore interface {
	// Pop searches for a ClientToken associated with the given key.
	// Since tokens are not supposed to be reused, it must remove the token from the cache.
	// It returns nil when no token is found.
	Pop(key string) (token *ClientToken)

	// Put adds a token to the cache with the given key. It might get called
	// multiple times in a connection.
	Put(key string, token *ClientToken)
}

func NewLRUTokenStore

func NewLRUTokenStore(maxOrigins, tokensPerOrigin int) TokenStore

NewLRUTokenStore creates a new LRU cache for tokens received by the client. maxOrigins specifies how many origins this cache is saving tokens for. tokensPerOrigin specifies the maximum number of tokens per origin.

type Transport

type Transport struct {
	// A single net.PacketConn can only be handled by one Transport.
	// Bad things will happen if passed to multiple Transports.
	//
	// A number of optimizations will be enabled if the connections implements the OOBCapablePacketConn interface,
	// as a *net.UDPConn does.
	// 1. It enables the Don't Fragment (DF) bit on the IP header.
	//    This is required to run DPLPMTUD (Path MTU Discovery, RFC 8899).
	// 2. It enables reading of the ECN bits from the IP header.
	//    This allows the remote node to speed up its loss detection and recovery.
	// 3. It uses batched syscalls (recvmmsg) to more efficiently receive packets from the socket.
	// 4. It uses Generic Segmentation Offload (GSO) to efficiently send batches of packets (on Linux).
	//
	// After passing the connection to the Transport, it's invalid to call ReadFrom or WriteTo on the connection.
	Conn net.PacketConn

	// The length of the connection ID in bytes.
	// It can be any value between 1 and 20.
	// Due to the increased risk of collisions, it is not recommended to use connection IDs shorter than 4 bytes.
	// If unset, a 4 byte connection ID will be used.
	ConnectionIDLength int

	// Use for generating new connection IDs.
	// This allows the application to control of the connection IDs used,
	// which allows routing / load balancing based on connection IDs.
	// All Connection IDs returned by the ConnectionIDGenerator MUST
	// have the same length.
	ConnectionIDGenerator ConnectionIDGenerator

	// The StatelessResetKey is used to generate stateless reset tokens.
	// If no key is configured, sending of stateless resets is disabled.
	// It is highly recommended to configure a stateless reset key, as stateless resets
	// allow the peer to quickly recover from crashes and reboots of this node.
	// See section 10.3 of RFC 9000 for details.
	StatelessResetKey *StatelessResetKey

	// The TokenGeneratorKey is used to encrypt session resumption tokens.
	// If no key is configured, a random key will be generated.
	// If multiple servers are authoritative for the same domain, they should use the same key,
	// see section 8.1.3 of RFC 9000 for details.
	TokenGeneratorKey *TokenGeneratorKey

	// MaxTokenAge is the maximum age of the resumption token presented during the handshake.
	// These tokens allow skipping address resumption when resuming a QUIC connection,
	// and are especially useful when using 0-RTT.
	// If not set, it defaults to 24 hours.
	// See section 8.1.3 of RFC 9000 for details.
	MaxTokenAge time.Duration

	// DisableVersionNegotiationPackets disables the sending of Version Negotiation packets.
	// This can be useful if version information is exchanged out-of-band.
	// It has no effect for clients.
	DisableVersionNegotiationPackets bool

	// VerifySourceAddress decides if a connection attempt originating from unvalidated source
	// addresses first needs to go through source address validation using QUIC's Retry mechanism,
	// as described in RFC 9000 section 8.1.2.
	// Note that the address passed to this callback is unvalidated, and might be spoofed in case
	// of an attack.
	// Validating the source address adds one additional network roundtrip to the handshake,
	// and should therefore only be used if a suspiciously high number of incoming connection is recorded.
	// For most use cases, wrapping the Allow function of a rate.Limiter will be a reasonable
	// implementation of this callback (negating its return value).
	VerifySourceAddress func(net.Addr) bool

	// ConnContext is called when the server accepts a new connection. To reject a connection return
	// a non-nil error.
	// The context is closed when the connection is closed, or when the handshake fails for any reason.
	// The context returned from the callback is used to derive every other context used during the
	// lifetime of the connection:
	// * the context passed to crypto/tls (and used on the tls.ClientHelloInfo)
	// * the context used in Config.QlogTrace
	// * the context returned from Conn.Context
	// * the context returned from SendStream.Context
	// It is not used for dialed connections.
	ConnContext func(context.Context, *ClientInfo) (context.Context, error)

	// A Tracer traces events that don't belong to a single QUIC connection.
	// Recorder.Close is called when the transport is closed.
	Tracer qlogwriter.Recorder
	// contains filtered or unexported fields
}

The Transport is the central point to manage incoming and outgoing QUIC connections. QUIC demultiplexes connections based on their QUIC Connection IDs, not based on the 4-tuple. This means that a single UDP socket can be used for listening for incoming connections, as well as for dialing an arbitrary number of outgoing connections. A Transport handles a single net.PacketConn, and offers a range of configuration options compared to the simple helper functions like Listen and Dial that this package provides.

func (*Transport) Close

func (t *Transport) Close() error

Close stops listening for UDP datagrams on the Transport.Conn. It abruptly terminates all existing connections, without sending a CONNECTION_CLOSE to the peers. It is the application's responsibility to cleanly terminate existing connections prior to calling Close.

If a server was started, it will be closed as well. It is not possible to start any new server or dial new connections after that.

func (*Transport) Dial

func (t *Transport) Dial(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)

Dial dials a new connection to a remote host (not using 0-RTT).

func (*Transport) DialEarly

func (t *Transport) DialEarly(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)

DialEarly dials a new connection, attempting to use 0-RTT if possible.

func (*Transport) Listen

func (t *Transport) Listen(tlsConf *tls.Config, conf *Config) (*Listener, error)

Listen starts listening for incoming QUIC connections. There can only be a single listener on any net.PacketConn. Listen may only be called again after the current listener was closed.

func (*Transport) ListenEarly

func (t *Transport) ListenEarly(tlsConf *tls.Config, conf *Config) (*EarlyListener, error)

ListenEarly starts listening for incoming QUIC connections. There can only be a single listener on any net.PacketConn. ListenEarly may only be called again after the current listener was closed.

func (*Transport) ReadNonQUICPacket

func (t *Transport) ReadNonQUICPacket(ctx context.Context, b []byte) (int, net.Addr, error)

ReadNonQUICPacket reads non-QUIC packets received on the underlying connection. The detection logic is very simple: Any packet that has the first and second bit of the packet set to 0. Note that this is stricter than the detection logic defined in RFC 9443.

func (*Transport) WriteTo

func (t *Transport) WriteTo(b []byte, addr net.Addr) (int, error)

WriteTo sends a packet on the underlying connection.

type TransportError

type TransportError = qerr.TransportError

TransportError indicates an error that occurred on the QUIC transport layer. Every transport error other than CONNECTION_REFUSED and APPLICATION_ERROR is likely a bug in the implementation.

type TransportErrorCode

type TransportErrorCode = qerr.TransportErrorCode

TransportErrorCode is a QUIC transport error code, see section 20 of RFC 9000.

type UTransport

type UTransport struct {
	*Transport

	QUICSpec *QUICSpec // [UQUIC] using ptr to avoid copying
}

UTransport is a Transport that emits the Initial flight described by QUICSpec instead of quic-go's default one. Dial and DialEarly behave as Transport's do, but the connection they create packs its Initial packets through uPacketPacker under the spec's control.

A nil QUICSpec makes UTransport behave like a plain Transport.

Spec fields take effect only where dial reads them, and the read points differ: SrcConnIDLength must be applied before Transport.init caches the connection ID generator, the TokenStore reaches the connection through Config (QUICSpec.UpdateConfig), and InitPacketNumber is passed into doDial as the Initial packet number space's seed. A new InitialPacketSpec field is not live until dial is taught to read it — declaring the field alone leaves it silently ignored on the wire.

func (*UTransport) Dial

func (t *UTransport) Dial(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)

Dial dials a new connection to a remote host (not using 0-RTT).

func (*UTransport) DialEarly

func (t *UTransport) DialEarly(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)

DialEarly dials a new connection, attempting to use 0-RTT if possible.

func (*UTransport) MakeDialer

func (ut *UTransport) MakeDialer() func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *Config) (*Conn, error)

type Version

type Version = protocol.Version

A Version is a QUIC version number.

func SupportedVersions

func SupportedVersions() []Version

SupportedVersions returns the support versions, sorted in descending order of preference.

type VersionNegotiationError

type VersionNegotiationError = qerr.VersionNegotiationError

VersionNegotiationError indicates a failure to negotiate a QUIC version.

Directories

Path Synopsis
client command
echo command
uquic command
fuzzing
frames/cmd command
handshake/cmd command
header/cmd command
integrationtests
internal
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
mocks/ackhandler
Package mockackhandler is a generated GoMock package.
Package mockackhandler is a generated GoMock package.
mocks/quic
Package mockquic is a generated GoMock package.
Package mockquic is a generated GoMock package.
monotime
Package monotime provides a monotonic time representation that is useful for measuring elapsed time.
Package monotime provides a monotonic time representation that is useful for measuring elapsed time.
utils/linkedlist
Package list implements a doubly linked list.
Package list implements a doubly linked list.
interop
Package logging defines a logging interface for quic-go.
Package logging defines a logging interface for quic-go.
jsontext
Package jsontext provides a fast JSON encoder providing only the necessary features for qlog encoding.
Package jsontext provides a fast JSON encoder providing only the necessary features for qlog encoding.
Package testutils contains utilities for simulating packet injection and man-in-the-middle (MITM) attacker tests.
Package testutils contains utilities for simulating packet injection and man-in-the-middle (MITM) attacker tests.

Jump to

Keyboard shortcuts

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