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