quic

package module
v1.0.28 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 47 Imported by: 2 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

Surf fork of official quic-go v0.65.0, supporting Go 1.27+. Protocol controls, verification limits and the update procedure are documented in UPSTREAM.md. Browser settings and TLS templates live in Surf; this module has no uTLS dependency.

A QUIC implementation in pure Go

Go checks Documentation PkgGoDev

quic-go is an implementation of the QUIC protocol (RFC 9000, RFC 9001, RFC 9002) in Go.

Other QUIC specifications:

quic-go also supports HTTP/3 (RFC 9114).

Other HTTP/3 specifications:

  • QPACK: Field Compression for HTTP/3 (RFC 9204)
  • Extensible Prioritization Scheme for HTTP (RFC 9218)
  • HTTP Datagrams and the Capsule Protocol (RFC 9297)

Related projects:

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

FIPS 140-3

Starting with v0.60, quic-go supports use in FIPS 140-3 environments when built with Go 1.26 or newer, using Go standard library cryptography for the QUIC code paths relevant in FIPS mode; see FIPS140.md for details.

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/WebSocket or HTTP/2 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.

Supported by

We are very grateful to the following organizations for supporting quic-go with free access to their tools:

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 (
	AckReorderingNative    = ackhandler.AckReorderingNative
	AckReorderingImmediate = ackhandler.AckReorderingImmediate
	AckReorderingWindow    = ackhandler.AckReorderingWindow
	AckECNNative           = ackhandler.AckECNNative
	AckECNTransitions      = ackhandler.AckECNTransitions
	AckECNCountOnly        = ackhandler.AckECNCountOnly
)
View Source
const (
	CongestionControlNative     = congestion.AlgorithmNative
	CongestionControlReno       = congestion.AlgorithmReno
	CongestionControlCubic      = congestion.AlgorithmCubic
	CongestionControlCubicBytes = congestion.AlgorithmCubicBytes
	SlowStartNative             = congestion.SlowStartNative
	SlowStartClassic            = congestion.SlowStartClassic
	SlowStartHybrid             = congestion.SlowStartHybrid
)
View Source
const (
	PacingNative      = congestion.PacingNative
	PacingLeakyBucket = congestion.PacingLeakyBucket
	PacingScheduled   = congestion.PacingScheduled
)
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 MaxUDPReceivePacketSize = 65527

MaxUDPReceivePacketSize is QUIC's default maximum UDP payload limit (RFC 9000). Applications omitting max_udp_payload_size must provision this receive size.

View Source
const VersionNegotiationErrorCode = qerr.VersionNegotiationErrorCode

VersionNegotiationErrorCode is RFC 9368's VERSION_NEGOTIATION_ERROR.

Variables

View Source
var (
	// ErrPathClosed can be returned by [Path.Probe] or [Path.Switch] after the path has been closed.
	ErrPathClosed = errors.New("path closed")
	// ErrPathNotValidated is returned by [Path.Switch] when the path has not yet been validated.
	ErrPathNotValidated = errors.New("path not yet validated")
)
View Source
var Err0RTTRejected = errors.New("0-RTT rejected")

Err0RTTRejected can be returned by methods such as:

when the server rejects a 0-RTT connection attempt.

View Source
var ErrServerClosed = errServerClosed{}

ErrServerClosed is returned by Listener.Accept or EarlyListener.Accept after Listener.Close or EarlyListener.Close is called, respectively.

View Source
var ErrStreamClosed = errors.New("stream closed")

ErrStreamClosed is returned when writing to a stream after SendStream.Close was called. Closing a stream also cancels its context with this error as the cause.

View Source
var ErrTransportClosed = &errTransportClosed{}

ErrTransportClosed is returned by Transport.Listen, Transport.ListenEarly, Transport.Dial, or Transport.DialEarly after Transport.Close is called.

View Source
var ErrWouldBlock = errors.New("operation would block")

ErrWouldBlock is returned by SendStream.TryWriteAll if the entire slice can't be queued immediately.

View Source
var ErrWriteLimitReached = errors.New("write limit reached")

ErrWriteLimitReached is returned by SendStream.WriteWithLimit when its limiter prevents accepting the entire slice.

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.ClientHelloInfo.Context.

Functions

This section is empty.

Types

type AckECNMode added in v1.0.3

type AckECNMode = ackhandler.AckECNMode

type AckPolicy added in v1.0.3

type AckPolicy = ackhandler.AckPolicy

type AckProbeInfo added in v1.0.6

type AckProbeInfo = ackhandler.AckProbeInfo

type AckReorderingMode added in v1.0.3

type AckReorderingMode = ackhandler.AckReorderingMode

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 ClientHandshake

