github.com/daeuniverse/quic-go@v0.0.0-20240413031024-943f218e0810/interface.go (about) 1 package quic 2 3 import ( 4 "context" 5 "crypto/tls" 6 "errors" 7 "io" 8 "net" 9 "time" 10 11 "github.com/daeuniverse/quic-go/congestion" 12 "github.com/daeuniverse/quic-go/internal/handshake" 13 "github.com/daeuniverse/quic-go/internal/protocol" 14 "github.com/daeuniverse/quic-go/logging" 15 ) 16 17 // The StreamID is the ID of a QUIC stream. 18 type StreamID = protocol.StreamID 19 20 // A Version is a QUIC version number. 21 type Version = protocol.Version 22 23 // A VersionNumber is a QUIC version number. 24 // Deprecated: VersionNumber was renamed to Version. 25 type VersionNumber = Version 26 27 const ( 28 // Version1 is RFC 9000 29 Version1 = protocol.Version1 30 // Version2 is RFC 9369 31 Version2 = protocol.Version2 32 ) 33 34 // A ClientToken is a token received by the client. 35 // It can be used to skip address validation on future connection attempts. 36 type ClientToken struct { 37 data []byte 38 } 39 40 type TokenStore interface { 41 // Pop searches for a ClientToken associated with the given key. 42 // Since tokens are not supposed to be reused, it must remove the token from the cache. 43 // It returns nil when no token is found. 44 Pop(key string) (token *ClientToken) 45 46 // Put adds a token to the cache with the given key. It might get called 47 // multiple times in a connection. 48 Put(key string, token *ClientToken) 49 } 50 51 // Err0RTTRejected is the returned from: 52 // * Open{Uni}Stream{Sync} 53 // * Accept{Uni}Stream 54 // * Stream.Read and Stream.Write 55 // when the server rejects a 0-RTT connection attempt. 56 var Err0RTTRejected = errors.New("0-RTT rejected") 57 58 // ConnectionTracingKey can be used to associate a ConnectionTracer with a Connection. 59 // It is set on the Connection.Context() context, 60 // as well as on the context passed to logging.Tracer.NewConnectionTracer. 61 var ConnectionTracingKey = connTracingCtxKey{} 62 63 type connTracingCtxKey struct{} 64 65 // QUICVersionContextKey can be used to find out the QUIC version of a TLS handshake from the 66 // context returned by tls.Config.ClientHelloInfo.Context. 67 var QUICVersionContextKey = handshake.QUICVersionContextKey 68 69 // Stream is the interface implemented by QUIC streams 70 // In addition to the errors listed on the Connection, 71 // calls to stream functions can return a StreamError if the stream is canceled. 72 type Stream interface { 73 ReceiveStream 74 SendStream 75 // SetDeadline sets the read and write deadlines associated 76 // with the connection. It is equivalent to calling both 77 // SetReadDeadline and SetWriteDeadline. 78 SetDeadline(t time.Time) error 79 } 80 81 // A ReceiveStream is a unidirectional Receive Stream. 82 type ReceiveStream interface { 83 // StreamID returns the stream ID. 84 StreamID() StreamID 85 // Read reads data from the stream. 86 // Read can be made to time out and return a net.Error with Timeout() == true 87 // after a fixed time limit; see SetDeadline and SetReadDeadline. 88 // If the stream was canceled by the peer, the error implements the StreamError 89 // interface, and Canceled() == true. 90 // If the connection was closed due to a timeout, the error satisfies 91 // the net.Error interface, and Timeout() will be true. 92 io.Reader 93 // CancelRead aborts receiving on this stream. 94 // It will ask the peer to stop transmitting stream data. 95 // Read will unblock immediately, and future Read calls will fail. 96 // When called multiple times or after reading the io.EOF it is a no-op. 97 CancelRead(StreamErrorCode) 98 // SetReadDeadline sets the deadline for future Read calls and 99 // any currently-blocked Read call. 100 // A zero value for t means Read will not time out. 101 102 SetReadDeadline(t time.Time) error 103 } 104 105 // A SendStream is a unidirectional Send Stream. 106 type SendStream interface { 107 // StreamID returns the stream ID. 108 StreamID() StreamID 109 // Write writes data to the stream. 110 // Write can be made to time out and return a net.Error with Timeout() == true 111 // after a fixed time limit; see SetDeadline and SetWriteDeadline. 112 // If the stream was canceled by the peer, the error implements the StreamError 113 // interface, and Canceled() == true. 114 // If the connection was closed due to a timeout, the error satisfies 115 // the net.Error interface, and Timeout() will be true. 116 io.Writer 117 // Close closes the write-direction of the stream. 118 // Future calls to Write are not permitted after calling Close. 119 // It must not be called concurrently with Write. 120 // It must not be called after calling CancelWrite. 121 io.Closer 122 // CancelWrite aborts sending on this stream. 123 // Data already written, but not yet delivered to the peer is not guaranteed to be delivered reliably. 124 // Write will unblock immediately, and future calls to Write will fail. 125 // When called multiple times or after closing the stream it is a no-op. 126 CancelWrite(StreamErrorCode) 127 // The Context is canceled as soon as the write-side of the stream is closed. 128 // This happens when Close() or CancelWrite() is called, or when the peer 129 // cancels the read-side of their stream. 130 // The cancellation cause is set to the error that caused the stream to 131 // close, or `context.Canceled` in case the stream is closed without error. 132 Context() context.Context 133 // SetWriteDeadline sets the deadline for future Write calls 134 // and any currently-blocked Write call. 135 // Even if write times out, it may return n > 0, indicating that 136 // some data was successfully written. 137 // A zero value for t means Write will not time out. 138 SetWriteDeadline(t time.Time) error 139 } 140 141 // A Connection is a QUIC connection between two peers. 142 // Calls to the connection (and to streams) can return the following types of errors: 143 // * ApplicationError: for errors triggered by the application running on top of QUIC 144 // * TransportError: for errors triggered by the QUIC transport (in many cases a misbehaving peer) 145 // * IdleTimeoutError: when the peer goes away unexpectedly (this is a net.Error timeout error) 146 // * HandshakeTimeoutError: when the cryptographic handshake takes too long (this is a net.Error timeout error) 147 // * StatelessResetError: when we receive a stateless reset (this is a net.Error temporary error) 148 // * VersionNegotiationError: returned by the client, when there's no version overlap between the peers 149 type Connection interface { 150 // AcceptStream returns the next stream opened by the peer, blocking until one is available. 151 // If the connection was closed due to a timeout, the error satisfies 152 // the net.Error interface, and Timeout() will be true. 153 AcceptStream(context.Context) (Stream, error) 154 // AcceptUniStream returns the next unidirectional stream opened by the peer, blocking until one is available. 155 // If the connection was closed due to a timeout, the error satisfies 156 // the net.Error interface, and Timeout() will be true. 157 AcceptUniStream(context.Context) (ReceiveStream, error) 158 // OpenStream opens a new bidirectional QUIC stream. 159 // There is no signaling to the peer about new streams: 160 // The peer can only accept the stream after data has been sent on the stream. 161 // If the error is non-nil, it satisfies the net.Error interface. 162 // When reaching the peer's stream limit, err.Temporary() will be true. 163 // If the connection was closed due to a timeout, Timeout() will be true. 164 OpenStream() (Stream, error) 165 // OpenStreamSync opens a new bidirectional QUIC stream. 166 // It blocks until a new stream can be opened. 167 // There is no signaling to the peer about new streams: 168 // The peer can only accept the stream after data has been sent on the stream, 169 // or the stream has been reset or closed. 170 // If the error is non-nil, it satisfies the net.Error interface. 171 // If the connection was closed due to a timeout, Timeout() will be true. 172 OpenStreamSync(context.Context) (Stream, error) 173 // OpenUniStream opens a new outgoing unidirectional QUIC stream. 174 // If the error is non-nil, it satisfies the net.Error interface. 175 // When reaching the peer's stream limit, Temporary() will be true. 176 // If the connection was closed due to a timeout, Timeout() will be true. 177 OpenUniStream() (SendStream, error) 178 // OpenUniStreamSync opens a new outgoing unidirectional QUIC stream. 179 // It blocks until a new stream can be opened. 180 // If the error is non-nil, it satisfies the net.Error interface. 181 // If the connection was closed due to a timeout, Timeout() will be true. 182 OpenUniStreamSync(context.Context) (SendStream, error) 183 // LocalAddr returns the local address. 184 LocalAddr() net.Addr 185 // RemoteAddr returns the address of the peer. 186 RemoteAddr() net.Addr 187 // CloseWithError closes the connection with an error. 188 // The error string will be sent to the peer. 189 CloseWithError(ApplicationErrorCode, string) error 190 // Context returns a context that is cancelled when the connection is closed. 191 // The cancellation cause is set to the error that caused the connection to 192 // close, or `context.Canceled` in case the listener is closed first. 193 Context() context.Context 194 // ConnectionState returns basic details about the QUIC connection. 195 // Warning: This API should not be considered stable and might change soon. 196 ConnectionState() ConnectionState 197 198 // SendDatagram sends a message using a QUIC datagram, as specified in RFC 9221. 199 // There is no delivery guarantee for DATAGRAM frames, they are not retransmitted if lost. 200 // The payload of the datagram needs to fit into a single QUIC packet. 201 // In addition, a datagram may be dropped before being sent out if the available packet size suddenly decreases. 202 // If the payload is too large to be sent at the current time, a DatagramTooLargeError is returned. 203 SendDatagram(payload []byte) error 204 // ReceiveDatagram gets a message received in a datagram, as specified in RFC 9221. 205 ReceiveDatagram(context.Context) ([]byte, error) 206 207 // Replace the current congestion control algorithm with a new one. 208 SetCongestionControl(congestion.CongestionControl) 209 } 210 211 // An EarlyConnection is a connection that is handshaking. 212 // Data sent during the handshake is encrypted using the forward secure keys. 213 // When using client certificates, the client's identity is only verified 214 // after completion of the handshake. 215 type EarlyConnection interface { 216 Connection 217 218 // HandshakeComplete blocks until the handshake completes (or fails). 219 // For the client, data sent before completion of the handshake is encrypted with 0-RTT keys. 220 // For the server, data sent before completion of the handshake is encrypted with 1-RTT keys, 221 // however the client's identity is only verified once the handshake completes. 222 HandshakeComplete() <-chan struct{} 223 224 NextConnection() Connection 225 } 226 227 // StatelessResetKey is a key used to derive stateless reset tokens. 228 type StatelessResetKey [32]byte 229 230 // TokenGeneratorKey is a key used to encrypt session resumption tokens. 231 type TokenGeneratorKey = handshake.TokenProtectorKey 232 233 // A ConnectionID is a QUIC Connection ID, as defined in RFC 9000. 234 // It is not able to handle QUIC Connection IDs longer than 20 bytes, 235 // as they are allowed by RFC 8999. 236 type ConnectionID = protocol.ConnectionID 237 238 // ConnectionIDFromBytes interprets b as a Connection ID. It panics if b is 239 // longer than 20 bytes. 240 func ConnectionIDFromBytes(b []byte) ConnectionID { 241 return protocol.ParseConnectionID(b) 242 } 243 244 // A ConnectionIDGenerator is an interface that allows clients to implement their own format 245 // for the Connection IDs that servers/clients use as SrcConnectionID in QUIC packets. 246 // 247 // Connection IDs generated by an implementation should always produce IDs of constant size. 248 type ConnectionIDGenerator interface { 249 // GenerateConnectionID generates a new ConnectionID. 250 // Generated ConnectionIDs should be unique and observers should not be able to correlate two ConnectionIDs. 251 GenerateConnectionID() (ConnectionID, error) 252 253 // ConnectionIDLen tells what is the length of the ConnectionIDs generated by the implementation of 254 // this interface. 255 // Effectively, this means that implementations of ConnectionIDGenerator must always return constant-size 256 // connection IDs. Valid lengths are between 0 and 20 and calls to GenerateConnectionID. 257 // 0-length ConnectionsIDs can be used when an endpoint (server or client) does not require multiplexing connections 258 // in the presence of a connection migration environment. 259 ConnectionIDLen() int 260 } 261 262 // Config contains all configuration data needed for a QUIC server or client. 263 type Config struct { 264 // GetConfigForClient is called for incoming connections. 265 // If the error is not nil, the connection attempt is refused. 266 GetConfigForClient func(info *ClientHelloInfo) (*Config, error) 267 // The QUIC versions that can be negotiated. 268 // If not set, it uses all versions available. 269 Versions []Version 270 // HandshakeIdleTimeout is the idle timeout before completion of the handshake. 271 // If we don't receive any packet from the peer within this time, the connection attempt is aborted. 272 // Additionally, if the handshake doesn't complete in twice this time, the connection attempt is also aborted. 273 // If this value is zero, the timeout is set to 5 seconds. 274 HandshakeIdleTimeout time.Duration 275 // MaxIdleTimeout is the maximum duration that may pass without any incoming network activity. 276 // The actual value for the idle timeout is the minimum of this value and the peer's. 277 // This value only applies after the handshake has completed. 278 // If the timeout is exceeded, the connection is closed. 279 // If this value is zero, the timeout is set to 30 seconds. 280 MaxIdleTimeout time.Duration 281 // The TokenStore stores tokens received from the server. 282 // Tokens are used to skip address validation on future connection attempts. 283 // The key used to store tokens is the ServerName from the tls.Config, if set 284 // otherwise the token is associated with the server's IP address. 285 TokenStore TokenStore 286 // InitialStreamReceiveWindow is the initial size of the stream-level flow control window for receiving data. 287 // If the application is consuming data quickly enough, the flow control auto-tuning algorithm 288 // will increase the window up to MaxStreamReceiveWindow. 289 // If this value is zero, it will default to 512 KB. 290 // Values larger than the maximum varint (quicvarint.Max) will be clipped to that value. 291 InitialStreamReceiveWindow uint64 292 // MaxStreamReceiveWindow is the maximum stream-level flow control window for receiving data. 293 // If this value is zero, it will default to 6 MB. 294 // Values larger than the maximum varint (quicvarint.Max) will be clipped to that value. 295 MaxStreamReceiveWindow uint64 296 // InitialConnectionReceiveWindow is the initial size of the stream-level flow control window for receiving data. 297 // If the application is consuming data quickly enough, the flow control auto-tuning algorithm 298 // will increase the window up to MaxConnectionReceiveWindow. 299 // If this value is zero, it will default to 512 KB. 300 // Values larger than the maximum varint (quicvarint.Max) will be clipped to that value. 301 InitialConnectionReceiveWindow uint64 302 // MaxConnectionReceiveWindow is the connection-level flow control window for receiving data. 303 // If this value is zero, it will default to 15 MB. 304 // Values larger than the maximum varint (quicvarint.Max) will be clipped to that value. 305 MaxConnectionReceiveWindow uint64 306 // AllowConnectionWindowIncrease is called every time the connection flow controller attempts 307 // to increase the connection flow control window. 308 // If set, the caller can prevent an increase of the window. Typically, it would do so to 309 // limit the memory usage. 310 // To avoid deadlocks, it is not valid to call other functions on the connection or on streams 311 // in this callback. 312 AllowConnectionWindowIncrease func(conn Connection, delta uint64) bool 313 // MaxIncomingStreams is the maximum number of concurrent bidirectional streams that a peer is allowed to open. 314 // If not set, it will default to 100. 315 // If set to a negative value, it doesn't allow any bidirectional streams. 316 // Values larger than 2^60 will be clipped to that value. 317 MaxIncomingStreams int64 318 // MaxIncomingUniStreams is the maximum number of concurrent unidirectional streams that a peer is allowed to open. 319 // If not set, it will default to 100. 320 // If set to a negative value, it doesn't allow any unidirectional streams. 321 // Values larger than 2^60 will be clipped to that value. 322 MaxIncomingUniStreams int64 323 // KeepAlivePeriod defines whether this peer will periodically send a packet to keep the connection alive. 324 // If set to 0, then no keep alive is sent. Otherwise, the keep alive is sent on that period (or at most 325 // every half of MaxIdleTimeout, whichever is smaller). 326 KeepAlivePeriod time.Duration 327 // DisablePathMTUDiscovery disables Path MTU Discovery (RFC 8899). 328 // This allows the sending of QUIC packets that fully utilize the available MTU of the path. 329 // Path MTU discovery is only available on systems that allow setting of the Don't Fragment (DF) bit. 330 // If unavailable or disabled, packets will be at most 1252 (IPv4) / 1232 (IPv6) bytes in size. 331 DisablePathMTUDiscovery bool 332 // Allow0RTT allows the application to decide if a 0-RTT connection attempt should be accepted. 333 // Only valid for the server. 334 Allow0RTT bool 335 // Enable QUIC datagram support (RFC 9221). 336 EnableDatagrams bool 337 Tracer func(context.Context, logging.Perspective, ConnectionID) *logging.ConnectionTracer 338 CapabilityCallback func(n int64) 339 } 340 341 // ClientHelloInfo contains information about an incoming connection attempt. 342 type ClientHelloInfo struct { 343 // RemoteAddr is the remote address on the Initial packet. 344 // Unless AddrVerified is set, the address is not yet verified, and could be a spoofed IP address. 345 RemoteAddr net.Addr 346 // AddrVerified says if the remote address was verified using QUIC's Retry mechanism. 347 // Note that the Retry mechanism costs one network roundtrip, 348 // and is not performed unless Transport.MaxUnvalidatedHandshakes is surpassed. 349 AddrVerified bool 350 } 351 352 // ConnectionState records basic details about a QUIC connection 353 type ConnectionState struct { 354 // TLS contains information about the TLS connection state, incl. the tls.ConnectionState. 355 TLS tls.ConnectionState 356 // SupportsDatagrams says if support for QUIC datagrams (RFC 9221) was negotiated. 357 // This requires both nodes to support and enable the datagram extensions (via Config.EnableDatagrams). 358 // If datagram support was negotiated, datagrams can be sent and received using the 359 // SendDatagram and ReceiveDatagram methods on the Connection. 360 SupportsDatagrams bool 361 // Used0RTT says if 0-RTT resumption was used. 362 Used0RTT bool 363 // Version is the QUIC version of the QUIC connection. 364 Version Version 365 // GSO says if generic segmentation offload is used 366 GSO bool 367 }