Thanks to visit codestin.com
Credit goes to pkg.go.dev

quic

package module
v0.54.0 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2025 License: MIT Imports: 40 Imported by: 1,384

README

A QUIC implementation in pure Go

Documentation PkgGoDev Code Coverage Fuzzing Status

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

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

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

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

Projects using quic-go

Project Description Stars
AdGuardHome Free and open source, powerful network-wide ads & trackers blocking DNS server. GitHub Repo stars
algernon Small self-contained pure-Go web server with Lua, Markdown, HTTP/2, QUIC, Redis and PostgreSQL support GitHub Repo stars
caddy Fast, multi-platform web server with automatic HTTPS GitHub Repo stars
cloudflared A tunneling daemon that proxies traffic from the Cloudflare network to your origins GitHub Repo stars
frp A fast reverse proxy to help you expose a local server behind a NAT or firewall to the internet GitHub Repo stars
go-libp2p libp2p implementation in Go, powering Kubo (IPFS) and Lotus (Filecoin), among others GitHub Repo stars
gost A simple security tunnel written in Go GitHub Repo stars
Hysteria A powerful, lightning fast and censorship resistant proxy GitHub Repo stars
Mercure An open, easy, fast, reliable and battery-efficient solution for real-time communications GitHub Repo stars
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.

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 ConnectionTracingKey = connTracingCtxKey{}

ConnectionTracingKey can be used to associate a logging.ConnectionTracer with a Conn. It is set on the Conn.Context() context, as well as on the context passed to logging.Tracer.NewConnectionTracer.

Deprecated: Applications can set their own tracing key using Transport.ConnContext.

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

Err0RTTRejected is the returned from:

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

when the server rejects a 0-RTT connection attempt.

View Source
var ErrServerClosed = errServerClosed{}

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

View Source
var ErrTransportClosed = &errTransportClosed{}

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

View Source
var QUICVersionContextKey = handshake.QUICVersionContextKey

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

Functions

This section is empty.

Types

type ApplicationError added in v0.32.0

type ApplicationError = qerr.ApplicationError

ApplicationError is an application-defined error.

type ApplicationErrorCode added in v0.32.0

type ApplicationErrorCode = qerr.ApplicationErrorCode

ApplicationErrorCode is an QUIC application error code.

type ClientHelloInfo deprecated added in v0.35.0

type ClientHelloInfo = ClientInfo

ClientHelloInfo contains information about an incoming connection attempt.

Deprecated: Use ClientInfo instead.

type ClientInfo added in v0.51.0

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

ClientInfo contains information about an incoming connection attempt.

type ClientToken added in v0.32.0

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-07.
	EnableStreamResetPartialDelivery bool
	Tracer                           func(context.Context, logging.Perspective, ConnectionID) *logging.ConnectionTracer
}

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

func (*Config) Clone added in v0.32.0

func (c *Config) Clone() *Config

Clone clones a Config.

type Conn added in v0.53.0

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 added in v0.32.0

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 added in v0.32.0

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 added in v0.53.0

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 added in v0.53.0

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 added in v0.53.0

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

func (*Conn) CloseWithError added in v0.53.0

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 added in v0.53.0

func (c *Conn) ConnectionState() ConnectionState

ConnectionState returns basic details about the QUIC connection.

func (*Conn) Context added in v0.53.0

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 added in v0.53.0

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 added in v0.53.0

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

LocalAddr returns the local address of the QUIC connection.

func (*Conn) NextConnection added in v0.53.0

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

func (*Conn) OpenStream added in v0.53.0

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 added in v0.53.0

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 added in v0.53.0

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 added in v0.53.0

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) ReceiveDatagram added in v0.53.0

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 added in v0.53.0

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

RemoteAddr returns the remote address of the QUIC connection.

func (*Conn) SendDatagram added in v0.53.0

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 added in v0.32.0

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 added in v0.32.0

func ConnectionIDFromBytes(b []byte) ConnectionID

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

type ConnectionIDGenerator added in v0.32.0

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 added in v0.7.0

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
}

ConnectionState records basic details about a QUIC connection.

type ConnectionTracingID deprecated added in v0.43.0

type ConnectionTracingID uint64

ConnectionTracingID is the type of the context value saved under the ConnectionTracingKey.

Deprecated: Applications can set their own tracing key using Transport.ConnContext.

type DatagramTooLargeError added in v0.41.0

type DatagramTooLargeError struct {
	MaxDatagramPayloadSize int64
}

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

func (*DatagramTooLargeError) Error added in v0.41.0

func (e *DatagramTooLargeError) Error() string

func (*DatagramTooLargeError) Is added in v0.41.0

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