type ClientHandshake struct {
	// InitialRTT supplies a local estimate until the first RTT measurement.
	// Zero retains native initialization. It does not advertise a parameter.
	InitialRTT time.Duration
	// OnEarlyDataRejected observes a client's TLS 0-RTT rejection. It runs on
	// the connection loop; callbacks must return promptly and not reenter it.
	OnEarlyDataRejected func(*Conn)
	// ResetStreamsOnEarlyDataRejection makes the fresh 1-RTT stream maps
	// available before OnApplicationReady after verified TLS and final transport
	// parameters. The application must recreate all rejected protocol state.
	// False retains the explicit NextConnection transition.
	ResetStreamsOnEarlyDataRejection bool
	// InitialPTOMultiplier scales the initial estimate before any measurement.
	// Zero retains the native factor of two. Positive values are 1..16.
	InitialPTOMultiplier uint32
	// CompatibleVersionNegotiation enables RFC 9368 / RFC 9369 client switching
	// between v1 and v2, with authenticated downgrade checks. A layout can supply
	// version_information ordering and GREASE; otherwise Config.Versions is used.
	CompatibleVersionNegotiation bool
	// NewInitialPacketNumber selects a fresh start for each new connection.
	NewInitialPacketNumber func() (uint64, error)
	// OmitMaxUDPPayloadSize selects the protocol default and requires a matching receive buffer.
	OmitMaxUDPPayloadSize bool
	// OmitLegacyResetStreamAt advertises only the current reliable-reset parameter.
	OmitLegacyResetStreamAt bool

	// NewTransportParameters produces a private layout for every handshake attempt,
	// including a restart after version negotiation. It receives the actual version.
	NewTransportParameters func(Version) (*transportparams.Layout, error)

	// MaxUDPPayloadSize must fit Transport.ReceivePacketSize. Zero preserves native.
	MaxUDPPayloadSize uint64
	// ActiveConnectionIDLimit sets the receive-side connection ID limit (at least 2).
	ActiveConnectionIDLimit uint64
	// MaxAckDelay sets the acknowledgment scheduling bound.
	// The protocol default is omitted automatically by the transport codec.
	MaxAckDelay time.Duration
	// AckPolicy controls local Application Data ACK scheduling. Nil keeps native behavior.
	AckPolicy *AckPolicy
	// LegacyAckFrequencyMinDelay enables the legacy ACK_FREQUENCY receive
	// format and advertises its min_ack_delay (0xff02de1a). Zero disables it.
	// Positive values must be whole microseconds no larger than MaxAckDelay.
	LegacyAckFrequencyMinDelay time.Duration
	// PeerAckFrequencyPolicy opts into sending legacy ACK_FREQUENCY requests
	// after a peer advertises its legacy minimum. Nil sends no requests.
	PeerAckFrequencyPolicy PeerAckFrequencyPolicy
	// InitialCongestionWindowPackets selects the initial congestion window in
	// units of the accounting segment (the initial MTU unless fixed below).
	// Zero retains the native packet count.
	InitialCongestionWindowPackets uint32
	// MaxCongestionWindowPackets sets a ceiling in accounting segments. Zero keeps
	// the native 10000-segment ceiling; -1 removes that ceiling. Internal packet
	// history and integer safety limits still apply. Positive values are 2..2^32-1.
	MaxCongestionWindowPackets int64
	Pacing                     *PacingConfig
	ProportionalRateReduction  bool
	RecoveryBurstPackets       uint32
	// PersistentCongestionThreshold collapses the window after this many base
	// PTO durations of consecutively lost ack-eliciting packets. Zero disables it.
	PersistentCongestionThreshold uint32
	// CongestionControl selects Reno, RFC 9438 CUBIC, or fixed-point byte-mode
	// CUBIC. Zero retains native Reno. Pacing and loss detection are independent.
	CongestionControl CongestionControlAlgorithm
	// SlowStart selects classic byte growth or original HyStart (not HyStart++).
	SlowStart SlowStartAlgorithm
	// CongestionControlSegmentSize fixes the accounting segment independently of
	// path MTU. Zero follows the MTU; explicit values must fit 1200..65527.
	CongestionControlSegmentSize uint16
	// CongestionControlConnections selects 1..16 emulated connections for byte-mode
	// CUBIC. Zero means one. Other algorithms accept only zero or one.
	CongestionControlConnections uint32
	// ReceiveWindowUpdateDivisor refreshes credit after more than 1/divisor
	// of the receive window is consumed. Zero retains the native policy.
	ReceiveWindowUpdateDivisor uint32
	// AckOnlyPingThreshold counts consecutive ACK-only packets before adding
	// a PING. Zero retains native behavior; -1 disables these extra PINGs.
	AckOnlyPingThreshold int
	// AckOnlyMaxDataThreshold requests a repeat of the current connection credit
	// after this many ACK-only packets, instead of injecting a periodic PING.
	// Zero disables this policy. It never grants additional receive credit.
	AckOnlyMaxDataThreshold int
	// AckProbePolicy optionally adds PING to an otherwise ACK-only packet. It
	// replaces periodic probes. Callbacks must not block or reenter the connection.
	AckProbePolicy func(AckProbeInfo) bool
	// PacketNumberLengthPolicy chooses encoded packet-number bytes from a live
	// snapshot. Unsafe short results are increased; invalid results use native.
	PacketNumberLengthPolicy func(PacketNumberLengthInfo) uint8
	// DisableConnectionIDRotation retains the active ID on an unchanged path.
	// Peer-requested retirement and path migration still select a replacement.
	DisableConnectionIDRotation bool
	// SortConnectionIDFrames orders queued NEW_CONNECTION_ID frames by ascending
	// sequence number while preserving positions of other control-frame types.
	SortConnectionIDFrames bool
	// OnApplicationReady runs once after verified TLS and peer transport
	// parameters, before releasing HandshakeComplete and sending the next flight.
	// It must not block, reenter Dial, call CloseWithError or use blocking Write.
	// OpenUniStream and SendStream.TryWriteAll may be used to stage initial data.
	OnApplicationReady func(*Conn)
	// OnEarlyDataReady runs once with restored transport parameters and 0-RTT
	// write keys, before releasing the early connection. By default it stages
	// data before the first Initial flight is packetized. FlushEarlyData selects
	// a separate send opportunity after currently sendable Initial data instead.
	// This does not authenticate the server. The callback runs on the connection
	// loop and must not block, reenter Dial, CloseWithError or TryWriteStreamBatch.
	// OpenUniStream and SendStream.TryWriteAll may stage bounded initial data.
	// Nil retains upstream early-connection readiness and scheduling.
	OnEarlyDataReady func(*Conn)
	// FlushEarlyData, when OnEarlyDataReady is set, packetizes sendable Initial
	// data before invoking that callback, then flushes sendable staged data before
	// releasing the early connection. Pacing, congestion and queue limits retain
	// authority; no delivery or fixed packet count is guaranteed. False stages
	// the callback's data before the first Initial flight, without a flush barrier.
	FlushEarlyData bool
	// CoalesceSmallEarlyPackets permits protected 0-RTT packets in a datagram
	// remainder below the native 128-byte coalescing threshold. Actual header,
	// AEAD and header-protection sample limits still apply. Other packet spaces
	// and the default coalescing threshold remain unchanged.
	CoalesceSmallEarlyPackets bool
	// InitialCryptoCoalescingBarrier keeps later packet spaces out of an Initial
	// datagram while more Initial CRYPTO remains queued. It does not wait for an
	// ACK or handshake confirmation. False retains the native normal-send path.
	InitialCryptoCoalescingBarrier bool
	// StreamSchedulingByCreation services writable streams in their creation
	// order instead of urgency/incremental queues. Retransmissions precede new
	// data unless PrioritizeFinishedStreams also admits finished writes to that
	// class. Blocked streams never block later streams. This
	// takes precedence over SetPriority and retains state only for open streams.
	StreamSchedulingByCreation bool
	// PrioritizeFinishedStreams groups new bytes and FIN of write-closed
	// streams with retransmissions, preserving creation order within that
	// class. Ordinary new data follows. Applies only to creation-order
	// scheduling; false retains retransmissions-before-new-data behavior.
	PrioritizeFinishedStreams bool
	// OmitInitialAckOnHandshake omits an ACK-only Initial when client
	// Handshake data is ready. Initial keys are discarded when Handshake sends.
	OmitInitialAckOnHandshake bool
	InitialPacketProtection   *InitialPacketProtection
	// InitialPaddingMode chooses encrypted packet padding or a zero datagram tail.
	InitialPaddingMode InitialPaddingMode
	// HandshakeAckBeforeData sends queued Initial/Handshake ACKs in a separate
	// datagram before the first local Handshake CRYPTO. It inserts no time delay
	// and does not alter TLS verification or native Initial key disposal.
	HandshakeAckBeforeData bool
	// NewInitialDestinationConnectionIDLength selects a fresh length (8..20).
	NewInitialDestinationConnectionIDLength func() (int, error)
	// NewInitialPacketSize selects the UDP payload floor from the actual remote
	// address for each dial attempt. Results must fit 1200..MaxPacketBufferSize.
	NewInitialPacketSize func(net.Addr) (uint16, error)

	// DisableClientHelloScrambling disables upstream SNI/ECH CRYPTO fragmentation.
	DisableClientHelloScrambling bool
	// InitialCryptoLayout optionally chooses ordered CRYPTO ranges and packet
	// boundaries for the first complete ClientHello. Nil results retain native
	// preparation. The callback runs in the send loop and must not block or
	// reenter the connection. See InitialCryptoLayoutInfo for validation rules.
	InitialCryptoLayout func(InitialCryptoLayoutInfo) [][]CryptoRange
	// InitialCryptoRecovery enables byte-range recovery and late-ACK retirement
	// for client Initial CRYPTO. Nil policies below select sequential lost ranges.
	InitialCryptoRecovery bool
	// InitialCryptoRecoveryLayout re-packetizes lost Initial bytes against live
	// budgets. Length may include later Initial messages; offsets remain absolute.
	// It requires InitialCryptoRecovery and follows InitialCryptoLayout validation.
	// It runs in the send loop and must not block or reenter the connection.
	InitialCryptoRecoveryLayout func(InitialCryptoLayoutInfo) [][]CryptoRange
	// InitialCryptoProbePackets selects the Initial PTO allowance and preparation
	// batch. Zero keeps native allowance and a one-packet batch; maximum is two
	// datagrams as specified by RFC 9002, Section 6.2.4.
	InitialCryptoProbePackets uint8
	// InitialProbeSkipPacketNumber skips one number on an Initial PTO to solicit
	// an immediate peer ACK. The skipped-number ACK defense remains enforced.
	InitialProbeSkipPacketNumber bool
	// InitialCryptoResendOnPeerProbe reschedules sent, unacknowledged Initial
	// bytes on a peer PING or a CRYPTO frame that delivers no new TLS bytes.
	InitialCryptoResendOnPeerProbe bool
	// HandshakeCryptoRecovery tracks Handshake CRYPTO byte ranges and retains
	// original PTO packet acknowledgments. Initial recovery is independent.
	HandshakeCryptoRecovery bool
	// StreamDataRecovery retires STREAM ranges acknowledged in any transmission
	// and preserves original PTO callbacks. Disabled retains native frame recovery.
	StreamDataRecovery bool
	// StreamLossRetention selects how long lost STREAM packet ACK metadata remains
	// useful. Nil keeps it until its data is acknowledged or tracking reaches the
	// engine's packet limit. The callback runs in the send loop and must not block.
	StreamLossRetention func(StreamLossInfo) bool
	// HandshakeCryptoResendOnPeerProbe reschedules unacknowledged Handshake
	// CRYPTO on PING or non-progressing CRYPTO, including duplicate Initial input.
	HandshakeCryptoResendOnPeerProbe bool
	// HandshakeProbePackets overrides the Handshake PTO allowance (0..2).
	// Zero preserves the engine's native allowance.
	HandshakeProbePackets uint8
	// ApplicationProbePackets overrides the Application Data PTO allowance
	// (0..2). Zero preserves the engine's native allowance.
	ApplicationProbePackets uint8
	// CoalescePTOProbes shares a datagram budget across timed packet-number
	// spaces, including retained crypto timer baselines and available 0-RTT data.
	CoalescePTOProbes bool
	// InitialACKResetsPTO resets PTO backoff on a new Initial ACK, independently
	// of peer address validation. False retains native RFC recovery behavior.
	InitialACKResetsPTO bool
	// HandshakeProbeSkipPacketNumber skips one Handshake number on PTO.
	HandshakeProbeSkipPacketNumber bool
	// ApplicationProbeSkipPacketNumber independently controls the Application
	// PTO gap. Nil retains DisablePacketNumberSkipping's native authority.
	ApplicationProbeSkipPacketNumber *bool
	// HandshakeProbeOnlyWithData suppresses empty follow-up Handshake probes
	// after the first PTO packet. Queued CRYPTO still uses the full allowance.
	HandshakeProbeOnlyWithData bool
	// PeerPacketRecoveryPolicy selects responses to routed packets whose keys
	// are unavailable. Nil preserves native behavior. Authentication failures
	// never invoke it. The callback runs in the send loop and must not block.
	PeerPacketRecoveryPolicy func(PeerPacketInfo) PeerPacketRecovery
	// EarlyDataResendOnPeerCrypto reschedules outstanding early-data packets on
	// authenticated Initial CRYPTO that does not advance TLS. It stops after
	// the first Application ACK and never treats a PING as an early-data hint.
	EarlyDataResendOnPeerCrypto bool
	// ImmediateACKOnPeerPing acknowledges an authenticated 1-RTT PING without
	// waiting for the normal ACK threshold. Initial/Handshake already ACK at once.
	ImmediateACKOnPeerPing bool

	StreamReceiveWindows *StreamReceiveWindows
	TransportParameters  *transportparams.Layout
	NewTLSClient         tlsquic.NewClient
	// WrapTLSClient decorates the selected TLS factory for one connection. The
	// supplied factory is non-nil and receives the normalized private TLS config.
	// The decorator runs before TLS starts and must not perform network I/O.
	// Nil preserves the selected native or application-provided factory.
	WrapTLSClient func(*Conn, tlsquic.NewClient) tlsquic.NewClient
	// MaxDatagramFrameSize overrides the advertised limit when datagrams are
	// enabled. Zero preserves upstream; values must fit a QUIC integer.
	MaxDatagramFrameSize uint64
	// InitialDestinationConnectionIDLength, when nonzero, must be 8 through 20.
	InitialDestinationConnectionIDLength int
	// InitialPacketNumber is used on the first connection attempt only.
	InitialPacketNumber uint64
	// SeparatePacketNumberSpaces starts Handshake and Application Data at zero,
	// independently of Initial. 0-RTT and 1-RTT share Application Data.
	SeparatePacketNumberSpaces bool
	// DisablePacketNumberSkipping suppresses artificial Application Data gaps,
	// including PTO skips unless ApplicationProbeSkipPacketNumber overrides them.
	// The native skipped-ACK defense remains the default.
	DisablePacketNumberSkipping bool
}

