quic

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 41 Imported by: 0

README

quic godoc test Coverage Status Release License

fork of github.com/quic-go/quic-go and github.com/quic-go/webtransport-go supporting fingerprinting and browser impersonation

  • . github.com/quic-go/quic-go v0.61.0 (with the fork's fingerprinting / browser-mimicry changes re-applied on top)
  • ./qpack github.com/quic-go/qpack v0.6.0
  • ./webtransport github.com/quic-go/webtransport-go v0.12.0 (with the fork's fingerprinting / browser-mimicry changes re-applied on top)
  • ./webtransport/httpsfv github.com/dunglas/httpsfv 4cd96cab33c4a28ca20f9a9a92d43ce85a9bf7ad

changes from github.com/pagpeter/quic-go v0.0.0-20260120153640-0de4e3b8377b are ported

Features

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
)

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 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 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.Config.ClientInfo.Context.

Functions

This section is empty.

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
	// Version is the QUIC version of the client's Initial packet.
	Version Version
	// InitialPacketSize is the size of the client's first Initial packet.
	InitialPacketSize int
	// SrcConnectionID is the source connection ID chosen by the client.
	SrcConnectionID ConnectionID
	// DestConnectionID is the destination connection ID the client addressed its first Initial to
	// (before any Retry-based swapping).
	DestConnectionID ConnectionID
	// ClientHello contains the raw ClientHello bytes, if they could be extracted from the client's
	// first Initial packet. This is best-effort:
	// it is nil if the ClientHello is not (yet) contained in the first packet, was split across
	// multiple packets, or could not be decrypted.
	// The complete ClientHello (accumulated over all fragments) is available via
	// [ConnectionState.ClientHello] once the connection is established.
	ClientHello []byte
}

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 {
	// 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-09.
	EnableStreamResetPartialDelivery bool
	// GreaseQuicBit advertises the grease_quic_bit transport parameter (RFC 9287).
	// It is used to elicit the QUIC bit greasing behavior from peers that support it.
	// When a peer advertises grease_quic_bit, incoming packets with the QUIC bit set
	// are accepted (as required by RFC 9287).
	GreaseQuicBit bool
	// Fingerprint configures how the client presents itself on the wire (client-side only).
	// It allows mimicking the connection establishment of specific QUIC implementations,
	// e.g. browsers. See [FingerprintConfig] for details.
	Fingerprint *FingerprintConfig

	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 whether the peer advertised support for QUIC datagrams (RFC 9221).
	// When true, datagrams can be sent using the Conn's SendDatagram method.
	// This is a unilateral declaration by the peer - receiving datagrams is only possible if
	// datagram support was enabled locally via Config.EnableDatagrams.
	SupportsDatagrams bool
	// SupportsStreamResetPartialDelivery indicates whether the peer advertised support for QUIC Stream Resets with Partial Delivery.
	SupportsStreamResetPartialDelivery 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
	// ClientHello contains the raw ClientHello bytes for TLS fingerprinting (server-side only)
	ClientHello []byte
	// PeerTransportParameters contains the transport parameters received from the peer,
	// in parsed form. It is nil until the handshake processed them.
	// The type is from the internal wire package; its exported fields and methods are usable directly.
	PeerTransportParameters *wire.TransportParameters
	// PeerTransportParametersRaw contains the raw transport parameter bytes received from the peer,
	// exactly as they appeared in the TLS handshake. This preserves the parameter order,
	// including GREASE and unknown parameters, and is intended for fingerprinting.
	// It is nil until the handshake processed them.
	PeerTransportParametersRaw []byte
	// SrcConnectionID is the source connection ID of the client's first Initial packet.
	// For the server, this is the connection ID chosen by the client.
	// For the client, this is the client's own source connection ID.
	SrcConnectionID ConnectionID
	// DestConnectionID is the destination connection ID of the client's first Initial packet
	// (before any Retry-based swapping).
	DestConnectionID ConnectionID
	// InitialPacketSize is the size of the client's first Initial packet.
	InitialPacketSize int
	// GreaseQuicBit indicates whether the peer advertised the grease_quic_bit transport
	// parameter (RFC 9287).
	GreaseQuicBit bool
}

ConnectionState records basic details about a QUIC connection.

func (ConnectionState) Fingerprint

func (cs ConnectionState) Fingerprint() Fingerprint

Fingerprint returns a normalized summary of the connection-relevant information that can be used to identify the peer's QUIC implementation. See Fingerprint for details.

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 Fingerprint

type Fingerprint struct {
	// Version is the Quic version of the connection.
	Version Version
	// ClientHello contains the raw ClientHello bytes (server-side only).
	ClientHello []byte
	// TransportParameterIDs lists the IDs of the peer's transport parameters, in wire order.
	// This includes GREASE and unknown parameters.
	TransportParameterIDs []uint64
	// TransportParameters maps the peer's transport parameter IDs to their raw values,
	// exactly as received on the wire.
	TransportParameters map[uint64][]byte
	// CipherSuites lists the cipher suites offered in the ClientHello, in order.
	CipherSuites []uint16
	// SupportedVersions lists the TLS versions offered in the ClientHello's supported_versions
	// extension (including GREASE values), in order.
	SupportedVersions []uint16
	// Extensions lists the TLS extension types of the ClientHello, in order.
	Extensions []uint16
	// SNIs lists the server names sent in the ClientHello's server_name extension.
	SNIs []string
	// ALPN lists the protocols offered in the ClientHello's ALPN extension, in order.
	ALPN []string
	// SrcConnectionID is the source connection ID of the client's first Initial packet.
	SrcConnectionID ConnectionID
	// DestConnectionID is the destination connection ID of the client's first Initial packet.
	DestConnectionID ConnectionID
	// InitialPacketSize is the size of the client's first Initial packet.
	InitialPacketSize int
	// GreaseQuicBit indicates whether the peer advertised the grease_quic_bit transport
	// parameter (RFC 9287).
	GreaseQuicBit bool
}