type EarlyListener added in v0.32.0

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 added in v0.32.0

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 added in v0.32.0

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 added in v0.32.0

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

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

func (*EarlyListener) Addr added in v0.32.0

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

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

func (*EarlyListener) Close added in v0.32.0

func (l *EarlyListener) Close() error

Close the server. All active connections will be closed.

type HandshakeTimeoutError added in v0.32.0

type HandshakeTimeoutError = qerr.HandshakeTimeoutError

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

type IdleTimeoutError added in v0.32.0

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 added in v0.6.0

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 added in v0.32.0

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 added in v0.51.0

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

Path is a network path.

func (*Path) Close added in v0.51.0

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 added in v0.51.0

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

func (*Path) Switch added in v0.51.0

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 added in v0.7.0

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

A ReceiveStream is a unidirectional Receive Stream.

func (*ReceiveStream) CancelRead added in v0.7.0

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) Read added in v0.53.0

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 added in v0.7.0

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

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

func (*ReceiveStream) StreamID added in v0.7.0

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

StreamID returns the stream ID.

type SendStream added in v0.7.0

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

A SendStream is a unidirectional Send Stream.

func (*SendStream) CancelWrite added in v0.7.0

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 added in v0.53.0

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 added in v0.7.0

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 added in v0.54.0

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 added in v0.7.0

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 added in v0.7.0

func (s *SendStream) StreamID() StreamID

StreamID returns the stream ID.

func (*SendStream) Write added in v0.53.0

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

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

type StatelessResetError added in v0.32.0

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 added in v0.32.0

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 added in v0.7.0

func (s *Stream) CancelRead(errorCode StreamErrorCode)

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

func (*Stream) CancelWrite added in v0.7.0

func (s *Stream) CancelWrite(errorCode StreamErrorCode)

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

func (*Stream) Close added in v0.53.0

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 added in v0.6.0

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) Read added in v0.53.0

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 added in v0.6.0

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 added in v0.6.0

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

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

func (*Stream) SetWriteDeadline added in v0.6.0

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

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

func (*Stream) StreamID

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

StreamID returns the stream ID.

func (*Stream) Write added in v0.53.0

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

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

type StreamError added in v0.7.0

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 added in v0.32.0

func (e *StreamError) Error() string

func (*StreamError) Is added in v0.32.0

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

type StreamErrorCode added in v0.32.0

type StreamErrorCode = qerr.StreamErrorCode

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

type StreamID added in v0.6.0

type StreamID = protocol.StreamID

The StreamID is the ID of a QUIC stream.

type StreamLimitReachedError added in v0.46.0

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 added in v0.46.0

func (e StreamLimitReachedError) Error() string

type TokenGeneratorKey added in v0.39.0

type TokenGeneratorKey = handshake.TokenProtectorKey

TokenGeneratorKey is a key used to encrypt session resumption tokens.

type TokenStore added in v0.32.0

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 added in v0.32.0

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 added in v0.35.0

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.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.
	// Tracer.Close is called when the transport is closed.
	Tracer *logging.Tracer
	// 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 added in v0.35.0

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 added in v0.35.0

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 added in v0.35.0

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 added in v0.35.0

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 added in v0.35.0

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 added in v0.38.0

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 added in v0.37.0

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

WriteTo sends a packet on the underlying connection.

type TransportError added in v0.32.0

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 added in v0.32.0

type TransportErrorCode = qerr.TransportErrorCode

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

type Version added in v0.42.0

type Version = protocol.Version

A Version is a QUIC version number.

func SupportedVersions added in v0.54.0

func SupportedVersions() []Version

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

type VersionNegotiationError added in v0.32.0

type VersionNegotiationError = qerr.VersionNegotiationError

VersionNegotiationError indicates a failure to negotiate a QUIC version.

Directories

Path Synopsis
client command
echo command
fuzzing
frames/cmd command
handshake/cmd command
header/cmd command
integrationtests
internal
mocks
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.
mocks/ackhandler
Package mockackhandler is a generated GoMock package.
Package mockackhandler is a generated GoMock package.
mocks/logging/internal
Package internal is a generated GoMock package.
Package internal is a generated GoMock package.
utils/linkedlist
Package list implements a doubly linked list.
Package list implements a doubly linked list.
interop
client command
server command
Package logging defines a logging interface for quic-go.
Package logging defines a logging interface for quic-go.
Package testutils contains utilities for simulating packet injection and man-in-the-middle (MITM) attacker tests.
Package testutils contains utilities for simulating packet injection and man-in-the-middle (MITM) attacker tests.

Jump to

Keyboard shortcuts

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