ClientHandshake exposes client-only protocol controls. Nil preserves upstream behavior. It contains no browser defaults or preset selection. Extension values and TLS templates are supplied by the application. Server behavior is unchanged.

func (*ClientHandshake) Clone

func (h *ClientHandshake) Clone() *ClientHandshake

Clone snapshots mutable configuration while retaining callback identity.

func (*ClientHandshake) Validate added in v1.0.6

func (h *ClientHandshake) Validate() error

Validate checks standalone client controls without invoking per-attempt factories. Config validation additionally checks runtime window/datagram coupling.

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 reports whether the remote address was verified by a valid address validation token,
	// including a token received in a NEW_TOKEN frame.
	// The Retry mechanism costs one network roundtrip and is only used when
	// [Transport.VerifySourceAddress] requests it.
	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.

type Config

type Config struct {
	// ServerTransportParameters optionally controls the server's parameter encoding
	// and advertises application-owned extensions. It does not implement those
	// extensions. Nil retains native encoding; client layouts use ClientHandshake.
	ServerTransportParameters *transportparams.Layout
	// PeerTransportParameterIDs selects unrecognized extension values to retain
	// from the current handshake for PeerTransportParameter. Nil retains none.
	// Values are not restored from session tickets or interpreted by the engine.
	PeerTransportParameterIDs []uint64
	// ValidatePeerTransportParameters validates private copies of the selected
	// unrecognized parameters before accepting current-handshake parameters.
	// It runs before peer authentication and must not block or reenter QUIC.
	// An error rejects the handshake with TRANSPORT_PARAMETER_ERROR. Nil does
	// not interpret extensions; session-ticket restoration never calls it.
	ValidatePeerTransportParameters func([]transportparams.Parameter) error
	// ClientHandshake provides optional application-owned client handshake controls.
	ClientHandshake *ClientHandshake
	// LegacyAckFrequencyMinDelay enables the legacy receive format and advertises
	// its minimum on either endpoint. Zero leaves it disabled. ClientHandshake's
	// client-only value, when set, overrides this value. Whole microseconds only.
	LegacyAckFrequencyMinDelay time.Duration

	// 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
	// RequireStreamCreditRelease requires the application to release the credit of streams opened by the peer.
	// By default, the peer is allowed to open a new stream as soon as one of its streams completes.
	// If set, a completed stream keeps counting towards MaxIncomingStreams and MaxIncomingUniStreams
	// until the application calls ReleaseStreamCredit on it.
	RequireStreamCreditRelease bool
	// 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.
	// If set to 0, it defaults to 1280 bytes and falls back to 1200 bytes if the first write at that size
	// returns a "message too long" error. An explicitly set value is kept as the lower limit;
	// a "message too long" error at that size fails the handshake instead.
	// 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-09.
	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 CongestionControlAlgorithm added in v1.0.11

type CongestionControlAlgorithm = congestion.Algorithm

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, packets will be read in batches, and OOBCapablePacketConn.WriteMsgUDP will be used instead of net.PacketConn.WriteTo. 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

ConnectionStats returns statistics about the connection. It can be called concurrently with other connection operations.

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) PeerTransportParameter added in v1.0.25

