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