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