func (c *Conn) PeerTransportParameter(id uint64) ([]byte, bool)

PeerTransportParameter returns a private copy of an unrecognized extension selected by Config.PeerTransportParameterIDs. It reports only the current verified handshake, never cached 0-RTT state. Known parameters are interpreted by the engine and are not returned here. Values are otherwise uninterpreted.

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.

func (*Conn) TryWriteStreamBatch added in v1.0.15

func (c *Conn) TryWriteStreamBatch(writes []StreamWrite) (int, error)

TryWriteStreamBatch queues writes in order in one connection-loop turn, before packetization can consume them. It waits for that turn, never for stream credit or another writer. The result counts fully accepted elements; retry only the remaining suffix after ErrWouldBlock. FIN is queued with its element's bytes. Packet size, pacing and flow control still determine actual packet boundaries. At most 64 elements and 1 MiB of data are accepted per call. Only already opened locally initiated streams are supported. Caller buffers may be reused on return.

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
	}
	// RequireStreamCreditRelease is true if Config.RequireStreamCreditRelease was set.
	RequireStreamCreditRelease 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 {
	// RTTMeasured is true after a valid RTT sample on the active path.
	// Local initial estimates and token restoration do not set it.
	RTTMeasured bool
	// 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

	// CongestionWindow is the local sender's congestion window on the active
	// network path, in bytes. It limits bytes in flight and includes QUIC
	// packet overhead, excluding UDP and IP headers.
	CongestionWindow uint64

	// 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 CryptoRange added in v1.0.21

type CryptoRange struct {
	// Offset is the zero-based position in the Initial CRYPTO stream.
	Offset int
	// Length is the number of ClientHello bytes in this range.
	Length int
}

CryptoRange selects Initial CRYPTO bytes by their absolute stream offset. Length must be positive. Offsets and lengths exclude CRYPTO frame headers.

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. EarlyListener.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 InitialCryptoLayoutInfo added in v1.0.21

type InitialCryptoLayoutInfo struct {
	// Length includes the four-byte TLS handshake header. A recovery callback
	// receives the retained Initial stream length, including later messages.
	Length int
	// SNIOffset is the hostname position, or -1 when SNI is absent.
	SNIOffset int
	// SNILength is the hostname length, or zero when SNI is absent.
	SNILength int
	// ECHOffset is the extension-type position, or -1 when ECH is absent.
	ECHOffset int
	// ECHLength includes the extension type, length and value, or zero if absent.
	ECHLength int
	// PacketSizeLimit includes the QUIC header but excludes AEAD expansion.
	PacketSizeLimit int
	// FrameBudget is the space left after the QUIC header and any ACK frame.
	FrameBudget int
	// Remaining is a private snapshot of unsent ClientHello ranges in ascending
	// offset order. It can be changed by the callback without affecting recovery.
	Remaining []CryptoRange
}

InitialCryptoLayoutInfo describes the first complete ClientHello and the packet available to carry it. InitialCryptoLayout runs before each packet while the first ClientHello has unsent bytes. Its result must cover Remaining exactly once; empty, overlapping, out-of-bounds or incomplete layouts fail before serialization. The engine sends only the first group, then invokes the callback again with the actual unsent ranges and next packet's budgets. A group may be split if it exceeds the frame budget. Nil initially retains native preparation; after a custom group it selects sequential unsent ranges. Subsequent TLS messages retain native first-send behavior. Optional InitialCryptoRecoveryLayout independently selects retransmitted byte ranges.

type InitialPacketProtection added in v1.0.6

type InitialPacketProtection struct {
	MinCryptoSplits, MaxCryptoSplits     int
	MinPingFrames, MaxPingFrames         int
	MinFirstFrameSize, MaxFirstFrameSize int
}

InitialPacketProtection controls optional client Initial CRYPTO fragmentation, PING insertion, padding distribution and frame shuffling. Counts are inclusive ranges of split attempts and PINGs, bounded by available padding. A zero first frame range leaves the native cross-packet CRYPTO layout. No browser values are selected by the engine. Nil preserves native behavior.

type InitialPaddingMode added in v1.0.6

type InitialPaddingMode uint8

InitialPaddingMode selects where client datagrams containing Initial packets carry their size padding. The mandatory header-protection sample padding stays encrypted in the packet in either mode.

const (
	// InitialPaddingPacket retains native encrypted PADDING frames.
	InitialPaddingPacket InitialPaddingMode = iota
	// InitialPaddingDatagram appends zeros after coalesced long-header packets.
	// When a short-header packet is last, its padding is encrypted inside it.
	InitialPaddingDatagram
)

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, packets will be read in batches, and OOBCapablePacketConn.WriteMsgUDP will be used instead of net.PacketConn.WriteTo. 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 protocol using tls.Config.NextProtos. The Config may be nil, in which 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. 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, packets will be read in batches, and OOBCapablePacketConn.WriteMsgUDP will be used instead of net.PacketConn.WriteTo to write packets.

type PacingAlgorithm added in v1.0.14

type PacingAlgorithm = congestion.PacingAlgorithm

type PacingConfig added in v1.0.14

type PacingConfig = congestion.PacingConfig

PacingConfig is snapshotted with ClientHandshake. Applications select policy.

type PacketNumberLengthInfo added in v1.0.6

type PacketNumberLengthInfo = ackhandler.PacketNumberLengthInfo

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, the path cannot be successfully probed again with Path.Probe.

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. It is possible to switch back to the old path without probing it again, until it is closed.

type PeerAckFrequency added in v1.0.9

type PeerAckFrequency struct {
	AckElicitingThreshold uint64
	MaxAckDelay           time.Duration
	IgnoreOrder           bool
}

PeerAckFrequency requests the peer's legacy Application Data ACK behavior.

type PeerAckFrequencyInfo added in v1.0.9

type PeerAckFrequencyInfo struct {
	CongestionWindow uint64
	MaxDatagramSize  uint64
	SmoothedRTT      time.Duration
	PeerMinAckDelay  time.Duration
	PeerMaxAckDelay  time.Duration
	Current          PeerAckFrequency // Last acknowledged request, initially the protocol defaults.
}

PeerAckFrequencyInfo is a connection-loop snapshot, supplied only after the handshake and negotiation of the peer's legacy min_ack_delay parameter.

type PeerAckFrequencyPolicy added in v1.0.9

type PeerAckFrequencyPolicy func(PeerAckFrequencyInfo) (target PeerAckFrequency, send bool)

PeerAckFrequencyPolicy returns a target and whether it needs to be sent. It must not block or reenter the connection. Invalid targets fail the local connection. Targets require a positive QUIC integer tolerance and a whole microsecond delay at least as large as the negotiated peer minimum. Delays must fit QUIC's max_ack_delay duration range (16383ms). A valid target is required even when send is false, for conservative PTO sizing. The engine handles sequencing, one outstanding frame, ACK/loss and PTO bounds. A shared policy can run concurrently on different connections.

type PeerPacketInfo added in v1.0.23

type PeerPacketInfo struct {
	// PacketType identifies the parsed QUIC encryption level.
	PacketType qlog.PacketType
	// KeysDropped distinguishes retired keys from keys not yet available.
	KeysDropped bool
	// ReceivedFirstPacket reports arrival of a successfully decrypted peer packet.
	ReceivedFirstPacket bool
	// HandshakeComplete reports completion of verified TLS.
	HandshakeComplete bool
	// BufferedHandshakePackets and BufferedApplicationPackets count packets
	// queued before the current packet, independently for each encryption level.
	BufferedHandshakePackets, BufferedApplicationPackets int
}

PeerPacketInfo describes a routed peer packet whose keys are unavailable. Authentication failures never reach this policy.

type PeerPacketRecovery added in v1.0.23

type PeerPacketRecovery struct {
	// ResendInitialCrypto schedules sent, unacknowledged Initial bytes.
	ResendInitialCrypto bool
	// ResendEarlyData discards outstanding 0-RTT packet accounting and schedules
	// their recovery tokens again, without a congestion loss or TLS restart.
	ResendEarlyData bool
	// ProbeHandshake schedules PING if Handshake keys are still available.
	ProbeHandshake bool
}

PeerPacketRecovery selects transport responses to a missing-key hint. Neither response authenticates the packet or delivers its payload to TLS.

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. ReceiveStream.Read will unblock immediately, and future calls to it will fail. When called multiple times or after ReceiveStream.Read returns 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 ReceiveStream.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) ReleaseStreamCredit