Fingerprint is a normalized summary of the information a connection reveals about the peer. It is intended to identify the peer's Quic implementation, and can be used as a hashable input for fingerprinting rules (e.g. allow/deny lists or rate limiting).

All fields are derived from public information exchanged during the connection establishment.

type FingerprintConfig

type FingerprintConfig struct {
	// ClientHelloID selects the uTLS ClientHello preset used to mimic the TLS fingerprint
	// of a specific client (e.g. tls.HelloChrome_133). The zero value disables TLS fingerprint
	// mimicry and uses the Go TLS stack's default ClientHello.
	// Note: when set, TLS session resumption (and thus 0-RTT) is not supported.
	ClientHelloID tls.ClientHelloID

	// TransportParameterOrder sets the order in which the client's transport parameters are
	// marshaled. IDs not listed are appended in the default order after the listed ones.
	// nil means the quic-go default order (with a random GREASE parameter prepended).
	// When set, no random GREASE parameter is added; use ExtraTransportParameters to add
	// GREASE parameters with full control.
	TransportParameterOrder []uint64
	// ExtraTransportParameters adds transport parameters with the given raw values
	// (ID -> value bytes), e.g. GREASE parameters.
	ExtraTransportParameters map[uint64][]byte

	// InitialPacketSize overrides the size of the client's initial packets.
	// 0 means use Config.InitialPacketSize. Values below 1200 are invalid.
	InitialPacketSize uint16
	// ConnectionIDLength sets the length of the client's source connection ID.
	// 0 means use the Transport's default connection ID length.
	// NOTE: incoming short-header packets are routed based on Transport.ConnectionIDLength,
	// which must be set to the same value, otherwise packets from the server cannot be routed.
	ConnectionIDLength int

	// GreaseQuicBit sends the grease_quic_bit transport parameter (RFC 9287).
	// Once the peer also advertises grease_quic_bit, the client sets the QUIC bit
	// randomly on ~50% of the packets it sends.
	GreaseQuicBit bool

	// MaxIdleTimeout overrides the advertised max_idle_timeout.
	MaxIdleTimeout *time.Duration
	// MaxUDPPayloadSize overrides the advertised max_udp_payload_size.
	MaxUDPPayloadSize *uint16
	// MaxAckDelay overrides the advertised max_ack_delay.
	MaxAckDelay *time.Duration
	// AckDelayExponent overrides the advertised ack_delay_exponent. When set, ACK frames are
	// encoded using this exponent.
	AckDelayExponent *uint8
	// ActiveConnectionIDLimit overrides the advertised active_connection_id_limit.
	ActiveConnectionIDLimit *uint64
	// InitialMaxData overrides the advertised initial_max_data.
	InitialMaxData *uint64
	// InitialMaxStreamDataBidiLocal overrides the advertised initial_max_stream_data_bidi_local.
	InitialMaxStreamDataBidiLocal *uint64
	// InitialMaxStreamDataBidiRemote overrides the advertised initial_max_stream_data_bidi_remote.
	InitialMaxStreamDataBidiRemote *uint64
	// InitialMaxStreamDataUni overrides the advertised initial_max_stream_data_uni.
	InitialMaxStreamDataUni *uint64
	// MaxBidiStreamNum overrides the advertised initial_max_streams_bidi.
	// WARNING: advertising more streams than Config.MaxIncomingStreams allows results in a
	// connection error if the peer opens more streams than allowed.
	MaxBidiStreamNum *uint64
	// MaxUniStreamNum overrides the advertised initial_max_streams_uni.
	// WARNING: advertising more streams than Config.MaxIncomingUniStreams allows results in a
	// connection error if the peer opens more streams than allowed.
	MaxUniStreamNum *uint64
	// DisableActiveMigration sends the disable_active_migration transport parameter.
	DisableActiveMigration bool
}

FingerprintConfig configures how the client presents itself on the wire, in order to mimic the connection establishment behavior of a specific Quic implementation (e.g. a browser). It is client-side only; it is ignored by the server.

A FingerprintConfig can be combined with the tls.Config's uTLS support (github.com/malivvan/tls.ClientHelloID) to also mimic the TLS-level ClientHello.

func FingerprintChrome133

func FingerprintChrome133() *FingerprintConfig

FingerprintChrome133 returns a FingerprintConfig mimicking Chrome 133. Chrome's ClientHello is mimicked via the uTLS HelloChrome_133 preset.

func FingerprintEdge133

func FingerprintEdge133() *FingerprintConfig

FingerprintEdge133 returns a FingerprintConfig mimicking Microsoft Edge 133. Edge is Chromium-based, so its QUIC fingerprint is identical to Chrome's.

func FingerprintFirefox120

func FingerprintFirefox120() *FingerprintConfig

FingerprintFirefox120 returns a FingerprintConfig mimicking Firefox 120. Firefox's ClientHello is mimicked via the uTLS HelloFirefox_120 preset.

func FingerprintSafari160

func FingerprintSafari160() *FingerprintConfig

FingerprintSafari160 returns a FingerprintConfig mimicking Safari 16.0. Safari's ClientHello is mimicked via the uTLS HelloSafari_16_0 preset.

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

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

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

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 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 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
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.
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.
httpsfv
Package httpsfv implements serializing and parsing of Structured Field Values for HTTP as defined in RFC 9651.
Package httpsfv implements serializing and parsing of Structured Field Values for HTTP as defined in RFC 9651.
interop/client command
interop/server command
interop_chrome command

Jump to

Keyboard shortcuts

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