Documentation
¶
Index ¶
- Constants
- Variables
- func NewOLIACongestionControlFactory(sharedState *oliaSharedState) ...
- func NewOLIASharedState() *oliaSharedState
- type AdvertisedAddress
- type ApplicationError
- type ApplicationErrorCode
- type ByteCount
- type ClientInfo
- type ClientToken
- type Config
- type Conn
- func Dial(ctx context.Context, c net.PacketConn, addr net.Addr, tlsConf *tls.Config, ...) (*Conn, error)
- func DialAddr(ctx context.Context, addr string, tlsConf *tls.Config, conf *Config) (*Conn, error)
- func DialAddrEarly(ctx context.Context, addr string, tlsConf *tls.Config, conf *Config) (*Conn, error)
- func DialEarly(ctx context.Context, c net.PacketConn, addr net.Addr, tlsConf *tls.Config, ...) (*Conn, error)
- func (c *Conn) AcceptStream(ctx context.Context) (*Stream, error)
- func (c *Conn) AcceptUniStream(ctx context.Context) (*ReceiveStream, error)
- func (c *Conn) AddPath(t *Transport) (*Path, error)
- func (c *Conn) AddPathFromAddr(local, remote net.Addr) (*Path, error)
- func (c *Conn) AdvertiseAddress(addr netip.AddrPort) error
- func (c *Conn) ClosePath(id PathID) error
- func (c *Conn) CloseWithError(code ApplicationErrorCode, desc string) error
- func (c *Conn) ConnectionState() ConnectionState
- func (c *Conn) ConnectionStats() ConnectionStats
- func (c *Conn) Context() context.Context
- func (c *Conn) HandshakeComplete() <-chan struct{}
- func (c *Conn) LocalAddr() net.Addr
- func (c *Conn) MultipathController() MultipathController
- func (c *Conn) NextConnection(ctx context.Context) (*Conn, error)
- func (c *Conn) ObservedAddr() (netip.AddrPort, bool)
- func (c *Conn) OpenStream() (*Stream, error)
- func (c *Conn) OpenStreamSync(ctx context.Context) (*Stream, error)
- func (c *Conn) OpenUniStream() (*SendStream, error)
- func (c *Conn) OpenUniStreamSync(ctx context.Context) (*SendStream, error)
- func (c *Conn) Paths() []PathInfo
- func (c *Conn) PeerAdvertisedAddresses() []AdvertisedAddress
- func (c *Conn) QlogTrace() qlogwriter.Trace
- func (c *Conn) QueueRawFrame(frame RawFrame) error
- func (c *Conn) ReceiveDatagram(ctx context.Context) ([]byte, error)
- func (c *Conn) RemoteAddr() net.Addr
- func (c *Conn) SendDatagram(p []byte) error
- func (c *Conn) SetPathStatus(id PathID, status PathStatus) error
- type ConnectionID
- type ConnectionIDGenerator
- type ConnectionState
- type ConnectionStats
- type DatagramTooLargeError
- type DefaultMultipathController
- func (c *DefaultMultipathController) GetScheduler() PathScheduler
- func (c *DefaultMultipathController) GetStatistics() map[PathID]PathStatistics
- func (c *DefaultMultipathController) OnPacketAcked(pathID PathID)
- func (c *DefaultMultipathController) OnPacketLost(pathID PathID)
- func (c *DefaultMultipathController) OnPacketSent(pathID PathID, packetSize ByteCount)
- func (c *DefaultMultipathController) RegisterPath(info PathInfo)
- func (c *DefaultMultipathController) RemovePath(pathID PathID)
- func (c *DefaultMultipathController) SelectPath(ctx PathSelectionContext) (PathInfo, bool)
- func (c *DefaultMultipathController) UpdatePathState(pathID PathID, update PathStateUpdate)
- type EarlyListener
- type EncryptionLevel
- type ExtensionFrameContext
- type ExtensionFrameHandler
- type HandshakeTimeoutError
- type IdleTimeoutError
- type Listener
- type LowLatencyScheduler
- type MinRTTScheduler
- type MultiSocketManager
- func (m *MultiSocketManager) AddLocalAddr(ip net.IP) (*net.UDPAddr, error)
- func (m *MultiSocketManager) Close() error
- func (m *MultiSocketManager) LocalAddr() net.Addr
- func (m *MultiSocketManager) LocalAddrs() []net.IP
- func (m *MultiSocketManager) ReadFrom(b []byte) (n int, addr net.Addr, err error)
- func (m *MultiSocketManager) ReadPacket() (receivedPacket, error)
- func (m *MultiSocketManager) RefreshInterfaces() error
- func (m *MultiSocketManager) RemoveLocalAddr(ip net.IP) bool
- func (m *MultiSocketManager) SetDeadline(t time.Time) error
- func (m *MultiSocketManager) SetLocalAddrs(addrs []net.IP) error
- func (m *MultiSocketManager) SetReadDeadline(t time.Time) error
- func (m *MultiSocketManager) SetWriteDeadline(t time.Time) error
- func (m *MultiSocketManager) WritePacket(b []byte, addr net.Addr, packetInfoOOB []byte, gsoSize uint16, ...) (int, error)
- func (m *MultiSocketManager) WritePacketWithInfo(b []byte, addr net.Addr, info packetInfo, gsoSize uint16, ecn protocol.ECN) (int, error)
- func (m *MultiSocketManager) WriteTo(b []byte, addr net.Addr) (int, error)
- type MultiSocketManagerConfig
- type MultipathAddressObserver
- type MultipathCongestionControl
- type MultipathController
- type MultipathDuplicationPolicy
- func (p *MultipathDuplicationPolicy) AddStreamForDuplication(streamID protocol.StreamID)
- func (p *MultipathDuplicationPolicy) Disable()
- func (p *MultipathDuplicationPolicy) Enable()
- func (p *MultipathDuplicationPolicy) GetDuplicatePathCount() int
- func (p *MultipathDuplicationPolicy) IsEnabled() bool
- func (p *MultipathDuplicationPolicy) RemoveStreamForDuplication(streamID protocol.StreamID)
- func (p *MultipathDuplicationPolicy) SetDuplicateAllStreams(enable bool)
- func (p *MultipathDuplicationPolicy) SetDuplicateCryptoFrames(enable bool)
- func (p *MultipathDuplicationPolicy) SetDuplicatePathCount(count int)
- func (p *MultipathDuplicationPolicy) SetDuplicateResets(enable bool)
- func (p *MultipathDuplicationPolicy) ShouldDuplicateCrypto() bool
- func (p *MultipathDuplicationPolicy) ShouldDuplicateReset() bool
- func (p *MultipathDuplicationPolicy) ShouldDuplicateStream(streamID protocol.StreamID) bool
- type MultipathObserver
- type MultipathReinjectionManager
- func (m *MultipathReinjectionManager) GetPendingReinjections(now time.Time) []*PacketReinjectionInfo
- func (m *MultipathReinjectionManager) GetStatistics() (pending, reinjected int)
- func (m *MultipathReinjectionManager) MarkReinjected(pathID protocol.PathID, pn protocol.PacketNumber, targetPath protocol.PathID)
- func (m *MultipathReinjectionManager) OnPacketAcked(pathID protocol.PathID, pn protocol.PacketNumber)
- func (m *MultipathReinjectionManager) OnPacketLost(pathID protocol.PathID, pn protocol.PacketNumber, ...)
- func (m *MultipathReinjectionManager) Reset()
- type MultipathReinjectionPolicy
- func (p *MultipathReinjectionPolicy) AddPreferredPathForReinjection(pathID protocol.PathID)
- func (p *MultipathReinjectionPolicy) Disable()
- func (p *MultipathReinjectionPolicy) Enable()
- func (p *MultipathReinjectionPolicy) GetMaxReinjectionQueuePerPath() int
- func (p *MultipathReinjectionPolicy) GetMaxReinjections() int
- func (p *MultipathReinjectionPolicy) GetMinReinjectionInterval() time.Duration
- func (p *MultipathReinjectionPolicy) GetReinjectionDelay() time.Duration
- func (p *MultipathReinjectionPolicy) IsEnabled() bool
- func (p *MultipathReinjectionPolicy) IsPreferredPathForReinjection(pathID protocol.PathID) bool
- func (p *MultipathReinjectionPolicy) ReinjectsOnPTO() bool
- func (p *MultipathReinjectionPolicy) RemovePreferredPathForReinjection(pathID protocol.PathID)
- func (p *MultipathReinjectionPolicy) SetMaxReinjectionQueuePerPath(max int)
- func (p *MultipathReinjectionPolicy) SetMaxReinjections(max int)
- func (p *MultipathReinjectionPolicy) SetMinReinjectionInterval(interval time.Duration)
- func (p *MultipathReinjectionPolicy) SetReinjectOnPTO(enable bool)
- func (p *MultipathReinjectionPolicy) SetReinjectionDelay(delay time.Duration)
- func (p *MultipathReinjectionPolicy) ShouldReinjectFrame(frame wire.Frame) bool
- type MultipathReinjectionTargetSelector
- type MultipathScheduler
- type OLIACongestionControl
- func (o *OLIACongestionControl) CanSend(bytesInFlight protocol.ByteCount) bool
- func (o *OLIACongestionControl) GetCongestionWindow() protocol.ByteCount
- func (o *OLIACongestionControl) GetStatistics() OLIAStatistics
- func (o *OLIACongestionControl) InRecovery() bool
- func (o *OLIACongestionControl) InSlowStart() bool
- func (o *OLIACongestionControl) MaybeExitSlowStart()
- func (o *OLIACongestionControl) OnCongestionEvent(packetNumber protocol.PacketNumber, lostBytes protocol.ByteCount, ...)
- func (o *OLIACongestionControl) OnPacketAcked(packetNumber protocol.PacketNumber, ackedBytes protocol.ByteCount, ...)
- func (o *OLIACongestionControl) OnPacketLost(packetNumber protocol.PacketNumber, lostBytes protocol.ByteCount, ...)
- func (o *OLIACongestionControl) OnPacketSent(sentTime time.Time, packetNumber protocol.PacketNumber, ...)
- func (o *OLIACongestionControl) OnPersistentCongestion()
- func (o *OLIACongestionControl) OnRetransmissionTimeout(packetsRetransmitted bool)
- func (o *OLIACongestionControl) Reset()
- func (o *OLIACongestionControl) SetMaxDatagramSize(size protocol.ByteCount)
- func (o *OLIACongestionControl) SmoothedBytesBetweenLosses() protocol.ByteCount
- func (o *OLIACongestionControl) Unregister()
- func (o *OLIACongestionControl) UpdateRTT(rtt, minRTT time.Duration)
- type OLIAStatistics
- type OOBCapablePacketConn
- type PacketNumber
- type PacketReinjectionInfo
- type Path
- type PathEvent
- type PathID
- type PathInfo
- type PathScheduler
- type PathSchedulerWrapper
- func (s *PathSchedulerWrapper) DisableMultipath()
- func (s *PathSchedulerWrapper) EnableMultipath()
- func (s *PathSchedulerWrapper) IsMultipathEnabled() bool
- func (s *PathSchedulerWrapper) OnPacketAcked(ev PathEvent)
- func (s *PathSchedulerWrapper) OnPacketLost(ev PathEvent)
- func (s *PathSchedulerWrapper) OnPacketSent(ev PathEvent)
- func (s *PathSchedulerWrapper) RecordSent(pathID protocol.PathID, packetSize uint64)
- func (s *PathSchedulerWrapper) RegisterPath(info PathInfo)
- func (s *PathSchedulerWrapper) RemovePath(pathID PathID)
- func (s *PathSchedulerWrapper) SelectPath(ctx PathSelectionContext) (PathInfo, bool)
- type PathSelectionContext
- type PathState
- type PathStateUpdate
- type PathStatistics
- type PathStatus
- type PreferredAddress
- type RawFrame
- type ReceiveStream
- func (s *ReceiveStream) CancelRead(errorCode StreamErrorCode)
- func (s *ReceiveStream) Peek(b []byte) (int, error)
- func (s *ReceiveStream) Read(p []byte) (int, error)
- func (s *ReceiveStream) SetReadDeadline(t time.Time) error
- func (s *ReceiveStream) SetReceiveFinalSizeCallback(callback func(int64))
- func (s *ReceiveStream) StreamID() StreamID
- type ReinjectionTargetContext
- type RoundRobinScheduler
- type SchedulerPathInfo
- type SchedulerStats
- type SchedulingPolicy
- type SendStream
- func (s *SendStream) CancelWrite(errorCode StreamErrorCode)
- func (s *SendStream) Close() error
- func (s *SendStream) Context() context.Context
- func (s *SendStream) SetPriority(urgency int8, incremental bool)
- func (s *SendStream) SetReliableBoundary()
- func (s *SendStream) SetWriteDeadline(t time.Time) error
- func (s *SendStream) StreamID() StreamID
- func (s *SendStream) TryWriteAll(p []byte) error
- func (s *SendStream) Write(p []byte) (int, error)
- func (s *SendStream) WriteWithLimit(p []byte, limiter func(maxBytes int) int) (int, error)
- type SessionTicketID
- type StatelessResetError
- type StatelessResetKey
- type Stream
- func (s *Stream) CancelRead(errorCode StreamErrorCode)
- func (s *Stream) CancelWrite(errorCode StreamErrorCode)
- func (s *Stream) Close() error
- func (s *Stream) Context() context.Context
- func (s *Stream) Peek(b []byte) (int, error)
- func (s *Stream) Read(p []byte) (int, error)
- func (s *Stream) SetDeadline(t time.Time) error
- func (s *Stream) SetPriority(urgency int8, incremental bool)
- func (s *Stream) SetReadDeadline(t time.Time) error
- func (s *Stream) SetReceiveFinalSizeCallback(callback func(int64))
- func (s *Stream) SetReliableBoundary()
- func (s *Stream) SetWriteDeadline(t time.Time) error
- func (s *Stream) StreamID() StreamID
- func (s *Stream) TryWriteAll(p []byte) error
- func (s *Stream) Write(p []byte) (int, error)
- func (s *Stream) WriteWithLimit(p []byte, limiter func(maxBytes int) int) (int, error)
- type StreamError
- type StreamErrorCode
- type StreamID
- type StreamLimitReachedError
- type TokenGeneratorKey
- type TokenStore
- type Transport
- func (t *Transport) Close() error
- func (t *Transport) Dial(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)
- func (t *Transport) DialEarly(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)
- func (t *Transport) Listen(tlsConf *tls.Config, conf *Config) (*Listener, error)
- func (t *Transport) ListenEarly(tlsConf *tls.Config, conf *Config) (*EarlyListener, error)
- func (t *Transport) ReadNonQUICPacket(ctx context.Context, b []byte) (int, net.Addr, error)
- func (t *Transport) WriteTo(b []byte, addr net.Addr) (int, error)
- type TransportError
- type TransportErrorCode
- type Version
- type VersionNegotiationError
- type ZeroRTTReplayCache
Constants ¶
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 // VersionNegotiationErrorCode is the VERSION_NEGOTIATION_ERROR transport error code (RFC 9368). VersionNegotiationErrorCode = qerr.VersionNegotiationErrorCode // ApplicationAbandonPath is the APPLICATION_ABANDON_PATH error code of the multipath extension. ApplicationAbandonPath = qerr.ApplicationAbandonPath // PathResourceLimitReached is the PATH_RESOURCE_LIMIT_REACHED error code of the multipath extension. PathResourceLimitReached = qerr.PathResourceLimitReached // PathUnstableOrPoor is the PATH_UNSTABLE_OR_POOR error code of the multipath extension. PathUnstableOrPoor = qerr.PathUnstableOrPoor // NoCIDAvailableForPath is the NO_CID_AVAILABLE_FOR_PATH error code of the multipath extension. NoCIDAvailableForPath = qerr.NoCIDAvailableForPath )
const ( // Version1 is RFC 9000 Version1 = protocol.Version1 // Version2 is RFC 9369 Version2 = protocol.Version2 )
const DefaultZeroRTTReplayCacheSize = 1 << 20
DefaultZeroRTTReplayCacheSize is the number of session tickets that the ZeroRTTReplayCache of a Transport that doesn't configure one keeps track of. Its IDs use less than 64 MB of memory. A server that accepts more than about 12 0-RTT handshakes per second on average over DefaultZeroRTTReplayWindow reaches this limit, and then rejects 0-RTT until older IDs are dropped. Such a server should configure a cache with a shorter window or a larger size.
const DefaultZeroRTTReplayWindow = 24 * time.Hour
DefaultZeroRTTReplayWindow is the window used by the ZeroRTTReplayCache of a Transport that doesn't configure one. A session ticket can only be used for 0-RTT during this time after it was issued.
Variables ¶
var ( // ErrAddressAdvertisementNotNegotiated is returned by Conn.AdvertiseAddress if the address advertisement // extension is not used on the connection (see Config.EnableAddressAdvertisement). ErrAddressAdvertisementNotNegotiated = errors.New("address advertisement extension not negotiated") // ErrTooManyAdvertisedAddresses is returned by Conn.AdvertiseAddress if the maximum number of addresses // was already advertised. ErrTooManyAdvertisedAddresses = errors.New("too many advertised addresses") )
var ( // ErrPathClosed can be returned by [Path.Probe] or [Path.Switch] after the path has been closed. ErrPathClosed = errors.New("path closed") // ErrPathNotValidated is returned by [Path.Switch] when the path has not yet been validated. ErrPathNotValidated = errors.New("path not yet validated") // ErrTooManyPaths is returned by [Path.Probe] if the path can't be opened // because as many paths as allowed by [Config.MaxPaths] are in use. ErrTooManyPaths = errors.New("too many paths") )
var Err0RTTRejected = errors.New("0-RTT rejected")
Err0RTTRejected can be returned by methods such as:
- Conn.OpenStream, Conn.OpenStreamSync, Conn.OpenUniStream, and Conn.OpenUniStreamSync
- Conn.AcceptStream and Conn.AcceptUniStream
- Stream.Read and Stream.Write
when the server rejects a 0-RTT connection attempt.
var ErrServerClosed = errServerClosed{}
ErrServerClosed is returned by Listener.Accept or EarlyListener.Accept after Listener.Close or EarlyListener.Close is called, respectively.
var ErrTransportClosed = &errTransportClosed{}
ErrTransportClosed is returned by Transport.Listen, Transport.ListenEarly, Transport.Dial, or Transport.DialEarly after Transport.Close is called.
var ErrWouldBlock = errors.New("operation would block")
ErrWouldBlock is returned by SendStream.TryWriteAll if the entire slice can't be queued immediately.
var ErrWriteLimitReached = errors.New("write limit reached")
ErrWriteLimitReached is returned by SendStream.WriteWithLimit when its limiter prevents accepting the entire slice.
var QUICVersionContextKey = handshake.QUICVersionContextKey
QUICVersionContextKey can be used to find out the QUIC version of a TLS handshake from the context returned by tls.ClientHelloInfo.Context.
Functions ¶
func NewOLIACongestionControlFactory ¶
func NewOLIACongestionControlFactory(sharedState *oliaSharedState) func(pathID protocol.PathID, rttStats *utils.RTTStats, initialMaxDatagramSize protocol.ByteCount) congestion.SendAlgorithmWithDebugInfos
NewOLIACongestionControlFactory creates a factory function for OLIA congestion controllers. This factory is used by sent_packet_handler to create per-path OLIA instances. The controllers take their RTT from the RTT stats passed to the factory. All controllers created by the factory are coupled through sharedState, so a factory (and a shared state) must only be used for a single connection. Closed paths should be removed from the shared state with Unregister.
func NewOLIASharedState ¶
func NewOLIASharedState() *oliaSharedState
NewOLIASharedState creates shared state for OLIA congestion control.
Types ¶
type AdvertisedAddress ¶ added in v0.3.0
type AdvertisedAddress struct {
// ID is the address ID chosen by the peer.
// If the peer advertises another address for the same ID, it replaces the previous address.
ID uint64
// Addr is the address.
Addr netip.AddrPort
}
AdvertisedAddress is an address that the peer advertised using the address advertisement extension (see Config.EnableAddressAdvertisement).
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 reports whether the remote address was verified by a valid address validation token,
// including a token received in a NEW_TOKEN frame.
// The Retry mechanism costs one network roundtrip and is only used when
// [Transport.VerifySourceAddress] requests it.
AddrVerified bool
}
ClientInfo contains information about an incoming connection attempt.
type ClientToken ¶
type ClientToken struct {
// contains filtered or unexported fields
}
A ClientToken is a token received by the client. It can be used to skip address validation on future connection attempts.
type Config ¶
type Config struct {
// 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, sorted by preference (descending).
// If not set, it uses all versions available.
// A client uses the first version for its first flight (unless InitialVersion is set), and offers the versions
// that this first flight is compatible with (QUIC version 1 and 2 are compatible with each other) for compatible
// version negotiation (RFC 9368), sorted by preference.
// A server only switches to a different compatible version if Versions is set: it then selects the first
// version that the client offered. Otherwise, the server uses the version of the client's first flight.
Versions []Version
// InitialVersion is the QUIC version that a client uses for its first flight. It must be one of Versions.
// If not set, the first version of Versions is used.
// It allows a client to start with a version that most servers support, while preferring another compatible
// version: with Versions set to QUIC version 2 and 1, and InitialVersion set to QUIC version 1, the client
// starts with version 1, and asks the server to switch to version 2 (section 3 of RFC 9368).
// Servers don't use it.
InitialVersion 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
// ZeroRTTReplayCache protects the server against the replay of 0-RTT data (section 9.2 of RFC 9001):
// it accepts 0-RTT at most once for every session ticket. It is used if Allow0RTT is set.
// If nil, a cache created with NewZeroRTTReplayCache(DefaultZeroRTTReplayWindow, DefaultZeroRTTReplayCacheSize)
// is used, which is shared by all listeners of a Transport. It only protects this server: servers sharing
// session ticket keys, and a server that is restarted, should share a cache.
// Only valid for the server.
ZeroRTTReplayCache ZeroRTTReplayCache
// 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-11.
// The reset_stream_at transport parameter is sent with the final code point (0x1d) and the code point of
// draft-07 (0x17f7586d2cb571). The extension is used if the peer sent either one of them.
EnableStreamResetPartialDelivery bool
// EnableQUICBitGreasing enables Greasing the QUIC Bit (RFC 9287). The grease_quic_bit transport parameter is sent,
// and packets with the QUIC Bit (the second-most significant bit of the first byte) set to 0 are accepted.
// If the peer sent the transport parameter as well, the QUIC Bit of every packet sent after processing the peer's
// transport parameters is set to a random value.
// Short header packets with the QUIC Bit set to 0 are then handled by the connection that their connection ID
// belongs to, instead of being returned by Transport.ReadNonQUICPacket. It shouldn't be enabled if the peer sends
// packets of other protocols to the same socket, especially with zero-length connection IDs.
// For a server, the Config passed to Listen decides if Initial packets with the QUIC Bit set to 0 are accepted
// (a client only sends them to a server that enabled the extension in a previous connection), and the Config
// returned by GetConfigForClient decides for all other packets.
EnableQUICBitGreasing bool
// RequestObservedAddress enables QUIC Address Discovery (draft-ietf-quic-address-discovery-01), and asks the
// peer to report the address it observes for this endpoint on every path, i.e. the reflexive transport address,
// using OBSERVED_ADDRESS frames.
// The reported addresses are returned by Conn.ObservedAddr, and in the ObservedAddr field of PathInfo.
// The peer might report a wrong address (see section 6.1 of the draft).
RequestObservedAddress bool
// ProvideObservedAddress enables QUIC Address Discovery (draft-ietf-quic-address-discovery-01), and offers to
// report the address observed for the peer. If the peer asks for it, an OBSERVED_ADDRESS frame is sent on
// every path, including the path used for the handshake, and when the peer's address on a path changes.
// It should not be set if the endpoint can't observe the peer's address, e.g. behind a proxy or a load balancer
// that changes the addresses of packets (section 6.2 of the draft).
ProvideObservedAddress bool
// MaxPaths is the number of paths of IETF Multipath QUIC that can be in use at the same time,
// including the path used during the handshake: the initial_max_path_id transport parameter is MaxPaths-1.
// If set to 0, it defaults to 3. Values larger than 64 are reduced to 64.
// It only applies if a multipath controller is configured.
// With MaxPaths 1, initial_max_path_id is 0, which enables the extension without allowing additional paths
// (section 2.1 of draft-ietf-quic-multipath-21). Some implementations (picoquic) only enable the extension if
// both endpoints send a value larger than 0, and close the connection when they receive the frames of the
// extension. To use a single path without the extension, don't configure a multipath controller.
MaxPaths int
// MultipathController enables path-aware scheduling and packet mapping.
// A controller keeps per-connection state, so it is only used by one connection at a time.
// If it is already used by another connection, the built-in controllers are cloned (without their paths),
// and multipath is disabled for other controllers.
// Use MultipathControllerFactory to create a controller per connection, e.g. on a server.
MultipathController MultipathController
// MultipathControllerFactory creates the multipath controller of a connection.
// If set, it takes precedence over MultipathController.
MultipathControllerFactory func() MultipathController
// MultipathCongestionControl selects the congestion control used on multipath connections.
// It defaults to MultipathCongestionControlReno.
MultipathCongestionControl MultipathCongestionControl
// MultipathDuplicationPolicy enables packet duplication across paths.
// Every path has its own packet number space: the selected frames are copied,
// and the copies are sent in separate packets on other paths. They are never retransmitted.
MultipathDuplicationPolicy *MultipathDuplicationPolicy
// MultipathReinjectionPolicy enables packet reinjection on alternate paths.
MultipathReinjectionPolicy *MultipathReinjectionPolicy
// MultipathAutoPaths automatically creates additional paths from the local addresses after the handshake.
// Only clients open paths, so this has no effect for servers.
// A path to the server address of the first path is opened from every local address
// other than the one of the first path, up to MaxPaths paths in total (see Conn.AddPathFromAddr).
// This requires a socket bound to an unspecified address, or a MultiSocketManager.
// No paths are opened to the server address of the first path if the server disabled active migration.
// If the address advertisement extension is used (see EnableAddressAdvertisement), a path is also opened to
// every address advertised by the server that uses the address family of the server address of the first path,
// from the local address of the first path, within the same limit.
MultipathAutoPaths bool
// EnableAddressAdvertisement enables the address advertisement extension of this module (ADD_ADDRESS frames),
// which is only used together with IETF Multipath QUIC. It is negotiated separately, using a transport parameter
// that is only sent if the initial_max_path_id transport parameter is sent as well.
// If both endpoints enable it, an endpoint can advertise its addresses using Conn.AdvertiseAddress.
// The addresses advertised by the peer are returned by Conn.PeerAdvertisedAddresses.
// Only clients open paths: a client can open paths to the addresses advertised by the server
// (see MultipathAutoPaths and Conn.AddPathFromAddr). A server only records the addresses advertised by the client.
EnableAddressAdvertisement bool
// MultipathAutoAdvertise makes a server advertise its local addresses using ADD_ADDRESS frames, once the handshake
// completed: the addresses in MultipathAutoAddrs, or the addresses of the local interfaces of the address family
// used by the client, except for the local address used during the handshake. They are advertised with the port of
// the connection's socket, which needs to be bound to an unspecified address.
// It only has an effect if the address advertisement extension is used (see EnableAddressAdvertisement),
// and it has no effect for clients.
MultipathAutoAdvertise bool
// MultipathAutoAddrs optionally overrides auto-discovered local addresses.
MultipathAutoAddrs []net.IP
// ExtensionFrameHandler enables parsing of custom frame types.
ExtensionFrameHandler ExtensionFrameHandler
Tracer func(ctx context.Context, isClient bool, connID ConnectionID) qlogwriter.Trace
// contains filtered or unexported fields
}
Config contains all configuration data needed for a QUIC server or client.
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:
- ApplicationError: for errors triggered by the application running on top of QUIC
- TransportError: for errors triggered by the QUIC transport (in many cases a misbehaving peer)
- IdleTimeoutError: when the peer goes away unexpectedly (this is a net.Error timeout error)
- HandshakeTimeoutError: when the cryptographic handshake takes too long (this is a net.Error timeout error)
- StatelessResetError: when we receive a stateless reset
- VersionNegotiationError: returned by the client, when there's no version overlap between the peers
func Dial ¶
func Dial(ctx context.Context, c net.PacketConn, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)
Dial establishes a new QUIC connection to a server using a net.PacketConn. If the PacketConn satisfies the OOBCapablePacketConn interface (as a net.UDPConn does), ECN and packet info support will be enabled. In this case, packets will be read in batches, and OOBCapablePacketConn.WriteMsgUDP will be used instead of net.PacketConn.WriteTo. The tls.Config must define an application protocol using tls.Config.NextProtos.
This is a convenience function. More advanced use cases should instantiate a Transport, which offers configuration options for a more fine-grained control of the connection establishment, including reusing the underlying UDP socket for multiple QUIC connections.
func DialAddr ¶
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 ¶
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 ¶
AddPath creates a new path that sends packets from the Transport's connection. Without IETF Multipath QUIC, the path can be used to migrate the connection (section 9 of RFC 9000). With IETF Multipath QUIC, it opens a new path of the connection when it is probed. If the client advertised IETF Multipath QUIC, whether the server supports it is only known once the handshake completed. A path added before is created when it is probed: Path.Probe waits for the handshake to complete. The Transport needs to stay open until the connection is closed: Transport.Close terminates the connection. If the server sent the disable_active_migration transport parameter, paths can only be added once the connection migrated to the server's preferred address (see PreferredAddress). With IETF Multipath QUIC, paths are opened to the server address that path 0 uses when the path is created.
func (*Conn) AddPathFromAddr ¶ added in v0.3.0
AddPathFromAddr creates a new path of IETF Multipath QUIC, using the connection's underlying network connection. Packets are sent to remote, or to the server address of the path that the handshake was performed on if remote is nil. If local is set, packets are sent from this local address. This requires a connection that allows setting the source address of packets, e.g. a UDP socket bound to an unspecified address, or a MultiSocketManager. The path is opened and validated by calling Path.Probe.
Paths can only be added by the client, if IETF Multipath QUIC was negotiated. If the server sent the disable_active_migration transport parameter, no path to the server's handshake address can be added (section 2.2 of draft-ietf-quic-multipath-21). Paths to other addresses of the server, e.g. its preferred address, can be added. A path added before completion of the handshake is created when it is probed: Path.Probe waits for the handshake to complete, and returns the error if the path can't be added.
func (*Conn) AdvertiseAddress ¶ added in v0.3.0
AdvertiseAddress advertises an address of this endpoint to the peer, using the address advertisement extension (see Config.EnableAddressAdvertisement). The application needs to make sure that the connection receives the packets sent to this address, e.g. by binding the socket to an unspecified address. A client can open paths to the addresses advertised by the server. A server only records the addresses advertised by the client: only clients open paths.
It can only be called after completion of the handshake. It returns ErrAddressAdvertisementNotNegotiated if the extension is not used, and ErrTooManyAdvertisedAddresses if the maximum number of addresses was advertised already. Unspecified, multicast and broadcast addresses, and port 0, are rejected. Advertising an address again is a no-op.
func (*Conn) ClosePath ¶ added in v0.3.0
ClosePath abandons the path of IETF Multipath QUIC with the given path ID, like Path.Close (section 3.4 of draft-ietf-quic-multipath-21). It can be used for paths that the application didn't open using Conn.AddPath or Conn.AddPathFromAddr, for example path 0 (the path of the handshake), paths opened by Config.MultipathAutoPaths, and paths opened by the client (when called by the server). The last path that can be used for sending can't be closed. It returns ErrPathClosed if there's no such path, or if the path was already abandoned. It returns an error if IETF Multipath QUIC is not used.
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 ¶
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) MultipathController ¶
func (c *Conn) MultipathController() MultipathController
MultipathController returns the multipath controller used by this connection. It is nil if multipath is not configured. When Config.MultipathController is used by multiple connections at the same time, the built-in controllers are cloned, so this might not be the controller set in the Config.
func (*Conn) NextConnection ¶
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) ObservedAddr ¶ added in v0.3.0
ObservedAddr returns the address that the peer observed for this endpoint on the primary path, i.e. the path that LocalAddr and RemoteAddr refer to, using QUIC Address Discovery (see Config.RequestObservedAddress). This is the reflexive transport address: if this endpoint is behind a NAT, it is the address that the NAT translates the local address to. Without IETF Multipath QUIC, it is the address reported last by the peer, which might be an address observed on a path that the connection probes (see Path.Probe). With IETF Multipath QUIC, Conn.Paths returns the address observed on every path.
It returns false if the peer didn't report an address (yet), if the extension is not used, or if the handshake is not complete. Peers can report a wrong address (see section 6.1 of draft-ietf-quic-address-discovery-01).
func (*Conn) OpenStream ¶
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 ¶
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) Paths ¶ added in v0.3.0
Paths returns the paths of IETF Multipath QUIC, in ascending order of their path IDs. This includes paths that are being validated, and abandoned paths whose state wasn't removed yet. It returns nil if IETF Multipath QUIC is not used. The paths are a snapshot, taken by the connection when the extension becomes active (on completion of the handshake), when a path is validated or abandoned, and after processing packets and timers.
func (*Conn) PeerAdvertisedAddresses ¶ added in v0.3.0
func (c *Conn) PeerAdvertisedAddresses() []AdvertisedAddress
PeerAdvertisedAddresses returns the addresses that the peer advertised using the address advertisement extension (see Config.EnableAddressAdvertisement), in ascending order of their address IDs. Addresses that can't be used for a path are ignored: unspecified, multicast and broadcast addresses, port 0, and loopback and link-local addresses unless the connection itself uses such an address. Up to 16 addresses are recorded. It returns nil if the extension is not used, or if the handshake is not complete.
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) QueueRawFrame ¶
QueueRawFrame queues a custom frame for sending. It returns an error if the frame type is used by QUIC or one of its extensions (including the multipath extensions), or doesn't fit into a varint.
func (*Conn) ReceiveDatagram ¶
ReceiveDatagram gets a message received in a QUIC datagram, as specified in RFC 9221.
func (*Conn) RemoteAddr ¶
RemoteAddr returns the remote address of the QUIC connection.
func (*Conn) SendDatagram ¶
SendDatagram sends a message using a QUIC datagram, as specified in RFC 9221, if the peer enabled datagram support. There is no delivery guarantee for DATAGRAM frames, they are not retransmitted if lost. The payload of the datagram needs to fit into a single QUIC packet. In addition, a datagram may be dropped before being sent out if the available packet size suddenly decreases. If the payload is too large to be sent at the current time, a DatagramTooLargeError is returned.
func (*Conn) SetPathStatus ¶ added in v0.3.0
func (c *Conn) SetPathStatus(id PathID, status PathStatus) error
SetPathStatus sets the status of the path of IETF Multipath QUIC with the given path ID, and signals it to the peer, like Path.SetStatus (section 3.3 of draft-ietf-quic-multipath-21). It can be used for paths that the application didn't open using Conn.AddPath or Conn.AddPathFromAddr, for example path 0 (the path of the handshake), paths opened by Config.MultipathAutoPaths, and paths opened by the client (when called by the server). It returns ErrPathClosed if there's no such path, or if the path was abandoned. It returns an error if IETF Multipath QUIC is not used.
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.
// A connection must never issue the same connection ID twice (section 5.1 of RFC 9000), so the generator must
// never return a connection ID that it returned before.
GenerateConnectionID() (ConnectionID, error)
// ConnectionIDLen returns the length of Connection IDs generated by this implementation.
// Implementations must return constant-length Connection IDs with lengths between 0 and 20 bytes.
// A length of 0 can only be used when an endpoint doesn't need to multiplex connections during migration.
ConnectionIDLen() int
}
A ConnectionIDGenerator allows the application to take control over the generation of Connection IDs. Connection IDs generated by an implementation must be of constant length.
type ConnectionState ¶
type ConnectionState struct {
// TLS contains information about the TLS connection state, incl. the tls.ConnectionState.
TLS tls.ConnectionState
// SupportsDatagrams indicates support for QUIC datagrams (RFC 9221).
SupportsDatagrams struct {
// Remote is true if the peer advertised datagram support.
// Local is true if datagram support was enabled via Config.EnableDatagrams.
Remote, Local bool
}
// SupportsMultipath is true if IETF Multipath QUIC (draft-ietf-quic-multipath-21) is used:
// a multipath controller is configured, and both endpoints advertised the initial_max_path_id transport parameter.
SupportsMultipath bool
// SupportsAddressAdvertisement is true if the address advertisement extension (ADD_ADDRESS) is used:
// IETF Multipath QUIC is used, and both endpoints enabled the extension (see Config.EnableAddressAdvertisement).
// It is only set once the handshake completed.
SupportsAddressAdvertisement bool
// SupportsAddressDiscovery describes the use of QUIC Address Discovery (draft-ietf-quic-address-discovery-01).
// It is only set once the handshake completed.
SupportsAddressDiscovery struct {
// Send is true if this endpoint reports the address it observes for the peer:
// Config.ProvideObservedAddress is set, and the peer requested address observations.
// Receive is true if the peer reports the address it observes for this endpoint (see Conn.ObservedAddr):
// Config.RequestObservedAddress is set, and the peer offered to provide address observations.
Send, Receive bool
}
// SupportsStreamResetPartialDelivery indicates support for QUIC Stream Resets with Partial Delivery.
SupportsStreamResetPartialDelivery struct {
// Remote is true if the peer advertised support.
// Local is true if support was enabled via Config.EnableStreamResetPartialDelivery.
Remote, Local bool
}
// SupportsQUICBitGreasing indicates support for Greasing the QUIC Bit (RFC 9287).
// The QUIC Bit of the packets sent is only greased if Remote is true and Local is true.
SupportsQUICBitGreasing struct {
// Remote is true if the peer sent the grease_quic_bit transport parameter.
// Local is true if support was enabled via Config.EnableQUICBitGreasing.
Remote, Local bool
}
// Used0RTT says if 0-RTT resumption was used.
Used0RTT bool
// Version is the QUIC version of the QUIC connection.
Version Version
// GSO says if generic segmentation offload is used.
GSO bool
}
ConnectionState records basic details about a QUIC connection.
type ConnectionStats ¶
type ConnectionStats struct {
// MinRTT is the estimate of the minimum RTT observed on the active network
// path.
MinRTT time.Duration
// LatestRTT is the last RTT sample observed on the active network path.
LatestRTT time.Duration
// SmoothedRTT is an exponentially weighted moving average of an endpoint's
// RTT samples. See https://www.rfc-editor.org/rfc/rfc9002#section-5.3
SmoothedRTT time.Duration
// MeanDeviation estimates the variation in the RTT samples using a mean
// variation. See https://www.rfc-editor.org/rfc/rfc9002#section-5.3
MeanDeviation time.Duration
// BytesSent is the number of bytes sent on the underlying connection,
// including retransmissions. Does not include UDP or any other outer
// framing.
BytesSent uint64
// PacketsSent is the number of packets sent on the underlying connection,
// including those that are determined to have been lost.
PacketsSent uint64
// BytesReceived is the number of total bytes received on the underlying
// connection, including duplicate data for streams. Does not include UDP or
// any other outer framing.
BytesReceived uint64
// PacketsReceived is the number of total packets received on the underlying
// connection, including packets that were not processable.
PacketsReceived uint64
// BytesLost is the number of bytes lost on the underlying connection (does
// not monotonically increase, because packets that are declared lost can
// subsequently be received). Does not include UDP or any other outer
// framing.
BytesLost uint64
// PacketsLost is the number of packets lost on the underlying connection
// (does not monotonically increase, because packets that are declared lost
// can subsequently be received).
PacketsLost uint64
}
ConnectionStats contains statistics about the QUIC connection
type DatagramTooLargeError ¶
type DatagramTooLargeError struct {
MaxDatagramPayloadSize int64
}
DatagramTooLargeError is returned from Conn.SendDatagram if the payload is too large to be sent.
func (*DatagramTooLargeError) Error ¶
func (e *DatagramTooLargeError) Error() string
func (*DatagramTooLargeError) Is ¶
func (e *DatagramTooLargeError) Is(target error) bool
type DefaultMultipathController ¶
type DefaultMultipathController struct {
// contains filtered or unexported fields
}
DefaultMultipathController is a MultipathController that selects paths using a PathScheduler. The connection opens, validates and abandons the paths. It informs the controller about the active paths (RegisterPath and RemovePath) and the packets sent, acknowledged and lost on them. The controller keeps statistics for these paths, which the scheduler uses to select one of the paths passed to SelectPath.
func NewDefaultMultipathController ¶
func NewDefaultMultipathController(scheduler PathScheduler) *DefaultMultipathController
NewDefaultMultipathController creates a new multipath controller with the specified scheduler. If scheduler is nil, it defaults to LowLatencyScheduler.
func (*DefaultMultipathController) GetScheduler ¶
func (c *DefaultMultipathController) GetScheduler() PathScheduler
GetScheduler returns the underlying PathScheduler.
func (*DefaultMultipathController) GetStatistics ¶
func (c *DefaultMultipathController) GetStatistics() map[PathID]PathStatistics
GetStatistics returns statistics for all paths.
func (*DefaultMultipathController) OnPacketAcked ¶
func (c *DefaultMultipathController) OnPacketAcked(pathID PathID)
OnPacketAcked is called when a packet is acknowledged.
func (*DefaultMultipathController) OnPacketLost ¶
func (c *DefaultMultipathController) OnPacketLost(pathID PathID)
OnPacketLost is called when a packet is lost.
func (*DefaultMultipathController) OnPacketSent ¶
func (c *DefaultMultipathController) OnPacketSent(pathID PathID, packetSize ByteCount)
OnPacketSent is called when a packet is sent on a path.
func (*DefaultMultipathController) RegisterPath ¶
func (c *DefaultMultipathController) RegisterPath(info PathInfo)
RegisterPath is called when a path becomes active. The controller collects statistics for the path from now on.
func (*DefaultMultipathController) RemovePath ¶
func (c *DefaultMultipathController) RemovePath(pathID PathID)
RemovePath is called when a path is abandoned. The statistics of the path are removed.
func (*DefaultMultipathController) SelectPath ¶
func (c *DefaultMultipathController) SelectPath(ctx PathSelectionContext) (PathInfo, bool)
SelectPath selects one of the paths in ctx.Paths for sending a packet, using the statistics collected for these paths. It returns false if ctx.Paths is empty, or if the scheduler doesn't select any of the paths.
func (*DefaultMultipathController) UpdatePathState ¶
func (c *DefaultMultipathController) UpdatePathState(pathID PathID, update PathStateUpdate)
UpdatePathState updates the state of a path.
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 ¶
ListenAddrEarly works like ListenAddr, but it returns connections before the handshake completes.
func ListenEarly ¶
func ListenEarly(conn net.PacketConn, tlsConf *tls.Config, config *Config) (*EarlyListener, error)
ListenEarly works like Listen, but it returns connections before the handshake completes.
func (*EarlyListener) Accept ¶
func (l *EarlyListener) Accept(ctx context.Context) (*Conn, error)
Accept returns a new connections. It should be called in a loop.
func (*EarlyListener) Addr ¶
func (l *EarlyListener) Addr() net.Addr
Addr returns the local network addr that the server is listening on.
func (*EarlyListener) Close ¶
func (l *EarlyListener) Close() error
Close closes the listener. EarlyListener.Accept will return ErrServerClosed as soon as all connections in the accept queue have been accepted. Early connections that are still in flight will be rejected with a CONNECTION_REFUSED error. Already established (accepted) connections will be unaffected.
type EncryptionLevel ¶
type EncryptionLevel = protocol.EncryptionLevel
EncryptionLevel is the QUIC encryption level.
type ExtensionFrameContext ¶
type ExtensionFrameContext struct {
FrameType uint64
EncryptionLevel EncryptionLevel
Version Version
Data []byte // frame payload without the type varint
}
ExtensionFrameContext provides context for a custom frame.
type ExtensionFrameHandler ¶
type ExtensionFrameHandler interface {
HandleFrame(ctx ExtensionFrameContext) (int, error)
}
ExtensionFrameHandler allows parsing of custom frame types.
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 ¶
Listen listens for QUIC connections on a given net.PacketConn. If the PacketConn satisfies the OOBCapablePacketConn interface (as a net.UDPConn does), ECN and packet info support will be enabled. In this case, packets will be read in batches, and OOBCapablePacketConn.WriteMsgUDP will be used instead of net.PacketConn.WriteTo. A single net.PacketConn can only be used for a single call to Listen.
The tls.Config must not be nil and must contain a certificate configuration. Furthermore, it must define an application protocol using tls.Config.NextProtos. The Config may be nil, in which case the default values will be used.
This is a convenience function. More advanced use cases should instantiate a Transport, which offers configuration options for a more fine-grained control of the connection establishment, including reusing the underlying UDP socket for outgoing QUIC connections. When closing a listener created with Listen, all established QUIC connections will be closed immediately.
func ListenAddr ¶
ListenAddr creates a QUIC server listening on a given address. See Listen for more details.
func (*Listener) Close ¶
Close closes the listener. Listener.Accept will return ErrServerClosed as soon as all connections in the accept queue have been accepted. QUIC handshakes that are still in flight will be rejected with a CONNECTION_REFUSED error. Already established (accepted) connections will be unaffected.
type LowLatencyScheduler ¶
type LowLatencyScheduler struct {
// contains filtered or unexported fields
}
LowLatencyScheduler implements a low-latency scheduling algorithm. It prefers paths with lower RTT for better latency.
func NewLowLatencyScheduler ¶
func NewLowLatencyScheduler() *LowLatencyScheduler
NewLowLatencyScheduler creates a new low-latency scheduler.
func (*LowLatencyScheduler) Reset ¶
func (s *LowLatencyScheduler) Reset()
Reset clears all quota counters.
func (*LowLatencyScheduler) SelectPath ¶
func (s *LowLatencyScheduler) SelectPath(paths []SchedulerPathInfo, hasRetransmission bool) *SchedulerPathInfo
SelectPath selects the path with the lowest RTT. For unprobed paths (RTT == 0), it uses quotas to distribute initial probing. Backup paths are only selected if no other path can be selected.
func (*LowLatencyScheduler) UpdateQuota ¶
func (s *LowLatencyScheduler) UpdateQuota(pathID PathID, packetSize ByteCount)
UpdateQuota increments the quota for a path after sending a packet.
type MinRTTScheduler ¶
type MinRTTScheduler struct {
// contains filtered or unexported fields
}
MinRTTScheduler implements a minimum RTT scheduling algorithm with smoothing. It uses a weighted approach to balance between RTT and path utilization.
func NewMinRTTScheduler ¶
func NewMinRTTScheduler(rttBias float64) *MinRTTScheduler
NewMinRTTScheduler creates a new minimum RTT scheduler. rttBias controls the trade-off between RTT optimization and load balancing: - 1.0: Pure minimum RTT (no load balancing) - 0.5: Balanced between RTT and load distribution - 0.0: Pure load balancing (ignores RTT)
func (*MinRTTScheduler) GetStatistics ¶
func (s *MinRTTScheduler) GetStatistics() map[PathID]SchedulerStats
GetStatistics returns scheduling statistics for monitoring and debugging.
func (*MinRTTScheduler) SelectPath ¶
func (s *MinRTTScheduler) SelectPath(paths []SchedulerPathInfo, hasRetransmission bool) *SchedulerPathInfo
SelectPath selects the path with the best score based on RTT and quota. Backup paths are only selected if no other path can be selected.
func (*MinRTTScheduler) UpdateQuota ¶
func (s *MinRTTScheduler) UpdateQuota(pathID PathID, packetSize ByteCount)
UpdateQuota updates statistics after sending a packet.
type MultiSocketManager ¶
type MultiSocketManager struct {
// contains filtered or unexported fields
}
MultiSocketManager manages multiple UDP sockets for multipath and hot-plug scenarios. It implements both net.PacketConn and rawConn, and can be used as Transport.Conn.
func NewMultiSocketManager ¶
func NewMultiSocketManager(cfg MultiSocketManagerConfig) (*MultiSocketManager, error)
NewMultiSocketManager creates a MultiSocketManager.
func (*MultiSocketManager) AddLocalAddr ¶
AddLocalAddr adds a new UDP socket bound to the given local IP.
func (*MultiSocketManager) Close ¶
func (m *MultiSocketManager) Close() error
func (*MultiSocketManager) LocalAddr ¶
func (m *MultiSocketManager) LocalAddr() net.Addr
func (*MultiSocketManager) LocalAddrs ¶
func (m *MultiSocketManager) LocalAddrs() []net.IP
LocalAddrs returns the list of managed local IPs.
func (*MultiSocketManager) ReadPacket ¶
func (m *MultiSocketManager) ReadPacket() (receivedPacket, error)
func (*MultiSocketManager) RefreshInterfaces ¶
func (m *MultiSocketManager) RefreshInterfaces() error
RefreshInterfaces scans system interfaces and syncs sockets.
func (*MultiSocketManager) RemoveLocalAddr ¶
func (m *MultiSocketManager) RemoveLocalAddr(ip net.IP) bool
RemoveLocalAddr removes and closes a socket bound to the given local IP.
func (*MultiSocketManager) SetDeadline ¶
func (m *MultiSocketManager) SetDeadline(t time.Time) error
func (*MultiSocketManager) SetLocalAddrs ¶
func (m *MultiSocketManager) SetLocalAddrs(addrs []net.IP) error
SetLocalAddrs synchronizes the managed sockets with the provided IP list.
func (*MultiSocketManager) SetReadDeadline ¶
func (m *MultiSocketManager) SetReadDeadline(t time.Time) error
func (*MultiSocketManager) SetWriteDeadline ¶
func (m *MultiSocketManager) SetWriteDeadline(t time.Time) error
func (*MultiSocketManager) WritePacket ¶
func (*MultiSocketManager) WritePacketWithInfo ¶
type MultiSocketManagerConfig ¶
type MultiSocketManagerConfig struct {
// BaseConn is the primary socket. If nil, a UDP socket is opened on 0.0.0.0:0.
BaseConn net.PacketConn
// ListenPort is the port to bind new sockets to. 0 uses an ephemeral port.
ListenPort int
// LocalAddrs are the local IPs to bind new sockets to.
LocalAddrs []net.IP
// RefreshInterval enables periodic interface refresh. 0 disables it.
RefreshInterval time.Duration
// IncludeLoopback enables loopback interface addresses in refresh.
IncludeLoopback bool
// AllowIPv6 enables IPv6 addresses in refresh.
AllowIPv6 bool
// Logger defaults to utils.DefaultLogger if nil.
Logger utils.Logger
}
MultiSocketManagerConfig controls MultiSocketManager behavior.
type MultipathAddressObserver ¶ added in v0.3.0
type MultipathAddressObserver interface {
OnAddressAdvertised(AdvertisedAddress)
}
MultipathAddressObserver is an optional interface of a MultipathController. OnAddressAdvertised is called when the peer advertised a new address using the address advertisement extension (see Config.EnableAddressAdvertisement), or a new address for an address ID it advertised before. It is called from the connection's run loop, and must not block.
type MultipathCongestionControl ¶
type MultipathCongestionControl uint8
MultipathCongestionControl is the congestion control algorithm used on multipath connections.
const ( // MultipathCongestionControlReno is the default: every path has its own congestion controller, the Reno // controller that quic-go uses for single-path connections (slow start, an increase of one datagram per window // in congestion avoidance, a multiplicative decrease of 0.7 as in CUBIC, and pacing). // The controllers are not coupled (section 5.3 of draft-ietf-quic-multipath-21). MultipathCongestionControlReno MultipathCongestionControl = iota // MultipathCongestionControlOLIA uses the coupled OLIA congestion controller. // Every path has its own controller, coupled to the controllers of the other paths, // and these controllers limit the sending rate. // The OLIA controller of path 0 takes over when the handshake completes, // continuing with the congestion window and the recovery state of the NewReno controller used until then. MultipathCongestionControlOLIA )
type MultipathController ¶
type MultipathController interface {
SelectPath(PathSelectionContext) (PathInfo, bool)
}
MultipathController selects the paths of IETF Multipath QUIC that packets are sent on. Configuring a controller enables IETF Multipath QUIC (draft-ietf-quic-multipath-21).
The connection opens, validates and closes the paths: the path of a received packet is identified by its connection ID. The connection calls SelectPath for every packet carrying data, passing the paths that can be used in the PathSelectionContext, and it informs the controller about the paths using the optional methods EnableMultipath, RegisterPath (when a path becomes active), ValidatePath, RemovePath (when a path is abandoned), UpdatePathState, OnPacketSent, OnPacketAcked and OnPacketLost (or the methods of MultipathObserver).
type MultipathDuplicationPolicy ¶
type MultipathDuplicationPolicy struct {
// contains filtered or unexported fields
}
MultipathDuplicationPolicy defines when and how to duplicate packets across paths
func NewMultipathDuplicationPolicy ¶
func NewMultipathDuplicationPolicy() *MultipathDuplicationPolicy
NewMultipathDuplicationPolicy creates a new duplication policy with defaults
func (*MultipathDuplicationPolicy) AddStreamForDuplication ¶
func (p *MultipathDuplicationPolicy) AddStreamForDuplication(streamID protocol.StreamID)
AddStreamForDuplication marks a stream for packet duplication
func (*MultipathDuplicationPolicy) Disable ¶
func (p *MultipathDuplicationPolicy) Disable()
Disable disables packet duplication
func (*MultipathDuplicationPolicy) Enable ¶
func (p *MultipathDuplicationPolicy) Enable()
Enable enables packet duplication
func (*MultipathDuplicationPolicy) GetDuplicatePathCount ¶
func (p *MultipathDuplicationPolicy) GetDuplicatePathCount() int
GetDuplicatePathCount returns how many paths to use for duplication
func (*MultipathDuplicationPolicy) IsEnabled ¶
func (p *MultipathDuplicationPolicy) IsEnabled() bool
IsEnabled returns whether duplication is enabled
func (*MultipathDuplicationPolicy) RemoveStreamForDuplication ¶
func (p *MultipathDuplicationPolicy) RemoveStreamForDuplication(streamID protocol.StreamID)
RemoveStreamForDuplication removes a stream from duplication
func (*MultipathDuplicationPolicy) SetDuplicateAllStreams ¶
func (p *MultipathDuplicationPolicy) SetDuplicateAllStreams(enable bool)
SetDuplicateAllStreams applies the policy to future as well as current streams.
func (*MultipathDuplicationPolicy) SetDuplicateCryptoFrames ¶
func (p *MultipathDuplicationPolicy) SetDuplicateCryptoFrames(enable bool)
SetDuplicateCryptoFrames sets whether to duplicate crypto frames
func (*MultipathDuplicationPolicy) SetDuplicatePathCount ¶
func (p *MultipathDuplicationPolicy) SetDuplicatePathCount(count int)
SetDuplicatePathCount sets how many paths to use for duplication
func (*MultipathDuplicationPolicy) SetDuplicateResets ¶
func (p *MultipathDuplicationPolicy) SetDuplicateResets(enable bool)
SetDuplicateResets sets whether to duplicate reset frames
func (*MultipathDuplicationPolicy) ShouldDuplicateCrypto ¶
func (p *MultipathDuplicationPolicy) ShouldDuplicateCrypto() bool
ShouldDuplicateCrypto returns whether crypto frames should be duplicated
func (*MultipathDuplicationPolicy) ShouldDuplicateReset ¶
func (p *MultipathDuplicationPolicy) ShouldDuplicateReset() bool
ShouldDuplicateReset returns whether RST_STREAM frames should be duplicated
func (*MultipathDuplicationPolicy) ShouldDuplicateStream ¶
func (p *MultipathDuplicationPolicy) ShouldDuplicateStream(streamID protocol.StreamID) bool
ShouldDuplicateStream returns whether frames for this stream should be duplicated
type MultipathObserver ¶
type MultipathObserver interface {
OnPacketSent(PathEvent)
OnPacketAcked(PathEvent)
OnPacketLost(PathEvent)
}
MultipathObserver receives per-packet events with path information.
type MultipathReinjectionManager ¶
type MultipathReinjectionManager struct {
// contains filtered or unexported fields
}
MultipathReinjectionManager manages packet reinjection across paths
func NewMultipathReinjectionManager ¶
func NewMultipathReinjectionManager(policy *MultipathReinjectionPolicy) *MultipathReinjectionManager
NewMultipathReinjectionManager creates a new reinjection manager
func (*MultipathReinjectionManager) GetPendingReinjections ¶
func (m *MultipathReinjectionManager) GetPendingReinjections(now time.Time) []*PacketReinjectionInfo
GetPendingReinjections returns packets ready for reinjection, in ascending order of their path IDs and packet numbers.
func (*MultipathReinjectionManager) GetStatistics ¶
func (m *MultipathReinjectionManager) GetStatistics() (pending, reinjected int)
GetStatistics returns reinjection statistics
func (*MultipathReinjectionManager) MarkReinjected ¶
func (m *MultipathReinjectionManager) MarkReinjected(pathID protocol.PathID, pn protocol.PacketNumber, targetPath protocol.PathID)
MarkReinjected marks a packet sent on a path as having been reinjected
func (*MultipathReinjectionManager) OnPacketAcked ¶
func (m *MultipathReinjectionManager) OnPacketAcked(pathID protocol.PathID, pn protocol.PacketNumber)
OnPacketAcked is called when a packet sent on a path is acknowledged, removing it from tracking
func (*MultipathReinjectionManager) OnPacketLost ¶
func (m *MultipathReinjectionManager) OnPacketLost( pathID protocol.PathID, pn protocol.PacketNumber, encLevel protocol.EncryptionLevel, frames []ackhandler.Frame, )
OnPacketLost is called when a packet is lost and should be considered for reinjection
func (*MultipathReinjectionManager) Reset ¶
func (m *MultipathReinjectionManager) Reset()
Reset clears all reinjection state
type MultipathReinjectionPolicy ¶
type MultipathReinjectionPolicy struct {
// contains filtered or unexported fields
}
MultipathReinjectionPolicy defines when and how to reinject lost packets on alternate paths
func NewMultipathReinjectionPolicy ¶
func NewMultipathReinjectionPolicy() *MultipathReinjectionPolicy
NewMultipathReinjectionPolicy creates a new reinjection policy with defaults
func (*MultipathReinjectionPolicy) AddPreferredPathForReinjection ¶
func (p *MultipathReinjectionPolicy) AddPreferredPathForReinjection(pathID protocol.PathID)
AddPreferredPathForReinjection adds a path to the preferred list
func (*MultipathReinjectionPolicy) Disable ¶
func (p *MultipathReinjectionPolicy) Disable()
Disable disables packet reinjection
func (*MultipathReinjectionPolicy) Enable ¶
func (p *MultipathReinjectionPolicy) Enable()
Enable enables packet reinjection
func (*MultipathReinjectionPolicy) GetMaxReinjectionQueuePerPath ¶
func (p *MultipathReinjectionPolicy) GetMaxReinjectionQueuePerPath() int
GetMaxReinjectionQueuePerPath returns the maximum queue size per target path
func (*MultipathReinjectionPolicy) GetMaxReinjections ¶
func (p *MultipathReinjectionPolicy) GetMaxReinjections() int
GetMaxReinjections returns the maximum number of reinjections
func (*MultipathReinjectionPolicy) GetMinReinjectionInterval ¶
func (p *MultipathReinjectionPolicy) GetMinReinjectionInterval() time.Duration
GetMinReinjectionInterval returns the minimum reinjection interval
func (*MultipathReinjectionPolicy) GetReinjectionDelay ¶
func (p *MultipathReinjectionPolicy) GetReinjectionDelay() time.Duration
GetReinjectionDelay returns the current reinjection delay
func (*MultipathReinjectionPolicy) IsEnabled ¶
func (p *MultipathReinjectionPolicy) IsEnabled() bool
IsEnabled returns whether reinjection is enabled
func (*MultipathReinjectionPolicy) IsPreferredPathForReinjection ¶
func (p *MultipathReinjectionPolicy) IsPreferredPathForReinjection(pathID protocol.PathID) bool
IsPreferredPathForReinjection checks if a path is preferred for reinjection
func (*MultipathReinjectionPolicy) ReinjectsOnPTO ¶ added in v0.3.0
func (p *MultipathReinjectionPolicy) ReinjectsOnPTO() bool
ReinjectsOnPTO returns whether frames are reinjected when the probe timeout of a path expires.
func (*MultipathReinjectionPolicy) RemovePreferredPathForReinjection ¶
func (p *MultipathReinjectionPolicy) RemovePreferredPathForReinjection(pathID protocol.PathID)
RemovePreferredPathForReinjection removes a path from the preferred list
func (*MultipathReinjectionPolicy) SetMaxReinjectionQueuePerPath ¶
func (p *MultipathReinjectionPolicy) SetMaxReinjectionQueuePerPath(max int)
SetMaxReinjectionQueuePerPath sets the maximum queue size per target path (0 = unlimited)
func (*MultipathReinjectionPolicy) SetMaxReinjections ¶
func (p *MultipathReinjectionPolicy) SetMaxReinjections(max int)
SetMaxReinjections sets the maximum number of reinjections per packet
func (*MultipathReinjectionPolicy) SetMinReinjectionInterval ¶
func (p *MultipathReinjectionPolicy) SetMinReinjectionInterval(interval time.Duration)
SetMinReinjectionInterval sets a minimum interval between reinjections on the same path
func (*MultipathReinjectionPolicy) SetReinjectOnPTO ¶ added in v0.3.0
func (p *MultipathReinjectionPolicy) SetReinjectOnPTO(enable bool)
SetReinjectOnPTO sets whether the frames of the packets outstanding on a path are sent on another path when the probe timeout (PTO) of the path expires (section 5.7 of draft-ietf-quic-multipath-21). This only applies to IETF Multipath QUIC. The frames are sent in addition to the probe packets on the path, if the congestion window of the other path allows. The packets are not declared lost: if one of them is lost later, its frames are retransmitted as usual. Like all reinjections, it requires the policy to be enabled.
func (*MultipathReinjectionPolicy) SetReinjectionDelay ¶
func (p *MultipathReinjectionPolicy) SetReinjectionDelay(delay time.Duration)
SetReinjectionDelay sets the delay before reinjecting a lost packet
func (*MultipathReinjectionPolicy) ShouldReinjectFrame ¶
func (p *MultipathReinjectionPolicy) ShouldReinjectFrame(frame wire.Frame) bool
ShouldReinjectFrame determines if a frame should be reinjected
type MultipathReinjectionTargetSelector ¶
type MultipathReinjectionTargetSelector interface {
SelectReinjectionTarget(ReinjectionTargetContext) (PathID, bool)
}
MultipathReinjectionTargetSelector allows overriding reinjection target selection. Implement this on your MultipathController to customize reinjection path choice.
type MultipathScheduler ¶
type MultipathScheduler interface {
MultipathController
// GetScheduler returns the underlying PathScheduler if available.
GetScheduler() PathScheduler
}
MultipathScheduler provides advanced path scheduling capabilities. This is an optional extension to MultipathController.
type OLIACongestionControl ¶
type OLIACongestionControl struct {
// contains filtered or unexported fields
}
OLIACongestionControl implements the OLIA (Opportunistic Linked-Increase Algorithm) congestion control for multipath connections. OLIA provides coupled congestion control across multiple paths to ensure fairness and performance.
Every path of a connection has its own OLIACongestionControl, and all of them share one oliaSharedState (see NewOLIASharedState). The window of path r evolves as follows, with windows w in packets and RTTs in seconds:
- Slow start (cwnd < ssthresh): the window grows by the number of acknowledged bytes. Slow start ends at the first loss, or earlier when hybrid slow start detects a rising RTT (MaybeExitSlowStart).
- Congestion avoidance: for each acknowledged packet, w_r grows by (w_r/rtt_r²) / (Σ_p w_p/rtt_p)² + α_r/w_r. α_r moves window from the paths with the largest window to the presumably best paths (largest ℓ_p²/rtt_p, where ℓ_p is the number of bytes acknowledged between the last two losses, or since the last loss if that is larger).
- Loss: the window is halved, at most once per recovery epoch, as in Reno.
- Persistent congestion (section 7.6 of RFC 9002): the window drops to the minimum window, and slow start begins again.
The window never drops below 2 packets.
All methods are safe for concurrent use. Each controller is protected by its own mutex. The shared state has a separate mutex and only stores copies of the paths' states, so a controller never takes another controller's mutex. The lock order is always controller first, then shared state.
Reference: "MPTCP is not Pareto-optimal: performance issues and a possible solution" by R. Khalili et al., CoNEXT 2012, and draft-khalili-mptcp-congestion-control.
func NewOLIACongestionControl ¶
func NewOLIACongestionControl( pathID protocol.PathID, sharedState *oliaSharedState, maxDatagramSize protocol.ByteCount, ) *OLIACongestionControl
NewOLIACongestionControl creates a new OLIA congestion controller for a path. The controller uses the RTT passed to UpdateRTT, and utils.DefaultInitialRTT until then. If sharedState is nil, the controller is not coupled to other paths and behaves like Reno.
func (*OLIACongestionControl) CanSend ¶
func (o *OLIACongestionControl) CanSend(bytesInFlight protocol.ByteCount) bool
CanSend returns whether a packet can be sent.
func (*OLIACongestionControl) GetCongestionWindow ¶
func (o *OLIACongestionControl) GetCongestionWindow() protocol.ByteCount
GetCongestionWindow returns the current congestion window.
func (*OLIACongestionControl) GetStatistics ¶
func (o *OLIACongestionControl) GetStatistics() OLIAStatistics
GetStatistics returns congestion control statistics.
func (*OLIACongestionControl) InRecovery ¶
func (o *OLIACongestionControl) InRecovery() bool
InRecovery returns whether the connection is in recovery, i.e. whether no packet sent after the last window reduction has been acknowledged yet.
func (*OLIACongestionControl) InSlowStart ¶
func (o *OLIACongestionControl) InSlowStart() bool
InSlowStart returns whether the connection is in slow start.
func (*OLIACongestionControl) MaybeExitSlowStart ¶
func (o *OLIACongestionControl) MaybeExitSlowStart()
MaybeExitSlowStart exits slow start if hybrid slow start detects an RTT increase. It is called when an ACK provides a new RTT sample.
func (*OLIACongestionControl) OnCongestionEvent ¶
func (o *OLIACongestionControl) OnCongestionEvent( packetNumber protocol.PacketNumber, lostBytes protocol.ByteCount, priorInFlight protocol.ByteCount, )
OnCongestionEvent is called when congestion is detected (packet loss or ECN-CE). All congestion events for packets sent before the last window reduction belong to the same recovery epoch and are ignored.
func (*OLIACongestionControl) OnPacketAcked ¶
func (o *OLIACongestionControl) OnPacketAcked( packetNumber protocol.PacketNumber, ackedBytes protocol.ByteCount, bytesInFlight protocol.ByteCount, eventTime time.Time, )
OnPacketAcked is called when a packet is acknowledged. bytesInFlight is the number of bytes in flight before the packet was acknowledged. The window only grows if the sender is (almost) limited by it.
func (*OLIACongestionControl) OnPacketLost ¶
func (o *OLIACongestionControl) OnPacketLost( packetNumber protocol.PacketNumber, lostBytes protocol.ByteCount, priorInFlight protocol.ByteCount, )
OnPacketLost is called when a packet is declared lost.
func (*OLIACongestionControl) OnPacketSent ¶
func (o *OLIACongestionControl) OnPacketSent( sentTime time.Time, packetNumber protocol.PacketNumber, bytes protocol.ByteCount, isRetransmittable bool, )
OnPacketSent is called when a packet is sent.
func (*OLIACongestionControl) OnPersistentCongestion ¶ added in v0.3.0
func (o *OLIACongestionControl) OnPersistentCongestion()
OnPersistentCongestion is called when persistent congestion is established (section 7.6 of RFC 9002). The congestion window is reduced to the minimum window, and slow start begins again. The slow start threshold and the recovery period of the preceding congestion event are kept, so that losses of packets sent before that event don't reduce the window again.
func (*OLIACongestionControl) OnRetransmissionTimeout ¶
func (o *OLIACongestionControl) OnRetransmissionTimeout(packetsRetransmitted bool)
OnRetransmissionTimeout is called on an retransmission timeout.
func (*OLIACongestionControl) Reset ¶
func (o *OLIACongestionControl) Reset()
Reset resets the congestion control state. The RTT estimate is kept.
func (*OLIACongestionControl) SetMaxDatagramSize ¶
func (o *OLIACongestionControl) SetMaxDatagramSize(size protocol.ByteCount)
SetMaxDatagramSize updates the maximum datagram size.
func (*OLIACongestionControl) SmoothedBytesBetweenLosses ¶
func (o *OLIACongestionControl) SmoothedBytesBetweenLosses() protocol.ByteCount
SmoothedBytesBetweenLosses returns ℓ_r: the number of bytes acknowledged between the last two losses, or since the last loss if that is larger.
func (*OLIACongestionControl) Unregister ¶
func (o *OLIACongestionControl) Unregister()
Unregister removes this path from shared state. It should be called when the path is closed. It is safe to call it multiple times.
func (*OLIACongestionControl) UpdateRTT ¶
func (o *OLIACongestionControl) UpdateRTT(rtt, minRTT time.Duration)
UpdateRTT updates the RTT estimate for this path. Controllers created by NewOLIACongestionControlFactory read the RTT from the path's RTT statistics on every ACK and loss, which overrides values set here.
type OLIAStatistics ¶
type OLIAStatistics struct {
PathID protocol.PathID
CongestionWindow protocol.ByteCount
SlowStartThreshold protocol.ByteCount
BytesInFlight protocol.ByteCount
InSlowStart bool
InRecovery bool
// α_r = EpsilonNum / EpsilonDen, from the last congestion avoidance update.
EpsilonNum int
EpsilonDen uint32
RTT time.Duration
}
OLIAStatistics contains statistics for OLIA congestion control.
type OOBCapablePacketConn ¶
type OOBCapablePacketConn interface {
net.PacketConn
SyscallConn() (syscall.RawConn, error)
SetReadBuffer(int) error
ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error)
WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error)
}
OOBCapablePacketConn is a connection that allows the reading of ECN bits from the IP header. If the PacketConn passed to the Transport satisfies this interface, quic-go will use it. In this case, packets will be read in batches, and OOBCapablePacketConn.WriteMsgUDP will be used instead of net.PacketConn.WriteTo to write packets.
type PacketReinjectionInfo ¶
type PacketReinjectionInfo struct {
OriginalPathID protocol.PathID
PacketNumber protocol.PacketNumber
EncryptionLevel protocol.EncryptionLevel
Frames []ackhandler.Frame
LostTime time.Time
NextAttemptAt time.Time
ReinjectionCount int
LastReinjectedAt time.Time
TargetPathID protocol.PathID
}
PacketReinjectionInfo tracks information about a packet pending reinjection
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path is a network path.
func (*Path) Close ¶
Close abandons a path. It is not possible to close the path that’s currently active. With IETF Multipath QUIC, the last path that can be used for sending can't be closed. After closing, the path cannot be successfully probed again with Path.Probe.
func (*Path) ID ¶ added in v0.3.0
ID returns the path ID of a path of IETF Multipath QUIC. It returns false until the path was opened by Path.Probe, and for paths that are not paths of IETF Multipath QUIC, i.e. if IETF Multipath QUIC was not negotiated.
func (*Path) Probe ¶
Probe validates the path. With IETF Multipath QUIC, it first opens the path, using an unused path ID. If all path IDs allowed by Config.MaxPaths are in use, it returns ErrTooManyPaths. If all path IDs allowed by the peer are in use, it sends a PATHS_BLOCKED frame and waits until the peer allows more paths using a MAX_PATH_ID frame (section 3.2.1 of draft-ietf-quic-multipath-21). The peer might never do so, so the context should have a deadline. If the context is canceled before the path is validated, the path is abandoned. For a path added before completion of the handshake, Probe waits for the handshake to complete.
func (*Path) SetStatus ¶ added in v0.3.0
func (p *Path) SetStatus(status PathStatus) error
SetStatus sets the status of the path, and signals it to the peer (see section 3.3 of draft-ietf-quic-multipath-21). Data is only sent on a backup path if no other path can be used. The peer is asked to do the same. The status can be set before the path is probed: it is then sent together with the frames validating the path. It is only supported for paths of IETF Multipath QUIC.
func (*Path) Switch ¶
Switch switches the QUIC connection to this path. It immediately stops sending on the old path, and sends on this new path. With IETF Multipath QUIC, all validated paths are used for sending. Switch makes the path the preferred path: as long as it can be used, data is only sent on this path. The other paths stay open.
type PathEvent ¶
type PathEvent struct {
PathID PathID
PacketNumber PacketNumber
PacketSize ByteCount
EncryptionLevel EncryptionLevel
AckEliciting bool
IsPathProbe bool
IsPathMTUProbe bool
IsDuplicate bool // True if the packet duplicates frames sent on another path
SentAt time.Time
EventAt time.Time
SmoothedRTT time.Duration
RTTVar time.Duration
// CongestionWindow and BytesInFlight of the path, if known
CongestionWindow ByteCount
BytesInFlight ByteCount
}
PathEvent reports a packet lifecycle event for a specific path.
type PathID ¶
PathID identifies a network path.
const InvalidPathID PathID = protocol.InvalidPathID
InvalidPathID represents an unspecified path.
type PathInfo ¶
type PathInfo struct {
// ID is the path ID. Both endpoints use the same path ID for a path.
ID PathID
LocalAddr net.Addr
RemoteAddr net.Addr
IfIndex int
// State, Status and PeerStatus are only set for paths of IETF Multipath QUIC.
State PathState
// Status is the status set using [Path.SetStatus] or [Conn.SetPathStatus].
Status PathStatus
// PeerStatus is the status that the peer signaled for the path.
PeerStatus PathStatus
// ObservedAddr is the address that the peer observed for this endpoint on the path, using QUIC Address Discovery
// (see Config.RequestObservedAddress). It is the zero value if the peer didn't report an address for the path.
ObservedAddr netip.AddrPort
}
PathInfo describes a path used for sending.
type PathScheduler ¶
type PathScheduler interface {
// SelectPath selects the best path for sending a packet.
// It returns nil if no path is available for sending.
SelectPath(paths []SchedulerPathInfo, hasRetransmission bool) *SchedulerPathInfo
// UpdateQuota is called after a packet is sent on a path.
UpdateQuota(pathID PathID, packetSize ByteCount)
// Reset resets the scheduler state.
Reset()
}
PathScheduler defines the interface for multipath scheduling algorithms. A PathScheduler decides which path to use for sending the next packet.
type PathSchedulerWrapper ¶
type PathSchedulerWrapper struct {
// contains filtered or unexported fields
}
PathSchedulerWrapper is a MultipathController that selects paths using the scheduler of a SchedulingPolicy. It collects the statistics of the paths from the packet events (see MultipathObserver).
func NewMultipathScheduler ¶
func NewMultipathScheduler(policy SchedulingPolicy) *PathSchedulerWrapper
NewMultipathScheduler creates a new multipath controller using the scheduler of the policy.
func (*PathSchedulerWrapper) DisableMultipath ¶
func (s *PathSchedulerWrapper) DisableMultipath()
DisableMultipath stops updating the scheduler's quota (see RecordSent).
func (*PathSchedulerWrapper) EnableMultipath ¶
func (s *PathSchedulerWrapper) EnableMultipath()
EnableMultipath is called when IETF Multipath QUIC becomes active on the connection.
func (*PathSchedulerWrapper) IsMultipathEnabled ¶
func (s *PathSchedulerWrapper) IsMultipathEnabled() bool
IsMultipathEnabled returns whether multipath is enabled
func (*PathSchedulerWrapper) OnPacketAcked ¶
func (s *PathSchedulerWrapper) OnPacketAcked(ev PathEvent)
OnPacketAcked updates RTT statistics for a path.
func (*PathSchedulerWrapper) OnPacketLost ¶
func (s *PathSchedulerWrapper) OnPacketLost(ev PathEvent)
OnPacketLost updates the loss statistics of a path.
func (*PathSchedulerWrapper) OnPacketSent ¶
func (s *PathSchedulerWrapper) OnPacketSent(ev PathEvent)
OnPacketSent updates scheduler and path statistics.
func (*PathSchedulerWrapper) RecordSent ¶
func (s *PathSchedulerWrapper) RecordSent(pathID protocol.PathID, packetSize uint64)
RecordSent updates scheduler state after sending a packet
func (*PathSchedulerWrapper) RegisterPath ¶
func (s *PathSchedulerWrapper) RegisterPath(info PathInfo)
RegisterPath is called when a path becomes active. The statistics collected for the path are used when it is passed to SelectPath.
func (*PathSchedulerWrapper) RemovePath ¶
func (s *PathSchedulerWrapper) RemovePath(pathID PathID)
RemovePath is called when a path is abandoned. The statistics of the path are removed.
func (*PathSchedulerWrapper) SelectPath ¶
func (s *PathSchedulerWrapper) SelectPath(ctx PathSelectionContext) (PathInfo, bool)
SelectPath implements MultipathController interface. It selects one of the paths in ctx.Paths, using the statistics collected for these paths. It returns false if ctx.Paths is empty, or if the scheduler doesn't select any of the paths.
type PathSelectionContext ¶
type PathSelectionContext struct {
Now time.Time
AckOnly bool
HasRetransmission bool
BytesInFlight ByteCount
// PathCongestion returns the congestion window and the bytes in flight of a path.
// ok is false if no packet was sent on the path yet.
// A path whose congestion window is full should only be used for ACK-only packets and retransmissions.
// It is nil if the information is not available.
PathCongestion func(PathID) (congestionWindow, bytesInFlight ByteCount, ok bool)
// Paths are the paths that the packet can be sent on, in ascending order of their path IDs:
// the active paths that can send a packet now, i.e. that are neither congestion nor pacing limited.
// Backup paths are only included if no other active path can be used (section 3.3 of
// draft-ietf-quic-multipath-21), and paths that potentially failed only if no other active path is left.
// If SelectPath returns a path that is not one of them, the connection selects the path itself.
// The slice must not be retained after SelectPath returns.
Paths []PathInfo
}
PathSelectionContext provides context for path selection.
type PathState ¶ added in v0.3.0
type PathState uint8
PathState is the state of a path of IETF Multipath QUIC.
const ( // PathStateValidating means that the path is being validated (section 3.1 of draft-ietf-quic-multipath-21). // Only the frames needed to validate the path and acknowledgments are sent on it. PathStateValidating PathState = iota // PathStateActive means that the path was validated. It can be used for sending. PathStateActive // PathStateAbandoned means that the path was abandoned (section 3.4 of draft-ietf-quic-multipath-21). // No packets are sent on it anymore. Its state is kept for a while, since packets might still arrive on it. PathStateAbandoned )
type PathStateUpdate ¶
type PathStateUpdate struct {
SendingAllowed *bool
CongestionLimited *bool
BytesInFlight *ByteCount
CongestionWindow *ByteCount
SmoothedRTT *time.Duration
RTTVar *time.Duration
PotentiallyFailed *bool
}
PathStateUpdate contains optional updates for path state.
type PathStatistics ¶
type PathStatistics struct {
PathID PathID
PacketsSent uint64
BytesSent ByteCount
PacketsLost uint64
PacketsRetransmitted uint64
SmoothedRTT time.Duration
RTTVar time.Duration
CongestionWindow ByteCount
BytesInFlight ByteCount
LastPacketTime time.Time
}
PathStatistics contains statistics for a path.
type PathStatus ¶ added in v0.3.0
type PathStatus uint8
PathStatus is the status of a path of IETF Multipath QUIC, see section 3.3 of draft-ietf-quic-multipath-21.
const ( // PathStatusUnknown means that no status was set for the path. // The path is used like an available path. PathStatusUnknown PathStatus = iota // PathStatusAvailable means that the path can be used for sending. PathStatusAvailable // PathStatusBackup means that the path should only be used for sending if no available path can be used. PathStatusBackup )
func (PathStatus) String ¶ added in v0.3.0
func (s PathStatus) String() string
type PreferredAddress ¶ added in v0.3.0
type PreferredAddress struct {
// IPv4 is the preferred IPv4 address.
// It is not set if the server doesn't have a preferred IPv4 address.
IPv4 netip.AddrPort
// IPv4Transport is the Transport that receives the packets sent to the IPv4 address.
//
// If it is nil, the Transport of the listener receives them. Its connection needs to receive the packets sent to
// this address, and to report the local address of every packet received, for example a [net.UDPConn] bound to
// the unspecified address and the port of the preferred address (on platforms that support reading the packet
// info, like Linux, macOS and FreeBSD), or a [MultiSocketManager] with a socket bound to the preferred address.
//
// Otherwise, the Transport needs to use the same connection ID length and the same StatelessResetKey as the
// Transport of the listener. It must not be closed before the listener's Transport:
// closing it closes the connections of the listener.
IPv4Transport *Transport
// IPv6 is the preferred IPv6 address.
// It is not set if the server doesn't have a preferred IPv6 address.
IPv6 netip.AddrPort
// IPv6Transport is the Transport that receives the packets sent to the IPv6 address,
// see IPv4Transport. It can be the same Transport as IPv4Transport.
IPv6Transport *Transport
}
A PreferredAddress is an address that a server asks its clients to migrate connections to, once the handshake is confirmed (section 9.6 of RFC 9000). A typical use is a server that accepts connections on an address shared by multiple servers, e.g. an anycast address, and prefers its clients to use an address of its own.
The server sends the preferred_address transport parameter on every connection, together with a connection ID and a stateless reset token. A client validates the preferred address of the address family of the server address it connected to (or of the other address family, if it can send to it), and migrates the connection there if the validation succeeds. Otherwise, it keeps using the original address.
The server recognizes the packets sent to the preferred address by their local IP address. The preferred IP addresses therefore need to be different from the addresses that clients connect to. If a client connected to the preferred IP address of an address family, the preferred address of this address family is not sent to this client.
type RawFrame ¶
type RawFrame struct {
FrameType uint64
Data []byte // payload without the frame type varint
NonAckEliciting bool
RetransmitOnLoss bool
OnAcked func()
OnLost func()
}
RawFrame represents a custom frame payload with optional callbacks.
type ReceiveStream ¶
type ReceiveStream struct {
// contains filtered or unexported fields
}
A ReceiveStream is a unidirectional Receive Stream.
func (*ReceiveStream) CancelRead ¶
func (s *ReceiveStream) CancelRead(errorCode StreamErrorCode)
CancelRead aborts receiving on this stream. It instructs the peer to stop transmitting stream data. ReceiveStream.Read will unblock immediately, and future calls to it will fail. When called multiple times or after ReceiveStream.Read returns io.EOF, it is a no-op.
func (*ReceiveStream) Peek ¶
func (s *ReceiveStream) Peek(b []byte) (int, error)
Peek fills b with stream data, without consuming the stream data. It blocks until len(b) bytes are available, or an error occurs. It respects the stream deadline set by ReceiveStream.SetReadDeadline. If the stream ends before len(b) bytes are available, it returns the number of bytes peeked along with io.EOF.
func (*ReceiveStream) Read ¶
func (s *ReceiveStream) Read(p []byte) (int, error)
Read reads data from the stream. Read can be made to time out using ReceiveStream.SetReadDeadline. If the stream was canceled, the error is a StreamError.
func (*ReceiveStream) SetReadDeadline ¶
func (s *ReceiveStream) SetReadDeadline(t time.Time) error
SetReadDeadline sets the deadline for future ReceiveStream.Read calls and any currently blocked call. A zero value for t means ReceiveStream.Read will not time out.
func (*ReceiveStream) SetReceiveFinalSizeCallback ¶ added in v0.3.0
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 ReinjectionTargetContext ¶
type ReinjectionTargetContext struct {
Now time.Time
OriginalPathID PathID
Candidates []PathInfo
Packet *PacketReinjectionInfo
}
ReinjectionTargetContext provides context for selecting a reinjection target.
type RoundRobinScheduler ¶
type RoundRobinScheduler struct {
// contains filtered or unexported fields
}
RoundRobinScheduler implements a round-robin scheduling algorithm with quotas. It distributes packets evenly across all available paths.
func NewRoundRobinScheduler ¶
func NewRoundRobinScheduler() *RoundRobinScheduler
NewRoundRobinScheduler creates a new round-robin scheduler.
func (*RoundRobinScheduler) Reset ¶
func (s *RoundRobinScheduler) Reset()
Reset clears all quota counters.
func (*RoundRobinScheduler) SelectPath ¶
func (s *RoundRobinScheduler) SelectPath(paths []SchedulerPathInfo, hasRetransmission bool) *SchedulerPathInfo
SelectPath selects the path with the lowest quota. Backup paths are only selected if no other path can be selected.
func (*RoundRobinScheduler) UpdateQuota ¶
func (s *RoundRobinScheduler) UpdateQuota(pathID PathID, packetSize ByteCount)
UpdateQuota increments the quota for a path after sending a packet.
type SchedulerPathInfo ¶
type SchedulerPathInfo struct {
PathID PathID
RemoteAddr string
SendingAllowed bool
CongestionLimited bool
BytesInFlight ByteCount
CongestionWindow ByteCount
SmoothedRTT time.Duration
RTTVar time.Duration
PotentiallyFailed bool
PacketsSent uint64
BytesSent ByteCount
PacketsLost uint64
PacketsRetransmitted uint64
// Backup is set for backup paths of IETF Multipath QUIC (section 3.3 of draft-ietf-quic-multipath-21).
// They are only selected if no other path can be selected.
Backup bool
}
SchedulerPathInfo contains information about a path for scheduling decisions.
type SchedulerStats ¶
SchedulerStats contains statistics for a single path.
type SchedulingPolicy ¶
type SchedulingPolicy int
SchedulingPolicy defines the scheduling algorithm to use
const ( SchedulingPolicyRoundRobin SchedulingPolicy = iota SchedulingPolicyMinRTT SchedulingPolicyLowLatency )
type SendStream ¶
type SendStream struct {
// contains filtered or unexported fields
}
A SendStream is a unidirectional Send Stream.
func (*SendStream) CancelWrite ¶
func (s *SendStream) CancelWrite(errorCode StreamErrorCode)
CancelWrite aborts sending on this stream. Data already written, but not yet delivered to the peer is not guaranteed to be delivered reliably. SendStream.Write will unblock immediately, and future calls to it will fail. When called multiple times it is a no-op. When called after SendStream.Close, it aborts reliable delivery of outstanding stream data. Note that there is no guarantee if the peer will receive the FIN or the cancellation error first.
func (*SendStream) Close ¶
func (s *SendStream) Close() error
Close closes the write-direction of the stream. Future calls to SendStream.Write are not permitted after calling Close. It must not be called concurrently with SendStream.Write. It must not be called after calling SendStream.CancelWrite.
func (*SendStream) Context ¶
func (s *SendStream) Context() context.Context
The Context is canceled as soon as the write-side of the stream is closed. This happens when SendStream.Close or SendStream.CancelWrite is called, or when the peer cancels the read-side of their stream. The cancellation cause is set to the error that caused the stream to close, or context.Canceled in case the stream is closed without error.
func (*SendStream) SetPriority ¶ added in v0.3.0
func (s *SendStream) SetPriority(urgency int8, incremental bool)
SetPriority sets the scheduling priority for data sent on the stream. It uses the urgency and incremental parameters defined by RFC 9218. Urgency is clipped to the range 0 through 7, with lower values taking priority. Within an urgency level, incremental streams are scheduled round-robin, while non-incremental streams are scheduled by stream ID.
The default priority is urgency 3 with incremental set to true. RFC 9218 instead defaults incremental to false.
func (*SendStream) SetReliableBoundary ¶
func (s *SendStream) SetReliableBoundary()
SetReliableBoundary marks the data written to this stream so far as reliable. It is valid to call this function multiple times, thereby increasing the reliable size. It only has an effect if the peer enabled support for the RESET_STREAM_AT extension, otherwise, it is a no-op. When the stream is canceled, and the peer's flow control limits don't allow sending all data up to the reliable boundary yet, the RESET_STREAM_AT frame is sent once this data was sent.
func (*SendStream) SetWriteDeadline ¶
func (s *SendStream) SetWriteDeadline(t time.Time) error
SetWriteDeadline sets the deadline for future SendStream.Write calls and any currently blocked call. Even if write times out, it may return n > 0, indicating that some data was successfully written. A zero value for t means SendStream.Write will not time out.
func (*SendStream) StreamID ¶
func (s *SendStream) StreamID() StreamID
StreamID returns the stream ID.
func (*SendStream) TryWriteAll ¶ added in v0.3.0
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 ¶ added in v0.3.0
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 SessionTicketID ¶ added in v0.3.0
type SessionTicketID = handshake.SessionTicketID
A SessionTicketID identifies a session ticket issued by a server.
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 ¶
Close closes the send-direction of the stream. It does not close the receive-direction of the stream.
func (*Stream) 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 ¶
Peek fills b with stream data, without consuming the stream data. It blocks until len(b) bytes are available, or an error occurs. It respects the stream deadline set by Stream.SetReadDeadline. If the stream ends before len(b) bytes are available, it returns the number of bytes peeked along with io.EOF.
func (*Stream) Read ¶
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 ¶
SetDeadline sets the read and write deadlines associated with the stream. It is equivalent to calling both Stream.SetReadDeadline and Stream.SetWriteDeadline.
func (*Stream) SetPriority ¶ added in v0.3.0
SetPriority sets the scheduling priority for data sent on the stream. See SendStream.SetPriority for details.
func (*Stream) SetReadDeadline ¶
SetReadDeadline sets the deadline for future Stream.Read calls. See ReceiveStream.SetReadDeadline for more details.
func (*Stream) SetReceiveFinalSizeCallback ¶ added in v0.3.0
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 ¶
SetWriteDeadline sets the deadline for future Stream.Write calls. See SendStream.SetWriteDeadline for more details.
func (*Stream) TryWriteAll ¶ added in v0.3.0
TryWriteAll writes data to the stream if it can be queued immediately. See SendStream.TryWriteAll for more details.
func (*Stream) Write ¶
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 ¶ added in v0.3.0
WriteWithLimit writes data to the stream, subject to an additional send limit. See SendStream.WriteWithLimit for more details.
type StreamError ¶
type StreamError struct {
StreamID StreamID
ErrorCode StreamErrorCode
Remote bool
}
A StreamError is used to signal stream cancellations. It can be returned by stream methods such as ReceiveStream.Read, SendStream.Write, Stream.Read, and Stream.Write.
func (*StreamError) Error ¶
func (e *StreamError) Error() string
func (*StreamError) Is ¶
func (e *StreamError) Is(target error) bool
type StreamErrorCode ¶
type StreamErrorCode = qerr.StreamErrorCode
StreamErrorCode is a QUIC stream error code. The meaning of the value is defined by the application.
type StreamLimitReachedError ¶
type StreamLimitReachedError struct{}
StreamLimitReachedError is returned from Conn.OpenStream and Conn.OpenUniStream when it is not possible to open a new stream because the number of open streams has reached the peer's stream limit.
func (StreamLimitReachedError) Error ¶
func (e StreamLimitReachedError) Error() string
type 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 connection implements [OOBCapablePacketConn],
// as a [net.UDPConn] does.
// 1. It enables the Don't Fragment (DF) bit on the IP header.
// This is required to run DPLPMTUD (Path MTU Discovery, RFC 8899).
// 2. It enables reading of the ECN bits from the IP header.
// This allows the remote node to speed up its loss detection and recovery.
// 3. It uses batched syscalls (recvmmsg) to more efficiently receive packets from the socket.
// 4. It uses Generic Segmentation Offload (GSO) to efficiently send batches of packets (on Linux).
//
// After passing the connection to the Transport, it's invalid to call [net.PacketConn.ReadFrom],
// [net.PacketConn.WriteTo], [OOBCapablePacketConn.ReadMsgUDP], or
// [OOBCapablePacketConn.WriteMsgUDP] on the connection.
//
// A client discards packets from server addresses other than the one it dialed (and the server's preferred
// address), as required by section 9 of RFC 9000. This only applies if the connection reports the source address
// of a packet as a [*net.UDPAddr]. A connection reporting other kinds of addresses is responsible for only
// passing packets from the server to the client.
// If the client dialed an unspecified IP address (e.g. 0.0.0.0 or ::), the operating system chooses where the
// packets go, usually to a loopback address. The client then accepts packets from the address that the first
// packet it processed came from.
// A server with multiple IP addresses has to send its packets from the address the client sent its packets to.
// A server using a connection that can't set the source address of packets (e.g. without
// [OOBCapablePacketConn], or on Windows) should therefore listen on a specific IP address.
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.
// A connection never issues the same connection ID twice (section 5.1 of RFC 9000). With the built-in generator,
// every connection generates its connection IDs with a keyed permutation, which never repeats a connection ID.
// A ConnectionIDGenerator set here MUST never return the same connection ID twice: the connection only checks
// that a new connection ID is not used by itself or by another connection of the Transport, but doesn't
// remember the connection IDs that were retired.
ConnectionIDGenerator ConnectionIDGenerator
// The StatelessResetKey is used to generate stateless reset tokens.
// If no key is configured, sending of stateless resets is disabled.
// It is highly recommended to configure a stateless reset key, as stateless resets
// allow the peer to quickly recover from crashes and reboots of this node.
// See section 10.3 of RFC 9000 for details.
StatelessResetKey *StatelessResetKey
// The TokenGeneratorKey is used to encrypt session resumption tokens.
// If no key is configured, a random key will be generated.
// If multiple servers are authoritative for the same domain, they should use the same key,
// see section 8.1.3 of RFC 9000 for details.
TokenGeneratorKey *TokenGeneratorKey
// MaxTokenAge is the maximum age of the resumption token presented during the handshake.
// These tokens allow skipping address resumption when resuming a QUIC connection,
// and are especially useful when using 0-RTT.
// If not set, it defaults to 24 hours.
// See section 8.1.3 of RFC 9000 for details.
MaxTokenAge time.Duration
// DisableVersionNegotiationPackets disables the sending of Version Negotiation packets.
// This can be useful if version information is exchanged out-of-band.
// It has no effect for clients.
DisableVersionNegotiationPackets bool
// VerifySourceAddress decides if a connection attempt originating from unvalidated source
// addresses first needs to go through source address validation using QUIC's Retry mechanism,
// as described in RFC 9000 section 8.1.2.
// Note that the address passed to this callback is unvalidated, and might be spoofed in case
// of an attack.
// Validating the source address adds one additional network roundtrip to the handshake,
// and should therefore only be used if a suspiciously high number of incoming connection is recorded.
// For most use cases, wrapping the Allow function of a rate.Limiter will be a reasonable
// implementation of this callback (negating its return value).
VerifySourceAddress func(net.Addr) bool
// ConnContext is called when the server accepts a new connection. To reject a connection return
// a non-nil error.
// The context is closed when the connection is closed, or when the handshake fails for any reason.
// The context returned from the callback is used to derive every other context used during the
// lifetime of the connection:
// * the context passed to crypto/tls (and used on the [tls.ClientHelloInfo])
// * the context used by [Config.Tracer]
// * the context returned from [Conn.Context]
// * the context returned from [SendStream.Context]
// It is not used for dialed connections.
ConnContext func(context.Context, *ClientInfo) (context.Context, error)
// A Tracer traces events that don't belong to a single QUIC connection.
// The [qlogwriter.Recorder] is closed when the transport is closed.
Tracer qlogwriter.Recorder
// PreferredAddress is the address that the server asks its clients to migrate connections to,
// once the handshake is confirmed (section 9.6 of RFC 9000).
// It applies to the connections accepted by the Listener of this Transport, and must be set before calling
// Listen or ListenEarly. It has no effect for clients.
PreferredAddress *PreferredAddress
// 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 ¶
Close stops listening for UDP datagrams on Transport.Conn. It abruptly terminates all existing connections, without sending a CONNECTION_CLOSE to the peers. It is the application's responsibility to cleanly terminate existing connections prior to calling Close.
If a server was started, it will be closed as well. It is not possible to start any new server or dial new connections after that.
func (*Transport) Dial ¶
func (t *Transport) Dial(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)
Dial dials a new connection to a remote host (not using 0-RTT).
func (*Transport) DialEarly ¶
func (t *Transport) DialEarly(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (*Conn, error)
DialEarly dials a new connection, attempting to use 0-RTT if possible.
func (*Transport) Listen ¶
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 ¶
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 ¶
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. Packets whose connection ID belongs to a connection with Config.EnableQUICBitGreasing are QUIC packets, since the peer might set the second bit (the QUIC Bit) to 0 (RFC 9287).
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 ¶
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.
type ZeroRTTReplayCache ¶ added in v0.3.0
type ZeroRTTReplayCache interface {
// UseTicket records that the session ticket with this ID is used for 0-RTT.
// It returns true if 0-RTT can be accepted, which must only happen once for every ID.
// issued is the time the ticket was issued, with microsecond precision.
// It is called concurrently by all connections of a server.
UseTicket(id SessionTicketID, issued time.Time) bool
}
A ZeroRTTReplayCache protects a server against the replay of 0-RTT data (section 9.2 of RFC 9001): 0-RTT is accepted at most once for every session ticket (section 8.1 of RFC 8446).
Every session ticket issued by the server contains a random ID and the time it was issued. When a client uses a session ticket for 0-RTT, UseTicket is called before 0-RTT is accepted. If UseTicket returns false, the server rejects 0-RTT, and the handshake continues as a 1-RTT handshake. The client then sends the data again in 1-RTT packets.
The cache built into the Transport (see NewZeroRTTReplayCache) only protects the server using that Transport. An attacker can replay a ClientHello to every server that can decrypt the session ticket, i.e. all servers that share the session ticket keys of the tls.Config. Deployments with several servers should therefore use a cache shared by these servers.
func NewZeroRTTReplayCache ¶ added in v0.3.0
func NewZeroRTTReplayCache(window time.Duration, maxTickets int) ZeroRTTReplayCache
NewZeroRTTReplayCache returns a ZeroRTTReplayCache that keeps the IDs of the session tickets used for 0-RTT in memory. A session ticket can be used for 0-RTT within the window after it was issued. Older session tickets can still be used for session resumption, but 0-RTT is rejected. IDs are kept for at least window, and at most 2 times the window. 0-RTT is rejected if maxTickets IDs are kept, which limits the memory used.
Session tickets issued before the cache was created are not used for 0-RTT, since they might have been used for 0-RTT before, e.g. before the server was restarted.
Source Files
¶
- address_discovery.go
- buffer_pool.go
- client.go
- closed_conn.go
- config.go
- conn_id_generator.go
- conn_id_manager.go
- conn_id_permutation.go
- connection.go
- connection_logging.go
- crypto_stream.go
- crypto_stream_manager.go
- datagram_queue.go
- errors.go
- flow_controller_base.go
- flow_controller_connection.go
- flow_controller_stream.go
- frame_sorter.go
- framer.go
- interface.go
- mtu_discoverer.go
- multi_socket_manager.go
- multipath.go
- multipath_address.go
- multipath_auto_paths.go
- multipath_congestion.go
- multipath_connection.go
- multipath_controller.go
- multipath_copies.go
- multipath_duplication.go
- multipath_events.go
- multipath_failure_detector.go
- multipath_olia.go
- multipath_path.go
- multipath_reinjection.go
- multipath_scheduler.go
- multipath_scheduler_wrapper.go
- multipath_send.go
- multipath_tuple_manager.go
- packet_packer.go
- packet_unpacker.go
- path_manager.go
- path_manager_outgoing.go
- preferred_address.go
- receive_stream.go
- retransmission_queue.go
- send_conn.go
- send_queue.go
- send_stream.go
- server.go
- sni.go
- stateless_reset.go
- stream.go
- streams_map.go
- streams_map_incoming.go
- streams_map_outgoing.go
- sys_conn.go
- sys_conn_buffers.go
- sys_conn_buffers_inspect.go
- sys_conn_buffers_nonopenbsd.go
- sys_conn_buffers_write.go
- sys_conn_df_linux.go
- sys_conn_helper_linux.go
- sys_conn_oob.go
- token_store.go
- transport.go
- version_negotiation.go
- zero_rtt_replay.go
Directories
¶
| Path | Synopsis |
|---|---|
|
client
command
|
|
|
echo
command
|
|
|
multipath
command
This example uses IETF Multipath QUIC (draft-ietf-quic-multipath-21).
|
This example uses IETF Multipath QUIC (draft-ietf-quic-multipath-21). |
|
integrationtests
|
|
|
internal
|
|
|
mocks
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |
|
mocks/ackhandler
Package mockackhandler is a generated GoMock package.
|
Package mockackhandler is a generated GoMock package. |
|
monotime
Package monotime provides a monotonic time representation that is useful for measuring elapsed time.
|
Package monotime provides a monotonic time representation that is useful for measuring elapsed time. |
|
utils/linkedlist
Package list implements a doubly linked list.
|
Package list implements a doubly linked list. |
|
interop
|
|
|
client
command
|
|
|
multipath
Package multipath contains interoperability tests of IETF Multipath QUIC (draft-ietf-quic-multipath-21) with picoquic.
|
Package multipath contains interoperability tests of IETF Multipath QUIC (draft-ietf-quic-multipath-21) with picoquic. |
|
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. |