func (s *ReceiveStream) ReleaseStreamCredit()

ReleaseStreamCredit allows the peer to open a new stream in place of this one. It only has an effect if Config.RequireStreamCreditRelease is set. The peer is granted the new stream credit once the stream has completed and ReleaseStreamCredit has been called, in any order. Calling it multiple times is a no-op.

func (*ReceiveStream) SetReadDeadline

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

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

func (*ReceiveStream) SetReceiveFinalSizeCallback

func (s *ReceiveStream) SetReceiveFinalSizeCallback(callback func(int64))

SetReceiveFinalSizeCallback sets a callback that is called when the receive stream's final size is known. The final size is learned from a FIN or RESET_STREAM frame. Most applications don't need this. It is mainly useful for protocol layers that need exact stream final sizes, such as WebTransport flow control accounting. If the final size is already known, the callback is called before this method returns. When the final size is learned later, the callback is called from the connection's event loop and must not block. The callback is not called if the connection is closed before the final size is known. Setting a nil callback removes it if the final size is not yet known.

func (*ReceiveStream) StreamID

func (s *ReceiveStream) StreamID() StreamID

StreamID returns the stream ID.

func (*ReceiveStream) WaitForReadReady

func (s *ReceiveStream) WaitForReadReady(ctx context.Context, ready <-chan struct{}) error

WaitForReadReady waits for another protocol stream to make buffered data decodable. It consumes no stream bytes and honors read cancellation, reset, connection shutdown and changes to the read deadline. FIN alone does not end the wait. Calls must be serialized with Read and Peek.

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. SendStream.Write will unblock immediately, and future calls to it will fail. When called multiple times it is a no-op. When called after SendStream.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 SendStream.Write are not permitted after calling Close. It must not be called concurrently with SendStream.Write. It must not be called after calling SendStream.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 SendStream.Close or SendStream.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, which is ErrStreamClosed if SendStream.Close was called.

func (*SendStream) SetPriority

func (s *SendStream) SetPriority(urgency int8, incremental bool)

SetPriority sets the scheduling priority for data sent on the stream. It uses the urgency and incremental parameters defined by RFC 9218. Urgency is clipped to the range 0 through 7, with lower values taking priority. Within an urgency level, incremental streams are scheduled round-robin, while non-incremental streams are scheduled by stream ID.

The default priority is urgency 3 with incremental set to true. RFC 9218 instead defaults incremental to false.

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 SendStream.Write calls and any currently blocked call. Even if write times out, it may return n > 0, indicating that some data was successfully written. A zero value for t means SendStream.Write will not time out.

func (*SendStream) StreamID

func (s *SendStream) StreamID() StreamID

StreamID returns the stream ID.

func (*SendStream) TryWriteAll

func (s *SendStream) TryWriteAll(p []byte) error

TryWriteAll writes data to the stream if it can be queued immediately. It doesn't block for flow control credit and doesn't respect the write deadline. If the entire slice can't be queued immediately, it queues nothing and returns ErrWouldBlock.

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. If the stream was closed, the error is ErrStreamClosed.

func (*SendStream) WriteWithLimit

func (s *SendStream) WriteWithLimit(p []byte, limiter func(maxBytes int) int) (int, error)

WriteWithLimit writes data to the stream, subject to an additional send limit. During packetization, limiter receives the bytes allowed for the next STREAM frame after QUIC flow control and returns how many may be sent. Returning n in [0, maxBytes] commits n bytes of limiter credit; the limiter is not called again when those bytes are retransmitted. Values outside [0, maxBytes] are clamped. A short result returns the accepted prefix and ErrWriteLimitReached; the caller can wait for external credit and retry the suffix. QUIC blocking behaves like SendStream.Write. limiter can run multiple times on another goroutine while QUIC send flow-control accounting is locked. It must be concurrency-safe and must not block or call QUIC methods. A nil limiter behaves like SendStream.Write.

type SessionMetadata added in v1.0.19

type SessionMetadata struct {
	Version Version
	RTT     time.Duration
	// ConnectionID identifies the Initial key context of the issuing connection.
	// It is local metadata and does not change the opaque server ticket.
	ConnectionID        []byte
	TransportParameters []byte
}

SessionMetadata describes locally remembered client transport state. RTT is zero without an actual measurement; it is never an advertised parameter. TransportParameters contains the serialized remembered 0-RTT limits and is copied, so a caller cannot mutate cached TLS metadata.

func ClientSessionMetadata added in v1.0.19

func ClientSessionMetadata(session *tls.ClientSessionState) (SessionMetadata, bool)

ClientSessionMetadata reads QUIC's local SessionState.Extra entry. It does not validate TLS ticket lifetime, certificates or authenticity. TLS retains those checks. Earlier version-bearing metadata remains readable with a zero RTT.

type SlowStartAlgorithm added in v1.0.11

type SlowStartAlgorithm = congestion.SlowStart

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 Stream.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) ReleaseStreamCredit

func (s *Stream) ReleaseStreamCredit()

ReleaseStreamCredit allows the peer to open a new stream in place of this one, once both directions of the stream have completed. See ReceiveStream.ReleaseStreamCredit for more details. For streams opened by us, it is a no-op.

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 Stream.SetReadDeadline and Stream.SetWriteDeadline.

func (*Stream) SetPriority

func (s *Stream) SetPriority(urgency int8, incremental bool)

SetPriority sets the scheduling priority for data sent on the stream. See SendStream.SetPriority for details.

func (*Stream) SetReadDeadline

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

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

func (*Stream) SetReceiveFinalSizeCallback

func (s *Stream) SetReceiveFinalSizeCallback(callback func(int64))

SetReceiveFinalSizeCallback sets a callback that is called when the receive side's final size is known. See ReceiveStream.SetReceiveFinalSizeCallback for more details. Most applications don't need this. It is mainly useful for protocol layers that need exact stream final sizes, such as WebTransport flow control accounting.

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 Stream.Write calls. See SendStream.SetWriteDeadline for more details.

func (*Stream) StreamID

func (s *Stream) StreamID() StreamID

StreamID returns the stream ID.

func (*Stream) TryWriteAll

func (s *Stream) TryWriteAll(p []byte) error

TryWriteAll writes data to the stream if it can be queued immediately. See SendStream.TryWriteAll for more details.

func (*Stream) WaitForReadReady

func (s *Stream) WaitForReadReady(ctx context.Context, ready <-chan struct{}) error

WaitForReadReady preserves the receive side's cancellation/deadline semantics. See ReceiveStream.WaitForReadReady.

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. If the stream was closed, the error is ErrStreamClosed.

func (*Stream) WriteWithLimit

func (s *Stream) WriteWithLimit(p []byte, limiter func(maxBytes int) int) (int, error)

WriteWithLimit writes data to the stream, subject to an additional send limit. See SendStream.WriteWithLimit for more details.

type StreamError

type StreamError struct {
	StreamID  StreamID
	ErrorCode StreamErrorCode
	Remote    bool
}

A StreamError is used to signal stream cancellations. It can be returned by stream methods such as ReceiveStream.Read, SendStream.Write, Stream.Read, and Stream.Write.

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 open streams has reached the peer's stream limit.

func (StreamLimitReachedError) Error

func (e StreamLimitReachedError) Error() string

type StreamLossInfo added in v1.0.23

type StreamLossInfo = ackhandler.StreamLossInfo

StreamLossInfo describes lost STREAM packet ACK metadata supplied to ClientHandshake.StreamLossRetention. Its counters are transport observations.

type StreamReceiveWindows

type StreamReceiveWindows struct{ BidiLocal, BidiRemote, Uni uint64 }

StreamReceiveWindows overrides the three initial receive windows independently. Local and Remote describe the initiator relative to this client. Zero explicitly advertises zero credit. The runtime flow controllers use the same values.

type StreamWrite added in v1.0.15

type StreamWrite struct {
	StreamID StreamID
	Data     []byte
	Fin      bool
}

StreamWrite stages bytes and optionally FIN on an already opened local stream.

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 {
	// ReceivePacketSize optionally increases the UDP receive limit using the
	// existing large-buffer pool. Zero retains the upstream receive size.
	ReceivePacketSize int

	// 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 connection implements [OOBCapablePacketConn],
	// 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 [net.PacketConn.ReadFrom],
	// [net.PacketConn.WriteTo], [OOBCapablePacketConn.ReadMsgUDP], or
	// [OOBCapablePacketConn.WriteMsgUDP] 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 by [Config.Tracer]
	// * 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.
	// The [qlogwriter.Recorder] is closed 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 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 Version

type Version = protocol.Version

A Version is a QUIC version number.

func SessionVersion added in v1.0.18

func SessionVersion(session *tls.ClientSessionState) (Version, bool)

SessionVersion returns the negotiated QUIC version recorded locally alongside a client session ticket. It does not validate ticket expiry or authenticity; the TLS engine retains all session validation. Unmarked/invalid states return false. The metadata uses SessionState.Extra and does not change ticket bytes.

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
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.
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.
qpack
Package qpack adds RFC 9204 dynamic tables around the official static table and Huffman codec.
Package qpack adds RFC 9204 dynamic tables around the official static table and Huffman codec.
utils/linkedlist
Package list implements a doubly linked list.
Package list implements a doubly linked list.
interop
client command
server command
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.
Package tlsquic defines the crypto/tls event interface used by QUIC.
Package tlsquic defines the crypto/tls event interface used by QUIC.
Package transportparams controls the encoding of client transport parameters.
Package transportparams controls the encoding of client transport parameters.

Jump to

Keyboard shortcuts

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