mirror of
https://github.com/DNSCrypt/dnscrypt-proxy.git
synced 2025-04-04 21:57:44 +03:00
Revert "Update quic-go"
This reverts commit f9f68cf0a3
.
quic-go >= 1.0.35 panics
We may not be using the new API correctly.
This commit is contained in:
parent
f42b7dad17
commit
23a6cd7504
112 changed files with 2571 additions and 5590 deletions
212
vendor/github.com/quic-go/quic-go/README.md
generated
vendored
212
vendor/github.com/quic-go/quic-go/README.md
generated
vendored
|
@ -5,185 +5,28 @@
|
|||
[](https://pkg.go.dev/github.com/quic-go/quic-go)
|
||||
[](https://codecov.io/gh/quic-go/quic-go/)
|
||||
|
||||
quic-go is an implementation of the QUIC protocol ([RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000), [RFC 9001](https://datatracker.ietf.org/doc/html/rfc9001), [RFC 9002](https://datatracker.ietf.org/doc/html/rfc9002)) in Go. It has support for HTTP/3 ([RFC 9114](https://datatracker.ietf.org/doc/html/rfc9114)), including QPACK ([RFC 9204](https://datatracker.ietf.org/doc/html/rfc9204)).
|
||||
|
||||
In addition to these base RFCs, it also implements the following RFCs:
|
||||
* Unreliable Datagram Extension ([RFC 9221](https://datatracker.ietf.org/doc/html/rfc9221))
|
||||
* Datagram Packetization Layer Path MTU Discovery (DPLPMTUD, [RFC 8899](https://datatracker.ietf.org/doc/html/rfc8899))
|
||||
* QUIC Version 2 ([RFC 9369](https://datatracker.ietf.org/doc/html/rfc9369))
|
||||
quic-go is an implementation of the QUIC protocol ([RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000), [RFC 9001](https://datatracker.ietf.org/doc/html/rfc9001), [RFC 9002](https://datatracker.ietf.org/doc/html/rfc9002)) in Go, including the Unreliable Datagram Extension ([RFC 9221](https://datatracker.ietf.org/doc/html/rfc9221)) and Datagram Packetization Layer Path MTU
|
||||
Discovery (DPLPMTUD, [RFC 8899](https://datatracker.ietf.org/doc/html/rfc8899)). It has support for HTTP/3 ([RFC 9114](https://datatracker.ietf.org/doc/html/rfc9114)), including QPACK ([RFC 9204](https://datatracker.ietf.org/doc/html/rfc9204)).
|
||||
|
||||
In addition to the RFCs listed above, it currently implements the [IETF QUIC draft-29](https://tools.ietf.org/html/draft-ietf-quic-transport-29). Support for draft-29 will eventually be dropped, as it is phased out of the ecosystem.
|
||||
|
||||
This repository provides both a QUIC implementation, located in the `quic` package, as well as an HTTP/3 implementation, located in the `http3` package.
|
||||
## Guides
|
||||
|
||||
## Using QUIC
|
||||
*We currently support Go 1.19.x and Go 1.20.x*
|
||||
|
||||
### Running a Server
|
||||
Running tests:
|
||||
|
||||
The central entry point is the `quic.Transport`. A transport manages QUIC connections running on a single UDP socket. Since QUIC uses Connection IDs, it can demultiplex a listener (accepting incoming connections) and an arbitrary number of outgoing QUIC connections on the same UDP socket.
|
||||
go test ./...
|
||||
|
||||
```go
|
||||
udpConn, err := net.ListenUDP("udp4", &net.UDPAddr{Port: 1234})
|
||||
// ... error handling
|
||||
tr := quic.Transport{
|
||||
Conn: udpConn,
|
||||
}
|
||||
ln, err := tr.Listen(tlsConf, quicConf)
|
||||
// ... error handling
|
||||
go func() {
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
// ... error handling
|
||||
// handle the connection, usually in a new Go routine
|
||||
}
|
||||
}
|
||||
```
|
||||
### QUIC without HTTP/3
|
||||
|
||||
The listener `ln` can now be used to accept incoming QUIC connections by (repeatedly) calling the `Accept` method (see below for more information on the `quic.Connection`).
|
||||
Take a look at [this echo example](example/echo/echo.go).
|
||||
|
||||
As a shortcut, `quic.Listen` and `quic.ListenAddr` can be used without explicitly initializing a `quic.Transport`:
|
||||
|
||||
```
|
||||
ln, err := quic.Listen(udpConn, tlsConf, quicConf)
|
||||
```
|
||||
|
||||
When using the shortcut, it's not possible to reuse the same UDP socket for outgoing connections.
|
||||
|
||||
### Running a Client
|
||||
|
||||
As mentioned above, multiple outgoing connections can share a single UDP socket, since QUIC uses Connection IDs to demultiplex connections.
|
||||
|
||||
```go
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) // 3s handshake timeout
|
||||
defer cancel()
|
||||
conn, err := tr.Dial(ctx, <server address>, <tls.Config>, <quic.Config>)
|
||||
// ... error handling
|
||||
```
|
||||
|
||||
As a shortcut, `quic.Dial` and `quic.DialAddr` can be used without explictly initializing a `quic.Transport`:
|
||||
|
||||
```go
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) // 3s handshake timeout
|
||||
defer cancel()
|
||||
conn, err := quic.Dial(ctx, conn, <server address>, <tls.Config>, <quic.Config>)
|
||||
```
|
||||
|
||||
Just as we saw before when used a similar shortcut to run a server, it's also not possible to reuse the same UDP socket for other outgoing connections, or to listen for incoming connections.
|
||||
|
||||
### Using a QUIC Connection
|
||||
|
||||
#### Accepting Streams
|
||||
|
||||
QUIC is a stream-multiplexed transport. A `quic.Connection` fundamentally differs from the `net.Conn` and the `net.PacketConn` interface defined in the standard library. Data is sent and received on (unidirectional and bidirectional) streams (and, if supported, in [datagrams](#quic-datagrams)), not on the connection itself. The stream state machine is described in detail in [Section 3 of RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000#section-3).
|
||||
|
||||
Note: A unidirectional stream is a stream that the initiator can only write to (`quic.SendStream`), and the receiver can only read from (`quic.ReceiveStream`). A bidirectional stream (`quic.Stream`) allows reading from and writing to for both sides.
|
||||
|
||||
On the receiver side, streams are accepted using the `AcceptStream` (for bidirectional) and `AcceptUniStream` functions. For most user cases, it makes sense to call these functions in a loop:
|
||||
|
||||
```go
|
||||
for {
|
||||
str, err := conn.AcceptStream(context.Background()) // for bidirectional streams
|
||||
// ... error handling
|
||||
// handle the stream, usually in a new Go routine
|
||||
}
|
||||
```
|
||||
|
||||
These functions return an error when the underlying QUIC connection is closed.
|
||||
|
||||
#### Opening Streams
|
||||
|
||||
There are two slightly different ways to open streams, one synchronous and one (potentially) asynchronous. This API is necessary since the receiver grants us a certain number of streams that we're allowed to open. It may grant us additional streams later on (typically when existing streams are closed), but it means that at the time we want to open a new stream, we might not be able to do so.
|
||||
|
||||
Using the synchronous method `OpenStreamSync` for bidirectional streams, and `OpenUniStreamSync` for unidirectional streams, an application can block until the peer allows opening additional streams. In case that we're allowed to open a new stream, these methods return right away:
|
||||
|
||||
```go
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
str, err := conn.OpenStreamSync(ctx) // wait up to 5s to open a new bidirectional stream
|
||||
```
|
||||
|
||||
The asynchronous version never blocks. If it's currently not possible to open a new stream, it returns a `net.Error` timeout error:
|
||||
|
||||
```go
|
||||
str, err := conn.OpenStream()
|
||||
if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
|
||||
// It's currently not possible to open another stream,
|
||||
// but it might be possible later, once the peer allowed us to do so.
|
||||
}
|
||||
```
|
||||
|
||||
These functions return an error when the underlying QUIC connection is closed.
|
||||
|
||||
#### Using Streams
|
||||
|
||||
Using QUIC streams is pretty straightforward. The `quic.ReceiveStream` implements the `io.Reader` interface, and the `quic.SendStream` implements the `io.Writer` interface. A bidirectional stream (`quic.Stream`) implements both these interfaces. Conceptually, a bidirectional stream can be thought of as the composition of two unidirectional streams in opposite directions.
|
||||
|
||||
Calling `Close` on a `quic.SendStream` or a `quic.Stream` closes the send side of the stream. On the receiver side, this will be surfaced as an `io.EOF` returned from the `io.Reader` once all data has been consumed. Note that for bidirectional streams, `Close` _only_ closes the send side of the stream. It is still possible to read from the stream until the peer closes or resets the stream.
|
||||
|
||||
In case the application wishes to abort sending on a `quic.SendStream` or a `quic.Stream` , it can reset the send side by calling `CancelWrite` with an application-defined error code (an unsigned 62-bit number). On the receiver side, this surfaced as a `quic.StreamError` containing that error code on the `io.Reader`. Note that for bidirectional streams, `CancelWrite` _only_ resets the send side of the stream. It is still possible to read from the stream until the peer closes or resets the stream.
|
||||
|
||||
Conversely, in case the application wishes to abort receiving from a `quic.ReceiveStream` or a `quic.Stream`, it can ask the sender to abort data transmission by calling `CancelRead` with an application-defined error code (an unsigned 62-bit number). On the receiver side, this surfaced as a `quic.StreamError` containing that error code on the `io.Writer`. Note that for bidirectional streams, `CancelWrite` _only_ resets the receive side of the stream. It is still possible to write to the stream.
|
||||
|
||||
A bidirectional stream is only closed once both the read and the write side of the stream have been either closed and reset. Only then the peer is granted a new stream according to the maximum number of concurrent streams configured via `quic.Config.MaxIncomingStreams`.
|
||||
|
||||
### Configuring QUIC
|
||||
|
||||
The `quic.Config` struct passed to both the listen and dial calls (see above) contains a wide range of configuration options for QUIC connections, incl. the ability to fine-tune flow control limits, the number of streams that the peer is allowed to open concurrently, keep-alives, idle timeouts, and many more. Please refer to the documentation for the `quic.Config` for details.
|
||||
|
||||
The `quic.Transport` contains a few configuration options that don't apply to any single QUIC connection, but to all connections handled by that transport. It is highly recommend to set the `StatelessResetToken`, which allows endpoints to quickly recover from crashes / reboots of our node (see [Section 10.3 of RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000#section-10.3)).
|
||||
|
||||
### Closing a Connection
|
||||
|
||||
#### When the remote Peer closes the Connection
|
||||
|
||||
In case the peer closes the QUIC connection, all calls to open streams, accept streams, as well as all methods on streams immediately return an error. Users can use errors assertions to find out what exactly went wrong:
|
||||
|
||||
* `quic.VersionNegotiationError`: Happens during the handshake, if there is no overlap between our and the remote's supported QUIC versions.
|
||||
* `quic.HandshakeTimeoutError`: Happens if the QUIC handshake doesn't complete within the time specified in `quic.Config.HandshakeTimeout`.
|
||||
* `quic.IdleTimeoutError`: Happens after completion of the handshake if the connection is idle for longer than the minimum of both peers idle timeouts (as configured by `quic.Config.IdleTimeout`). The connection is considered idle when no stream data (and datagrams, if applicable) are exchanged for that period. The QUIC connection can be instructed to regularly send a packet to prevent a connection from going idle by setting `quic.Config.KeepAlive`. However, this is no guarantee that the peer doesn't suddenly go away (e.g. by abruptly shutting down the node or by crashing), or by a NAT binding expiring, in which case this error might still occur.
|
||||
* `quic.StatelessResetError`: Happens when the remote peer lost the state required to decrypt the packet. This requires the `quic.Transport.StatelessResetToken` to be configured by the peer.
|
||||
* `quic.TransportError`: Happens if when the QUIC protocol is violated. Unless the error code is `APPLICATION_ERROR`, this will not happen unless one of the QUIC stacks involved is misbehaving. Please open an issue if you encounter this error.
|
||||
* `quic.ApplicationError`: Happens when the remote decides to close the connection, see below.
|
||||
|
||||
#### Initiated by the Application
|
||||
|
||||
A `quic.Connection` can be closed using `CloseWithError`:
|
||||
|
||||
```go
|
||||
conn.CloseWithError(0x42, "error 0x42 occurred")
|
||||
```
|
||||
|
||||
Applications can transmit both an error code (an unsigned 62-bit number) as well as a UTF-8 encoded human-readable reason. The error code allows the receiver to learn why the connection was closed, and the reason can be useful for debugging purposes.
|
||||
|
||||
On the receiver side, this is surfaced as a `quic.ApplicationError`.
|
||||
|
||||
### QUIC Datagrams
|
||||
|
||||
Unreliable datagrams are a QUIC extension ([RFC 9221](https://datatracker.ietf.org/doc/html/rfc9221)) that is negotiated during the handshake. Support can be enabled by setting the `quic.Config.EnableDatagram` flag. Note that this doesn't guarantee that the peer also supports datagrams. Whether or not the feature negotiation succeeded can be learned from the `quic.ConnectionState.SupportsDatagrams` obtained from `quic.Connection.ConnectionState()`.
|
||||
|
||||
QUIC DATAGRAMs are a new QUIC frame type sent in QUIC 1-RTT packets (i.e. after completion of the handshake). Therefore, they're end-to-end encrypted and congestion-controlled. However, if a DATAGRAM frame is deemed lost by QUIC's loss detection mechanism, they are not automatically retransmitted.
|
||||
|
||||
Datagrams are sent using the `SendMessage` method on the `quic.Connection`:
|
||||
|
||||
```go
|
||||
conn.SendMessage([]byte("foobar"))
|
||||
```
|
||||
|
||||
And received using `ReceiveMessage`:
|
||||
|
||||
```go
|
||||
msg, err := conn.ReceiveMessage()
|
||||
```
|
||||
|
||||
Note that this code path is currently not optimized. It works for datagrams that are sent occasionally, but it doesn't achieve the same throughput as writing data on a stream. Please get in touch on issue #3766 if your use case relies on high datagram throughput, or if you'd like to help fix this issue. There are also some restrictions regarding the maximum message size (see #3599).
|
||||
|
||||
|
||||
|
||||
## Using HTTP/3
|
||||
## Usage
|
||||
|
||||
### As a server
|
||||
|
||||
See the [example server](example/main.go). Starting a QUIC server is very similar to the standard library http package in Go:
|
||||
See the [example server](example/main.go). Starting a QUIC server is very similar to the standard lib http in go:
|
||||
|
||||
```go
|
||||
http.Handle("/", http.FileServer(http.Dir(wwwDir)))
|
||||
|
@ -202,29 +45,18 @@ http.Client{
|
|||
|
||||
## Projects using quic-go
|
||||
|
||||
| Project | Description | Stars |
|
||||
|-----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
|
||||
| [AdGuardHome](https://github.com/AdguardTeam/AdGuardHome) | Free and open source, powerful network-wide ads & trackers blocking DNS server. |  |
|
||||
| [algernon](https://github.com/xyproto/algernon) | Small self-contained pure-Go web server with Lua, Markdown, HTTP/2, QUIC, Redis and PostgreSQL support |  |
|
||||
| [caddy](https://github.com/caddyserver/caddy/) | Fast, multi-platform web server with automatic HTTPS |  |
|
||||
| [cloudflared](https://github.com/cloudflare/cloudflared) | A tunneling daemon that proxies traffic from the Cloudflare network to your origins |  |
|
||||
| [go-libp2p](https://github.com/libp2p/go-libp2p) | libp2p implementation in Go, powering [Kubo](https://github.com/ipfs/kubo) (IPFS) and [Lotus](https://github.com/filecoin-project/lotus) (Filecoin), among others |  |
|
||||
| [Mercure](https://github.com/dunglas/mercure) | An open, easy, fast, reliable and battery-efficient solution for real-time communications |  |
|
||||
| [OONI Probe](https://github.com/ooni/probe-cli) | Next generation OONI Probe. Library and CLI tool. |  |
|
||||
| [syncthing](https://github.com/syncthing/syncthing/) | Open Source Continuous File Synchronization |  |
|
||||
| [traefik](https://github.com/traefik/traefik) | The Cloud Native Application Proxy |  |
|
||||
| [v2ray-core](https://github.com/v2fly/v2ray-core) | A platform for building proxies to bypass network restrictions |  |
|
||||
| [YoMo](https://github.com/yomorun/yomo) | Streaming Serverless Framework for Geo-distributed System |  |
|
||||
|
||||
If you'd like to see your project added to this list, please send us a PR.
|
||||
|
||||
## Release Policy
|
||||
|
||||
quic-go always aims to support the latest two Go releases.
|
||||
|
||||
### Dependency on forked crypto/tls
|
||||
|
||||
Since the standard library didn't provide any QUIC APIs before the Go 1.21 release, we had to fork crypto/tls to add the required APIs ourselves: [qtls for Go 1.20](https://github.com/quic-go/qtls-go1-20) and [qtls for Go 1.19](https://github.com/quic-go/qtls-go1-19). This had led to a lot of pain in the Go ecosystem, and we're happy that we can rely on Go 1.21 going forward.
|
||||
| Project | Description | Stars |
|
||||
|-----------------------------------------------------------|---------------------------------------------------------------------------------------------------------|-------|
|
||||
| [AdGuardHome](https://github.com/AdguardTeam/AdGuardHome) | Free and open source, powerful network-wide ads & trackers blocking DNS server. |  |
|
||||
| [algernon](https://github.com/xyproto/algernon) | Small self-contained pure-Go web server with Lua, Markdown, HTTP/2, QUIC, Redis and PostgreSQL support |  |
|
||||
| [caddy](https://github.com/caddyserver/caddy/) | Fast, multi-platform web server with automatic HTTPS |  |
|
||||
| [cloudflared](https://github.com/cloudflare/cloudflared) | A tunneling daemon that proxies traffic from the Cloudflare network to your origins |  |
|
||||
| [go-libp2p](https://github.com/libp2p/go-libp2p) | libp2p implementation in Go, powering [Kubo](https://github.com/ipfs/kubo) (IPFS) and [Lotus](https://github.com/filecoin-project/lotus) (Filecoin), among others |  |
|
||||
| [OONI Probe](https://github.com/ooni/probe-cli) | Next generation OONI Probe. Library and CLI tool. |  |
|
||||
| [syncthing](https://github.com/syncthing/syncthing/) | Open Source Continuous File Synchronization |  |
|
||||
| [traefik](https://github.com/traefik/traefik) | The Cloud Native Application Proxy |  |
|
||||
| [v2ray-core](https://github.com/v2fly/v2ray-core) | A platform for building proxies to bypass network restrictions |  |
|
||||
| [YoMo](https://github.com/yomorun/yomo) | Streaming Serverless Framework for Geo-distributed System |  |
|
||||
|
||||
## Contributing
|
||||
|
||||
|
|
40
vendor/github.com/quic-go/quic-go/buffer_pool.go
generated
vendored
40
vendor/github.com/quic-go/quic-go/buffer_pool.go
generated
vendored
|
@ -51,22 +51,18 @@ func (b *packetBuffer) Release() {
|
|||
}
|
||||
|
||||
// Len returns the length of Data
|
||||
func (b *packetBuffer) Len() protocol.ByteCount { return protocol.ByteCount(len(b.Data)) }
|
||||
func (b *packetBuffer) Cap() protocol.ByteCount { return protocol.ByteCount(cap(b.Data)) }
|
||||
|
||||
func (b *packetBuffer) putBack() {
|
||||
if cap(b.Data) == protocol.MaxPacketBufferSize {
|
||||
bufferPool.Put(b)
|
||||
return
|
||||
}
|
||||
if cap(b.Data) == protocol.MaxLargePacketBufferSize {
|
||||
largeBufferPool.Put(b)
|
||||
return
|
||||
}
|
||||
panic("putPacketBuffer called with packet of wrong size!")
|
||||
func (b *packetBuffer) Len() protocol.ByteCount {
|
||||
return protocol.ByteCount(len(b.Data))
|
||||
}
|
||||
|
||||
var bufferPool, largeBufferPool sync.Pool
|
||||
func (b *packetBuffer) putBack() {
|
||||
if cap(b.Data) != int(protocol.MaxPacketBufferSize) {
|
||||
panic("putPacketBuffer called with packet of wrong size!")
|
||||
}
|
||||
bufferPool.Put(b)
|
||||
}
|
||||
|
||||
var bufferPool sync.Pool
|
||||
|
||||
func getPacketBuffer() *packetBuffer {
|
||||
buf := bufferPool.Get().(*packetBuffer)
|
||||
|
@ -75,18 +71,10 @@ func getPacketBuffer() *packetBuffer {
|
|||
return buf
|
||||
}
|
||||
|
||||
func getLargePacketBuffer() *packetBuffer {
|
||||
buf := largeBufferPool.Get().(*packetBuffer)
|
||||
buf.refCount = 1
|
||||
buf.Data = buf.Data[:0]
|
||||
return buf
|
||||
}
|
||||
|
||||
func init() {
|
||||
bufferPool.New = func() any {
|
||||
return &packetBuffer{Data: make([]byte, 0, protocol.MaxPacketBufferSize)}
|
||||
}
|
||||
largeBufferPool.New = func() any {
|
||||
return &packetBuffer{Data: make([]byte, 0, protocol.MaxLargePacketBufferSize)}
|
||||
bufferPool.New = func() interface{} {
|
||||
return &packetBuffer{
|
||||
Data: make([]byte, 0, protocol.MaxPacketBufferSize),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
307
vendor/github.com/quic-go/quic-go/client.go
generated
vendored
307
vendor/github.com/quic-go/quic-go/client.go
generated
vendored
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
|
@ -12,19 +13,20 @@ import (
|
|||
)
|
||||
|
||||
type client struct {
|
||||
sendConn sendConn
|
||||
sconn sendConn
|
||||
// If the client is created with DialAddr, we create a packet conn.
|
||||
// If it is started with Dial, we take a packet conn as a parameter.
|
||||
createdPacketConn bool
|
||||
|
||||
use0RTT bool
|
||||
|
||||
packetHandlers packetHandlerManager
|
||||
onClose func()
|
||||
|
||||
tlsConf *tls.Config
|
||||
config *Config
|
||||
|
||||
connIDGenerator ConnectionIDGenerator
|
||||
srcConnID protocol.ConnectionID
|
||||
destConnID protocol.ConnectionID
|
||||
srcConnID protocol.ConnectionID
|
||||
destConnID protocol.ConnectionID
|
||||
|
||||
initialPacketNumber protocol.PacketNumber
|
||||
hasNegotiatedVersion bool
|
||||
|
@ -43,107 +45,153 @@ type client struct {
|
|||
var generateConnectionIDForInitial = protocol.GenerateConnectionIDForInitial
|
||||
|
||||
// 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 DialAddr(ctx context.Context, addr string, tlsConf *tls.Config, conf *Config) (Connection, error) {
|
||||
udpConn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4zero, Port: 0})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dl, err := setupTransport(udpConn, tlsConf, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dl.Dial(ctx, udpAddr, tlsConf, conf)
|
||||
// It uses a new UDP connection and closes this connection when the QUIC connection is closed.
|
||||
// The hostname for SNI is taken from the given address.
|
||||
func DialAddr(
|
||||
addr string,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
) (Connection, error) {
|
||||
return DialAddrContext(context.Background(), addr, tlsConf, config)
|
||||
}
|
||||
|
||||
// DialAddrEarly establishes a new 0-RTT QUIC connection to a server.
|
||||
// See DialAddr for more details.
|
||||
func DialAddrEarly(ctx context.Context, addr string, tlsConf *tls.Config, conf *Config) (EarlyConnection, error) {
|
||||
udpConn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4zero, Port: 0})
|
||||
// It uses a new UDP connection and closes this connection when the QUIC connection is closed.
|
||||
// The hostname for SNI is taken from the given address.
|
||||
func DialAddrEarly(
|
||||
addr string,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
) (EarlyConnection, error) {
|
||||
return DialAddrEarlyContext(context.Background(), addr, tlsConf, config)
|
||||
}
|
||||
|
||||
// DialAddrEarlyContext establishes a new 0-RTT QUIC connection to a server using provided context.
|
||||
// See DialAddrEarly for details
|
||||
func DialAddrEarlyContext(
|
||||
ctx context.Context,
|
||||
addr string,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
) (EarlyConnection, error) {
|
||||
conn, err := dialAddrContext(ctx, addr, tlsConf, config, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
utils.Logger.WithPrefix(utils.DefaultLogger, "client").Debugf("Returning early connection")
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// DialAddrContext establishes a new QUIC connection to a server using the provided context.
|
||||
// See DialAddr for details.
|
||||
func DialAddrContext(
|
||||
ctx context.Context,
|
||||
addr string,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
) (Connection, error) {
|
||||
return dialAddrContext(ctx, addr, tlsConf, config, false)
|
||||
}
|
||||
|
||||
func dialAddrContext(
|
||||
ctx context.Context,
|
||||
addr string,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
use0RTT bool,
|
||||
) (quicConn, error) {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dl, err := setupTransport(udpConn, tlsConf, true)
|
||||
udpConn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4zero, Port: 0})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := dl.DialEarly(ctx, udpAddr, tlsConf, conf)
|
||||
if err != nil {
|
||||
dl.Close()
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
return dialContext(ctx, udpConn, udpAddr, addr, tlsConf, config, use0RTT, true)
|
||||
}
|
||||
|
||||
// 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, ReadMsgUDP
|
||||
// and WriteMsgUDP will be used instead of ReadFrom and WriteTo to read/write
|
||||
// packets. The same PacketConn can be used for multiple calls to Dial and
|
||||
// Listen, QUIC connection IDs are used for demultiplexing the different
|
||||
// connections. The host parameter is used for SNI. The tls.Config must define
|
||||
// an application protocol (using NextProtos).
|
||||
func Dial(
|
||||
pconn net.PacketConn,
|
||||
remoteAddr net.Addr,
|
||||
host string,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
) (Connection, error) {
|
||||
return dialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config, false, false)
|
||||
}
|
||||
|
||||
// DialEarly establishes a new 0-RTT QUIC connection to a server using a net.PacketConn.
|
||||
// See Dial for more details.
|
||||
func DialEarly(ctx context.Context, c net.PacketConn, addr net.Addr, tlsConf *tls.Config, conf *Config) (EarlyConnection, error) {
|
||||
dl, err := setupTransport(c, tlsConf, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := dl.DialEarly(ctx, addr, tlsConf, conf)
|
||||
if err != nil {
|
||||
dl.Close()
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
// 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, ReadMsgUDP and WriteMsgUDP
|
||||
// will be used instead of ReadFrom and WriteTo to read/write packets.
|
||||
// The same PacketConn can be used for multiple calls to Dial and Listen,
|
||||
// QUIC connection IDs are used for demultiplexing the different connections.
|
||||
// The host parameter is used for SNI.
|
||||
// The tls.Config must define an application protocol (using 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 Dial(ctx context.Context, c net.PacketConn, addr net.Addr, tlsConf *tls.Config, conf *Config) (Connection, error) {
|
||||
dl, err := setupTransport(c, tlsConf, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := dl.Dial(ctx, addr, tlsConf, conf)
|
||||
if err != nil {
|
||||
dl.Close()
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
func DialEarly(
|
||||
pconn net.PacketConn,
|
||||
remoteAddr net.Addr,
|
||||
host string,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
) (EarlyConnection, error) {
|
||||
return DialEarlyContext(context.Background(), pconn, remoteAddr, host, tlsConf, config)
|
||||
}
|
||||
|
||||
func setupTransport(c net.PacketConn, tlsConf *tls.Config, createdPacketConn bool) (*Transport, error) {
|
||||
// DialEarlyContext establishes a new 0-RTT QUIC connection to a server using a net.PacketConn using the provided context.
|
||||
// See DialEarly for details.
|
||||
func DialEarlyContext(
|
||||
ctx context.Context,
|
||||
pconn net.PacketConn,
|
||||
remoteAddr net.Addr,
|
||||
host string,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
) (EarlyConnection, error) {
|
||||
return dialContext(ctx, pconn, remoteAddr, host, tlsConf, config, true, false)
|
||||
}
|
||||
|
||||
// DialContext establishes a new QUIC connection to a server using a net.PacketConn using the provided context.
|
||||
// See Dial for details.
|
||||
func DialContext(
|
||||
ctx context.Context,
|
||||
pconn net.PacketConn,
|
||||
remoteAddr net.Addr,
|
||||
host string,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
) (Connection, error) {
|
||||
return dialContext(ctx, pconn, remoteAddr, host, tlsConf, config, false, false)
|
||||
}
|
||||
|
||||
func dialContext(
|
||||
ctx context.Context,
|
||||
pconn net.PacketConn,
|
||||
remoteAddr net.Addr,
|
||||
host string,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
use0RTT bool,
|
||||
createdPacketConn bool,
|
||||
) (quicConn, error) {
|
||||
if tlsConf == nil {
|
||||
return nil, errors.New("quic: tls.Config not set")
|
||||
}
|
||||
return &Transport{
|
||||
Conn: c,
|
||||
createdConn: createdPacketConn,
|
||||
isSingleUse: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func dial(
|
||||
ctx context.Context,
|
||||
conn sendConn,
|
||||
connIDGenerator ConnectionIDGenerator,
|
||||
packetHandlers packetHandlerManager,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
onClose func(),
|
||||
use0RTT bool,
|
||||
) (quicConn, error) {
|
||||
c, err := newClient(conn, connIDGenerator, config, tlsConf, onClose, use0RTT)
|
||||
if err := validateConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config = populateClientConfig(config, createdPacketConn)
|
||||
packetHandlers, err := getMultiplexer().AddConn(pconn, config.ConnectionIDGenerator.ConnectionIDLen(), config.StatelessResetKey, config.Tracer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, err := newClient(pconn, remoteAddr, config, tlsConf, host, use0RTT, createdPacketConn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -151,10 +199,14 @@ func dial(
|
|||
|
||||
c.tracingID = nextConnTracingID()
|
||||
if c.config.Tracer != nil {
|
||||
c.tracer = c.config.Tracer(context.WithValue(ctx, ConnectionTracingKey, c.tracingID), protocol.PerspectiveClient, c.destConnID)
|
||||
c.tracer = c.config.Tracer.TracerForConnection(
|
||||
context.WithValue(ctx, ConnectionTracingKey, c.tracingID),
|
||||
protocol.PerspectiveClient,
|
||||
c.destConnID,
|
||||
)
|
||||
}
|
||||
if c.tracer != nil {
|
||||
c.tracer.StartedConnection(c.sendConn.LocalAddr(), c.sendConn.RemoteAddr(), c.srcConnID, c.destConnID)
|
||||
c.tracer.StartedConnection(c.sconn.LocalAddr(), c.sconn.RemoteAddr(), c.srcConnID, c.destConnID)
|
||||
}
|
||||
if err := c.dial(ctx); err != nil {
|
||||
return nil, err
|
||||
|
@ -162,14 +214,40 @@ func dial(
|
|||
return c.conn, nil
|
||||
}
|
||||
|
||||
func newClient(sendConn sendConn, connIDGenerator ConnectionIDGenerator, config *Config, tlsConf *tls.Config, onClose func(), use0RTT bool) (*client, error) {
|
||||
func newClient(
|
||||
pconn net.PacketConn,
|
||||
remoteAddr net.Addr,
|
||||
config *Config,
|
||||
tlsConf *tls.Config,
|
||||
host string,
|
||||
use0RTT bool,
|
||||
createdPacketConn bool,
|
||||
) (*client, error) {
|
||||
if tlsConf == nil {
|
||||
tlsConf = &tls.Config{}
|
||||
} else {
|
||||
tlsConf = tlsConf.Clone()
|
||||
}
|
||||
if tlsConf.ServerName == "" {
|
||||
sni, _, err := net.SplitHostPort(host)
|
||||
if err != nil {
|
||||
// It's ok if net.SplitHostPort returns an error - it could be a hostname/IP address without a port.
|
||||
sni = host
|
||||
}
|
||||
|
||||
srcConnID, err := connIDGenerator.GenerateConnectionID()
|
||||
tlsConf.ServerName = sni
|
||||
}
|
||||
|
||||
// check that all versions are actually supported
|
||||
if config != nil {
|
||||
for _, v := range config.Versions {
|
||||
if !protocol.IsValidVersion(v) {
|
||||
return nil, fmt.Errorf("%s is not a valid QUIC version", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
srcConnID, err := config.ConnectionIDGenerator.GenerateConnectionID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -178,30 +256,28 @@ func newClient(sendConn sendConn, connIDGenerator ConnectionIDGenerator, config
|
|||
return nil, err
|
||||
}
|
||||
c := &client{
|
||||
connIDGenerator: connIDGenerator,
|
||||
srcConnID: srcConnID,
|
||||
destConnID: destConnID,
|
||||
sendConn: sendConn,
|
||||
use0RTT: use0RTT,
|
||||
onClose: onClose,
|
||||
tlsConf: tlsConf,
|
||||
config: config,
|
||||
version: config.Versions[0],
|
||||
handshakeChan: make(chan struct{}),
|
||||
logger: utils.DefaultLogger.WithPrefix("client"),
|
||||
srcConnID: srcConnID,
|
||||
destConnID: destConnID,
|
||||
sconn: newSendPconn(pconn, remoteAddr),
|
||||
createdPacketConn: createdPacketConn,
|
||||
use0RTT: use0RTT,
|
||||
tlsConf: tlsConf,
|
||||
config: config,
|
||||
version: config.Versions[0],
|
||||
handshakeChan: make(chan struct{}),
|
||||
logger: utils.DefaultLogger.WithPrefix("client"),
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *client) dial(ctx context.Context) error {
|
||||
c.logger.Infof("Starting new connection to %s (%s -> %s), source connection ID %s, destination connection ID %s, version %s", c.tlsConf.ServerName, c.sendConn.LocalAddr(), c.sendConn.RemoteAddr(), c.srcConnID, c.destConnID, c.version)
|
||||
c.logger.Infof("Starting new connection to %s (%s -> %s), source connection ID %s, destination connection ID %s, version %s", c.tlsConf.ServerName, c.sconn.LocalAddr(), c.sconn.RemoteAddr(), c.srcConnID, c.destConnID, c.version)
|
||||
|
||||
c.conn = newClientConnection(
|
||||
c.sendConn,
|
||||
c.sconn,
|
||||
c.packetHandlers,
|
||||
c.destConnID,
|
||||
c.srcConnID,
|
||||
c.connIDGenerator,
|
||||
c.config,
|
||||
c.tlsConf,
|
||||
c.initialPacketNumber,
|
||||
|
@ -215,18 +291,13 @@ func (c *client) dial(ctx context.Context) error {
|
|||
c.packetHandlers.Add(c.srcConnID, c.conn)
|
||||
|
||||
errorChan := make(chan error, 1)
|
||||
recreateChan := make(chan errCloseForRecreating)
|
||||
go func() {
|
||||
err := c.conn.run()
|
||||
var recreateErr *errCloseForRecreating
|
||||
if errors.As(err, &recreateErr) {
|
||||
recreateChan <- *recreateErr
|
||||
return
|
||||
err := c.conn.run() // returns as soon as the connection is closed
|
||||
|
||||
if e := (&errCloseForRecreating{}); !errors.As(err, &e) && c.createdPacketConn {
|
||||
c.packetHandlers.Destroy()
|
||||
}
|
||||
if c.onClose != nil {
|
||||
c.onClose()
|
||||
}
|
||||
errorChan <- err // returns as soon as the connection is closed
|
||||
errorChan <- err
|
||||
}()
|
||||
|
||||
// only set when we're using 0-RTT
|
||||
|
@ -241,12 +312,14 @@ func (c *client) dial(ctx context.Context) error {
|
|||
c.conn.shutdown()
|
||||
return ctx.Err()
|
||||
case err := <-errorChan:
|
||||
var recreateErr *errCloseForRecreating
|
||||
if errors.As(err, &recreateErr) {
|
||||
c.initialPacketNumber = recreateErr.nextPacketNumber
|
||||
c.version = recreateErr.nextVersion
|
||||
c.hasNegotiatedVersion = true
|
||||
return c.dial(ctx)
|
||||
}
|
||||
return err
|
||||
case recreateErr := <-recreateChan:
|
||||
c.initialPacketNumber = recreateErr.nextPacketNumber
|
||||
c.version = recreateErr.nextVersion
|
||||
c.hasNegotiatedVersion = true
|
||||
return c.dial(ctx)
|
||||
case <-earlyConnChan:
|
||||
// ready to send 0-RTT data
|
||||
return nil
|
||||
|
|
8
vendor/github.com/quic-go/quic-go/closed_conn.go
generated
vendored
8
vendor/github.com/quic-go/quic-go/closed_conn.go
generated
vendored
|
@ -16,13 +16,13 @@ type closedLocalConn struct {
|
|||
perspective protocol.Perspective
|
||||
logger utils.Logger
|
||||
|
||||
sendPacket func(net.Addr, packetInfo)
|
||||
sendPacket func(net.Addr, *packetInfo)
|
||||
}
|
||||
|
||||
var _ packetHandler = &closedLocalConn{}
|
||||
|
||||
// newClosedLocalConn creates a new closedLocalConn and runs it.
|
||||
func newClosedLocalConn(sendPacket func(net.Addr, packetInfo), pers protocol.Perspective, logger utils.Logger) packetHandler {
|
||||
func newClosedLocalConn(sendPacket func(net.Addr, *packetInfo), pers protocol.Perspective, logger utils.Logger) packetHandler {
|
||||
return &closedLocalConn{
|
||||
sendPacket: sendPacket,
|
||||
perspective: pers,
|
||||
|
@ -30,7 +30,7 @@ func newClosedLocalConn(sendPacket func(net.Addr, packetInfo), pers protocol.Per
|
|||
}
|
||||
}
|
||||
|
||||
func (c *closedLocalConn) handlePacket(p receivedPacket) {
|
||||
func (c *closedLocalConn) handlePacket(p *receivedPacket) {
|
||||
c.counter++
|
||||
// exponential backoff
|
||||
// only send a CONNECTION_CLOSE for the 1st, 2nd, 4th, 8th, 16th, ... packet arriving
|
||||
|
@ -58,7 +58,7 @@ func newClosedRemoteConn(pers protocol.Perspective) packetHandler {
|
|||
return &closedRemoteConn{perspective: pers}
|
||||
}
|
||||
|
||||
func (s *closedRemoteConn) handlePacket(receivedPacket) {}
|
||||
func (s *closedRemoteConn) handlePacket(*receivedPacket) {}
|
||||
func (s *closedRemoteConn) shutdown() {}
|
||||
func (s *closedRemoteConn) destroy(error) {}
|
||||
func (s *closedRemoteConn) getPerspective() protocol.Perspective { return s.perspective }
|
||||
|
|
52
vendor/github.com/quic-go/quic-go/config.go
generated
vendored
52
vendor/github.com/quic-go/quic-go/config.go
generated
vendored
|
@ -1,13 +1,12 @@
|
|||
package quic
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
"github.com/quic-go/quic-go/internal/utils"
|
||||
"github.com/quic-go/quic-go/quicvarint"
|
||||
)
|
||||
|
||||
// Clone clones a Config
|
||||
|
@ -24,24 +23,11 @@ func validateConfig(config *Config) error {
|
|||
if config == nil {
|
||||
return nil
|
||||
}
|
||||
const maxStreams = 1 << 60
|
||||
if config.MaxIncomingStreams > maxStreams {
|
||||
config.MaxIncomingStreams = maxStreams
|
||||
if config.MaxIncomingStreams > 1<<60 {
|
||||
return errors.New("invalid value for Config.MaxIncomingStreams")
|
||||
}
|
||||
if config.MaxIncomingUniStreams > maxStreams {
|
||||
config.MaxIncomingUniStreams = maxStreams
|
||||
}
|
||||
if config.MaxStreamReceiveWindow > quicvarint.Max {
|
||||
config.MaxStreamReceiveWindow = quicvarint.Max
|
||||
}
|
||||
if config.MaxConnectionReceiveWindow > quicvarint.Max {
|
||||
config.MaxConnectionReceiveWindow = quicvarint.Max
|
||||
}
|
||||
// check that all QUIC versions are actually supported
|
||||
for _, v := range config.Versions {
|
||||
if !protocol.IsValidVersion(v) {
|
||||
return fmt.Errorf("invalid QUIC version: %s", v)
|
||||
}
|
||||
if config.MaxIncomingUniStreams > 1<<60 {
|
||||
return errors.New("invalid value for Config.MaxIncomingUniStreams")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -49,7 +35,7 @@ func validateConfig(config *Config) error {
|
|||
// populateServerConfig populates fields in the quic.Config with their default values, if none are set
|
||||
// it may be called with nil
|
||||
func populateServerConfig(config *Config) *Config {
|
||||
config = populateConfig(config)
|
||||
config = populateConfig(config, protocol.DefaultConnectionIDLength)
|
||||
if config.MaxTokenAge == 0 {
|
||||
config.MaxTokenAge = protocol.TokenValidity
|
||||
}
|
||||
|
@ -62,9 +48,19 @@ func populateServerConfig(config *Config) *Config {
|
|||
return config
|
||||
}
|
||||
|
||||
// populateConfig populates fields in the quic.Config with their default values, if none are set
|
||||
// populateClientConfig populates fields in the quic.Config with their default values, if none are set
|
||||
// it may be called with nil
|
||||
func populateConfig(config *Config) *Config {
|
||||
func populateClientConfig(config *Config, createdPacketConn bool) *Config {
|
||||
defaultConnIDLen := protocol.DefaultConnectionIDLength
|
||||
if createdPacketConn {
|
||||
defaultConnIDLen = 0
|
||||
}
|
||||
|
||||
config = populateConfig(config, defaultConnIDLen)
|
||||
return config
|
||||
}
|
||||
|
||||
func populateConfig(config *Config, defaultConnIDLen int) *Config {
|
||||
if config == nil {
|
||||
config = &Config{}
|
||||
}
|
||||
|
@ -72,6 +68,10 @@ func populateConfig(config *Config) *Config {
|
|||
if len(versions) == 0 {
|
||||
versions = protocol.SupportedVersions
|
||||
}
|
||||
conIDLen := config.ConnectionIDLength
|
||||
if config.ConnectionIDLength == 0 {
|
||||
conIDLen = defaultConnIDLen
|
||||
}
|
||||
handshakeIdleTimeout := protocol.DefaultHandshakeIdleTimeout
|
||||
if config.HandshakeIdleTimeout != 0 {
|
||||
handshakeIdleTimeout = config.HandshakeIdleTimeout
|
||||
|
@ -108,9 +108,12 @@ func populateConfig(config *Config) *Config {
|
|||
} else if maxIncomingUniStreams < 0 {
|
||||
maxIncomingUniStreams = 0
|
||||
}
|
||||
connIDGenerator := config.ConnectionIDGenerator
|
||||
if connIDGenerator == nil {
|
||||
connIDGenerator = &protocol.DefaultConnectionIDGenerator{ConnLen: conIDLen}
|
||||
}
|
||||
|
||||
return &Config{
|
||||
GetConfigForClient: config.GetConfigForClient,
|
||||
Versions: versions,
|
||||
HandshakeIdleTimeout: handshakeIdleTimeout,
|
||||
MaxIdleTimeout: idleTimeout,
|
||||
|
@ -125,6 +128,9 @@ func populateConfig(config *Config) *Config {
|
|||
AllowConnectionWindowIncrease: config.AllowConnectionWindowIncrease,
|
||||
MaxIncomingStreams: maxIncomingStreams,
|
||||
MaxIncomingUniStreams: maxIncomingUniStreams,
|
||||
ConnectionIDLength: conIDLen,
|
||||
ConnectionIDGenerator: connIDGenerator,
|
||||
StatelessResetKey: config.StatelessResetKey,
|
||||
TokenStore: config.TokenStore,
|
||||
EnableDatagrams: config.EnableDatagrams,
|
||||
DisablePathMTUDiscovery: config.DisablePathMTUDiscovery,
|
||||
|
|
489
vendor/github.com/quic-go/quic-go/connection.go
generated
vendored
489
vendor/github.com/quic-go/quic-go/connection.go
generated
vendored
|
@ -61,6 +61,11 @@ type cryptoStreamHandler interface {
|
|||
ConnectionState() handshake.ConnectionState
|
||||
}
|
||||
|
||||
type packetInfo struct {
|
||||
addr net.IP
|
||||
ifIndex uint32
|
||||
}
|
||||
|
||||
type receivedPacket struct {
|
||||
buffer *packetBuffer
|
||||
|
||||
|
@ -70,7 +75,7 @@ type receivedPacket struct {
|
|||
|
||||
ecn protocol.ECN
|
||||
|
||||
info packetInfo // only valid if the contained IP address is valid
|
||||
info *packetInfo
|
||||
}
|
||||
|
||||
func (p *receivedPacket) Size() protocol.ByteCount { return protocol.ByteCount(len(p.data)) }
|
||||
|
@ -168,7 +173,7 @@ type connection struct {
|
|||
oneRTTStream cryptoStream // only set for the server
|
||||
cryptoStreamHandler cryptoStreamHandler
|
||||
|
||||
receivedPackets chan receivedPacket
|
||||
receivedPackets chan *receivedPacket
|
||||
sendingScheduled chan struct{}
|
||||
|
||||
closeOnce sync.Once
|
||||
|
@ -180,8 +185,8 @@ type connection struct {
|
|||
handshakeCtx context.Context
|
||||
handshakeCtxCancel context.CancelFunc
|
||||
|
||||
undecryptablePackets []receivedPacket // undecryptable packets, waiting for a change in encryption level
|
||||
undecryptablePacketsToProcess []receivedPacket
|
||||
undecryptablePackets []*receivedPacket // undecryptable packets, waiting for a change in encryption level
|
||||
undecryptablePacketsToProcess []*receivedPacket
|
||||
|
||||
clientHelloWritten <-chan *wire.TransportParameters
|
||||
earlyConnReadyChan chan struct{}
|
||||
|
@ -194,7 +199,6 @@ type connection struct {
|
|||
versionNegotiated bool
|
||||
receivedFirstPacket bool
|
||||
|
||||
// the minimum of the max_idle_timeout values advertised by both endpoints
|
||||
idleTimeout time.Duration
|
||||
creationTime time.Time
|
||||
// The idle timeout is set based on the max of the time we received the last packet...
|
||||
|
@ -236,7 +240,6 @@ var newConnection = func(
|
|||
clientDestConnID protocol.ConnectionID,
|
||||
destConnID protocol.ConnectionID,
|
||||
srcConnID protocol.ConnectionID,
|
||||
connIDGenerator ConnectionIDGenerator,
|
||||
statelessResetToken protocol.StatelessResetToken,
|
||||
conf *Config,
|
||||
tlsConf *tls.Config,
|
||||
|
@ -280,7 +283,7 @@ var newConnection = func(
|
|||
runner.Retire,
|
||||
runner.ReplaceWithClosed,
|
||||
s.queueControlFrame,
|
||||
connIDGenerator,
|
||||
s.config.ConnectionIDGenerator,
|
||||
)
|
||||
s.preSetup()
|
||||
s.ctx, s.ctxCancel = context.WithCancel(context.WithValue(context.Background(), ConnectionTracingKey, tracingID))
|
||||
|
@ -293,7 +296,6 @@ var newConnection = func(
|
|||
s.tracer,
|
||||
s.logger,
|
||||
)
|
||||
s.mtuDiscoverer = newMTUDiscoverer(s.rttStats, getMaxPacketSize(s.conn.RemoteAddr()), s.sentPacketHandler.SetMaxDatagramSize)
|
||||
initialStream := newCryptoStream()
|
||||
handshakeStream := newCryptoStream()
|
||||
params := &wire.TransportParameters{
|
||||
|
@ -309,14 +311,9 @@ var newConnection = func(
|
|||
DisableActiveMigration: true,
|
||||
StatelessResetToken: &statelessResetToken,
|
||||
OriginalDestinationConnectionID: origDestConnID,
|
||||
// For interoperability with quic-go versions before May 2023, this value must be set to a value
|
||||
// different from protocol.DefaultActiveConnectionIDLimit.
|
||||
// If set to the default value, it will be omitted from the transport parameters, which will make
|
||||
// old quic-go versions interpret it as 0, instead of the default value of 2.
|
||||
// See https://github.com/quic-go/quic-go/pull/3806.
|
||||
ActiveConnectionIDLimit: protocol.MaxActiveConnectionIDs,
|
||||
InitialSourceConnectionID: srcConnID,
|
||||
RetrySourceConnectionID: retrySrcConnID,
|
||||
ActiveConnectionIDLimit: protocol.MaxActiveConnectionIDs,
|
||||
InitialSourceConnectionID: srcConnID,
|
||||
RetrySourceConnectionID: retrySrcConnID,
|
||||
}
|
||||
if s.config.EnableDatagrams {
|
||||
params.MaxDatagramFrameSize = protocol.MaxDatagramFrameSize
|
||||
|
@ -326,6 +323,10 @@ var newConnection = func(
|
|||
if s.tracer != nil {
|
||||
s.tracer.SentTransportParameters(params)
|
||||
}
|
||||
var allow0RTT func() bool
|
||||
if conf.Allow0RTT != nil {
|
||||
allow0RTT = func() bool { return conf.Allow0RTT(conn.RemoteAddr()) }
|
||||
}
|
||||
cs := handshake.NewCryptoSetupServer(
|
||||
initialStream,
|
||||
handshakeStream,
|
||||
|
@ -343,14 +344,14 @@ var newConnection = func(
|
|||
},
|
||||
},
|
||||
tlsConf,
|
||||
conf.Allow0RTT,
|
||||
allow0RTT,
|
||||
s.rttStats,
|
||||
tracer,
|
||||
logger,
|
||||
s.version,
|
||||
)
|
||||
s.cryptoStreamHandler = cs
|
||||
s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, initialStream, handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective)
|
||||
s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, initialStream, handshakeStream, s.sentPacketHandler, s.retransmissionQueue, s.RemoteAddr(), cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective)
|
||||
s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen)
|
||||
s.cryptoStreamManager = newCryptoStreamManager(cs, initialStream, handshakeStream, s.oneRTTStream)
|
||||
return s
|
||||
|
@ -362,7 +363,6 @@ var newClientConnection = func(
|
|||
runner connRunner,
|
||||
destConnID protocol.ConnectionID,
|
||||
srcConnID protocol.ConnectionID,
|
||||
connIDGenerator ConnectionIDGenerator,
|
||||
conf *Config,
|
||||
tlsConf *tls.Config,
|
||||
initialPacketNumber protocol.PacketNumber,
|
||||
|
@ -402,7 +402,7 @@ var newClientConnection = func(
|
|||
runner.Retire,
|
||||
runner.ReplaceWithClosed,
|
||||
s.queueControlFrame,
|
||||
connIDGenerator,
|
||||
s.config.ConnectionIDGenerator,
|
||||
)
|
||||
s.preSetup()
|
||||
s.ctx, s.ctxCancel = context.WithCancel(context.WithValue(context.Background(), ConnectionTracingKey, tracingID))
|
||||
|
@ -415,7 +415,6 @@ var newClientConnection = func(
|
|||
s.tracer,
|
||||
s.logger,
|
||||
)
|
||||
s.mtuDiscoverer = newMTUDiscoverer(s.rttStats, getMaxPacketSize(s.conn.RemoteAddr()), s.sentPacketHandler.SetMaxDatagramSize)
|
||||
initialStream := newCryptoStream()
|
||||
handshakeStream := newCryptoStream()
|
||||
params := &wire.TransportParameters{
|
||||
|
@ -429,13 +428,8 @@ var newClientConnection = func(
|
|||
MaxAckDelay: protocol.MaxAckDelayInclGranularity,
|
||||
AckDelayExponent: protocol.AckDelayExponent,
|
||||
DisableActiveMigration: true,
|
||||
// For interoperability with quic-go versions before May 2023, this value must be set to a value
|
||||
// different from protocol.DefaultActiveConnectionIDLimit.
|
||||
// If set to the default value, it will be omitted from the transport parameters, which will make
|
||||
// old quic-go versions interpret it as 0, instead of the default value of 2.
|
||||
// See https://github.com/quic-go/quic-go/pull/3806.
|
||||
ActiveConnectionIDLimit: protocol.MaxActiveConnectionIDs,
|
||||
InitialSourceConnectionID: srcConnID,
|
||||
ActiveConnectionIDLimit: protocol.MaxActiveConnectionIDs,
|
||||
InitialSourceConnectionID: srcConnID,
|
||||
}
|
||||
if s.config.EnableDatagrams {
|
||||
params.MaxDatagramFrameSize = protocol.MaxDatagramFrameSize
|
||||
|
@ -469,7 +463,7 @@ var newClientConnection = func(
|
|||
s.cryptoStreamHandler = cs
|
||||
s.cryptoStreamManager = newCryptoStreamManager(cs, initialStream, handshakeStream, newCryptoStream())
|
||||
s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen)
|
||||
s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, initialStream, handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective)
|
||||
s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, initialStream, handshakeStream, s.sentPacketHandler, s.retransmissionQueue, s.RemoteAddr(), cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective)
|
||||
if len(tlsConf.ServerName) > 0 {
|
||||
s.tokenStoreKey = tlsConf.ServerName
|
||||
} else {
|
||||
|
@ -510,7 +504,7 @@ func (s *connection) preSetup() {
|
|||
s.perspective,
|
||||
)
|
||||
s.framer = newFramer(s.streamsMap)
|
||||
s.receivedPackets = make(chan receivedPacket, protocol.MaxConnUnprocessedPackets)
|
||||
s.receivedPackets = make(chan *receivedPacket, protocol.MaxConnUnprocessedPackets)
|
||||
s.closeChan = make(chan closeError, 1)
|
||||
s.sendingScheduled = make(chan struct{}, 1)
|
||||
s.handshakeCtx, s.handshakeCtxCancel = context.WithCancel(context.Background())
|
||||
|
@ -663,7 +657,7 @@ runLoop:
|
|||
} else {
|
||||
idleTimeoutStartTime := s.idleTimeoutStartTime()
|
||||
if (!s.handshakeComplete && now.Sub(idleTimeoutStartTime) >= s.config.HandshakeIdleTimeout) ||
|
||||
(s.handshakeComplete && now.After(s.nextIdleTimeoutTime())) {
|
||||
(s.handshakeComplete && now.Sub(idleTimeoutStartTime) >= s.idleTimeout) {
|
||||
s.destroyImpl(qerr.ErrIdleTimeout)
|
||||
continue
|
||||
}
|
||||
|
@ -675,7 +669,7 @@ runLoop:
|
|||
sendQueueAvailable = s.sendQueue.Available()
|
||||
continue
|
||||
}
|
||||
if err := s.triggerSending(); err != nil {
|
||||
if err := s.sendPackets(); err != nil {
|
||||
s.closeLocal(err)
|
||||
}
|
||||
if s.sendQueue.WouldBlock() {
|
||||
|
@ -687,12 +681,12 @@ runLoop:
|
|||
|
||||
s.cryptoStreamHandler.Close()
|
||||
<-handshaking
|
||||
s.sendQueue.Close() // close the send queue before sending the CONNECTION_CLOSE
|
||||
s.handleCloseError(&closeErr)
|
||||
if e := (&errCloseForRecreating{}); !errors.As(closeErr.err, &e) && s.tracer != nil {
|
||||
s.tracer.Close()
|
||||
}
|
||||
s.logger.Infof("Connection %s closed.", s.logID)
|
||||
s.sendQueue.Close()
|
||||
s.timer.Stop()
|
||||
return closeErr.err
|
||||
}
|
||||
|
@ -721,20 +715,13 @@ func (s *connection) ConnectionState() ConnectionState {
|
|||
return s.connState
|
||||
}
|
||||
|
||||
// Time when the connection should time out
|
||||
func (s *connection) nextIdleTimeoutTime() time.Time {
|
||||
idleTimeout := utils.Max(s.idleTimeout, s.rttStats.PTO(true)*3)
|
||||
return s.idleTimeoutStartTime().Add(idleTimeout)
|
||||
}
|
||||
|
||||
// Time when the next keep-alive packet should be sent.
|
||||
// It returns a zero time if no keep-alive should be sent.
|
||||
func (s *connection) nextKeepAliveTime() time.Time {
|
||||
if s.config.KeepAlivePeriod == 0 || s.keepAlivePingSent || !s.firstAckElicitingPacketAfterIdleSentTime.IsZero() {
|
||||
return time.Time{}
|
||||
}
|
||||
keepAliveInterval := utils.Max(s.keepAliveInterval, s.rttStats.PTO(true)*3/2)
|
||||
return s.lastPacketReceivedTime.Add(keepAliveInterval)
|
||||
return s.lastPacketReceivedTime.Add(s.keepAliveInterval)
|
||||
}
|
||||
|
||||
func (s *connection) maybeResetTimer() {
|
||||
|
@ -748,7 +735,7 @@ func (s *connection) maybeResetTimer() {
|
|||
if keepAliveTime := s.nextKeepAliveTime(); !keepAliveTime.IsZero() {
|
||||
deadline = keepAliveTime
|
||||
} else {
|
||||
deadline = s.nextIdleTimeoutTime()
|
||||
deadline = s.idleTimeoutStartTime().Add(s.idleTimeout)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -805,16 +792,25 @@ func (s *connection) handleHandshakeConfirmed() {
|
|||
s.sentPacketHandler.SetHandshakeConfirmed()
|
||||
s.cryptoStreamHandler.SetHandshakeConfirmed()
|
||||
|
||||
if !s.config.DisablePathMTUDiscovery && s.conn.capabilities().DF {
|
||||
if !s.config.DisablePathMTUDiscovery {
|
||||
maxPacketSize := s.peerParams.MaxUDPPayloadSize
|
||||
if maxPacketSize == 0 {
|
||||
maxPacketSize = protocol.MaxByteCount
|
||||
}
|
||||
s.mtuDiscoverer.Start(utils.Min(maxPacketSize, protocol.MaxPacketBufferSize))
|
||||
maxPacketSize = utils.Min(maxPacketSize, protocol.MaxPacketBufferSize)
|
||||
s.mtuDiscoverer = newMTUDiscoverer(
|
||||
s.rttStats,
|
||||
getMaxPacketSize(s.conn.RemoteAddr()),
|
||||
maxPacketSize,
|
||||
func(size protocol.ByteCount) {
|
||||
s.sentPacketHandler.SetMaxDatagramSize(size)
|
||||
s.packer.SetMaxPacketSize(size)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *connection) handlePacketImpl(rp receivedPacket) bool {
|
||||
func (s *connection) handlePacketImpl(rp *receivedPacket) bool {
|
||||
s.sentPacketHandler.ReceivedBytes(rp.Size())
|
||||
|
||||
if wire.IsVersionNegotiationPacket(rp.data) {
|
||||
|
@ -830,7 +826,7 @@ func (s *connection) handlePacketImpl(rp receivedPacket) bool {
|
|||
for len(data) > 0 {
|
||||
var destConnID protocol.ConnectionID
|
||||
if counter > 0 {
|
||||
p = *(p.Clone())
|
||||
p = p.Clone()
|
||||
p.data = data
|
||||
|
||||
var err error
|
||||
|
@ -903,7 +899,7 @@ func (s *connection) handlePacketImpl(rp receivedPacket) bool {
|
|||
return processed
|
||||
}
|
||||
|
||||
func (s *connection) handleShortHeaderPacket(p receivedPacket, destConnID protocol.ConnectionID) bool {
|
||||
func (s *connection) handleShortHeaderPacket(p *receivedPacket, destConnID protocol.ConnectionID) bool {
|
||||
var wasQueued bool
|
||||
|
||||
defer func() {
|
||||
|
@ -954,7 +950,7 @@ func (s *connection) handleShortHeaderPacket(p receivedPacket, destConnID protoc
|
|||
return true
|
||||
}
|
||||
|
||||
func (s *connection) handleLongHeaderPacket(p receivedPacket, hdr *wire.Header) bool /* was the packet successfully processed */ {
|
||||
func (s *connection) handleLongHeaderPacket(p *receivedPacket, hdr *wire.Header) bool /* was the packet successfully processed */ {
|
||||
var wasQueued bool
|
||||
|
||||
defer func() {
|
||||
|
@ -1011,7 +1007,7 @@ func (s *connection) handleLongHeaderPacket(p receivedPacket, hdr *wire.Header)
|
|||
return true
|
||||
}
|
||||
|
||||
func (s *connection) handleUnpackError(err error, p receivedPacket, pt logging.PacketType) (wasQueued bool) {
|
||||
func (s *connection) handleUnpackError(err error, p *receivedPacket, pt logging.PacketType) (wasQueued bool) {
|
||||
switch err {
|
||||
case handshake.ErrKeysDropped:
|
||||
if s.tracer != nil {
|
||||
|
@ -1113,7 +1109,7 @@ func (s *connection) handleRetryPacket(hdr *wire.Header, data []byte) bool /* wa
|
|||
return true
|
||||
}
|
||||
|
||||
func (s *connection) handleVersionNegotiationPacket(p receivedPacket) {
|
||||
func (s *connection) handleVersionNegotiationPacket(p *receivedPacket) {
|
||||
if s.perspective == protocol.PerspectiveServer || // servers never receive version negotiation packets
|
||||
s.receivedFirstPacket || s.versionNegotiated { // ignore delayed / duplicated version negotiation packets
|
||||
if s.tracer != nil {
|
||||
|
@ -1257,11 +1253,7 @@ func (s *connection) handleFrames(
|
|||
) (isAckEliciting bool, _ error) {
|
||||
// Only used for tracing.
|
||||
// If we're not tracing, this slice will always remain empty.
|
||||
var frames []logging.Frame
|
||||
if log != nil {
|
||||
frames = make([]logging.Frame, 0, 4)
|
||||
}
|
||||
var handleErr error
|
||||
var frames []wire.Frame
|
||||
for len(data) > 0 {
|
||||
l, frame, err := s.frameParser.ParseNext(data, encLevel, s.version)
|
||||
if err != nil {
|
||||
|
@ -1274,27 +1266,27 @@ func (s *connection) handleFrames(
|
|||
if ackhandler.IsFrameAckEliciting(frame) {
|
||||
isAckEliciting = true
|
||||
}
|
||||
if log != nil {
|
||||
frames = append(frames, logutils.ConvertFrame(frame))
|
||||
}
|
||||
// An error occurred handling a previous frame.
|
||||
// Don't handle the current frame.
|
||||
if handleErr != nil {
|
||||
continue
|
||||
}
|
||||
if err := s.handleFrame(frame, encLevel, destConnID); err != nil {
|
||||
if log == nil {
|
||||
// Only process frames now if we're not logging.
|
||||
// If we're logging, we need to make sure that the packet_received event is logged first.
|
||||
if log == nil {
|
||||
if err := s.handleFrame(frame, encLevel, destConnID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
// If we're logging, we need to keep parsing (but not handling) all frames.
|
||||
handleErr = err
|
||||
} else {
|
||||
frames = append(frames, frame)
|
||||
}
|
||||
}
|
||||
|
||||
if log != nil {
|
||||
log(frames)
|
||||
if handleErr != nil {
|
||||
return false, handleErr
|
||||
fs := make([]logging.Frame, len(frames))
|
||||
for i, frame := range frames {
|
||||
fs[i] = logutils.ConvertFrame(frame)
|
||||
}
|
||||
log(fs)
|
||||
for _, frame := range frames {
|
||||
if err := s.handleFrame(frame, encLevel, destConnID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
|
@ -1310,6 +1302,7 @@ func (s *connection) handleFrame(f wire.Frame, encLevel protocol.EncryptionLevel
|
|||
err = s.handleStreamFrame(frame)
|
||||
case *wire.AckFrame:
|
||||
err = s.handleAckFrame(frame, encLevel)
|
||||
wire.PutAckFrame(frame)
|
||||
case *wire.ConnectionCloseFrame:
|
||||
s.handleConnectionCloseFrame(frame)
|
||||
case *wire.ResetStreamFrame:
|
||||
|
@ -1348,7 +1341,7 @@ func (s *connection) handleFrame(f wire.Frame, encLevel protocol.EncryptionLevel
|
|||
}
|
||||
|
||||
// handlePacket is called by the server with a new packet
|
||||
func (s *connection) handlePacket(p receivedPacket) {
|
||||
func (s *connection) handlePacket(p *receivedPacket) {
|
||||
// Discard packets once the amount of queued packets is larger than
|
||||
// the channel size, protocol.MaxConnUnprocessedPackets
|
||||
select {
|
||||
|
@ -1722,6 +1715,7 @@ func (s *connection) applyTransportParameters() {
|
|||
s.idleTimeout = utils.MinNonZeroDuration(s.config.MaxIdleTimeout, params.MaxIdleTimeout)
|
||||
s.keepAliveInterval = utils.Min(s.config.KeepAlivePeriod, utils.Min(s.idleTimeout/2, protocol.MaxKeepAliveInterval))
|
||||
s.streamsMap.UpdateLimits(params)
|
||||
s.packer.HandleTransportParameters(params)
|
||||
s.frameParser.SetAckDelayExponent(params.AckDelayExponent)
|
||||
s.connFlowController.UpdateSendWindow(params.InitialMaxData)
|
||||
s.rttStats.SetMaxAckDelay(params.MaxAckDelay)
|
||||
|
@ -1736,208 +1730,75 @@ func (s *connection) applyTransportParameters() {
|
|||
}
|
||||
}
|
||||
|
||||
func (s *connection) triggerSending() error {
|
||||
func (s *connection) sendPackets() error {
|
||||
s.pacingDeadline = time.Time{}
|
||||
now := time.Now()
|
||||
|
||||
sendMode := s.sentPacketHandler.SendMode(now)
|
||||
//nolint:exhaustive // No need to handle pacing limited here.
|
||||
switch sendMode {
|
||||
case ackhandler.SendAny:
|
||||
return s.sendPackets(now)
|
||||
case ackhandler.SendNone:
|
||||
return nil
|
||||
case ackhandler.SendPacingLimited:
|
||||
deadline := s.sentPacketHandler.TimeUntilSend()
|
||||
if deadline.IsZero() {
|
||||
deadline = deadlineSendImmediately
|
||||
}
|
||||
s.pacingDeadline = deadline
|
||||
// Allow sending of an ACK if we're pacing limit.
|
||||
// This makes sure that a peer that is mostly receiving data (and thus has an inaccurate cwnd estimate)
|
||||
// sends enough ACKs to allow its peer to utilize the bandwidth.
|
||||
fallthrough
|
||||
case ackhandler.SendAck:
|
||||
// We can at most send a single ACK only packet.
|
||||
// There will only be a new ACK after receiving new packets.
|
||||
// SendAck is only returned when we're congestion limited, so we don't need to set the pacinggs timer.
|
||||
return s.maybeSendAckOnlyPacket(now)
|
||||
case ackhandler.SendPTOInitial:
|
||||
if err := s.sendProbePacket(protocol.EncryptionInitial, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.sendQueue.WouldBlock() {
|
||||
s.scheduleSending()
|
||||
return nil
|
||||
}
|
||||
return s.triggerSending()
|
||||
case ackhandler.SendPTOHandshake:
|
||||
if err := s.sendProbePacket(protocol.EncryptionHandshake, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.sendQueue.WouldBlock() {
|
||||
s.scheduleSending()
|
||||
return nil
|
||||
}
|
||||
return s.triggerSending()
|
||||
case ackhandler.SendPTOAppData:
|
||||
if err := s.sendProbePacket(protocol.Encryption1RTT, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.sendQueue.WouldBlock() {
|
||||
s.scheduleSending()
|
||||
return nil
|
||||
}
|
||||
return s.triggerSending()
|
||||
default:
|
||||
return fmt.Errorf("BUG: invalid send mode %d", sendMode)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *connection) sendPackets(now time.Time) error {
|
||||
// Path MTU Discovery
|
||||
// Can't use GSO, since we need to send a single packet that's larger than our current maximum size.
|
||||
// Performance-wise, this doesn't matter, since we only send a very small (<10) number of
|
||||
// MTU probe packets per connection.
|
||||
if s.handshakeConfirmed && s.mtuDiscoverer != nil && s.mtuDiscoverer.ShouldSendProbe(now) {
|
||||
ping, size := s.mtuDiscoverer.GetPing()
|
||||
p, buf, err := s.packer.PackMTUProbePacket(ping, size, s.version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, buf.Len(), false)
|
||||
s.registerPackedShortHeaderPacket(p, now)
|
||||
s.sendQueue.Send(buf, buf.Len())
|
||||
// This is kind of a hack. We need to trigger sending again somehow.
|
||||
s.pacingDeadline = deadlineSendImmediately
|
||||
return nil
|
||||
}
|
||||
|
||||
if isBlocked, offset := s.connFlowController.IsNewlyBlocked(); isBlocked {
|
||||
s.framer.QueueControlFrame(&wire.DataBlockedFrame{MaximumData: offset})
|
||||
}
|
||||
s.windowUpdateQueue.QueueAll()
|
||||
|
||||
if !s.handshakeConfirmed {
|
||||
packet, err := s.packer.PackCoalescedPacket(false, s.mtuDiscoverer.CurrentSize(), s.version)
|
||||
if err != nil || packet == nil {
|
||||
return err
|
||||
}
|
||||
s.sentFirstPacket = true
|
||||
s.sendPackedCoalescedPacket(packet, now)
|
||||
sendMode := s.sentPacketHandler.SendMode(now)
|
||||
if sendMode == ackhandler.SendPacingLimited {
|
||||
s.resetPacingDeadline()
|
||||
} else if sendMode == ackhandler.SendAny {
|
||||
s.pacingDeadline = deadlineSendImmediately
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if s.conn.capabilities().GSO {
|
||||
return s.sendPacketsWithGSO(now)
|
||||
}
|
||||
return s.sendPacketsWithoutGSO(now)
|
||||
}
|
||||
|
||||
func (s *connection) sendPacketsWithoutGSO(now time.Time) error {
|
||||
var sentPacket bool // only used in for packets sent in send mode SendAny
|
||||
for {
|
||||
buf := getPacketBuffer()
|
||||
if _, err := s.appendPacket(buf, s.mtuDiscoverer.CurrentSize(), now); err != nil {
|
||||
if err == errNothingToPack {
|
||||
buf.Release()
|
||||
sendMode := s.sentPacketHandler.SendMode()
|
||||
if sendMode == ackhandler.SendAny && s.handshakeComplete && !s.sentPacketHandler.HasPacingBudget() {
|
||||
deadline := s.sentPacketHandler.TimeUntilSend()
|
||||
if deadline.IsZero() {
|
||||
deadline = deadlineSendImmediately
|
||||
}
|
||||
s.pacingDeadline = deadline
|
||||
// Allow sending of an ACK if we're pacing limit (if we haven't sent out a packet yet).
|
||||
// This makes sure that a peer that is mostly receiving data (and thus has an inaccurate cwnd estimate)
|
||||
// sends enough ACKs to allow its peer to utilize the bandwidth.
|
||||
if sentPacket {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
sendMode = ackhandler.SendAck
|
||||
}
|
||||
|
||||
s.sendQueue.Send(buf, buf.Len())
|
||||
|
||||
if s.sendQueue.WouldBlock() {
|
||||
switch sendMode {
|
||||
case ackhandler.SendNone:
|
||||
return nil
|
||||
}
|
||||
sendMode := s.sentPacketHandler.SendMode(now)
|
||||
if sendMode == ackhandler.SendPacingLimited {
|
||||
s.resetPacingDeadline()
|
||||
return nil
|
||||
}
|
||||
if sendMode != ackhandler.SendAny {
|
||||
return nil
|
||||
}
|
||||
// Prioritize receiving of packets over sending out more packets.
|
||||
if len(s.receivedPackets) > 0 {
|
||||
s.pacingDeadline = deadlineSendImmediately
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *connection) sendPacketsWithGSO(now time.Time) error {
|
||||
buf := getLargePacketBuffer()
|
||||
maxSize := s.mtuDiscoverer.CurrentSize()
|
||||
|
||||
for {
|
||||
var dontSendMore bool
|
||||
size, err := s.appendPacket(buf, maxSize, now)
|
||||
if err != nil {
|
||||
if err != errNothingToPack {
|
||||
case ackhandler.SendAck:
|
||||
// If we already sent packets, and the send mode switches to SendAck,
|
||||
// as we've just become congestion limited.
|
||||
// There's no need to try to send an ACK at this moment.
|
||||
if sentPacket {
|
||||
return nil
|
||||
}
|
||||
// We can at most send a single ACK only packet.
|
||||
// There will only be a new ACK after receiving new packets.
|
||||
// SendAck is only returned when we're congestion limited, so we don't need to set the pacinggs timer.
|
||||
return s.maybeSendAckOnlyPacket()
|
||||
case ackhandler.SendPTOInitial:
|
||||
if err := s.sendProbePacket(protocol.EncryptionInitial); err != nil {
|
||||
return err
|
||||
}
|
||||
if buf.Len() == 0 {
|
||||
buf.Release()
|
||||
return nil
|
||||
case ackhandler.SendPTOHandshake:
|
||||
if err := s.sendProbePacket(protocol.EncryptionHandshake); err != nil {
|
||||
return err
|
||||
}
|
||||
dontSendMore = true
|
||||
}
|
||||
|
||||
if !dontSendMore {
|
||||
sendMode := s.sentPacketHandler.SendMode(now)
|
||||
if sendMode == ackhandler.SendPacingLimited {
|
||||
s.resetPacingDeadline()
|
||||
case ackhandler.SendPTOAppData:
|
||||
if err := s.sendProbePacket(protocol.Encryption1RTT); err != nil {
|
||||
return err
|
||||
}
|
||||
if sendMode != ackhandler.SendAny {
|
||||
dontSendMore = true
|
||||
case ackhandler.SendAny:
|
||||
sent, err := s.sendPacket()
|
||||
if err != nil || !sent {
|
||||
return err
|
||||
}
|
||||
sentPacket = true
|
||||
default:
|
||||
return fmt.Errorf("BUG: invalid send mode %d", sendMode)
|
||||
}
|
||||
|
||||
// Append another packet if
|
||||
// 1. The congestion controller and pacer allow sending more
|
||||
// 2. The last packet appended was a full-size packet
|
||||
// 3. We still have enough space for another full-size packet in the buffer
|
||||
if !dontSendMore && size == maxSize && buf.Len()+maxSize <= buf.Cap() {
|
||||
continue
|
||||
}
|
||||
|
||||
s.sendQueue.Send(buf, maxSize)
|
||||
|
||||
if dontSendMore {
|
||||
return nil
|
||||
}
|
||||
if s.sendQueue.WouldBlock() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Prioritize receiving of packets over sending out more packets.
|
||||
if len(s.receivedPackets) > 0 {
|
||||
s.pacingDeadline = deadlineSendImmediately
|
||||
return nil
|
||||
}
|
||||
|
||||
buf = getLargePacketBuffer()
|
||||
if s.sendQueue.WouldBlock() {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *connection) resetPacingDeadline() {
|
||||
deadline := s.sentPacketHandler.TimeUntilSend()
|
||||
if deadline.IsZero() {
|
||||
deadline = deadlineSendImmediately
|
||||
}
|
||||
s.pacingDeadline = deadline
|
||||
}
|
||||
|
||||
func (s *connection) maybeSendAckOnlyPacket(now time.Time) error {
|
||||
func (s *connection) maybeSendAckOnlyPacket() error {
|
||||
if !s.handshakeConfirmed {
|
||||
packet, err := s.packer.PackCoalescedPacket(true, s.mtuDiscoverer.CurrentSize(), s.version)
|
||||
packet, err := s.packer.PackCoalescedPacket(true, s.version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -1948,20 +1809,20 @@ func (s *connection) maybeSendAckOnlyPacket(now time.Time) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
p, buf, err := s.packer.PackAckOnlyPacket(s.mtuDiscoverer.CurrentSize(), s.version)
|
||||
now := time.Now()
|
||||
p, buffer, err := s.packer.PackPacket(true, now, s.version)
|
||||
if err != nil {
|
||||
if err == errNothingToPack {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, buf.Len(), false)
|
||||
s.registerPackedShortHeaderPacket(p, now)
|
||||
s.sendQueue.Send(buf, buf.Len())
|
||||
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, buffer.Len(), false)
|
||||
s.sendPackedShortHeaderPacket(buffer, p.Packet, now)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *connection) sendProbePacket(encLevel protocol.EncryptionLevel, now time.Time) error {
|
||||
func (s *connection) sendProbePacket(encLevel protocol.EncryptionLevel) error {
|
||||
// Queue probe packets until we actually send out a packet,
|
||||
// or until there are no more packets to queue.
|
||||
var packet *coalescedPacket
|
||||
|
@ -1970,7 +1831,7 @@ func (s *connection) sendProbePacket(encLevel protocol.EncryptionLevel, now time
|
|||
break
|
||||
}
|
||||
var err error
|
||||
packet, err = s.packer.MaybePackProbePacket(encLevel, s.mtuDiscoverer.CurrentSize(), s.version)
|
||||
packet, err = s.packer.MaybePackProbePacket(encLevel, s.version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -1979,9 +1840,19 @@ func (s *connection) sendProbePacket(encLevel protocol.EncryptionLevel, now time
|
|||
}
|
||||
}
|
||||
if packet == nil {
|
||||
s.retransmissionQueue.AddPing(encLevel)
|
||||
//nolint:exhaustive // Cannot send probe packets for 0-RTT.
|
||||
switch encLevel {
|
||||
case protocol.EncryptionInitial:
|
||||
s.retransmissionQueue.AddInitial(&wire.PingFrame{})
|
||||
case protocol.EncryptionHandshake:
|
||||
s.retransmissionQueue.AddHandshake(&wire.PingFrame{})
|
||||
case protocol.Encryption1RTT:
|
||||
s.retransmissionQueue.AddAppData(&wire.PingFrame{})
|
||||
default:
|
||||
panic("unexpected encryption level")
|
||||
}
|
||||
var err error
|
||||
packet, err = s.packer.MaybePackProbePacket(encLevel, s.mtuDiscoverer.CurrentSize(), s.version)
|
||||
packet, err = s.packer.MaybePackProbePacket(encLevel, s.version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -1989,35 +1860,55 @@ func (s *connection) sendProbePacket(encLevel protocol.EncryptionLevel, now time
|
|||
if packet == nil || (len(packet.longHdrPackets) == 0 && packet.shortHdrPacket == nil) {
|
||||
return fmt.Errorf("connection BUG: couldn't pack %s probe packet", encLevel)
|
||||
}
|
||||
s.sendPackedCoalescedPacket(packet, now)
|
||||
s.sendPackedCoalescedPacket(packet, time.Now())
|
||||
return nil
|
||||
}
|
||||
|
||||
// appendPacket appends a new packet to the given packetBuffer.
|
||||
// If there was nothing to pack, the returned size is 0.
|
||||
func (s *connection) appendPacket(buf *packetBuffer, maxSize protocol.ByteCount, now time.Time) (protocol.ByteCount, error) {
|
||||
startLen := buf.Len()
|
||||
p, err := s.packer.AppendPacket(buf, maxSize, s.version)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
func (s *connection) sendPacket() (bool, error) {
|
||||
if isBlocked, offset := s.connFlowController.IsNewlyBlocked(); isBlocked {
|
||||
s.framer.QueueControlFrame(&wire.DataBlockedFrame{MaximumData: offset})
|
||||
}
|
||||
size := buf.Len() - startLen
|
||||
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, size, false)
|
||||
s.registerPackedShortHeaderPacket(p, now)
|
||||
return size, nil
|
||||
s.windowUpdateQueue.QueueAll()
|
||||
|
||||
now := time.Now()
|
||||
if !s.handshakeConfirmed {
|
||||
packet, err := s.packer.PackCoalescedPacket(false, s.version)
|
||||
if err != nil || packet == nil {
|
||||
return false, err
|
||||
}
|
||||
s.sentFirstPacket = true
|
||||
s.sendPackedCoalescedPacket(packet, now)
|
||||
return true, nil
|
||||
} else if !s.config.DisablePathMTUDiscovery && s.mtuDiscoverer.ShouldSendProbe(now) {
|
||||
ping, size := s.mtuDiscoverer.GetPing()
|
||||
p, buffer, err := s.packer.PackMTUProbePacket(ping, size, now, s.version)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, buffer.Len(), false)
|
||||
s.sendPackedShortHeaderPacket(buffer, p.Packet, now)
|
||||
return true, nil
|
||||
}
|
||||
p, buffer, err := s.packer.PackPacket(false, now, s.version)
|
||||
if err != nil {
|
||||
if err == errNothingToPack {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, buffer.Len(), false)
|
||||
s.sendPackedShortHeaderPacket(buffer, p.Packet, now)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *connection) registerPackedShortHeaderPacket(p shortHeaderPacket, now time.Time) {
|
||||
if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && (len(p.StreamFrames) > 0 || ackhandler.HasAckElicitingFrames(p.Frames)) {
|
||||
func (s *connection) sendPackedShortHeaderPacket(buffer *packetBuffer, p *ackhandler.Packet, now time.Time) {
|
||||
if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && ackhandler.HasAckElicitingFrames(p.Frames) {
|
||||
s.firstAckElicitingPacketAfterIdleSentTime = now
|
||||
}
|
||||
|
||||
largestAcked := protocol.InvalidPacketNumber
|
||||
if p.Ack != nil {
|
||||
largestAcked = p.Ack.LargestAcked()
|
||||
}
|
||||
s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, p.Length, p.IsPathMTUProbePacket)
|
||||
s.sentPacketHandler.SentPacket(p)
|
||||
s.connIDManager.SentPacket()
|
||||
s.sendQueue.Send(buffer)
|
||||
}
|
||||
|
||||
func (s *connection) sendPackedCoalescedPacket(packet *coalescedPacket, now time.Time) {
|
||||
|
@ -2026,24 +1917,16 @@ func (s *connection) sendPackedCoalescedPacket(packet *coalescedPacket, now time
|
|||
if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && p.IsAckEliciting() {
|
||||
s.firstAckElicitingPacketAfterIdleSentTime = now
|
||||
}
|
||||
largestAcked := protocol.InvalidPacketNumber
|
||||
if p.ack != nil {
|
||||
largestAcked = p.ack.LargestAcked()
|
||||
}
|
||||
s.sentPacketHandler.SentPacket(now, p.header.PacketNumber, largestAcked, p.streamFrames, p.frames, p.EncryptionLevel(), p.length, false)
|
||||
s.sentPacketHandler.SentPacket(p.ToAckHandlerPacket(now, s.retransmissionQueue))
|
||||
}
|
||||
if p := packet.shortHdrPacket; p != nil {
|
||||
if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && p.IsAckEliciting() {
|
||||
s.firstAckElicitingPacketAfterIdleSentTime = now
|
||||
}
|
||||
largestAcked := protocol.InvalidPacketNumber
|
||||
if p.Ack != nil {
|
||||
largestAcked = p.Ack.LargestAcked()
|
||||
}
|
||||
s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, p.Length, p.IsPathMTUProbePacket)
|
||||
s.sentPacketHandler.SentPacket(p.Packet)
|
||||
}
|
||||
s.connIDManager.SentPacket()
|
||||
s.sendQueue.Send(packet.buffer, packet.buffer.Len())
|
||||
s.sendQueue.Send(packet.buffer)
|
||||
}
|
||||
|
||||
func (s *connection) sendConnectionClose(e error) ([]byte, error) {
|
||||
|
@ -2052,20 +1935,20 @@ func (s *connection) sendConnectionClose(e error) ([]byte, error) {
|
|||
var transportErr *qerr.TransportError
|
||||
var applicationErr *qerr.ApplicationError
|
||||
if errors.As(e, &transportErr) {
|
||||
packet, err = s.packer.PackConnectionClose(transportErr, s.mtuDiscoverer.CurrentSize(), s.version)
|
||||
packet, err = s.packer.PackConnectionClose(transportErr, s.version)
|
||||
} else if errors.As(e, &applicationErr) {
|
||||
packet, err = s.packer.PackApplicationClose(applicationErr, s.mtuDiscoverer.CurrentSize(), s.version)
|
||||
packet, err = s.packer.PackApplicationClose(applicationErr, s.version)
|
||||
} else {
|
||||
packet, err = s.packer.PackConnectionClose(&qerr.TransportError{
|
||||
ErrorCode: qerr.InternalError,
|
||||
ErrorMessage: fmt.Sprintf("connection BUG: unspecified error type (msg: %s)", e.Error()),
|
||||
}, s.mtuDiscoverer.CurrentSize(), s.version)
|
||||
}, s.version)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.logCoalescedPacket(packet)
|
||||
return packet.buffer.Data, s.conn.Write(packet.buffer.Data, packet.buffer.Len())
|
||||
return packet.buffer.Data, s.conn.Write(packet.buffer.Data)
|
||||
}
|
||||
|
||||
func (s *connection) logLongHeaderPacket(p *longHeaderPacket) {
|
||||
|
@ -2097,8 +1980,7 @@ func (s *connection) logLongHeaderPacket(p *longHeaderPacket) {
|
|||
func (s *connection) logShortHeaderPacket(
|
||||
destConnID protocol.ConnectionID,
|
||||
ackFrame *wire.AckFrame,
|
||||
frames []ackhandler.Frame,
|
||||
streamFrames []ackhandler.StreamFrame,
|
||||
frames []*ackhandler.Frame,
|
||||
pn protocol.PacketNumber,
|
||||
pnLen protocol.PacketNumberLen,
|
||||
kp protocol.KeyPhaseBit,
|
||||
|
@ -2114,23 +1996,17 @@ func (s *connection) logShortHeaderPacket(
|
|||
if ackFrame != nil {
|
||||
wire.LogFrame(s.logger, ackFrame, true)
|
||||
}
|
||||
for _, f := range frames {
|
||||
wire.LogFrame(s.logger, f.Frame, true)
|
||||
}
|
||||
for _, f := range streamFrames {
|
||||
wire.LogFrame(s.logger, f.Frame, true)
|
||||
for _, frame := range frames {
|
||||
wire.LogFrame(s.logger, frame.Frame, true)
|
||||
}
|
||||
}
|
||||
|
||||
// tracing
|
||||
if s.tracer != nil {
|
||||
fs := make([]logging.Frame, 0, len(frames)+len(streamFrames))
|
||||
fs := make([]logging.Frame, 0, len(frames))
|
||||
for _, f := range frames {
|
||||
fs = append(fs, logutils.ConvertFrame(f.Frame))
|
||||
}
|
||||
for _, f := range streamFrames {
|
||||
fs = append(fs, logutils.ConvertFrame(f.Frame))
|
||||
}
|
||||
var ack *logging.AckFrame
|
||||
if ackFrame != nil {
|
||||
ack = logutils.ConvertAckFrame(ackFrame)
|
||||
|
@ -2158,7 +2034,6 @@ func (s *connection) logCoalescedPacket(packet *coalescedPacket) {
|
|||
packet.shortHdrPacket.DestConnID,
|
||||
packet.shortHdrPacket.Ack,
|
||||
packet.shortHdrPacket.Frames,
|
||||
packet.shortHdrPacket.StreamFrames,
|
||||
packet.shortHdrPacket.PacketNumber,
|
||||
packet.shortHdrPacket.PacketNumberLen,
|
||||
packet.shortHdrPacket.KeyPhase,
|
||||
|
@ -2177,7 +2052,7 @@ func (s *connection) logCoalescedPacket(packet *coalescedPacket) {
|
|||
s.logLongHeaderPacket(p)
|
||||
}
|
||||
if p := packet.shortHdrPacket; p != nil {
|
||||
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, p.Length, true)
|
||||
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, p.Length, true)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -2238,7 +2113,7 @@ func (s *connection) scheduleSending() {
|
|||
|
||||
// tryQueueingUndecryptablePacket queues a packet for which we're missing the decryption keys.
|
||||
// The logging.PacketType is only used for logging purposes.
|
||||
func (s *connection) tryQueueingUndecryptablePacket(p receivedPacket, pt logging.PacketType) {
|
||||
func (s *connection) tryQueueingUndecryptablePacket(p *receivedPacket, pt logging.PacketType) {
|
||||
if s.handshakeComplete {
|
||||
panic("shouldn't queue undecryptable packets after handshake completion")
|
||||
}
|
||||
|
|
49
vendor/github.com/quic-go/quic-go/framer.go
generated
vendored
49
vendor/github.com/quic-go/quic-go/framer.go
generated
vendored
|
@ -6,7 +6,6 @@ import (
|
|||
|
||||
"github.com/quic-go/quic-go/internal/ackhandler"
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
"github.com/quic-go/quic-go/internal/utils/ringbuffer"
|
||||
"github.com/quic-go/quic-go/internal/wire"
|
||||
"github.com/quic-go/quic-go/quicvarint"
|
||||
)
|
||||
|
@ -15,10 +14,10 @@ type framer interface {
|
|||
HasData() bool
|
||||
|
||||
QueueControlFrame(wire.Frame)
|
||||
AppendControlFrames([]ackhandler.Frame, protocol.ByteCount, protocol.VersionNumber) ([]ackhandler.Frame, protocol.ByteCount)
|
||||
AppendControlFrames([]*ackhandler.Frame, protocol.ByteCount, protocol.VersionNumber) ([]*ackhandler.Frame, protocol.ByteCount)
|
||||
|
||||
AddActiveStream(protocol.StreamID)
|
||||
AppendStreamFrames([]ackhandler.StreamFrame, protocol.ByteCount, protocol.VersionNumber) ([]ackhandler.StreamFrame, protocol.ByteCount)
|
||||
AppendStreamFrames([]*ackhandler.Frame, protocol.ByteCount, protocol.VersionNumber) ([]*ackhandler.Frame, protocol.ByteCount)
|
||||
|
||||
Handle0RTTRejection() error
|
||||
}
|
||||
|
@ -29,7 +28,7 @@ type framerI struct {
|
|||
streamGetter streamGetter
|
||||
|
||||
activeStreams map[protocol.StreamID]struct{}
|
||||
streamQueue ringbuffer.RingBuffer[protocol.StreamID]
|
||||
streamQueue []protocol.StreamID
|
||||
|
||||
controlFrameMutex sync.Mutex
|
||||
controlFrames []wire.Frame
|
||||
|
@ -46,7 +45,7 @@ func newFramer(streamGetter streamGetter) framer {
|
|||
|
||||
func (f *framerI) HasData() bool {
|
||||
f.mutex.Lock()
|
||||
hasData := !f.streamQueue.Empty()
|
||||
hasData := len(f.streamQueue) > 0
|
||||
f.mutex.Unlock()
|
||||
if hasData {
|
||||
return true
|
||||
|
@ -63,7 +62,7 @@ func (f *framerI) QueueControlFrame(frame wire.Frame) {
|
|||
f.controlFrameMutex.Unlock()
|
||||
}
|
||||
|
||||
func (f *framerI) AppendControlFrames(frames []ackhandler.Frame, maxLen protocol.ByteCount, v protocol.VersionNumber) ([]ackhandler.Frame, protocol.ByteCount) {
|
||||
func (f *framerI) AppendControlFrames(frames []*ackhandler.Frame, maxLen protocol.ByteCount, v protocol.VersionNumber) ([]*ackhandler.Frame, protocol.ByteCount) {
|
||||
var length protocol.ByteCount
|
||||
f.controlFrameMutex.Lock()
|
||||
for len(f.controlFrames) > 0 {
|
||||
|
@ -72,7 +71,9 @@ func (f *framerI) AppendControlFrames(frames []ackhandler.Frame, maxLen protocol
|
|||
if length+frameLen > maxLen {
|
||||
break
|
||||
}
|
||||
frames = append(frames, ackhandler.Frame{Frame: frame})
|
||||
af := ackhandler.GetFrame()
|
||||
af.Frame = frame
|
||||
frames = append(frames, af)
|
||||
length += frameLen
|
||||
f.controlFrames = f.controlFrames[:len(f.controlFrames)-1]
|
||||
}
|
||||
|
@ -83,23 +84,24 @@ func (f *framerI) AppendControlFrames(frames []ackhandler.Frame, maxLen protocol
|
|||
func (f *framerI) AddActiveStream(id protocol.StreamID) {
|
||||
f.mutex.Lock()
|
||||
if _, ok := f.activeStreams[id]; !ok {
|
||||
f.streamQueue.PushBack(id)
|
||||
f.streamQueue = append(f.streamQueue, id)
|
||||
f.activeStreams[id] = struct{}{}
|
||||
}
|
||||
f.mutex.Unlock()
|
||||
}
|
||||
|
||||
func (f *framerI) AppendStreamFrames(frames []ackhandler.StreamFrame, maxLen protocol.ByteCount, v protocol.VersionNumber) ([]ackhandler.StreamFrame, protocol.ByteCount) {
|
||||
startLen := len(frames)
|
||||
func (f *framerI) AppendStreamFrames(frames []*ackhandler.Frame, maxLen protocol.ByteCount, v protocol.VersionNumber) ([]*ackhandler.Frame, protocol.ByteCount) {
|
||||
var length protocol.ByteCount
|
||||
var lastFrame *ackhandler.Frame
|
||||
f.mutex.Lock()
|
||||
// pop STREAM frames, until less than MinStreamFrameSize bytes are left in the packet
|
||||
numActiveStreams := f.streamQueue.Len()
|
||||
numActiveStreams := len(f.streamQueue)
|
||||
for i := 0; i < numActiveStreams; i++ {
|
||||
if protocol.MinStreamFrameSize+length > maxLen {
|
||||
break
|
||||
}
|
||||
id := f.streamQueue.PopFront()
|
||||
id := f.streamQueue[0]
|
||||
f.streamQueue = f.streamQueue[1:]
|
||||
// This should never return an error. Better check it anyway.
|
||||
// The stream will only be in the streamQueue, if it enqueued itself there.
|
||||
str, err := f.streamGetter.GetOrOpenSendStream(id)
|
||||
|
@ -113,27 +115,28 @@ func (f *framerI) AppendStreamFrames(frames []ackhandler.StreamFrame, maxLen pro
|
|||
// Therefore, we can pretend to have more bytes available when popping
|
||||
// the STREAM frame (which will always have the DataLen set).
|
||||
remainingLen += quicvarint.Len(uint64(remainingLen))
|
||||
frame, ok, hasMoreData := str.popStreamFrame(remainingLen, v)
|
||||
frame, hasMoreData := str.popStreamFrame(remainingLen, v)
|
||||
if hasMoreData { // put the stream back in the queue (at the end)
|
||||
f.streamQueue.PushBack(id)
|
||||
} else { // no more data to send. Stream is not active
|
||||
f.streamQueue = append(f.streamQueue, id)
|
||||
} else { // no more data to send. Stream is not active any more
|
||||
delete(f.activeStreams, id)
|
||||
}
|
||||
// The frame can be "nil"
|
||||
// The frame can be nil
|
||||
// * if the receiveStream was canceled after it said it had data
|
||||
// * the remaining size doesn't allow us to add another STREAM frame
|
||||
if !ok {
|
||||
if frame == nil {
|
||||
continue
|
||||
}
|
||||
frames = append(frames, frame)
|
||||
length += frame.Frame.Length(v)
|
||||
length += frame.Length(v)
|
||||
lastFrame = frame
|
||||
}
|
||||
f.mutex.Unlock()
|
||||
if len(frames) > startLen {
|
||||
l := frames[len(frames)-1].Frame.Length(v)
|
||||
if lastFrame != nil {
|
||||
lastFrameLen := lastFrame.Length(v)
|
||||
// account for the smaller size of the last STREAM frame
|
||||
frames[len(frames)-1].Frame.DataLenPresent = false
|
||||
length += frames[len(frames)-1].Frame.Length(v) - l
|
||||
lastFrame.Frame.(*wire.StreamFrame).DataLenPresent = false
|
||||
length += lastFrame.Length(v) - lastFrameLen
|
||||
}
|
||||
return frames, length
|
||||
}
|
||||
|
@ -143,7 +146,7 @@ func (f *framerI) Handle0RTTRejection() error {
|
|||
defer f.mutex.Unlock()
|
||||
|
||||
f.controlFrameMutex.Lock()
|
||||
f.streamQueue.Clear()
|
||||
f.streamQueue = f.streamQueue[:0]
|
||||
for id := range f.activeStreams {
|
||||
delete(f.activeStreams, id)
|
||||
}
|
||||
|
|
17
vendor/github.com/quic-go/quic-go/http3/client.go
generated
vendored
17
vendor/github.com/quic-go/quic-go/http3/client.go
generated
vendored
|
@ -6,7 +6,6 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
@ -34,11 +33,12 @@ const (
|
|||
var defaultQuicConfig = &quic.Config{
|
||||
MaxIncomingStreams: -1, // don't allow the server to create bidirectional streams
|
||||
KeepAlivePeriod: 10 * time.Second,
|
||||
Versions: []protocol.VersionNumber{protocol.Version1},
|
||||
}
|
||||
|
||||
type dialFunc func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error)
|
||||
|
||||
var dialAddr dialFunc = quic.DialAddrEarly
|
||||
var dialAddr = quic.DialAddrEarlyContext
|
||||
|
||||
type roundTripperOpts struct {
|
||||
DisableCompression bool
|
||||
|
@ -74,10 +74,9 @@ var _ roundTripCloser = &client{}
|
|||
func newClient(hostname string, tlsConf *tls.Config, opts *roundTripperOpts, conf *quic.Config, dialer dialFunc) (roundTripCloser, error) {
|
||||
if conf == nil {
|
||||
conf = defaultQuicConfig.Clone()
|
||||
}
|
||||
if len(conf.Versions) == 0 {
|
||||
} else if len(conf.Versions) == 0 {
|
||||
conf = conf.Clone()
|
||||
conf.Versions = []quic.VersionNumber{protocol.SupportedVersions[0]}
|
||||
conf.Versions = []quic.VersionNumber{defaultQuicConfig.Versions[0]}
|
||||
}
|
||||
if len(conf.Versions) != 1 {
|
||||
return nil, errors.New("can only use a single QUIC version for dialing a HTTP/3 connection")
|
||||
|
@ -93,14 +92,6 @@ func newClient(hostname string, tlsConf *tls.Config, opts *roundTripperOpts, con
|
|||
} else {
|
||||
tlsConf = tlsConf.Clone()
|
||||
}
|
||||
if tlsConf.ServerName == "" {
|
||||
sni, _, err := net.SplitHostPort(hostname)
|
||||
if err != nil {
|
||||
// It's ok if net.SplitHostPort returns an error - it could be a hostname/IP address without a port.
|
||||
sni = hostname
|
||||
}
|
||||
tlsConf.ServerName = sni
|
||||
}
|
||||
// Replace existing ALPNs by H3
|
||||
tlsConf.NextProtos = []string{versionToALPN(conf.Versions[0])}
|
||||
|
||||
|
|
2
vendor/github.com/quic-go/quic-go/http3/mockgen.go
generated
vendored
2
vendor/github.com/quic-go/quic-go/http3/mockgen.go
generated
vendored
|
@ -4,5 +4,3 @@ package http3
|
|||
|
||||
//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package http3 -destination mock_roundtripcloser_test.go github.com/quic-go/quic-go/http3 RoundTripCloser"
|
||||
type RoundTripCloser = roundTripCloser
|
||||
|
||||
//go:generate sh -c "go run github.com/golang/mock/mockgen -package http3 -destination mock_quic_early_listener_test.go github.com/quic-go/quic-go/http3 QUICEarlyListener"
|
||||
|
|
11
vendor/github.com/quic-go/quic-go/http3/response_writer.go
generated
vendored
11
vendor/github.com/quic-go/quic-go/http3/response_writer.go
generated
vendored
|
@ -6,7 +6,6 @@ import (
|
|||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go"
|
||||
"github.com/quic-go/quic-go/internal/utils"
|
||||
|
@ -16,7 +15,6 @@ import (
|
|||
|
||||
type responseWriter struct {
|
||||
conn quic.Connection
|
||||
str quic.Stream
|
||||
bufferedStr *bufio.Writer
|
||||
buf []byte
|
||||
|
||||
|
@ -38,7 +36,6 @@ func newResponseWriter(str quic.Stream, conn quic.Connection, logger utils.Logge
|
|||
header: http.Header{},
|
||||
buf: make([]byte, 16),
|
||||
conn: conn,
|
||||
str: str,
|
||||
bufferedStr: bufio.NewWriter(str),
|
||||
logger: logger,
|
||||
}
|
||||
|
@ -124,14 +121,6 @@ func (w *responseWriter) StreamCreator() StreamCreator {
|
|||
return w.conn
|
||||
}
|
||||
|
||||
func (w *responseWriter) SetReadDeadline(deadline time.Time) error {
|
||||
return w.str.SetReadDeadline(deadline)
|
||||
}
|
||||
|
||||
func (w *responseWriter) SetWriteDeadline(deadline time.Time) error {
|
||||
return w.str.SetWriteDeadline(deadline)
|
||||
}
|
||||
|
||||
// copied from http2/http2.go
|
||||
// bodyAllowedForStatus reports whether a given response status code
|
||||
// permits a body. See RFC 2616, section 4.4.
|
||||
|
|
51
vendor/github.com/quic-go/quic-go/http3/roundtrip.go
generated
vendored
51
vendor/github.com/quic-go/quic-go/http3/roundtrip.go
generated
vendored
|
@ -10,24 +10,21 @@ import (
|
|||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"golang.org/x/net/http/httpguts"
|
||||
|
||||
"github.com/quic-go/quic-go"
|
||||
)
|
||||
|
||||
// declare this as a variable, such that we can it mock it in the tests
|
||||
var quicDialer = quic.DialEarlyContext
|
||||
|
||||
type roundTripCloser interface {
|
||||
RoundTripOpt(*http.Request, RoundTripOpt) (*http.Response, error)
|
||||
HandshakeComplete() bool
|
||||
io.Closer
|
||||
}
|
||||
|
||||
type roundTripCloserWithCount struct {
|
||||
roundTripCloser
|
||||
useCount atomic.Int64
|
||||
}
|
||||
|
||||
// RoundTripper implements the http.RoundTripper interface
|
||||
type RoundTripper struct {
|
||||
mutex sync.Mutex
|
||||
|
@ -85,8 +82,8 @@ type RoundTripper struct {
|
|||
MaxResponseHeaderBytes int64
|
||||
|
||||
newClient func(hostname string, tlsConf *tls.Config, opts *roundTripperOpts, conf *quic.Config, dialer dialFunc) (roundTripCloser, error) // so we can mock it in tests
|
||||
clients map[string]*roundTripCloserWithCount
|
||||
transport *quic.Transport
|
||||
clients map[string]roundTripCloser
|
||||
udpConn *net.UDPConn
|
||||
}
|
||||
|
||||
// RoundTripOpt are options for the Transport.RoundTripOpt method.
|
||||
|
@ -146,7 +143,6 @@ func (r *RoundTripper) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cl.useCount.Add(-1)
|
||||
rsp, err := cl.RoundTripOpt(req, opt)
|
||||
if err != nil {
|
||||
r.removeClient(hostname)
|
||||
|
@ -164,12 +160,12 @@ func (r *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
|||
return r.RoundTripOpt(req, RoundTripOpt{})
|
||||
}
|
||||
|
||||
func (r *RoundTripper) getClient(hostname string, onlyCached bool) (rtc *roundTripCloserWithCount, isReused bool, err error) {
|
||||
func (r *RoundTripper) getClient(hostname string, onlyCached bool) (rtc roundTripCloser, isReused bool, err error) {
|
||||
r.mutex.Lock()
|
||||
defer r.mutex.Unlock()
|
||||
|
||||
if r.clients == nil {
|
||||
r.clients = make(map[string]*roundTripCloserWithCount)
|
||||
r.clients = make(map[string]roundTripCloser)
|
||||
}
|
||||
|
||||
client, ok := r.clients[hostname]
|
||||
|
@ -184,16 +180,15 @@ func (r *RoundTripper) getClient(hostname string, onlyCached bool) (rtc *roundTr
|
|||
}
|
||||
dial := r.Dial
|
||||
if dial == nil {
|
||||
if r.transport == nil {
|
||||
udpConn, err := net.ListenUDP("udp", nil)
|
||||
if r.udpConn == nil {
|
||||
r.udpConn, err = net.ListenUDP("udp", nil)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
r.transport = &quic.Transport{Conn: udpConn}
|
||||
}
|
||||
dial = r.makeDialer()
|
||||
}
|
||||
c, err := newCl(
|
||||
client, err = newCl(
|
||||
hostname,
|
||||
r.TLSClientConfig,
|
||||
&roundTripperOpts{
|
||||
|
@ -209,12 +204,10 @@ func (r *RoundTripper) getClient(hostname string, onlyCached bool) (rtc *roundTr
|
|||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
client = &roundTripCloserWithCount{roundTripCloser: c}
|
||||
r.clients[hostname] = client
|
||||
} else if client.HandshakeComplete() {
|
||||
isReused = true
|
||||
}
|
||||
client.useCount.Add(1)
|
||||
return client, isReused, nil
|
||||
}
|
||||
|
||||
|
@ -238,14 +231,9 @@ func (r *RoundTripper) Close() error {
|
|||
}
|
||||
}
|
||||
r.clients = nil
|
||||
if r.transport != nil {
|
||||
if err := r.transport.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.transport.Conn.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.transport = nil
|
||||
if r.udpConn != nil {
|
||||
r.udpConn.Close()
|
||||
r.udpConn = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -285,17 +273,6 @@ func (r *RoundTripper) makeDialer() func(ctx context.Context, addr string, tlsCf
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.transport.DialEarly(ctx, udpAddr, tlsCfg, cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RoundTripper) CloseIdleConnections() {
|
||||
r.mutex.Lock()
|
||||
defer r.mutex.Unlock()
|
||||
for hostname, client := range r.clients {
|
||||
if client.useCount.Load() == 0 {
|
||||
client.Close()
|
||||
delete(r.clients, hostname)
|
||||
}
|
||||
return quicDialer(ctx, r.udpConn, udpAddr, addr, tlsCfg, cfg)
|
||||
}
|
||||
}
|
||||
|
|
76
vendor/github.com/quic-go/quic-go/http3/server.go
generated
vendored
76
vendor/github.com/quic-go/quic-go/http3/server.go
generated
vendored
|
@ -23,12 +23,8 @@ import (
|
|||
|
||||
// allows mocking of quic.Listen and quic.ListenAddr
|
||||
var (
|
||||
quicListen = func(conn net.PacketConn, tlsConf *tls.Config, config *quic.Config) (QUICEarlyListener, error) {
|
||||
return quic.ListenEarly(conn, tlsConf, config)
|
||||
}
|
||||
quicListenAddr = func(addr string, tlsConf *tls.Config, config *quic.Config) (QUICEarlyListener, error) {
|
||||
return quic.ListenAddrEarly(addr, tlsConf, config)
|
||||
}
|
||||
quicListen = quic.ListenEarly
|
||||
quicListenAddr = quic.ListenAddrEarly
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -48,15 +44,6 @@ const (
|
|||
streamTypeQPACKDecoderStream = 3
|
||||
)
|
||||
|
||||
// A QUICEarlyListener listens for incoming QUIC connections.
|
||||
type QUICEarlyListener interface {
|
||||
Accept(context.Context) (quic.EarlyConnection, error)
|
||||
Addr() net.Addr
|
||||
io.Closer
|
||||
}
|
||||
|
||||
var _ QUICEarlyListener = &quic.EarlyListener{}
|
||||
|
||||
func versionToALPN(v protocol.VersionNumber) string {
|
||||
//nolint:exhaustive // These are all the versions we care about.
|
||||
switch v {
|
||||
|
@ -206,7 +193,7 @@ type Server struct {
|
|||
UniStreamHijacker func(StreamType, quic.Connection, quic.ReceiveStream, error) (hijacked bool)
|
||||
|
||||
mutex sync.RWMutex
|
||||
listeners map[*QUICEarlyListener]listenerInfo
|
||||
listeners map[*quic.EarlyListener]listenerInfo
|
||||
|
||||
closed bool
|
||||
|
||||
|
@ -262,26 +249,13 @@ func (s *Server) ServeQUICConn(conn quic.Connection) error {
|
|||
// Make sure you use http3.ConfigureTLSConfig to configure a tls.Config
|
||||
// and use it to construct a http3-friendly QUIC listener.
|
||||
// Closing the server does close the listener.
|
||||
// ServeListener always returns a non-nil error. After Shutdown or Close, the returned error is http.ErrServerClosed.
|
||||
func (s *Server) ServeListener(ln QUICEarlyListener) error {
|
||||
func (s *Server) ServeListener(ln quic.EarlyListener) error {
|
||||
if err := s.addListener(&ln); err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.removeListener(&ln)
|
||||
for {
|
||||
conn, err := ln.Accept(context.Background())
|
||||
if err == quic.ErrServerClosed {
|
||||
return http.ErrServerClosed
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
go func() {
|
||||
if err := s.handleConn(conn); err != nil {
|
||||
s.logger.Debugf(err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
err := s.serveListener(ln)
|
||||
s.removeListener(&ln)
|
||||
return err
|
||||
}
|
||||
|
||||
var errServerWithoutTLSConfig = errors.New("use of http3.Server without TLSConfig")
|
||||
|
@ -301,7 +275,7 @@ func (s *Server) serveConn(tlsConf *tls.Config, conn net.PacketConn) error {
|
|||
baseConf := ConfigureTLSConfig(tlsConf)
|
||||
quicConf := s.QuicConfig
|
||||
if quicConf == nil {
|
||||
quicConf = &quic.Config{Allow0RTT: true}
|
||||
quicConf = &quic.Config{Allow0RTT: func(net.Addr) bool { return true }}
|
||||
} else {
|
||||
quicConf = s.QuicConfig.Clone()
|
||||
}
|
||||
|
@ -309,7 +283,7 @@ func (s *Server) serveConn(tlsConf *tls.Config, conn net.PacketConn) error {
|
|||
quicConf.EnableDatagrams = true
|
||||
}
|
||||
|
||||
var ln QUICEarlyListener
|
||||
var ln quic.EarlyListener
|
||||
var err error
|
||||
if conn == nil {
|
||||
addr := s.Addr
|
||||
|
@ -323,7 +297,26 @@ func (s *Server) serveConn(tlsConf *tls.Config, conn net.PacketConn) error {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.ServeListener(ln)
|
||||
if err := s.addListener(&ln); err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.serveListener(ln)
|
||||
s.removeListener(&ln)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) serveListener(ln quic.EarlyListener) error {
|
||||
for {
|
||||
conn, err := ln.Accept(context.Background())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
go func() {
|
||||
if err := s.handleConn(conn); err != nil {
|
||||
s.logger.Debugf(err.Error())
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func extractPort(addr string) (int, error) {
|
||||
|
@ -398,7 +391,7 @@ func (s *Server) generateAltSvcHeader() {
|
|||
// We store a pointer to interface in the map set. This is safe because we only
|
||||
// call trackListener via Serve and can track+defer untrack the same pointer to
|
||||
// local variable there. We never need to compare a Listener from another caller.
|
||||
func (s *Server) addListener(l *QUICEarlyListener) error {
|
||||
func (s *Server) addListener(l *quic.EarlyListener) error {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
|
@ -409,24 +402,25 @@ func (s *Server) addListener(l *QUICEarlyListener) error {
|
|||
s.logger = utils.DefaultLogger.WithPrefix("server")
|
||||
}
|
||||
if s.listeners == nil {
|
||||
s.listeners = make(map[*QUICEarlyListener]listenerInfo)
|
||||
s.listeners = make(map[*quic.EarlyListener]listenerInfo)
|
||||
}
|
||||
|
||||
if port, err := extractPort((*l).Addr().String()); err == nil {
|
||||
s.listeners[l] = listenerInfo{port}
|
||||
} else {
|
||||
s.logger.Errorf("Unable to extract port from listener %+v, will not be announced using SetQuicHeaders: %s", err)
|
||||
s.logger.Errorf(
|
||||
"Unable to extract port from listener %+v, will not be announced using SetQuicHeaders: %s", err)
|
||||
s.listeners[l] = listenerInfo{}
|
||||
}
|
||||
s.generateAltSvcHeader()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) removeListener(l *QUICEarlyListener) {
|
||||
func (s *Server) removeListener(l *quic.EarlyListener) {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
delete(s.listeners, l)
|
||||
s.generateAltSvcHeader()
|
||||
s.mutex.Unlock()
|
||||
}
|
||||
|
||||
func (s *Server) handleConn(conn quic.Connection) error {
|
||||
|
|
74
vendor/github.com/quic-go/quic-go/interface.go
generated
vendored
74
vendor/github.com/quic-go/quic-go/interface.go
generated
vendored
|
@ -198,7 +198,7 @@ type EarlyConnection interface {
|
|||
|
||||
// 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,
|
||||
// For the serfer, 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.
|
||||
HandshakeComplete() <-chan struct{}
|
||||
|
||||
|
@ -239,12 +239,21 @@ type ConnectionIDGenerator interface {
|
|||
|
||||
// Config contains all configuration data needed for a QUIC server or client.
|
||||
type Config struct {
|
||||
// GetConfigForClient is called for incoming connections.
|
||||
// If the error is not nil, the connection attempt is refused.
|
||||
GetConfigForClient func(info *ClientHelloInfo) (*Config, error)
|
||||
// The QUIC versions that can be negotiated.
|
||||
// If not set, it uses all versions available.
|
||||
Versions []VersionNumber
|
||||
// The length of the connection ID in bytes.
|
||||
// It can be 0, or any value between 4 and 18.
|
||||
// If not set, the interpretation depends on where the Config is used:
|
||||
// If used for dialing an address, a 0 byte connection ID will be used.
|
||||
// If used for a server, or dialing on a packet conn, a 4 byte connection ID will be used.
|
||||
// When dialing on a packet conn, the ConnectionIDLength value must be the same for every Dial call.
|
||||
ConnectionIDLength int
|
||||
// An optional ConnectionIDGenerator to be used for ConnectionIDs generated during the lifecycle of a QUIC connection.
|
||||
// The goal is to give some control on how connection IDs, which can be useful in some scenarios, in particular for servers.
|
||||
// By default, if not provided, random connection IDs with the length given by ConnectionIDLength is used.
|
||||
// Otherwise, if one is provided, then ConnectionIDLength is ignored.
|
||||
ConnectionIDGenerator ConnectionIDGenerator
|
||||
// HandshakeIdleTimeout is the idle timeout before completion of the handshake.
|
||||
// Specifically, if we don't receive any packet from the peer within this time, the connection attempt is aborted.
|
||||
// If this value is zero, the timeout is set to 5 seconds.
|
||||
|
@ -276,21 +285,17 @@ type Config struct {
|
|||
// 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.
|
||||
|
@ -300,49 +305,64 @@ type Config struct {
|
|||
// in this callback.
|
||||
AllowConnectionWindowIncrease func(conn Connection, delta uint64) bool
|
||||
// MaxIncomingStreams is the maximum number of concurrent bidirectional streams that a peer is allowed to open.
|
||||
// Values above 2^60 are invalid.
|
||||
// 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.
|
||||
// Values above 2^60 are invalid.
|
||||
// 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
|
||||
// The StatelessResetKey is used to generate stateless reset tokens.
|
||||
// If no key is configured, sending of stateless resets is disabled.
|
||||
StatelessResetKey *StatelessResetKey
|
||||
// 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
|
||||
// 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.
|
||||
// If unavailable or disabled, packets will be at most 1252 (IPv4) / 1232 (IPv6) bytes in size.
|
||||
// Packets will then be at most 1252 (IPv4) / 1232 (IPv6) bytes in size.
|
||||
// Note that if Path MTU discovery is causing issues on your system, please open a new issue
|
||||
DisablePathMTUDiscovery bool
|
||||
// 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 a client.
|
||||
DisableVersionNegotiationPackets bool
|
||||
// Allow0RTT allows the application to decide if a 0-RTT connection attempt should be accepted.
|
||||
// When set, 0-RTT is enabled. When not set, 0-RTT is disabled.
|
||||
// Only valid for the server.
|
||||
Allow0RTT bool
|
||||
// Warning: This API should not be considered stable and might change soon.
|
||||
Allow0RTT func(net.Addr) bool
|
||||
// Enable QUIC datagram support (RFC 9221).
|
||||
EnableDatagrams bool
|
||||
Tracer func(context.Context, logging.Perspective, ConnectionID) logging.ConnectionTracer
|
||||
}
|
||||
|
||||
type ClientHelloInfo struct {
|
||||
RemoteAddr net.Addr
|
||||
Tracer logging.Tracer
|
||||
}
|
||||
|
||||
// ConnectionState records basic details about a QUIC connection
|
||||
type ConnectionState struct {
|
||||
// TLS contains information about the TLS connection state, incl. the tls.ConnectionState.
|
||||
TLS handshake.ConnectionState
|
||||
// SupportsDatagrams says if support for QUIC datagrams (RFC 9221) was negotiated.
|
||||
// This requires both nodes to support and enable the datagram extensions (via Config.EnableDatagrams).
|
||||
// If datagram support was negotiated, datagrams can be sent and received using the
|
||||
// SendMessage and ReceiveMessage methods on the Connection.
|
||||
TLS handshake.ConnectionState
|
||||
SupportsDatagrams bool
|
||||
// Version is the QUIC version of the QUIC connection.
|
||||
Version VersionNumber
|
||||
Version VersionNumber
|
||||
}
|
||||
|
||||
// A Listener for incoming QUIC connections
|
||||
type Listener interface {
|
||||
// Close the server. All active connections will be closed.
|
||||
Close() error
|
||||
// Addr returns the local network addr that the server is listening on.
|
||||
Addr() net.Addr
|
||||
// Accept returns new connections. It should be called in a loop.
|
||||
Accept(context.Context) (Connection, error)
|
||||
}
|
||||
|
||||
// An EarlyListener listens for incoming QUIC connections,
|
||||
// and returns them before the handshake completes.
|
||||
type EarlyListener interface {
|
||||
// Close the server. All active connections will be closed.
|
||||
Close() error
|
||||
// Addr returns the local network addr that the server is listening on.
|
||||
Addr() net.Addr
|
||||
// Accept returns new early connections. It should be called in a loop.
|
||||
Accept(context.Context) (EarlyConnection, error)
|
||||
}
|
||||
|
|
2
vendor/github.com/quic-go/quic-go/internal/ackhandler/ack_eliciting.go
generated
vendored
2
vendor/github.com/quic-go/quic-go/internal/ackhandler/ack_eliciting.go
generated
vendored
|
@ -10,7 +10,7 @@ func IsFrameAckEliciting(f wire.Frame) bool {
|
|||
}
|
||||
|
||||
// HasAckElicitingFrames returns true if at least one frame is ack-eliciting.
|
||||
func HasAckElicitingFrames(fs []Frame) bool {
|
||||
func HasAckElicitingFrames(fs []*Frame) bool {
|
||||
for _, f := range fs {
|
||||
if IsFrameAckEliciting(f.Frame) {
|
||||
return true
|
||||
|
|
30
vendor/github.com/quic-go/quic-go/internal/ackhandler/frame.go
generated
vendored
30
vendor/github.com/quic-go/quic-go/internal/ackhandler/frame.go
generated
vendored
|
@ -1,21 +1,29 @@
|
|||
package ackhandler
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/wire"
|
||||
)
|
||||
|
||||
// FrameHandler handles the acknowledgement and the loss of a frame.
|
||||
type FrameHandler interface {
|
||||
OnAcked(wire.Frame)
|
||||
OnLost(wire.Frame)
|
||||
}
|
||||
|
||||
type Frame struct {
|
||||
Frame wire.Frame // nil if the frame has already been acknowledged in another packet
|
||||
Handler FrameHandler
|
||||
wire.Frame // nil if the frame has already been acknowledged in another packet
|
||||
OnLost func(wire.Frame)
|
||||
OnAcked func(wire.Frame)
|
||||
}
|
||||
|
||||
type StreamFrame struct {
|
||||
Frame *wire.StreamFrame
|
||||
Handler FrameHandler
|
||||
var framePool = sync.Pool{New: func() any { return &Frame{} }}
|
||||
|
||||
func GetFrame() *Frame {
|
||||
f := framePool.Get().(*Frame)
|
||||
f.OnLost = nil
|
||||
f.OnAcked = nil
|
||||
return f
|
||||
}
|
||||
|
||||
func putFrame(f *Frame) {
|
||||
f.Frame = nil
|
||||
f.OnLost = nil
|
||||
f.OnAcked = nil
|
||||
framePool.Put(f)
|
||||
}
|
||||
|
|
10
vendor/github.com/quic-go/quic-go/internal/ackhandler/interfaces.go
generated
vendored
10
vendor/github.com/quic-go/quic-go/internal/ackhandler/interfaces.go
generated
vendored
|
@ -10,20 +10,20 @@ import (
|
|||
// SentPacketHandler handles ACKs received for outgoing packets
|
||||
type SentPacketHandler interface {
|
||||
// SentPacket may modify the packet
|
||||
SentPacket(t time.Time, pn, largestAcked protocol.PacketNumber, streamFrames []StreamFrame, frames []Frame, encLevel protocol.EncryptionLevel, size protocol.ByteCount, isPathMTUProbePacket bool)
|
||||
// ReceivedAck processes an ACK frame.
|
||||
// It does not store a copy of the frame.
|
||||
ReceivedAck(f *wire.AckFrame, encLevel protocol.EncryptionLevel, recvTime time.Time) (bool /* 1-RTT packet acked */, error)
|
||||
SentPacket(packet *Packet)
|
||||
ReceivedAck(ackFrame *wire.AckFrame, encLevel protocol.EncryptionLevel, recvTime time.Time) (bool /* 1-RTT packet acked */, error)
|
||||
ReceivedBytes(protocol.ByteCount)
|
||||
DropPackets(protocol.EncryptionLevel)
|
||||
ResetForRetry() error
|
||||
SetHandshakeConfirmed()
|
||||
|
||||
// The SendMode determines if and what kind of packets can be sent.
|
||||
SendMode(now time.Time) SendMode
|
||||
SendMode() SendMode
|
||||
// TimeUntilSend is the time when the next packet should be sent.
|
||||
// It is used for pacing packets.
|
||||
TimeUntilSend() time.Time
|
||||
// HasPacingBudget says if the pacer allows sending of a (full size) packet at this moment.
|
||||
HasPacingBudget() bool
|
||||
SetMaxDatagramSize(count protocol.ByteCount)
|
||||
|
||||
// only to be called once the handshake is complete
|
||||
|
|
22
vendor/github.com/quic-go/quic-go/internal/ackhandler/packet.go
generated
vendored
22
vendor/github.com/quic-go/quic-go/internal/ackhandler/packet.go
generated
vendored
|
@ -8,14 +8,13 @@ import (
|
|||
)
|
||||
|
||||
// A Packet is a packet
|
||||
type packet struct {
|
||||
SendTime time.Time
|
||||
type Packet struct {
|
||||
PacketNumber protocol.PacketNumber
|
||||
StreamFrames []StreamFrame
|
||||
Frames []Frame
|
||||
Frames []*Frame
|
||||
LargestAcked protocol.PacketNumber // InvalidPacketNumber if the packet doesn't contain an ACK
|
||||
Length protocol.ByteCount
|
||||
EncryptionLevel protocol.EncryptionLevel
|
||||
SendTime time.Time
|
||||
|
||||
IsPathMTUProbePacket bool // We don't report the loss of Path MTU probe packets to the congestion controller.
|
||||
|
||||
|
@ -24,16 +23,15 @@ type packet struct {
|
|||
skippedPacket bool
|
||||
}
|
||||
|
||||
func (p *packet) outstanding() bool {
|
||||
func (p *Packet) outstanding() bool {
|
||||
return !p.declaredLost && !p.skippedPacket && !p.IsPathMTUProbePacket
|
||||
}
|
||||
|
||||
var packetPool = sync.Pool{New: func() any { return &packet{} }}
|
||||
var packetPool = sync.Pool{New: func() any { return &Packet{} }}
|
||||
|
||||
func getPacket() *packet {
|
||||
p := packetPool.Get().(*packet)
|
||||
func GetPacket() *Packet {
|
||||
p := packetPool.Get().(*Packet)
|
||||
p.PacketNumber = 0
|
||||
p.StreamFrames = nil
|
||||
p.Frames = nil
|
||||
p.LargestAcked = 0
|
||||
p.Length = 0
|
||||
|
@ -48,8 +46,10 @@ func getPacket() *packet {
|
|||
|
||||
// We currently only return Packets back into the pool when they're acknowledged (not when they're lost).
|
||||
// This simplifies the code, and gives the vast majority of the performance benefit we can gain from using the pool.
|
||||
func putPacket(p *packet) {
|
||||
func putPacket(p *Packet) {
|
||||
for _, f := range p.Frames {
|
||||
putFrame(f)
|
||||
}
|
||||
p.Frames = nil
|
||||
p.StreamFrames = nil
|
||||
packetPool.Put(p)
|
||||
}
|
||||
|
|
28
vendor/github.com/quic-go/quic-go/internal/ackhandler/packet_number_generator.go
generated
vendored
28
vendor/github.com/quic-go/quic-go/internal/ackhandler/packet_number_generator.go
generated
vendored
|
@ -7,10 +7,7 @@ import (
|
|||
|
||||
type packetNumberGenerator interface {
|
||||
Peek() protocol.PacketNumber
|
||||
// Pop pops the packet number.
|
||||
// It reports if the packet number (before the one just popped) was skipped.
|
||||
// It never skips more than one packet number in a row.
|
||||
Pop() (skipped bool, _ protocol.PacketNumber)
|
||||
Pop() protocol.PacketNumber
|
||||
}
|
||||
|
||||
type sequentialPacketNumberGenerator struct {
|
||||
|
@ -27,10 +24,10 @@ func (p *sequentialPacketNumberGenerator) Peek() protocol.PacketNumber {
|
|||
return p.next
|
||||
}
|
||||
|
||||
func (p *sequentialPacketNumberGenerator) Pop() (bool, protocol.PacketNumber) {
|
||||
func (p *sequentialPacketNumberGenerator) Pop() protocol.PacketNumber {
|
||||
next := p.next
|
||||
p.next++
|
||||
return false, next
|
||||
return next
|
||||
}
|
||||
|
||||
// The skippingPacketNumberGenerator generates the packet number for the next packet
|
||||
|
@ -59,26 +56,21 @@ func newSkippingPacketNumberGenerator(initial, initialPeriod, maxPeriod protocol
|
|||
}
|
||||
|
||||
func (p *skippingPacketNumberGenerator) Peek() protocol.PacketNumber {
|
||||
if p.next == p.nextToSkip {
|
||||
return p.next + 1
|
||||
}
|
||||
return p.next
|
||||
}
|
||||
|
||||
func (p *skippingPacketNumberGenerator) Pop() (bool, protocol.PacketNumber) {
|
||||
func (p *skippingPacketNumberGenerator) Pop() protocol.PacketNumber {
|
||||
next := p.next
|
||||
if p.next == p.nextToSkip {
|
||||
next++
|
||||
p.next += 2
|
||||
p.generateNewSkip()
|
||||
return true, next
|
||||
}
|
||||
p.next++ // generate a new packet number for the next packet
|
||||
return false, next
|
||||
if p.next == p.nextToSkip {
|
||||
p.next++
|
||||
p.generateNewSkip()
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func (p *skippingPacketNumberGenerator) generateNewSkip() {
|
||||
// make sure that there are never two consecutive packet numbers that are skipped
|
||||
p.nextToSkip = p.next + 3 + protocol.PacketNumber(p.rng.Int31n(int32(2*p.period)))
|
||||
p.nextToSkip = p.next + 2 + protocol.PacketNumber(p.rng.Int31n(int32(2*p.period)))
|
||||
p.period = utils.Min(2*p.period, p.maxPeriod)
|
||||
}
|
||||
|
|
10
vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_tracker.go
generated
vendored
10
vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_tracker.go
generated
vendored
|
@ -169,18 +169,16 @@ func (h *receivedPacketTracker) GetAckFrame(onlyIfQueued bool) *wire.AckFrame {
|
|||
}
|
||||
}
|
||||
|
||||
// This function always returns the same ACK frame struct, filled with the most recent values.
|
||||
ack := h.lastAck
|
||||
if ack == nil {
|
||||
ack = &wire.AckFrame{}
|
||||
}
|
||||
ack.Reset()
|
||||
ack := wire.GetAckFrame()
|
||||
ack.DelayTime = utils.Max(0, now.Sub(h.largestObservedReceivedTime))
|
||||
ack.ECT0 = h.ect0
|
||||
ack.ECT1 = h.ect1
|
||||
ack.ECNCE = h.ecnce
|
||||
ack.AckRanges = h.packetHistory.AppendAckRanges(ack.AckRanges)
|
||||
|
||||
if h.lastAck != nil {
|
||||
wire.PutAckFrame(h.lastAck)
|
||||
}
|
||||
h.lastAck = ack
|
||||
h.ackAlarm = time.Time{}
|
||||
h.ackQueued = false
|
||||
|
|
6
vendor/github.com/quic-go/quic-go/internal/ackhandler/send_mode.go
generated
vendored
6
vendor/github.com/quic-go/quic-go/internal/ackhandler/send_mode.go
generated
vendored
|
@ -16,10 +16,6 @@ const (
|
|||
SendPTOHandshake
|
||||
// SendPTOAppData means that an Application data probe packet should be sent
|
||||
SendPTOAppData
|
||||
// SendPacingLimited means that the pacer doesn't allow sending of a packet right now,
|
||||
// but will do in a little while.
|
||||
// The timestamp when sending is allowed again can be obtained via the SentPacketHandler.TimeUntilSend.
|
||||
SendPacingLimited
|
||||
// SendAny means that any packet should be sent
|
||||
SendAny
|
||||
)
|
||||
|
@ -38,8 +34,6 @@ func (s SendMode) String() string {
|
|||
return "pto (Application Data)"
|
||||
case SendAny:
|
||||
return "any"
|
||||
case SendPacingLimited:
|
||||
return "pacing limited"
|
||||
default:
|
||||
return fmt.Sprintf("invalid send mode: %d", s)
|
||||
}
|
||||
|
|
224
vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_handler.go
generated
vendored
224
vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_handler.go
generated
vendored
|
@ -38,7 +38,7 @@ type packetNumberSpace struct {
|
|||
largestSent protocol.PacketNumber
|
||||
}
|
||||
|
||||
func newPacketNumberSpace(initialPN protocol.PacketNumber, skipPNs bool) *packetNumberSpace {
|
||||
func newPacketNumberSpace(initialPN protocol.PacketNumber, skipPNs bool, rttStats *utils.RTTStats) *packetNumberSpace {
|
||||
var pns packetNumberGenerator
|
||||
if skipPNs {
|
||||
pns = newSkippingPacketNumberGenerator(initialPN, protocol.SkipPacketInitialPeriod, protocol.SkipPacketMaxPeriod)
|
||||
|
@ -46,7 +46,7 @@ func newPacketNumberSpace(initialPN protocol.PacketNumber, skipPNs bool) *packet
|
|||
pns = newSequentialPacketNumberGenerator(initialPN)
|
||||
}
|
||||
return &packetNumberSpace{
|
||||
history: newSentPacketHistory(),
|
||||
history: newSentPacketHistory(rttStats),
|
||||
pns: pns,
|
||||
largestSent: protocol.InvalidPacketNumber,
|
||||
largestAcked: protocol.InvalidPacketNumber,
|
||||
|
@ -75,7 +75,7 @@ type sentPacketHandler struct {
|
|||
// Only applies to the application-data packet number space.
|
||||
lowestNotConfirmedAcked protocol.PacketNumber
|
||||
|
||||
ackedPackets []*packet // to avoid allocations in detectAndRemoveAckedPackets
|
||||
ackedPackets []*Packet // to avoid allocations in detectAndRemoveAckedPackets
|
||||
|
||||
bytesInFlight protocol.ByteCount
|
||||
|
||||
|
@ -125,9 +125,9 @@ func newSentPacketHandler(
|
|||
return &sentPacketHandler{
|
||||
peerCompletedAddressValidation: pers == protocol.PerspectiveServer,
|
||||
peerAddressValidated: pers == protocol.PerspectiveClient || clientAddressValidated,
|
||||
initialPackets: newPacketNumberSpace(initialPN, false),
|
||||
handshakePackets: newPacketNumberSpace(0, false),
|
||||
appDataPackets: newPacketNumberSpace(0, true),
|
||||
initialPackets: newPacketNumberSpace(initialPN, false, rttStats),
|
||||
handshakePackets: newPacketNumberSpace(0, false, rttStats),
|
||||
appDataPackets: newPacketNumberSpace(0, true, rttStats),
|
||||
rttStats: rttStats,
|
||||
congestion: congestion,
|
||||
perspective: pers,
|
||||
|
@ -146,7 +146,7 @@ func (h *sentPacketHandler) DropPackets(encLevel protocol.EncryptionLevel) {
|
|||
h.dropPackets(encLevel)
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) removeFromBytesInFlight(p *packet) {
|
||||
func (h *sentPacketHandler) removeFromBytesInFlight(p *Packet) {
|
||||
if p.includedInBytesInFlight {
|
||||
if p.Length > h.bytesInFlight {
|
||||
panic("negative bytes_in_flight")
|
||||
|
@ -165,7 +165,7 @@ func (h *sentPacketHandler) dropPackets(encLevel protocol.EncryptionLevel) {
|
|||
// remove outstanding packets from bytes_in_flight
|
||||
if encLevel == protocol.EncryptionInitial || encLevel == protocol.EncryptionHandshake {
|
||||
pnSpace := h.getPacketNumberSpace(encLevel)
|
||||
pnSpace.history.Iterate(func(p *packet) (bool, error) {
|
||||
pnSpace.history.Iterate(func(p *Packet) (bool, error) {
|
||||
h.removeFromBytesInFlight(p)
|
||||
return true, nil
|
||||
})
|
||||
|
@ -182,8 +182,8 @@ func (h *sentPacketHandler) dropPackets(encLevel protocol.EncryptionLevel) {
|
|||
// and not when the client drops 0-RTT keys when the handshake completes.
|
||||
// When 0-RTT is rejected, all application data sent so far becomes invalid.
|
||||
// Delete the packets from the history and remove them from bytes_in_flight.
|
||||
h.appDataPackets.history.Iterate(func(p *packet) (bool, error) {
|
||||
if p.EncryptionLevel != protocol.Encryption0RTT && !p.skippedPacket {
|
||||
h.appDataPackets.history.Iterate(func(p *Packet) (bool, error) {
|
||||
if p.EncryptionLevel != protocol.Encryption0RTT {
|
||||
return false, nil
|
||||
}
|
||||
h.removeFromBytesInFlight(p)
|
||||
|
@ -228,64 +228,26 @@ func (h *sentPacketHandler) packetsInFlight() int {
|
|||
return packetsInFlight
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) SentPacket(
|
||||
t time.Time,
|
||||
pn, largestAcked protocol.PacketNumber,
|
||||
streamFrames []StreamFrame,
|
||||
frames []Frame,
|
||||
encLevel protocol.EncryptionLevel,
|
||||
size protocol.ByteCount,
|
||||
isPathMTUProbePacket bool,
|
||||
) {
|
||||
h.bytesSent += size
|
||||
func (h *sentPacketHandler) SentPacket(p *Packet) {
|
||||
h.bytesSent += p.Length
|
||||
// For the client, drop the Initial packet number space when the first Handshake packet is sent.
|
||||
if h.perspective == protocol.PerspectiveClient && encLevel == protocol.EncryptionHandshake && h.initialPackets != nil {
|
||||
if h.perspective == protocol.PerspectiveClient && p.EncryptionLevel == protocol.EncryptionHandshake && h.initialPackets != nil {
|
||||
h.dropPackets(protocol.EncryptionInitial)
|
||||
}
|
||||
|
||||
pnSpace := h.getPacketNumberSpace(encLevel)
|
||||
if h.logger.Debug() && pnSpace.history.HasOutstandingPackets() {
|
||||
for p := utils.Max(0, pnSpace.largestSent+1); p < pn; p++ {
|
||||
h.logger.Debugf("Skipping packet number %d", p)
|
||||
}
|
||||
}
|
||||
|
||||
pnSpace.largestSent = pn
|
||||
isAckEliciting := len(streamFrames) > 0 || len(frames) > 0
|
||||
|
||||
isAckEliciting := h.sentPacketImpl(p)
|
||||
if isAckEliciting {
|
||||
pnSpace.lastAckElicitingPacketTime = t
|
||||
h.bytesInFlight += size
|
||||
if h.numProbesToSend > 0 {
|
||||
h.numProbesToSend--
|
||||
}
|
||||
h.getPacketNumberSpace(p.EncryptionLevel).history.SentAckElicitingPacket(p)
|
||||
} else {
|
||||
h.getPacketNumberSpace(p.EncryptionLevel).history.SentNonAckElicitingPacket(p.PacketNumber, p.EncryptionLevel, p.SendTime)
|
||||
putPacket(p)
|
||||
p = nil //nolint:ineffassign // This is just to be on the safe side.
|
||||
}
|
||||
h.congestion.OnPacketSent(t, h.bytesInFlight, pn, size, isAckEliciting)
|
||||
|
||||
if !isAckEliciting {
|
||||
pnSpace.history.SentNonAckElicitingPacket(pn)
|
||||
if !h.peerCompletedAddressValidation {
|
||||
h.setLossDetectionTimer()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
p := getPacket()
|
||||
p.SendTime = t
|
||||
p.PacketNumber = pn
|
||||
p.EncryptionLevel = encLevel
|
||||
p.Length = size
|
||||
p.LargestAcked = largestAcked
|
||||
p.StreamFrames = streamFrames
|
||||
p.Frames = frames
|
||||
p.IsPathMTUProbePacket = isPathMTUProbePacket
|
||||
p.includedInBytesInFlight = true
|
||||
|
||||
pnSpace.history.SentAckElicitingPacket(p)
|
||||
if h.tracer != nil {
|
||||
if h.tracer != nil && isAckEliciting {
|
||||
h.tracer.UpdatedMetrics(h.rttStats, h.congestion.GetCongestionWindow(), h.bytesInFlight, h.packetsInFlight())
|
||||
}
|
||||
h.setLossDetectionTimer()
|
||||
if isAckEliciting || !h.peerCompletedAddressValidation {
|
||||
h.setLossDetectionTimer()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) getPacketNumberSpace(encLevel protocol.EncryptionLevel) *packetNumberSpace {
|
||||
|
@ -301,6 +263,31 @@ func (h *sentPacketHandler) getPacketNumberSpace(encLevel protocol.EncryptionLev
|
|||
}
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) sentPacketImpl(packet *Packet) bool /* is ack-eliciting */ {
|
||||
pnSpace := h.getPacketNumberSpace(packet.EncryptionLevel)
|
||||
|
||||
if h.logger.Debug() && pnSpace.history.HasOutstandingPackets() {
|
||||
for p := utils.Max(0, pnSpace.largestSent+1); p < packet.PacketNumber; p++ {
|
||||
h.logger.Debugf("Skipping packet number %d", p)
|
||||
}
|
||||
}
|
||||
|
||||
pnSpace.largestSent = packet.PacketNumber
|
||||
isAckEliciting := len(packet.Frames) > 0
|
||||
|
||||
if isAckEliciting {
|
||||
pnSpace.lastAckElicitingPacketTime = packet.SendTime
|
||||
packet.includedInBytesInFlight = true
|
||||
h.bytesInFlight += packet.Length
|
||||
if h.numProbesToSend > 0 {
|
||||
h.numProbesToSend--
|
||||
}
|
||||
}
|
||||
h.congestion.OnPacketSent(packet.SendTime, h.bytesInFlight, packet.PacketNumber, packet.Length, isAckEliciting)
|
||||
|
||||
return isAckEliciting
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) ReceivedAck(ack *wire.AckFrame, encLevel protocol.EncryptionLevel, rcvTime time.Time) (bool /* contained 1-RTT packet */, error) {
|
||||
pnSpace := h.getPacketNumberSpace(encLevel)
|
||||
|
||||
|
@ -374,6 +361,7 @@ func (h *sentPacketHandler) ReceivedAck(ack *wire.AckFrame, encLevel protocol.En
|
|||
h.tracer.UpdatedMetrics(h.rttStats, h.congestion.GetCongestionWindow(), h.bytesInFlight, h.packetsInFlight())
|
||||
}
|
||||
|
||||
pnSpace.history.DeleteOldPackets(rcvTime)
|
||||
h.setLossDetectionTimer()
|
||||
return acked1RTTPacket, nil
|
||||
}
|
||||
|
@ -383,13 +371,13 @@ func (h *sentPacketHandler) GetLowestPacketNotConfirmedAcked() protocol.PacketNu
|
|||
}
|
||||
|
||||
// Packets are returned in ascending packet number order.
|
||||
func (h *sentPacketHandler) detectAndRemoveAckedPackets(ack *wire.AckFrame, encLevel protocol.EncryptionLevel) ([]*packet, error) {
|
||||
func (h *sentPacketHandler) detectAndRemoveAckedPackets(ack *wire.AckFrame, encLevel protocol.EncryptionLevel) ([]*Packet, error) {
|
||||
pnSpace := h.getPacketNumberSpace(encLevel)
|
||||
h.ackedPackets = h.ackedPackets[:0]
|
||||
ackRangeIndex := 0
|
||||
lowestAcked := ack.LowestAcked()
|
||||
largestAcked := ack.LargestAcked()
|
||||
err := pnSpace.history.Iterate(func(p *packet) (bool, error) {
|
||||
err := pnSpace.history.Iterate(func(p *Packet) (bool, error) {
|
||||
// Ignore packets below the lowest acked
|
||||
if p.PacketNumber < lowestAcked {
|
||||
return true, nil
|
||||
|
@ -437,13 +425,8 @@ func (h *sentPacketHandler) detectAndRemoveAckedPackets(ack *wire.AckFrame, encL
|
|||
}
|
||||
|
||||
for _, f := range p.Frames {
|
||||
if f.Handler != nil {
|
||||
f.Handler.OnAcked(f.Frame)
|
||||
}
|
||||
}
|
||||
for _, f := range p.StreamFrames {
|
||||
if f.Handler != nil {
|
||||
f.Handler.OnAcked(f.Frame)
|
||||
if f.OnAcked != nil {
|
||||
f.OnAcked(f.Frame)
|
||||
}
|
||||
}
|
||||
if err := pnSpace.history.Remove(p.PacketNumber); err != nil {
|
||||
|
@ -604,31 +587,30 @@ func (h *sentPacketHandler) detectLostPackets(now time.Time, encLevel protocol.E
|
|||
lostSendTime := now.Add(-lossDelay)
|
||||
|
||||
priorInFlight := h.bytesInFlight
|
||||
return pnSpace.history.Iterate(func(p *packet) (bool, error) {
|
||||
return pnSpace.history.Iterate(func(p *Packet) (bool, error) {
|
||||
if p.PacketNumber > pnSpace.largestAcked {
|
||||
return false, nil
|
||||
}
|
||||
if p.declaredLost || p.skippedPacket {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
var packetLost bool
|
||||
if p.SendTime.Before(lostSendTime) {
|
||||
packetLost = true
|
||||
if !p.skippedPacket {
|
||||
if h.logger.Debug() {
|
||||
h.logger.Debugf("\tlost packet %d (time threshold)", p.PacketNumber)
|
||||
}
|
||||
if h.tracer != nil {
|
||||
h.tracer.LostPacket(p.EncryptionLevel, p.PacketNumber, logging.PacketLossTimeThreshold)
|
||||
}
|
||||
if h.logger.Debug() {
|
||||
h.logger.Debugf("\tlost packet %d (time threshold)", p.PacketNumber)
|
||||
}
|
||||
if h.tracer != nil {
|
||||
h.tracer.LostPacket(p.EncryptionLevel, p.PacketNumber, logging.PacketLossTimeThreshold)
|
||||
}
|
||||
} else if pnSpace.largestAcked >= p.PacketNumber+packetThreshold {
|
||||
packetLost = true
|
||||
if !p.skippedPacket {
|
||||
if h.logger.Debug() {
|
||||
h.logger.Debugf("\tlost packet %d (reordering threshold)", p.PacketNumber)
|
||||
}
|
||||
if h.tracer != nil {
|
||||
h.tracer.LostPacket(p.EncryptionLevel, p.PacketNumber, logging.PacketLossReorderingThreshold)
|
||||
}
|
||||
if h.logger.Debug() {
|
||||
h.logger.Debugf("\tlost packet %d (reordering threshold)", p.PacketNumber)
|
||||
}
|
||||
if h.tracer != nil {
|
||||
h.tracer.LostPacket(p.EncryptionLevel, p.PacketNumber, logging.PacketLossReorderingThreshold)
|
||||
}
|
||||
} else if pnSpace.lossTime.IsZero() {
|
||||
// Note: This conditional is only entered once per call
|
||||
|
@ -639,14 +621,12 @@ func (h *sentPacketHandler) detectLostPackets(now time.Time, encLevel protocol.E
|
|||
pnSpace.lossTime = lossTime
|
||||
}
|
||||
if packetLost {
|
||||
pnSpace.history.DeclareLost(p.PacketNumber)
|
||||
if !p.skippedPacket {
|
||||
// the bytes in flight need to be reduced no matter if the frames in this packet will be retransmitted
|
||||
h.removeFromBytesInFlight(p)
|
||||
h.queueFramesForRetransmission(p)
|
||||
if !p.IsPathMTUProbePacket {
|
||||
h.congestion.OnPacketLost(p.PacketNumber, p.Length, priorInFlight)
|
||||
}
|
||||
p = pnSpace.history.DeclareLost(p)
|
||||
// the bytes in flight need to be reduced no matter if the frames in this packet will be retransmitted
|
||||
h.removeFromBytesInFlight(p)
|
||||
h.queueFramesForRetransmission(p)
|
||||
if !p.IsPathMTUProbePacket {
|
||||
h.congestion.OnPacketLost(p.PacketNumber, p.Length, priorInFlight)
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
|
@ -709,8 +689,7 @@ func (h *sentPacketHandler) OnLossDetectionTimeout() error {
|
|||
h.ptoMode = SendPTOHandshake
|
||||
case protocol.Encryption1RTT:
|
||||
// skip a packet number in order to elicit an immediate ACK
|
||||
pn := h.PopPacketNumber(protocol.Encryption1RTT)
|
||||
h.getPacketNumberSpace(protocol.Encryption1RTT).history.SkippedPacket(pn)
|
||||
_ = h.PopPacketNumber(protocol.Encryption1RTT)
|
||||
h.ptoMode = SendPTOAppData
|
||||
default:
|
||||
return fmt.Errorf("PTO timer in unexpected encryption level: %s", encLevel)
|
||||
|
@ -724,25 +703,23 @@ func (h *sentPacketHandler) GetLossDetectionTimeout() time.Time {
|
|||
|
||||
func (h *sentPacketHandler) PeekPacketNumber(encLevel protocol.EncryptionLevel) (protocol.PacketNumber, protocol.PacketNumberLen) {
|
||||
pnSpace := h.getPacketNumberSpace(encLevel)
|
||||
|
||||
var lowestUnacked protocol.PacketNumber
|
||||
if p := pnSpace.history.FirstOutstanding(); p != nil {
|
||||
lowestUnacked = p.PacketNumber
|
||||
} else {
|
||||
lowestUnacked = pnSpace.largestAcked + 1
|
||||
}
|
||||
|
||||
pn := pnSpace.pns.Peek()
|
||||
// See section 17.1 of RFC 9000.
|
||||
return pn, protocol.GetPacketNumberLengthForHeader(pn, pnSpace.largestAcked)
|
||||
return pn, protocol.GetPacketNumberLengthForHeader(pn, lowestUnacked)
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) PopPacketNumber(encLevel protocol.EncryptionLevel) protocol.PacketNumber {
|
||||
pnSpace := h.getPacketNumberSpace(encLevel)
|
||||
skipped, pn := pnSpace.pns.Pop()
|
||||
if skipped {
|
||||
skippedPN := pn - 1
|
||||
pnSpace.history.SkippedPacket(skippedPN)
|
||||
if h.logger.Debug() {
|
||||
h.logger.Debugf("Skipping packet number %d", skippedPN)
|
||||
}
|
||||
}
|
||||
return pn
|
||||
return h.getPacketNumberSpace(encLevel).pns.Pop()
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) SendMode(now time.Time) SendMode {
|
||||
func (h *sentPacketHandler) SendMode() SendMode {
|
||||
numTrackedPackets := h.appDataPackets.history.Len()
|
||||
if h.initialPackets != nil {
|
||||
numTrackedPackets += h.initialPackets.history.Len()
|
||||
|
@ -781,9 +758,6 @@ func (h *sentPacketHandler) SendMode(now time.Time) SendMode {
|
|||
}
|
||||
return SendAck
|
||||
}
|
||||
if !h.congestion.HasPacingBudget(now) {
|
||||
return SendPacingLimited
|
||||
}
|
||||
return SendAny
|
||||
}
|
||||
|
||||
|
@ -791,6 +765,10 @@ func (h *sentPacketHandler) TimeUntilSend() time.Time {
|
|||
return h.congestion.TimeUntilSend(h.bytesInFlight)
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) HasPacingBudget() bool {
|
||||
return h.congestion.HasPacingBudget()
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) SetMaxDatagramSize(s protocol.ByteCount) {
|
||||
h.congestion.SetMaxDatagramSize(s)
|
||||
}
|
||||
|
@ -812,32 +790,24 @@ func (h *sentPacketHandler) QueueProbePacket(encLevel protocol.EncryptionLevel)
|
|||
// TODO: don't declare the packet lost here.
|
||||
// Keep track of acknowledged frames instead.
|
||||
h.removeFromBytesInFlight(p)
|
||||
pnSpace.history.DeclareLost(p.PacketNumber)
|
||||
pnSpace.history.DeclareLost(p)
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) queueFramesForRetransmission(p *packet) {
|
||||
if len(p.Frames) == 0 && len(p.StreamFrames) == 0 {
|
||||
func (h *sentPacketHandler) queueFramesForRetransmission(p *Packet) {
|
||||
if len(p.Frames) == 0 {
|
||||
panic("no frames")
|
||||
}
|
||||
for _, f := range p.Frames {
|
||||
if f.Handler != nil {
|
||||
f.Handler.OnLost(f.Frame)
|
||||
}
|
||||
f.OnLost(f.Frame)
|
||||
}
|
||||
for _, f := range p.StreamFrames {
|
||||
if f.Handler != nil {
|
||||
f.Handler.OnLost(f.Frame)
|
||||
}
|
||||
}
|
||||
p.StreamFrames = nil
|
||||
p.Frames = nil
|
||||
}
|
||||
|
||||
func (h *sentPacketHandler) ResetForRetry() error {
|
||||
h.bytesInFlight = 0
|
||||
var firstPacketSendTime time.Time
|
||||
h.initialPackets.history.Iterate(func(p *packet) (bool, error) {
|
||||
h.initialPackets.history.Iterate(func(p *Packet) (bool, error) {
|
||||
if firstPacketSendTime.IsZero() {
|
||||
firstPacketSendTime = p.SendTime
|
||||
}
|
||||
|
@ -849,7 +819,7 @@ func (h *sentPacketHandler) ResetForRetry() error {
|
|||
})
|
||||
// All application data packets sent at this point are 0-RTT packets.
|
||||
// In the case of a Retry, we can assume that the server dropped all of them.
|
||||
h.appDataPackets.history.Iterate(func(p *packet) (bool, error) {
|
||||
h.appDataPackets.history.Iterate(func(p *Packet) (bool, error) {
|
||||
if !p.declaredLost && !p.skippedPacket {
|
||||
h.queueFramesForRetransmission(p)
|
||||
}
|
||||
|
@ -869,8 +839,8 @@ func (h *sentPacketHandler) ResetForRetry() error {
|
|||
h.tracer.UpdatedMetrics(h.rttStats, h.congestion.GetCongestionWindow(), h.bytesInFlight, h.packetsInFlight())
|
||||
}
|
||||
}
|
||||
h.initialPackets = newPacketNumberSpace(h.initialPackets.pns.Peek(), false)
|
||||
h.appDataPackets = newPacketNumberSpace(h.appDataPackets.pns.Peek(), true)
|
||||
h.initialPackets = newPacketNumberSpace(h.initialPackets.pns.Pop(), false, h.rttStats)
|
||||
h.appDataPackets = newPacketNumberSpace(h.appDataPackets.pns.Pop(), true, h.rttStats)
|
||||
oldAlarm := h.alarm
|
||||
h.alarm = time.Time{}
|
||||
if h.tracer != nil {
|
||||
|
|
226
vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_history.go
generated
vendored
226
vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_history.go
generated
vendored
|
@ -2,176 +2,162 @@ package ackhandler
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
"github.com/quic-go/quic-go/internal/utils"
|
||||
list "github.com/quic-go/quic-go/internal/utils/linkedlist"
|
||||
)
|
||||
|
||||
type sentPacketHistory struct {
|
||||
packets []*packet
|
||||
|
||||
numOutstanding int
|
||||
|
||||
highestPacketNumber protocol.PacketNumber
|
||||
rttStats *utils.RTTStats
|
||||
outstandingPacketList *list.List[*Packet]
|
||||
etcPacketList *list.List[*Packet]
|
||||
packetMap map[protocol.PacketNumber]*list.Element[*Packet]
|
||||
highestSent protocol.PacketNumber
|
||||
}
|
||||
|
||||
func newSentPacketHistory() *sentPacketHistory {
|
||||
var packetElementPool sync.Pool
|
||||
|
||||
func init() {
|
||||
packetElementPool = *list.NewPool[*Packet]()
|
||||
}
|
||||
|
||||
func newSentPacketHistory(rttStats *utils.RTTStats) *sentPacketHistory {
|
||||
return &sentPacketHistory{
|
||||
packets: make([]*packet, 0, 32),
|
||||
highestPacketNumber: protocol.InvalidPacketNumber,
|
||||
rttStats: rttStats,
|
||||
outstandingPacketList: list.NewWithPool[*Packet](&packetElementPool),
|
||||
etcPacketList: list.NewWithPool[*Packet](&packetElementPool),
|
||||
packetMap: make(map[protocol.PacketNumber]*list.Element[*Packet]),
|
||||
highestSent: protocol.InvalidPacketNumber,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *sentPacketHistory) checkSequentialPacketNumberUse(pn protocol.PacketNumber) {
|
||||
if h.highestPacketNumber != protocol.InvalidPacketNumber {
|
||||
if pn != h.highestPacketNumber+1 {
|
||||
panic("non-sequential packet number use")
|
||||
}
|
||||
}
|
||||
func (h *sentPacketHistory) SentNonAckElicitingPacket(pn protocol.PacketNumber, encLevel protocol.EncryptionLevel, t time.Time) {
|
||||
h.registerSentPacket(pn, encLevel, t)
|
||||
}
|
||||
|
||||
func (h *sentPacketHistory) SkippedPacket(pn protocol.PacketNumber) {
|
||||
h.checkSequentialPacketNumberUse(pn)
|
||||
h.highestPacketNumber = pn
|
||||
h.packets = append(h.packets, &packet{
|
||||
PacketNumber: pn,
|
||||
skippedPacket: true,
|
||||
})
|
||||
}
|
||||
func (h *sentPacketHistory) SentAckElicitingPacket(p *Packet) {
|
||||
h.registerSentPacket(p.PacketNumber, p.EncryptionLevel, p.SendTime)
|
||||
|
||||
func (h *sentPacketHistory) SentNonAckElicitingPacket(pn protocol.PacketNumber) {
|
||||
h.checkSequentialPacketNumberUse(pn)
|
||||
h.highestPacketNumber = pn
|
||||
if len(h.packets) > 0 {
|
||||
h.packets = append(h.packets, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *sentPacketHistory) SentAckElicitingPacket(p *packet) {
|
||||
h.checkSequentialPacketNumberUse(p.PacketNumber)
|
||||
h.highestPacketNumber = p.PacketNumber
|
||||
h.packets = append(h.packets, p)
|
||||
var el *list.Element[*Packet]
|
||||
if p.outstanding() {
|
||||
h.numOutstanding++
|
||||
el = h.outstandingPacketList.PushBack(p)
|
||||
} else {
|
||||
el = h.etcPacketList.PushBack(p)
|
||||
}
|
||||
h.packetMap[p.PacketNumber] = el
|
||||
}
|
||||
|
||||
func (h *sentPacketHistory) registerSentPacket(pn protocol.PacketNumber, encLevel protocol.EncryptionLevel, t time.Time) {
|
||||
if pn <= h.highestSent {
|
||||
panic("non-sequential packet number use")
|
||||
}
|
||||
// Skipped packet numbers.
|
||||
for p := h.highestSent + 1; p < pn; p++ {
|
||||
el := h.etcPacketList.PushBack(&Packet{
|
||||
PacketNumber: p,
|
||||
EncryptionLevel: encLevel,
|
||||
SendTime: t,
|
||||
skippedPacket: true,
|
||||
})
|
||||
h.packetMap[p] = el
|
||||
}
|
||||
h.highestSent = pn
|
||||
}
|
||||
|
||||
// Iterate iterates through all packets.
|
||||
func (h *sentPacketHistory) Iterate(cb func(*packet) (cont bool, err error)) error {
|
||||
for _, p := range h.packets {
|
||||
if p == nil {
|
||||
continue
|
||||
func (h *sentPacketHistory) Iterate(cb func(*Packet) (cont bool, err error)) error {
|
||||
cont := true
|
||||
outstandingEl := h.outstandingPacketList.Front()
|
||||
etcEl := h.etcPacketList.Front()
|
||||
var el *list.Element[*Packet]
|
||||
// whichever has the next packet number is returned first
|
||||
for cont {
|
||||
if outstandingEl == nil || (etcEl != nil && etcEl.Value.PacketNumber < outstandingEl.Value.PacketNumber) {
|
||||
el = etcEl
|
||||
} else {
|
||||
el = outstandingEl
|
||||
}
|
||||
cont, err := cb(p)
|
||||
if el == nil {
|
||||
return nil
|
||||
}
|
||||
if el == outstandingEl {
|
||||
outstandingEl = outstandingEl.Next()
|
||||
} else {
|
||||
etcEl = etcEl.Next()
|
||||
}
|
||||
var err error
|
||||
cont, err = cb(el.Value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !cont {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FirstOutstanding returns the first outstanding packet.
|
||||
func (h *sentPacketHistory) FirstOutstanding() *packet {
|
||||
if !h.HasOutstandingPackets() {
|
||||
func (h *sentPacketHistory) FirstOutstanding() *Packet {
|
||||
el := h.outstandingPacketList.Front()
|
||||
if el == nil {
|
||||
return nil
|
||||
}
|
||||
for _, p := range h.packets {
|
||||
if p != nil && p.outstanding() {
|
||||
return p
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return el.Value
|
||||
}
|
||||
|
||||
func (h *sentPacketHistory) Len() int {
|
||||
return len(h.packets)
|
||||
return len(h.packetMap)
|
||||
}
|
||||
|
||||
func (h *sentPacketHistory) Remove(pn protocol.PacketNumber) error {
|
||||
idx, ok := h.getIndex(pn)
|
||||
func (h *sentPacketHistory) Remove(p protocol.PacketNumber) error {
|
||||
el, ok := h.packetMap[p]
|
||||
if !ok {
|
||||
return fmt.Errorf("packet %d not found in sent packet history", pn)
|
||||
}
|
||||
p := h.packets[idx]
|
||||
if p.outstanding() {
|
||||
h.numOutstanding--
|
||||
if h.numOutstanding < 0 {
|
||||
panic("negative number of outstanding packets")
|
||||
}
|
||||
}
|
||||
h.packets[idx] = nil
|
||||
// clean up all skipped packets directly before this packet number
|
||||
for idx > 0 {
|
||||
idx--
|
||||
p := h.packets[idx]
|
||||
if p == nil || !p.skippedPacket {
|
||||
break
|
||||
}
|
||||
h.packets[idx] = nil
|
||||
}
|
||||
if idx == 0 {
|
||||
h.cleanupStart()
|
||||
}
|
||||
if len(h.packets) > 0 && h.packets[0] == nil {
|
||||
panic("remove failed")
|
||||
return fmt.Errorf("packet %d not found in sent packet history", p)
|
||||
}
|
||||
el.List().Remove(el)
|
||||
delete(h.packetMap, p)
|
||||
return nil
|
||||
}
|
||||
|
||||
// getIndex gets the index of packet p in the packets slice.
|
||||
func (h *sentPacketHistory) getIndex(p protocol.PacketNumber) (int, bool) {
|
||||
if len(h.packets) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
first := h.packets[0].PacketNumber
|
||||
if p < first {
|
||||
return 0, false
|
||||
}
|
||||
index := int(p - first)
|
||||
if index > len(h.packets)-1 {
|
||||
return 0, false
|
||||
}
|
||||
return index, true
|
||||
}
|
||||
|
||||
func (h *sentPacketHistory) HasOutstandingPackets() bool {
|
||||
return h.numOutstanding > 0
|
||||
return h.outstandingPacketList.Len() > 0
|
||||
}
|
||||
|
||||
// delete all nil entries at the beginning of the packets slice
|
||||
func (h *sentPacketHistory) cleanupStart() {
|
||||
for i, p := range h.packets {
|
||||
if p != nil {
|
||||
h.packets = h.packets[i:]
|
||||
return
|
||||
func (h *sentPacketHistory) DeleteOldPackets(now time.Time) {
|
||||
maxAge := 3 * h.rttStats.PTO(false)
|
||||
var nextEl *list.Element[*Packet]
|
||||
// we don't iterate outstandingPacketList, as we should not delete outstanding packets.
|
||||
// being outstanding for more than 3*PTO should only happen in the case of drastic RTT changes.
|
||||
for el := h.etcPacketList.Front(); el != nil; el = nextEl {
|
||||
nextEl = el.Next()
|
||||
p := el.Value
|
||||
if p.SendTime.After(now.Add(-maxAge)) {
|
||||
break
|
||||
}
|
||||
delete(h.packetMap, p.PacketNumber)
|
||||
h.etcPacketList.Remove(el)
|
||||
}
|
||||
h.packets = h.packets[:0]
|
||||
}
|
||||
|
||||
func (h *sentPacketHistory) LowestPacketNumber() protocol.PacketNumber {
|
||||
if len(h.packets) == 0 {
|
||||
return protocol.InvalidPacketNumber
|
||||
}
|
||||
return h.packets[0].PacketNumber
|
||||
}
|
||||
|
||||
func (h *sentPacketHistory) DeclareLost(pn protocol.PacketNumber) {
|
||||
idx, ok := h.getIndex(pn)
|
||||
func (h *sentPacketHistory) DeclareLost(p *Packet) *Packet {
|
||||
el, ok := h.packetMap[p.PacketNumber]
|
||||
if !ok {
|
||||
return
|
||||
return nil
|
||||
}
|
||||
p := h.packets[idx]
|
||||
if p.outstanding() {
|
||||
h.numOutstanding--
|
||||
if h.numOutstanding < 0 {
|
||||
panic("negative number of outstanding packets")
|
||||
el.List().Remove(el)
|
||||
p.declaredLost = true
|
||||
// move it to the correct position in the etc list (based on the packet number)
|
||||
for el = h.etcPacketList.Back(); el != nil; el = el.Prev() {
|
||||
if el.Value.PacketNumber < p.PacketNumber {
|
||||
break
|
||||
}
|
||||
}
|
||||
h.packets[idx] = nil
|
||||
if idx == 0 {
|
||||
h.cleanupStart()
|
||||
if el == nil {
|
||||
el = h.etcPacketList.PushFront(p)
|
||||
} else {
|
||||
el = h.etcPacketList.InsertAfter(p, el)
|
||||
}
|
||||
h.packetMap[p.PacketNumber] = el
|
||||
return el.Value
|
||||
}
|
||||
|
|
4
vendor/github.com/quic-go/quic-go/internal/congestion/cubic_sender.go
generated
vendored
4
vendor/github.com/quic-go/quic-go/internal/congestion/cubic_sender.go
generated
vendored
|
@ -120,8 +120,8 @@ func (c *cubicSender) TimeUntilSend(_ protocol.ByteCount) time.Time {
|
|||
return c.pacer.TimeUntilSend()
|
||||
}
|
||||
|
||||
func (c *cubicSender) HasPacingBudget(now time.Time) bool {
|
||||
return c.pacer.Budget(now) >= c.maxDatagramSize
|
||||
func (c *cubicSender) HasPacingBudget() bool {
|
||||
return c.pacer.Budget(c.clock.Now()) >= c.maxDatagramSize
|
||||
}
|
||||
|
||||
func (c *cubicSender) maxCongestionWindow() protocol.ByteCount {
|
||||
|
|
2
vendor/github.com/quic-go/quic-go/internal/congestion/interface.go
generated
vendored
2
vendor/github.com/quic-go/quic-go/internal/congestion/interface.go
generated
vendored
|
@ -9,7 +9,7 @@ import (
|
|||
// A SendAlgorithm performs congestion control
|
||||
type SendAlgorithm interface {
|
||||
TimeUntilSend(bytesInFlight protocol.ByteCount) time.Time
|
||||
HasPacingBudget(now time.Time) bool
|
||||
HasPacingBudget() bool
|
||||
OnPacketSent(sentTime time.Time, bytesInFlight protocol.ByteCount, packetNumber protocol.PacketNumber, bytes protocol.ByteCount, isRetransmittable bool)
|
||||
CanSend(bytesInFlight protocol.ByteCount) bool
|
||||
MaybeExitSlowStart()
|
||||
|
|
19
vendor/github.com/quic-go/quic-go/internal/congestion/pacer.go
generated
vendored
19
vendor/github.com/quic-go/quic-go/internal/congestion/pacer.go
generated
vendored
|
@ -12,16 +12,16 @@ const maxBurstSizePackets = 10
|
|||
|
||||
// The pacer implements a token bucket pacing algorithm.
|
||||
type pacer struct {
|
||||
budgetAtLastSent protocol.ByteCount
|
||||
maxDatagramSize protocol.ByteCount
|
||||
lastSentTime time.Time
|
||||
adjustedBandwidth func() uint64 // in bytes/s
|
||||
budgetAtLastSent protocol.ByteCount
|
||||
maxDatagramSize protocol.ByteCount
|
||||
lastSentTime time.Time
|
||||
getAdjustedBandwidth func() uint64 // in bytes/s
|
||||
}
|
||||
|
||||
func newPacer(getBandwidth func() Bandwidth) *pacer {
|
||||
p := &pacer{
|
||||
maxDatagramSize: initialMaxDatagramSize,
|
||||
adjustedBandwidth: func() uint64 {
|
||||
getAdjustedBandwidth: func() uint64 {
|
||||
// Bandwidth is in bits/s. We need the value in bytes/s.
|
||||
bw := uint64(getBandwidth() / BytesPerSecond)
|
||||
// Use a slightly higher value than the actual measured bandwidth.
|
||||
|
@ -49,16 +49,13 @@ func (p *pacer) Budget(now time.Time) protocol.ByteCount {
|
|||
if p.lastSentTime.IsZero() {
|
||||
return p.maxBurstSize()
|
||||
}
|
||||
budget := p.budgetAtLastSent + (protocol.ByteCount(p.adjustedBandwidth())*protocol.ByteCount(now.Sub(p.lastSentTime).Nanoseconds()))/1e9
|
||||
if budget < 0 { // protect against overflows
|
||||
budget = protocol.MaxByteCount
|
||||
}
|
||||
budget := p.budgetAtLastSent + (protocol.ByteCount(p.getAdjustedBandwidth())*protocol.ByteCount(now.Sub(p.lastSentTime).Nanoseconds()))/1e9
|
||||
return utils.Min(p.maxBurstSize(), budget)
|
||||
}
|
||||
|
||||
func (p *pacer) maxBurstSize() protocol.ByteCount {
|
||||
return utils.Max(
|
||||
protocol.ByteCount(uint64((protocol.MinPacingDelay+protocol.TimerGranularity).Nanoseconds())*p.adjustedBandwidth())/1e9,
|
||||
protocol.ByteCount(uint64((protocol.MinPacingDelay+protocol.TimerGranularity).Nanoseconds())*p.getAdjustedBandwidth())/1e9,
|
||||
maxBurstSizePackets*p.maxDatagramSize,
|
||||
)
|
||||
}
|
||||
|
@ -71,7 +68,7 @@ func (p *pacer) TimeUntilSend() time.Time {
|
|||
}
|
||||
return p.lastSentTime.Add(utils.Max(
|
||||
protocol.MinPacingDelay,
|
||||
time.Duration(math.Ceil(float64(p.maxDatagramSize-p.budgetAtLastSent)*1e9/float64(p.adjustedBandwidth())))*time.Nanosecond,
|
||||
time.Duration(math.Ceil(float64(p.maxDatagramSize-p.budgetAtLastSent)*1e9/float64(p.getAdjustedBandwidth())))*time.Nanosecond,
|
||||
))
|
||||
}
|
||||
|
||||
|
|
10
vendor/github.com/quic-go/quic-go/internal/handshake/crypto_setup.go
generated
vendored
10
vendor/github.com/quic-go/quic-go/internal/handshake/crypto_setup.go
generated
vendored
|
@ -116,7 +116,7 @@ type cryptoSetup struct {
|
|||
clientHelloWritten bool
|
||||
clientHelloWrittenChan chan struct{} // is closed as soon as the ClientHello is written
|
||||
zeroRTTParametersChan chan<- *wire.TransportParameters
|
||||
allow0RTT bool
|
||||
allow0RTT func() bool
|
||||
|
||||
rttStats *utils.RTTStats
|
||||
|
||||
|
@ -197,7 +197,7 @@ func NewCryptoSetupServer(
|
|||
tp *wire.TransportParameters,
|
||||
runner handshakeRunner,
|
||||
tlsConf *tls.Config,
|
||||
allow0RTT bool,
|
||||
allow0RTT func() bool,
|
||||
rttStats *utils.RTTStats,
|
||||
tracer logging.ConnectionTracer,
|
||||
logger utils.Logger,
|
||||
|
@ -210,13 +210,14 @@ func NewCryptoSetupServer(
|
|||
tp,
|
||||
runner,
|
||||
tlsConf,
|
||||
allow0RTT,
|
||||
allow0RTT != nil,
|
||||
rttStats,
|
||||
tracer,
|
||||
logger,
|
||||
protocol.PerspectiveServer,
|
||||
version,
|
||||
)
|
||||
cs.allow0RTT = allow0RTT
|
||||
cs.conn = qtls.Server(newConn(localAddr, remoteAddr), cs.tlsConf, cs.extraConf)
|
||||
return cs
|
||||
}
|
||||
|
@ -252,7 +253,6 @@ func newCryptoSetup(
|
|||
readEncLevel: protocol.EncryptionInitial,
|
||||
writeEncLevel: protocol.EncryptionInitial,
|
||||
runner: runner,
|
||||
allow0RTT: enable0RTT,
|
||||
ourParams: tp,
|
||||
paramsChan: extHandler.TransportParameters(),
|
||||
rttStats: rttStats,
|
||||
|
@ -503,7 +503,7 @@ func (h *cryptoSetup) accept0RTT(sessionTicketData []byte) bool {
|
|||
h.logger.Debugf("Transport parameters changed. Rejecting 0-RTT.")
|
||||
return false
|
||||
}
|
||||
if !h.allow0RTT {
|
||||
if !h.allow0RTT() {
|
||||
h.logger.Debugf("0-RTT not allowed. Rejecting 0-RTT.")
|
||||
return false
|
||||
}
|
||||
|
|
3
vendor/github.com/quic-go/quic-go/internal/protocol/params.go
generated
vendored
3
vendor/github.com/quic-go/quic-go/internal/protocol/params.go
generated
vendored
|
@ -5,9 +5,6 @@ import "time"
|
|||
// DesiredReceiveBufferSize is the kernel UDP receive buffer size that we'd like to use.
|
||||
const DesiredReceiveBufferSize = (1 << 20) * 2 // 2 MB
|
||||
|
||||
// DesiredSendBufferSize is the kernel UDP send buffer size that we'd like to use.
|
||||
const DesiredSendBufferSize = (1 << 20) * 2 // 2 MB
|
||||
|
||||
// InitialPacketSizeIPv4 is the maximum packet size that we use for sending IPv4 packets.
|
||||
const InitialPacketSizeIPv4 = 1252
|
||||
|
||||
|
|
8
vendor/github.com/quic-go/quic-go/internal/protocol/protocol.go
generated
vendored
8
vendor/github.com/quic-go/quic-go/internal/protocol/protocol.go
generated
vendored
|
@ -59,10 +59,7 @@ type StatelessResetToken [16]byte
|
|||
// ethernet's max size, minus the IP and UDP headers. IPv6 has a 40 byte header,
|
||||
// UDP adds an additional 8 bytes. This is a total overhead of 48 bytes.
|
||||
// Ethernet's max packet size is 1500 bytes, 1500 - 48 = 1452.
|
||||
const MaxPacketBufferSize = 1452
|
||||
|
||||
// MaxLargePacketBufferSize is used when using GSO
|
||||
const MaxLargePacketBufferSize = 20 * 1024
|
||||
const MaxPacketBufferSize ByteCount = 1452
|
||||
|
||||
// MinInitialPacketSize is the minimum size an Initial packet is required to have.
|
||||
const MinInitialPacketSize = 1200
|
||||
|
@ -80,9 +77,6 @@ const MinConnectionIDLenInitial = 8
|
|||
// DefaultAckDelayExponent is the default ack delay exponent
|
||||
const DefaultAckDelayExponent = 3
|
||||
|
||||
// DefaultActiveConnectionIDLimit is the default active connection ID limit
|
||||
const DefaultActiveConnectionIDLimit = 2
|
||||
|
||||
// MaxAckDelayExponent is the maximum ack delay exponent
|
||||
const MaxAckDelayExponent = 20
|
||||
|
||||
|
|
86
vendor/github.com/quic-go/quic-go/internal/utils/ringbuffer/ringbuffer.go
generated
vendored
86
vendor/github.com/quic-go/quic-go/internal/utils/ringbuffer/ringbuffer.go
generated
vendored
|
@ -1,86 +0,0 @@
|
|||
package ringbuffer
|
||||
|
||||
// A RingBuffer is a ring buffer.
|
||||
// It acts as a heap that doesn't cause any allocations.
|
||||
type RingBuffer[T any] struct {
|
||||
ring []T
|
||||
headPos, tailPos int
|
||||
full bool
|
||||
}
|
||||
|
||||
// Init preallocs a buffer with a certain size.
|
||||
func (r *RingBuffer[T]) Init(size int) {
|
||||
r.ring = make([]T, size)
|
||||
}
|
||||
|
||||
// Len returns the number of elements in the ring buffer.
|
||||
func (r *RingBuffer[T]) Len() int {
|
||||
if r.full {
|
||||
return len(r.ring)
|
||||
}
|
||||
if r.tailPos >= r.headPos {
|
||||
return r.tailPos - r.headPos
|
||||
}
|
||||
return r.tailPos - r.headPos + len(r.ring)
|
||||
}
|
||||
|
||||
// Empty says if the ring buffer is empty.
|
||||
func (r *RingBuffer[T]) Empty() bool {
|
||||
return !r.full && r.headPos == r.tailPos
|
||||
}
|
||||
|
||||
// PushBack adds a new element.
|
||||
// If the ring buffer is full, its capacity is increased first.
|
||||
func (r *RingBuffer[T]) PushBack(t T) {
|
||||
if r.full || len(r.ring) == 0 {
|
||||
r.grow()
|
||||
}
|
||||
r.ring[r.tailPos] = t
|
||||
r.tailPos++
|
||||
if r.tailPos == len(r.ring) {
|
||||
r.tailPos = 0
|
||||
}
|
||||
if r.tailPos == r.headPos {
|
||||
r.full = true
|
||||
}
|
||||
}
|
||||
|
||||
// PopFront returns the next element.
|
||||
// It must not be called when the buffer is empty, that means that
|
||||
// callers might need to check if there are elements in the buffer first.
|
||||
func (r *RingBuffer[T]) PopFront() T {
|
||||
if r.Empty() {
|
||||
panic("github.com/quic-go/quic-go/internal/utils/ringbuffer: pop from an empty queue")
|
||||
}
|
||||
r.full = false
|
||||
t := r.ring[r.headPos]
|
||||
r.ring[r.headPos] = *new(T)
|
||||
r.headPos++
|
||||
if r.headPos == len(r.ring) {
|
||||
r.headPos = 0
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// Grow the maximum size of the queue.
|
||||
// This method assume the queue is full.
|
||||
func (r *RingBuffer[T]) grow() {
|
||||
oldRing := r.ring
|
||||
newSize := len(oldRing) * 2
|
||||
if newSize == 0 {
|
||||
newSize = 1
|
||||
}
|
||||
r.ring = make([]T, newSize)
|
||||
headLen := copy(r.ring, oldRing[r.headPos:])
|
||||
copy(r.ring[headLen:], oldRing[:r.headPos])
|
||||
r.headPos, r.tailPos, r.full = 0, len(oldRing), false
|
||||
}
|
||||
|
||||
// Clear removes all elements.
|
||||
func (r *RingBuffer[T]) Clear() {
|
||||
var zeroValue T
|
||||
for i := range r.ring {
|
||||
r.ring[i] = zeroValue
|
||||
}
|
||||
r.headPos, r.tailPos, r.full = 0, 0, false
|
||||
}
|
6
vendor/github.com/quic-go/quic-go/internal/utils/rtt_stats.go
generated
vendored
6
vendor/github.com/quic-go/quic-go/internal/utils/rtt_stats.go
generated
vendored
|
@ -103,12 +103,8 @@ func (r *RTTStats) SetMaxAckDelay(mad time.Duration) {
|
|||
// SetInitialRTT sets the initial RTT.
|
||||
// It is used during the 0-RTT handshake when restoring the RTT stats from the session state.
|
||||
func (r *RTTStats) SetInitialRTT(t time.Duration) {
|
||||
// On the server side, by the time we get to process the session ticket,
|
||||
// we might already have obtained an RTT measurement.
|
||||
// This can happen if we received the ClientHello in multiple pieces, and one of those pieces was lost.
|
||||
// Discard the restored value. A fresh measurement is always better.
|
||||
if r.hasMeasurement {
|
||||
return
|
||||
panic("initial RTT set after first measurement")
|
||||
}
|
||||
r.smoothedRTT = t
|
||||
r.latestRTT = t
|
||||
|
|
57
vendor/github.com/quic-go/quic-go/internal/wire/ack_frame.go
generated
vendored
57
vendor/github.com/quic-go/quic-go/internal/wire/ack_frame.go
generated
vendored
|
@ -22,17 +22,19 @@ type AckFrame struct {
|
|||
}
|
||||
|
||||
// parseAckFrame reads an ACK frame
|
||||
func parseAckFrame(frame *AckFrame, r *bytes.Reader, typ uint64, ackDelayExponent uint8, _ protocol.VersionNumber) error {
|
||||
func parseAckFrame(r *bytes.Reader, typ uint64, ackDelayExponent uint8, _ protocol.VersionNumber) (*AckFrame, error) {
|
||||
ecn := typ == ackECNFrameType
|
||||
|
||||
frame := GetAckFrame()
|
||||
|
||||
la, err := quicvarint.Read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
largestAcked := protocol.PacketNumber(la)
|
||||
delay, err := quicvarint.Read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
delayTime := time.Duration(delay*1<<ackDelayExponent) * time.Microsecond
|
||||
|
@ -44,17 +46,17 @@ func parseAckFrame(frame *AckFrame, r *bytes.Reader, typ uint64, ackDelayExponen
|
|||
|
||||
numBlocks, err := quicvarint.Read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// read the first ACK range
|
||||
ab, err := quicvarint.Read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
ackBlock := protocol.PacketNumber(ab)
|
||||
if ackBlock > largestAcked {
|
||||
return errors.New("invalid first ACK range")
|
||||
return nil, errors.New("invalid first ACK range")
|
||||
}
|
||||
smallest := largestAcked - ackBlock
|
||||
|
||||
|
@ -63,50 +65,41 @@ func parseAckFrame(frame *AckFrame, r *bytes.Reader, typ uint64, ackDelayExponen
|
|||
for i := uint64(0); i < numBlocks; i++ {
|
||||
g, err := quicvarint.Read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
gap := protocol.PacketNumber(g)
|
||||
if smallest < gap+2 {
|
||||
return errInvalidAckRanges
|
||||
return nil, errInvalidAckRanges
|
||||
}
|
||||
largest := smallest - gap - 2
|
||||
|
||||
ab, err := quicvarint.Read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
ackBlock := protocol.PacketNumber(ab)
|
||||
|
||||
if ackBlock > largest {
|
||||
return errInvalidAckRanges
|
||||
return nil, errInvalidAckRanges
|
||||
}
|
||||
smallest = largest - ackBlock
|
||||
frame.AckRanges = append(frame.AckRanges, AckRange{Smallest: smallest, Largest: largest})
|
||||
}
|
||||
|
||||
if !frame.validateAckRanges() {
|
||||
return errInvalidAckRanges
|
||||
return nil, errInvalidAckRanges
|
||||
}
|
||||
|
||||
// parse (and skip) the ECN section
|
||||
if ecn {
|
||||
ect0, err := quicvarint.Read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
for i := 0; i < 3; i++ {
|
||||
if _, err := quicvarint.Read(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
frame.ECT0 = ect0
|
||||
ect1, err := quicvarint.Read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
frame.ECT1 = ect1
|
||||
ecnce, err := quicvarint.Read(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
frame.ECNCE = ecnce
|
||||
}
|
||||
|
||||
return nil
|
||||
return frame, nil
|
||||
}
|
||||
|
||||
// Append appends an ACK frame.
|
||||
|
@ -249,18 +242,6 @@ func (f *AckFrame) AcksPacket(p protocol.PacketNumber) bool {
|
|||
return p <= f.AckRanges[i].Largest
|
||||
}
|
||||
|
||||
func (f *AckFrame) Reset() {
|
||||
f.DelayTime = 0
|
||||
f.ECT0 = 0
|
||||
f.ECT1 = 0
|
||||
f.ECNCE = 0
|
||||
for _, r := range f.AckRanges {
|
||||
r.Largest = 0
|
||||
r.Smallest = 0
|
||||
}
|
||||
f.AckRanges = f.AckRanges[:0]
|
||||
}
|
||||
|
||||
func encodeAckDelay(delay time.Duration) uint64 {
|
||||
return uint64(delay.Nanoseconds() / (1000 * (1 << protocol.AckDelayExponent)))
|
||||
}
|
||||
|
|
24
vendor/github.com/quic-go/quic-go/internal/wire/ack_frame_pool.go
generated
vendored
Normal file
24
vendor/github.com/quic-go/quic-go/internal/wire/ack_frame_pool.go
generated
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
package wire
|
||||
|
||||
import "sync"
|
||||
|
||||
var ackFramePool = sync.Pool{New: func() any {
|
||||
return &AckFrame{}
|
||||
}}
|
||||
|
||||
func GetAckFrame() *AckFrame {
|
||||
f := ackFramePool.Get().(*AckFrame)
|
||||
f.AckRanges = f.AckRanges[:0]
|
||||
f.ECNCE = 0
|
||||
f.ECT0 = 0
|
||||
f.ECT1 = 0
|
||||
f.DelayTime = 0
|
||||
return f
|
||||
}
|
||||
|
||||
func PutAckFrame(f *AckFrame) {
|
||||
if cap(f.AckRanges) > 4 {
|
||||
return
|
||||
}
|
||||
ackFramePool.Put(f)
|
||||
}
|
12
vendor/github.com/quic-go/quic-go/internal/wire/frame_parser.go
generated
vendored
12
vendor/github.com/quic-go/quic-go/internal/wire/frame_parser.go
generated
vendored
|
@ -39,12 +39,9 @@ const (
|
|||
type frameParser struct {
|
||||
r bytes.Reader // cached bytes.Reader, so we don't have to repeatedly allocate them
|
||||
|
||||
ackDelayExponent uint8
|
||||
supportsDatagrams bool
|
||||
ackDelayExponent uint8
|
||||
|
||||
// To avoid allocating when parsing, keep a single ACK frame struct.
|
||||
// It is used over and over again.
|
||||
ackFrame *AckFrame
|
||||
supportsDatagrams bool
|
||||
}
|
||||
|
||||
var _ FrameParser = &frameParser{}
|
||||
|
@ -54,7 +51,6 @@ func NewFrameParser(supportsDatagrams bool) *frameParser {
|
|||
return &frameParser{
|
||||
r: *bytes.NewReader(nil),
|
||||
supportsDatagrams: supportsDatagrams,
|
||||
ackFrame: &AckFrame{},
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -109,9 +105,7 @@ func (p *frameParser) parseFrame(r *bytes.Reader, typ uint64, encLevel protocol.
|
|||
if encLevel != protocol.Encryption1RTT {
|
||||
ackDelayExponent = protocol.DefaultAckDelayExponent
|
||||
}
|
||||
p.ackFrame.Reset()
|
||||
err = parseAckFrame(p.ackFrame, r, typ, ackDelayExponent, v)
|
||||
frame = p.ackFrame
|
||||
frame, err = parseAckFrame(r, typ, ackDelayExponent, v)
|
||||
case resetStreamFrameType:
|
||||
frame, err = parseResetStreamFrame(r, v)
|
||||
case stopSendingFrameType:
|
||||
|
|
2
vendor/github.com/quic-go/quic-go/internal/wire/header.go
generated
vendored
2
vendor/github.com/quic-go/quic-go/internal/wire/header.go
generated
vendored
|
@ -13,6 +13,8 @@ import (
|
|||
)
|
||||
|
||||
// ParseConnectionID parses the destination connection ID of a packet.
|
||||
// It uses the data slice for the connection ID.
|
||||
// That means that the connection ID must not be used after the packet buffer is released.
|
||||
func ParseConnectionID(data []byte, shortHeaderConnIDLen int) (protocol.ConnectionID, error) {
|
||||
if len(data) == 0 {
|
||||
return protocol.ConnectionID{}, io.EOF
|
||||
|
|
35
vendor/github.com/quic-go/quic-go/internal/wire/transport_parameters.go
generated
vendored
35
vendor/github.com/quic-go/quic-go/internal/wire/transport_parameters.go
generated
vendored
|
@ -2,13 +2,14 @@ package wire
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
|
@ -25,6 +26,15 @@ var AdditionalTransportParametersClient map[uint64][]byte
|
|||
|
||||
const transportParameterMarshalingVersion = 1
|
||||
|
||||
var (
|
||||
randomMutex sync.Mutex
|
||||
random rand.Rand
|
||||
)
|
||||
|
||||
func init() {
|
||||
random = *rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
}
|
||||
|
||||
type transportParameterID uint64
|
||||
|
||||
const (
|
||||
|
@ -108,7 +118,6 @@ func (p *TransportParameters) unmarshal(r *bytes.Reader, sentBy protocol.Perspec
|
|||
var (
|
||||
readOriginalDestinationConnectionID bool
|
||||
readInitialSourceConnectionID bool
|
||||
readActiveConnectionIDLimit bool
|
||||
)
|
||||
|
||||
p.AckDelayExponent = protocol.DefaultAckDelayExponent
|
||||
|
@ -130,9 +139,6 @@ func (p *TransportParameters) unmarshal(r *bytes.Reader, sentBy protocol.Perspec
|
|||
}
|
||||
parameterIDs = append(parameterIDs, paramID)
|
||||
switch paramID {
|
||||
case activeConnectionIDLimitParameterID:
|
||||
readActiveConnectionIDLimit = true
|
||||
fallthrough
|
||||
case maxIdleTimeoutParameterID,
|
||||
maxUDPPayloadSizeParameterID,
|
||||
initialMaxDataParameterID,
|
||||
|
@ -142,6 +148,7 @@ func (p *TransportParameters) unmarshal(r *bytes.Reader, sentBy protocol.Perspec
|
|||
initialMaxStreamsBidiParameterID,
|
||||
initialMaxStreamsUniParameterID,
|
||||
maxAckDelayParameterID,
|
||||
activeConnectionIDLimitParameterID,
|
||||
maxDatagramFrameSizeParameterID,
|
||||
ackDelayExponentParameterID:
|
||||
if err := p.readNumericTransportParameter(r, paramID, int(paramLen)); err != nil {
|
||||
|
@ -189,9 +196,6 @@ func (p *TransportParameters) unmarshal(r *bytes.Reader, sentBy protocol.Perspec
|
|||
}
|
||||
}
|
||||
|
||||
if !readActiveConnectionIDLimit {
|
||||
p.ActiveConnectionIDLimit = protocol.DefaultActiveConnectionIDLimit
|
||||
}
|
||||
if !fromSessionTicket {
|
||||
if sentBy == protocol.PerspectiveServer && !readOriginalDestinationConnectionID {
|
||||
return errors.New("missing original_destination_connection_id")
|
||||
|
@ -331,12 +335,13 @@ func (p *TransportParameters) Marshal(pers protocol.Perspective) []byte {
|
|||
b := make([]byte, 0, 256)
|
||||
|
||||
// add a greased value
|
||||
random := make([]byte, 18)
|
||||
rand.Read(random)
|
||||
b = quicvarint.Append(b, 27+31*uint64(random[0]))
|
||||
length := random[1] % 16
|
||||
b = quicvarint.Append(b, uint64(27+31*rand.Intn(100)))
|
||||
randomMutex.Lock()
|
||||
length := random.Intn(16)
|
||||
b = quicvarint.Append(b, uint64(length))
|
||||
b = append(b, random[2:2+length]...)
|
||||
b = b[:len(b)+length]
|
||||
random.Read(b[len(b)-length:])
|
||||
randomMutex.Unlock()
|
||||
|
||||
// initial_max_stream_data_bidi_local
|
||||
b = p.marshalVarintParam(b, initialMaxStreamDataBidiLocalParameterID, uint64(p.InitialMaxStreamDataBidiLocal))
|
||||
|
@ -397,9 +402,7 @@ func (p *TransportParameters) Marshal(pers protocol.Perspective) []byte {
|
|||
}
|
||||
}
|
||||
// active_connection_id_limit
|
||||
if p.ActiveConnectionIDLimit != protocol.DefaultActiveConnectionIDLimit {
|
||||
b = p.marshalVarintParam(b, activeConnectionIDLimitParameterID, p.ActiveConnectionIDLimit)
|
||||
}
|
||||
b = p.marshalVarintParam(b, activeConnectionIDLimitParameterID, p.ActiveConnectionIDLimit)
|
||||
// initial_source_connection_id
|
||||
b = quicvarint.Append(b, uint64(initialSourceConnectionIDParameterID))
|
||||
b = quicvarint.Append(b, uint64(p.InitialSourceConnectionID.Len()))
|
||||
|
|
7
vendor/github.com/quic-go/quic-go/logging/interface.go
generated
vendored
7
vendor/github.com/quic-go/quic-go/logging/interface.go
generated
vendored
|
@ -3,6 +3,7 @@
|
|||
package logging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
|
@ -100,6 +101,12 @@ type ShortHeader struct {
|
|||
|
||||
// A Tracer traces events.
|
||||
type Tracer interface {
|
||||
// TracerForConnection requests a new tracer for a connection.
|
||||
// The ODCID is the original destination connection ID:
|
||||
// The destination connection ID that the client used on the first Initial packet it sent on this connection.
|
||||
// If nil is returned, tracing will be disabled for this connection.
|
||||
TracerForConnection(ctx context.Context, p Perspective, odcid ConnectionID) ConnectionTracer
|
||||
|
||||
SentPacket(net.Addr, *Header, ByteCount, []Frame)
|
||||
SentVersionNegotiationPacket(_ net.Addr, dest, src ArbitraryLenConnectionID, _ []VersionNumber)
|
||||
DroppedPacket(net.Addr, PacketType, ByteCount, PacketDropReason)
|
||||
|
|
11
vendor/github.com/quic-go/quic-go/logging/multiplex.go
generated
vendored
11
vendor/github.com/quic-go/quic-go/logging/multiplex.go
generated
vendored
|
@ -1,6 +1,7 @@
|
|||
package logging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
@ -22,6 +23,16 @@ func NewMultiplexedTracer(tracers ...Tracer) Tracer {
|
|||
return &tracerMultiplexer{tracers}
|
||||
}
|
||||
|
||||
func (m *tracerMultiplexer) TracerForConnection(ctx context.Context, p Perspective, odcid ConnectionID) ConnectionTracer {
|
||||
var connTracers []ConnectionTracer
|
||||
for _, t := range m.tracers {
|
||||
if ct := t.TracerForConnection(ctx, p, odcid); ct != nil {
|
||||
connTracers = append(connTracers, ct)
|
||||
}
|
||||
}
|
||||
return NewMultiplexedConnectionTracer(connTracers...)
|
||||
}
|
||||
|
||||
func (m *tracerMultiplexer) SentPacket(remote net.Addr, hdr *Header, size ByteCount, frames []Frame) {
|
||||
for _, t := range m.tracers {
|
||||
t.SentPacket(remote, hdr, size, frames)
|
||||
|
|
4
vendor/github.com/quic-go/quic-go/logging/null_tracer.go
generated
vendored
4
vendor/github.com/quic-go/quic-go/logging/null_tracer.go
generated
vendored
|
@ -1,6 +1,7 @@
|
|||
package logging
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
@ -11,6 +12,9 @@ type NullTracer struct{}
|
|||
|
||||
var _ Tracer = &NullTracer{}
|
||||
|
||||
func (n NullTracer) TracerForConnection(context.Context, Perspective, ConnectionID) ConnectionTracer {
|
||||
return NullConnectionTracer{}
|
||||
}
|
||||
func (n NullTracer) SentPacket(net.Addr, *Header, ByteCount, []Frame) {}
|
||||
func (n NullTracer) SentVersionNegotiationPacket(_ net.Addr, dest, src ArbitraryLenConnectionID, _ []VersionNumber) {
|
||||
}
|
||||
|
|
3
vendor/github.com/quic-go/quic-go/mockgen.go
generated
vendored
3
vendor/github.com/quic-go/quic-go/mockgen.go
generated
vendored
|
@ -65,6 +65,9 @@ type UnknownPacketHandler = unknownPacketHandler
|
|||
//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_packet_handler_manager_test.go github.com/quic-go/quic-go PacketHandlerManager"
|
||||
type PacketHandlerManager = packetHandlerManager
|
||||
|
||||
//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_multiplexer_test.go github.com/quic-go/quic-go Multiplexer"
|
||||
type Multiplexer = multiplexer
|
||||
|
||||
// Need to use source mode for the batchConn, since reflect mode follows type aliases.
|
||||
// See https://github.com/golang/mock/issues/244 for details.
|
||||
//
|
||||
|
|
83
vendor/github.com/quic-go/quic-go/mtu_discoverer.go
generated
vendored
83
vendor/github.com/quic-go/quic-go/mtu_discoverer.go
generated
vendored
|
@ -1,7 +1,6 @@
|
|||
package quic
|
||||
|
||||
import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/ackhandler"
|
||||
|
@ -11,11 +10,7 @@ import (
|
|||
)
|
||||
|
||||
type mtuDiscoverer interface {
|
||||
// Start starts the MTU discovery process.
|
||||
// It's unnecessary to call ShouldSendProbe before that.
|
||||
Start(maxPacketSize protocol.ByteCount)
|
||||
ShouldSendProbe(now time.Time) bool
|
||||
CurrentSize() protocol.ByteCount
|
||||
GetPing() (ping ackhandler.Frame, datagramSize protocol.ByteCount)
|
||||
}
|
||||
|
||||
|
@ -27,38 +22,25 @@ const (
|
|||
mtuProbeDelay = 5
|
||||
)
|
||||
|
||||
func getMaxPacketSize(addr net.Addr) protocol.ByteCount {
|
||||
maxSize := protocol.ByteCount(protocol.MinInitialPacketSize)
|
||||
// If this is not a UDP address, we don't know anything about the MTU.
|
||||
// Use the minimum size of an Initial packet as the max packet size.
|
||||
if udpAddr, ok := addr.(*net.UDPAddr); ok {
|
||||
if utils.IsIPv4(udpAddr.IP) {
|
||||
maxSize = protocol.InitialPacketSizeIPv4
|
||||
} else {
|
||||
maxSize = protocol.InitialPacketSizeIPv6
|
||||
}
|
||||
}
|
||||
return maxSize
|
||||
}
|
||||
|
||||
type mtuFinder struct {
|
||||
lastProbeTime time.Time
|
||||
probeInFlight bool
|
||||
mtuIncreased func(protocol.ByteCount)
|
||||
|
||||
rttStats *utils.RTTStats
|
||||
inFlight protocol.ByteCount // the size of the probe packet currently in flight. InvalidByteCount if none is in flight
|
||||
current protocol.ByteCount
|
||||
max protocol.ByteCount // the maximum value, as advertised by the peer (or our maximum size buffer)
|
||||
}
|
||||
|
||||
var _ mtuDiscoverer = &mtuFinder{}
|
||||
|
||||
func newMTUDiscoverer(rttStats *utils.RTTStats, start protocol.ByteCount, mtuIncreased func(protocol.ByteCount)) *mtuFinder {
|
||||
func newMTUDiscoverer(rttStats *utils.RTTStats, start, max protocol.ByteCount, mtuIncreased func(protocol.ByteCount)) mtuDiscoverer {
|
||||
return &mtuFinder{
|
||||
inFlight: protocol.InvalidByteCount,
|
||||
current: start,
|
||||
rttStats: rttStats,
|
||||
mtuIncreased: mtuIncreased,
|
||||
current: start,
|
||||
rttStats: rttStats,
|
||||
lastProbeTime: time.Now(), // to make sure the first probe packet is not sent immediately
|
||||
mtuIncreased: mtuIncreased,
|
||||
max: max,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -66,16 +48,8 @@ func (f *mtuFinder) done() bool {
|
|||
return f.max-f.current <= maxMTUDiff+1
|
||||
}
|
||||
|
||||
func (f *mtuFinder) Start(maxPacketSize protocol.ByteCount) {
|
||||
f.lastProbeTime = time.Now() // makes sure the first probe packet is not sent immediately
|
||||
f.max = maxPacketSize
|
||||
}
|
||||
|
||||
func (f *mtuFinder) ShouldSendProbe(now time.Time) bool {
|
||||
if f.max == 0 || f.lastProbeTime.IsZero() {
|
||||
return false
|
||||
}
|
||||
if f.inFlight != protocol.InvalidByteCount || f.done() {
|
||||
if f.probeInFlight || f.done() {
|
||||
return false
|
||||
}
|
||||
return !now.Before(f.lastProbeTime.Add(mtuProbeDelay * f.rttStats.SmoothedRTT()))
|
||||
|
@ -84,36 +58,17 @@ func (f *mtuFinder) ShouldSendProbe(now time.Time) bool {
|
|||
func (f *mtuFinder) GetPing() (ackhandler.Frame, protocol.ByteCount) {
|
||||
size := (f.max + f.current) / 2
|
||||
f.lastProbeTime = time.Now()
|
||||
f.inFlight = size
|
||||
f.probeInFlight = true
|
||||
return ackhandler.Frame{
|
||||
Frame: &wire.PingFrame{},
|
||||
Handler: (*mtuFinderAckHandler)(f),
|
||||
Frame: &wire.PingFrame{},
|
||||
OnLost: func(wire.Frame) {
|
||||
f.probeInFlight = false
|
||||
f.max = size
|
||||
},
|
||||
OnAcked: func(wire.Frame) {
|
||||
f.probeInFlight = false
|
||||
f.current = size
|
||||
f.mtuIncreased(size)
|
||||
},
|
||||
}, size
|
||||
}
|
||||
|
||||
func (f *mtuFinder) CurrentSize() protocol.ByteCount {
|
||||
return f.current
|
||||
}
|
||||
|
||||
type mtuFinderAckHandler mtuFinder
|
||||
|
||||
var _ ackhandler.FrameHandler = &mtuFinderAckHandler{}
|
||||
|
||||
func (h *mtuFinderAckHandler) OnAcked(wire.Frame) {
|
||||
size := h.inFlight
|
||||
if size == protocol.InvalidByteCount {
|
||||
panic("OnAcked callback called although there's no MTU probe packet in flight")
|
||||
}
|
||||
h.inFlight = protocol.InvalidByteCount
|
||||
h.current = size
|
||||
h.mtuIncreased(size)
|
||||
}
|
||||
|
||||
func (h *mtuFinderAckHandler) OnLost(wire.Frame) {
|
||||
size := h.inFlight
|
||||
if size == protocol.InvalidByteCount {
|
||||
panic("OnLost callback called although there's no MTU probe packet in flight")
|
||||
}
|
||||
h.max = size
|
||||
h.inFlight = protocol.InvalidByteCount
|
||||
}
|
||||
|
|
69
vendor/github.com/quic-go/quic-go/multiplexer.go
generated
vendored
69
vendor/github.com/quic-go/quic-go/multiplexer.go
generated
vendored
|
@ -6,6 +6,7 @@ import (
|
|||
"sync"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/utils"
|
||||
"github.com/quic-go/quic-go/logging"
|
||||
)
|
||||
|
||||
var (
|
||||
|
@ -13,19 +14,30 @@ var (
|
|||
connMuxer multiplexer
|
||||
)
|
||||
|
||||
type indexableConn interface{ LocalAddr() net.Addr }
|
||||
type indexableConn interface {
|
||||
LocalAddr() net.Addr
|
||||
}
|
||||
|
||||
type multiplexer interface {
|
||||
AddConn(conn indexableConn)
|
||||
AddConn(c net.PacketConn, connIDLen int, statelessResetKey *StatelessResetKey, tracer logging.Tracer) (packetHandlerManager, error)
|
||||
RemoveConn(indexableConn) error
|
||||
}
|
||||
|
||||
type connManager struct {
|
||||
connIDLen int
|
||||
statelessResetKey *StatelessResetKey
|
||||
tracer logging.Tracer
|
||||
manager packetHandlerManager
|
||||
}
|
||||
|
||||
// The connMultiplexer listens on multiple net.PacketConns and dispatches
|
||||
// incoming packets to the connection handler.
|
||||
type connMultiplexer struct {
|
||||
mutex sync.Mutex
|
||||
|
||||
conns map[string] /* LocalAddr().String() */ indexableConn
|
||||
conns map[string] /* LocalAddr().String() */ connManager
|
||||
newPacketHandlerManager func(net.PacketConn, int, *StatelessResetKey, logging.Tracer, utils.Logger) (packetHandlerManager, error) // so it can be replaced in the tests
|
||||
|
||||
logger utils.Logger
|
||||
}
|
||||
|
||||
|
@ -34,38 +46,57 @@ var _ multiplexer = &connMultiplexer{}
|
|||
func getMultiplexer() multiplexer {
|
||||
connMuxerOnce.Do(func() {
|
||||
connMuxer = &connMultiplexer{
|
||||
conns: make(map[string]indexableConn),
|
||||
logger: utils.DefaultLogger.WithPrefix("muxer"),
|
||||
conns: make(map[string]connManager),
|
||||
logger: utils.DefaultLogger.WithPrefix("muxer"),
|
||||
newPacketHandlerManager: newPacketHandlerMap,
|
||||
}
|
||||
})
|
||||
return connMuxer
|
||||
}
|
||||
|
||||
func (m *connMultiplexer) index(addr net.Addr) string {
|
||||
return addr.Network() + " " + addr.String()
|
||||
}
|
||||
|
||||
func (m *connMultiplexer) AddConn(c indexableConn) {
|
||||
func (m *connMultiplexer) AddConn(
|
||||
c net.PacketConn,
|
||||
connIDLen int,
|
||||
statelessResetKey *StatelessResetKey,
|
||||
tracer logging.Tracer,
|
||||
) (packetHandlerManager, error) {
|
||||
m.mutex.Lock()
|
||||
defer m.mutex.Unlock()
|
||||
|
||||
connIndex := m.index(c.LocalAddr())
|
||||
addr := c.LocalAddr()
|
||||
connIndex := addr.Network() + " " + addr.String()
|
||||
p, ok := m.conns[connIndex]
|
||||
if ok {
|
||||
// Panics if we're already listening on this connection.
|
||||
// This is a safeguard because we're introducing a breaking API change, see
|
||||
// https://github.com/quic-go/quic-go/issues/3727 for details.
|
||||
// We'll remove this at a later time, when most users of the library have made the switch.
|
||||
panic("connection already exists") // TODO: write a nice message
|
||||
if !ok {
|
||||
manager, err := m.newPacketHandlerManager(c, connIDLen, statelessResetKey, tracer, m.logger)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p = connManager{
|
||||
connIDLen: connIDLen,
|
||||
statelessResetKey: statelessResetKey,
|
||||
manager: manager,
|
||||
tracer: tracer,
|
||||
}
|
||||
m.conns[connIndex] = p
|
||||
} else {
|
||||
if p.connIDLen != connIDLen {
|
||||
return nil, fmt.Errorf("cannot use %d byte connection IDs on a connection that is already using %d byte connction IDs", connIDLen, p.connIDLen)
|
||||
}
|
||||
if statelessResetKey != nil && p.statelessResetKey != statelessResetKey {
|
||||
return nil, fmt.Errorf("cannot use different stateless reset keys on the same packet conn")
|
||||
}
|
||||
if tracer != p.tracer {
|
||||
return nil, fmt.Errorf("cannot use different tracers on the same packet conn")
|
||||
}
|
||||
}
|
||||
m.conns[connIndex] = p
|
||||
return p.manager, nil
|
||||
}
|
||||
|
||||
func (m *connMultiplexer) RemoveConn(c indexableConn) error {
|
||||
m.mutex.Lock()
|
||||
defer m.mutex.Unlock()
|
||||
|
||||
connIndex := m.index(c.LocalAddr())
|
||||
connIndex := c.LocalAddr().Network() + " " + c.LocalAddr().String()
|
||||
if _, ok := m.conns[connIndex]; !ok {
|
||||
return fmt.Errorf("cannote remove connection, connection is unknown")
|
||||
}
|
||||
|
|
364
vendor/github.com/quic-go/quic-go/packet_handler_map.go
generated
vendored
364
vendor/github.com/quic-go/quic-go/packet_handler_map.go
generated
vendored
|
@ -5,86 +5,147 @@ import (
|
|||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
"github.com/quic-go/quic-go/internal/utils"
|
||||
"github.com/quic-go/quic-go/internal/wire"
|
||||
"github.com/quic-go/quic-go/logging"
|
||||
)
|
||||
|
||||
type connCapabilities struct {
|
||||
// This connection has the Don't Fragment (DF) bit set.
|
||||
// This means it makes to run DPLPMTUD.
|
||||
DF bool
|
||||
// GSO (Generic Segmentation Offload) supported
|
||||
GSO bool
|
||||
}
|
||||
|
||||
// rawConn is a connection that allow reading of a receivedPackeh.
|
||||
// rawConn is a connection that allow reading of a receivedPacket.
|
||||
type rawConn interface {
|
||||
ReadPacket() (receivedPacket, error)
|
||||
// The size parameter is used for GSO.
|
||||
// If GSO is not support, len(b) must be equal to size.
|
||||
WritePacket(b []byte, size uint16, addr net.Addr, oob []byte) (int, error)
|
||||
ReadPacket() (*receivedPacket, error)
|
||||
WritePacket(b []byte, addr net.Addr, oob []byte) (int, error)
|
||||
LocalAddr() net.Addr
|
||||
SetReadDeadline(time.Time) error
|
||||
io.Closer
|
||||
|
||||
capabilities() connCapabilities
|
||||
}
|
||||
|
||||
type closePacket struct {
|
||||
payload []byte
|
||||
addr net.Addr
|
||||
info packetInfo
|
||||
info *packetInfo
|
||||
}
|
||||
|
||||
type unknownPacketHandler interface {
|
||||
handlePacket(receivedPacket)
|
||||
setCloseError(error)
|
||||
}
|
||||
|
||||
var errListenerAlreadySet = errors.New("listener already set")
|
||||
|
||||
// The packetHandlerMap stores packetHandlers, identified by connection ID.
|
||||
// It is used:
|
||||
// * by the server to store connections
|
||||
// * when multiplexing outgoing connections to store clients
|
||||
type packetHandlerMap struct {
|
||||
mutex sync.Mutex
|
||||
handlers map[protocol.ConnectionID]packetHandler
|
||||
resetTokens map[protocol.StatelessResetToken] /* stateless reset token */ packetHandler
|
||||
mutex sync.Mutex
|
||||
|
||||
conn rawConn
|
||||
connIDLen int
|
||||
|
||||
closeQueue chan closePacket
|
||||
|
||||
handlers map[protocol.ConnectionID]packetHandler
|
||||
resetTokens map[protocol.StatelessResetToken] /* stateless reset token */ packetHandler
|
||||
server unknownPacketHandler
|
||||
numZeroRTTEntries int
|
||||
|
||||
listening chan struct{} // is closed when listen returns
|
||||
closed bool
|
||||
closeChan chan struct{}
|
||||
|
||||
enqueueClosePacket func(closePacket)
|
||||
|
||||
deleteRetiredConnsAfter time.Duration
|
||||
zeroRTTQueueDuration time.Duration
|
||||
|
||||
statelessResetMutex sync.Mutex
|
||||
statelessResetHasher hash.Hash
|
||||
statelessResetEnabled bool
|
||||
statelessResetMutex sync.Mutex
|
||||
statelessResetHasher hash.Hash
|
||||
|
||||
tracer logging.Tracer
|
||||
logger utils.Logger
|
||||
}
|
||||
|
||||
var _ packetHandlerManager = &packetHandlerMap{}
|
||||
|
||||
func newPacketHandlerMap(key *StatelessResetKey, enqueueClosePacket func(closePacket), logger utils.Logger) *packetHandlerMap {
|
||||
h := &packetHandlerMap{
|
||||
closeChan: make(chan struct{}),
|
||||
func setReceiveBuffer(c net.PacketConn, logger utils.Logger) error {
|
||||
conn, ok := c.(interface{ SetReadBuffer(int) error })
|
||||
if !ok {
|
||||
return errors.New("connection doesn't allow setting of receive buffer size. Not a *net.UDPConn?")
|
||||
}
|
||||
size, err := inspectReadBuffer(c)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to determine receive buffer size: %w", err)
|
||||
}
|
||||
if size >= protocol.DesiredReceiveBufferSize {
|
||||
logger.Debugf("Conn has receive buffer of %d kiB (wanted: at least %d kiB)", size/1024, protocol.DesiredReceiveBufferSize/1024)
|
||||
return nil
|
||||
}
|
||||
if err := conn.SetReadBuffer(protocol.DesiredReceiveBufferSize); err != nil {
|
||||
return fmt.Errorf("failed to increase receive buffer size: %w", err)
|
||||
}
|
||||
newSize, err := inspectReadBuffer(c)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to determine receive buffer size: %w", err)
|
||||
}
|
||||
if newSize == size {
|
||||
return fmt.Errorf("failed to increase receive buffer size (wanted: %d kiB, got %d kiB)", protocol.DesiredReceiveBufferSize/1024, newSize/1024)
|
||||
}
|
||||
if newSize < protocol.DesiredReceiveBufferSize {
|
||||
return fmt.Errorf("failed to sufficiently increase receive buffer size (was: %d kiB, wanted: %d kiB, got: %d kiB)", size/1024, protocol.DesiredReceiveBufferSize/1024, newSize/1024)
|
||||
}
|
||||
logger.Debugf("Increased receive buffer size to %d kiB", newSize/1024)
|
||||
return nil
|
||||
}
|
||||
|
||||
// only print warnings about the UDP receive buffer size once
|
||||
var receiveBufferWarningOnce sync.Once
|
||||
|
||||
func newPacketHandlerMap(
|
||||
c net.PacketConn,
|
||||
connIDLen int,
|
||||
statelessResetKey *StatelessResetKey,
|
||||
tracer logging.Tracer,
|
||||
logger utils.Logger,
|
||||
) (packetHandlerManager, error) {
|
||||
if err := setReceiveBuffer(c, logger); err != nil {
|
||||
if !strings.Contains(err.Error(), "use of closed network connection") {
|
||||
receiveBufferWarningOnce.Do(func() {
|
||||
if disable, _ := strconv.ParseBool(os.Getenv("QUIC_GO_DISABLE_RECEIVE_BUFFER_WARNING")); disable {
|
||||
return
|
||||
}
|
||||
log.Printf("%s. See https://github.com/quic-go/quic-go/wiki/UDP-Receive-Buffer-Size for details.", err)
|
||||
})
|
||||
}
|
||||
}
|
||||
conn, err := wrapConn(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m := &packetHandlerMap{
|
||||
conn: conn,
|
||||
connIDLen: connIDLen,
|
||||
listening: make(chan struct{}),
|
||||
handlers: make(map[protocol.ConnectionID]packetHandler),
|
||||
resetTokens: make(map[protocol.StatelessResetToken]packetHandler),
|
||||
deleteRetiredConnsAfter: protocol.RetiredConnectionIDDeleteTimeout,
|
||||
enqueueClosePacket: enqueueClosePacket,
|
||||
zeroRTTQueueDuration: protocol.Max0RTTQueueingDuration,
|
||||
closeQueue: make(chan closePacket, 4),
|
||||
statelessResetEnabled: statelessResetKey != nil,
|
||||
tracer: tracer,
|
||||
logger: logger,
|
||||
}
|
||||
if key != nil {
|
||||
h.statelessResetHasher = hmac.New(sha256.New, key[:])
|
||||
if m.statelessResetEnabled {
|
||||
m.statelessResetHasher = hmac.New(sha256.New, statelessResetKey[:])
|
||||
}
|
||||
if h.logger.Debug() {
|
||||
go h.logUsage()
|
||||
go m.listen()
|
||||
go m.runCloseQueue()
|
||||
|
||||
if logger.Debug() {
|
||||
go m.logUsage()
|
||||
}
|
||||
return h
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) logUsage() {
|
||||
|
@ -92,7 +153,7 @@ func (h *packetHandlerMap) logUsage() {
|
|||
var printedZero bool
|
||||
for {
|
||||
select {
|
||||
case <-h.closeChan:
|
||||
case <-h.listening:
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
|
@ -113,14 +174,6 @@ func (h *packetHandlerMap) logUsage() {
|
|||
}
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) Get(id protocol.ConnectionID) (packetHandler, bool) {
|
||||
h.mutex.Lock()
|
||||
defer h.mutex.Unlock()
|
||||
|
||||
handler, ok := h.handlers[id]
|
||||
return handler, ok
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) Add(id protocol.ConnectionID, handler packetHandler) bool /* was added */ {
|
||||
h.mutex.Lock()
|
||||
defer h.mutex.Unlock()
|
||||
|
@ -134,17 +187,26 @@ func (h *packetHandlerMap) Add(id protocol.ConnectionID, handler packetHandler)
|
|||
return true
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) AddWithConnID(clientDestConnID, newConnID protocol.ConnectionID, fn func() (packetHandler, bool)) bool {
|
||||
func (h *packetHandlerMap) AddWithConnID(clientDestConnID, newConnID protocol.ConnectionID, fn func() packetHandler) bool {
|
||||
h.mutex.Lock()
|
||||
defer h.mutex.Unlock()
|
||||
|
||||
if _, ok := h.handlers[clientDestConnID]; ok {
|
||||
h.logger.Debugf("Not adding connection ID %s for a new connection, as it already exists.", clientDestConnID)
|
||||
return false
|
||||
var q *zeroRTTQueue
|
||||
if handler, ok := h.handlers[clientDestConnID]; ok {
|
||||
q, ok = handler.(*zeroRTTQueue)
|
||||
if !ok {
|
||||
h.logger.Debugf("Not adding connection ID %s for a new connection, as it already exists.", clientDestConnID)
|
||||
return false
|
||||
}
|
||||
q.retireTimer.Stop()
|
||||
h.numZeroRTTEntries--
|
||||
if h.numZeroRTTEntries < 0 {
|
||||
panic("number of 0-RTT queues < 0")
|
||||
}
|
||||
}
|
||||
conn, ok := fn()
|
||||
if !ok {
|
||||
return false
|
||||
conn := fn()
|
||||
if q != nil {
|
||||
q.EnqueueAll(conn)
|
||||
}
|
||||
h.handlers[clientDestConnID] = conn
|
||||
h.handlers[newConnID] = conn
|
||||
|
@ -177,8 +239,13 @@ func (h *packetHandlerMap) ReplaceWithClosed(ids []protocol.ConnectionID, pers p
|
|||
var handler packetHandler
|
||||
if connClosePacket != nil {
|
||||
handler = newClosedLocalConn(
|
||||
func(addr net.Addr, info packetInfo) {
|
||||
h.enqueueClosePacket(closePacket{payload: connClosePacket, addr: addr, info: info})
|
||||
func(addr net.Addr, info *packetInfo) {
|
||||
select {
|
||||
case h.closeQueue <- closePacket{payload: connClosePacket, addr: addr, info: info}:
|
||||
default:
|
||||
// Oops, we're backlogged.
|
||||
// Just drop the packet, sending CONNECTION_CLOSE copies is best effort anyway.
|
||||
}
|
||||
},
|
||||
pers,
|
||||
h.logger,
|
||||
|
@ -205,6 +272,17 @@ func (h *packetHandlerMap) ReplaceWithClosed(ids []protocol.ConnectionID, pers p
|
|||
})
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) runCloseQueue() {
|
||||
for {
|
||||
select {
|
||||
case <-h.listening:
|
||||
return
|
||||
case p := <-h.closeQueue:
|
||||
h.conn.WritePacket(p.payload, p.addr, p.info.OOB())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) AddResetToken(token protocol.StatelessResetToken, handler packetHandler) {
|
||||
h.mutex.Lock()
|
||||
h.resetTokens[token] = handler
|
||||
|
@ -217,16 +295,19 @@ func (h *packetHandlerMap) RemoveResetToken(token protocol.StatelessResetToken)
|
|||
h.mutex.Unlock()
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) GetByResetToken(token protocol.StatelessResetToken) (packetHandler, bool) {
|
||||
func (h *packetHandlerMap) SetServer(s unknownPacketHandler) {
|
||||
h.mutex.Lock()
|
||||
defer h.mutex.Unlock()
|
||||
|
||||
handler, ok := h.resetTokens[token]
|
||||
return handler, ok
|
||||
h.server = s
|
||||
h.mutex.Unlock()
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) CloseServer() {
|
||||
h.mutex.Lock()
|
||||
if h.server == nil {
|
||||
h.mutex.Unlock()
|
||||
return
|
||||
}
|
||||
h.server = nil
|
||||
var wg sync.WaitGroup
|
||||
for _, handler := range h.handlers {
|
||||
if handler.getPerspective() == protocol.PerspectiveServer {
|
||||
|
@ -242,16 +323,23 @@ func (h *packetHandlerMap) CloseServer() {
|
|||
wg.Wait()
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) Close(e error) {
|
||||
h.mutex.Lock()
|
||||
// Destroy closes the underlying connection and waits until listen() has returned.
|
||||
// It does not close active connections.
|
||||
func (h *packetHandlerMap) Destroy() error {
|
||||
if err := h.conn.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
<-h.listening // wait until listening returns
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) close(e error) error {
|
||||
h.mutex.Lock()
|
||||
if h.closed {
|
||||
h.mutex.Unlock()
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
close(h.closeChan)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for _, handler := range h.handlers {
|
||||
wg.Add(1)
|
||||
|
@ -260,14 +348,129 @@ func (h *packetHandlerMap) Close(e error) {
|
|||
wg.Done()
|
||||
}(handler)
|
||||
}
|
||||
|
||||
if h.server != nil {
|
||||
h.server.setCloseError(e)
|
||||
}
|
||||
h.closed = true
|
||||
h.mutex.Unlock()
|
||||
wg.Wait()
|
||||
return getMultiplexer().RemoveConn(h.conn)
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) listen() {
|
||||
defer close(h.listening)
|
||||
for {
|
||||
p, err := h.conn.ReadPacket()
|
||||
//nolint:staticcheck // SA1019 ignore this!
|
||||
// TODO: This code is used to ignore wsa errors on Windows.
|
||||
// Since net.Error.Temporary is deprecated as of Go 1.18, we should find a better solution.
|
||||
// See https://github.com/quic-go/quic-go/issues/1737 for details.
|
||||
if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
|
||||
h.logger.Debugf("Temporary error reading from conn: %w", err)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
h.close(err)
|
||||
return
|
||||
}
|
||||
h.handlePacket(p)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) handlePacket(p *receivedPacket) {
|
||||
connID, err := wire.ParseConnectionID(p.data, h.connIDLen)
|
||||
if err != nil {
|
||||
h.logger.Debugf("error parsing connection ID on packet from %s: %s", p.remoteAddr, err)
|
||||
if h.tracer != nil {
|
||||
h.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropHeaderParseError)
|
||||
}
|
||||
p.buffer.MaybeRelease()
|
||||
return
|
||||
}
|
||||
|
||||
h.mutex.Lock()
|
||||
defer h.mutex.Unlock()
|
||||
|
||||
if isStatelessReset := h.maybeHandleStatelessReset(p.data); isStatelessReset {
|
||||
return
|
||||
}
|
||||
|
||||
if handler, ok := h.handlers[connID]; ok {
|
||||
if ha, ok := handler.(*zeroRTTQueue); ok { // only enqueue 0-RTT packets in the 0-RTT queue
|
||||
if wire.Is0RTTPacket(p.data) {
|
||||
ha.handlePacket(p)
|
||||
return
|
||||
}
|
||||
} else { // existing connection
|
||||
handler.handlePacket(p)
|
||||
return
|
||||
}
|
||||
}
|
||||
if !wire.IsLongHeaderPacket(p.data[0]) {
|
||||
go h.maybeSendStatelessReset(p, connID)
|
||||
return
|
||||
}
|
||||
if h.server == nil { // no server set
|
||||
h.logger.Debugf("received a packet with an unexpected connection ID %s", connID)
|
||||
return
|
||||
}
|
||||
if wire.Is0RTTPacket(p.data) {
|
||||
if h.numZeroRTTEntries >= protocol.Max0RTTQueues {
|
||||
if h.tracer != nil {
|
||||
h.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropDOSPrevention)
|
||||
}
|
||||
return
|
||||
}
|
||||
h.numZeroRTTEntries++
|
||||
queue := &zeroRTTQueue{queue: make([]*receivedPacket, 0, 8)}
|
||||
h.handlers[connID] = queue
|
||||
queue.retireTimer = time.AfterFunc(h.zeroRTTQueueDuration, func() {
|
||||
h.mutex.Lock()
|
||||
defer h.mutex.Unlock()
|
||||
// The entry might have been replaced by an actual connection.
|
||||
// Only delete it if it's still a 0-RTT queue.
|
||||
if handler, ok := h.handlers[connID]; ok {
|
||||
if q, ok := handler.(*zeroRTTQueue); ok {
|
||||
delete(h.handlers, connID)
|
||||
h.numZeroRTTEntries--
|
||||
if h.numZeroRTTEntries < 0 {
|
||||
panic("number of 0-RTT queues < 0")
|
||||
}
|
||||
q.Clear()
|
||||
if h.logger.Debug() {
|
||||
h.logger.Debugf("Removing 0-RTT queue for %s.", connID)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
queue.handlePacket(p)
|
||||
return
|
||||
}
|
||||
h.server.handlePacket(p)
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) maybeHandleStatelessReset(data []byte) bool {
|
||||
// stateless resets are always short header packets
|
||||
if wire.IsLongHeaderPacket(data[0]) {
|
||||
return false
|
||||
}
|
||||
if len(data) < 17 /* type byte + 16 bytes for the reset token */ {
|
||||
return false
|
||||
}
|
||||
|
||||
token := *(*protocol.StatelessResetToken)(data[len(data)-16:])
|
||||
if sess, ok := h.resetTokens[token]; ok {
|
||||
h.logger.Debugf("Received a stateless reset with token %#x. Closing connection.", token)
|
||||
go sess.destroy(&StatelessResetError{Token: token})
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) GetStatelessResetToken(connID protocol.ConnectionID) protocol.StatelessResetToken {
|
||||
var token protocol.StatelessResetToken
|
||||
if h.statelessResetHasher == nil {
|
||||
if !h.statelessResetEnabled {
|
||||
// Return a random stateless reset token.
|
||||
// This token will be sent in the server's transport parameters.
|
||||
// By using a random token, an off-path attacker won't be able to disrupt the connection.
|
||||
|
@ -281,3 +484,24 @@ func (h *packetHandlerMap) GetStatelessResetToken(connID protocol.ConnectionID)
|
|||
h.statelessResetMutex.Unlock()
|
||||
return token
|
||||
}
|
||||
|
||||
func (h *packetHandlerMap) maybeSendStatelessReset(p *receivedPacket, connID protocol.ConnectionID) {
|
||||
defer p.buffer.Release()
|
||||
if !h.statelessResetEnabled {
|
||||
return
|
||||
}
|
||||
// Don't send a stateless reset in response to very small packets.
|
||||
// This includes packets that could be stateless resets.
|
||||
if len(p.data) <= protocol.MinStatelessResetSize {
|
||||
return
|
||||
}
|
||||
token := h.GetStatelessResetToken(connID)
|
||||
h.logger.Debugf("Sending stateless reset to %s (connection ID: %s). Token: %#x", p.remoteAddr, connID, token)
|
||||
data := make([]byte, protocol.MinStatelessResetSize-16, protocol.MinStatelessResetSize)
|
||||
rand.Read(data)
|
||||
data[0] = (data[0] & 0x7f) | 0x40
|
||||
data = append(data, token[:]...)
|
||||
if _, err := h.conn.WritePacket(data, p.remoteAddr, p.info.OOB()); err != nil {
|
||||
h.logger.Debugf("Error sending Stateless Reset: %s", err)
|
||||
}
|
||||
}
|
||||
|
|
387
vendor/github.com/quic-go/quic-go/packet_packer.go
generated
vendored
387
vendor/github.com/quic-go/quic-go/packet_packer.go
generated
vendored
|
@ -3,25 +3,30 @@ package quic
|
|||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/ackhandler"
|
||||
"github.com/quic-go/quic-go/internal/handshake"
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
"github.com/quic-go/quic-go/internal/qerr"
|
||||
"github.com/quic-go/quic-go/internal/utils"
|
||||
"github.com/quic-go/quic-go/internal/wire"
|
||||
)
|
||||
|
||||
var errNothingToPack = errors.New("nothing to pack")
|
||||
|
||||
type packer interface {
|
||||
PackCoalescedPacket(onlyAck bool, maxPacketSize protocol.ByteCount, v protocol.VersionNumber) (*coalescedPacket, error)
|
||||
PackAckOnlyPacket(maxPacketSize protocol.ByteCount, v protocol.VersionNumber) (shortHeaderPacket, *packetBuffer, error)
|
||||
AppendPacket(buf *packetBuffer, maxPacketSize protocol.ByteCount, v protocol.VersionNumber) (shortHeaderPacket, error)
|
||||
MaybePackProbePacket(protocol.EncryptionLevel, protocol.ByteCount, protocol.VersionNumber) (*coalescedPacket, error)
|
||||
PackConnectionClose(*qerr.TransportError, protocol.ByteCount, protocol.VersionNumber) (*coalescedPacket, error)
|
||||
PackApplicationClose(*qerr.ApplicationError, protocol.ByteCount, protocol.VersionNumber) (*coalescedPacket, error)
|
||||
PackMTUProbePacket(ping ackhandler.Frame, size protocol.ByteCount, v protocol.VersionNumber) (shortHeaderPacket, *packetBuffer, error)
|
||||
PackCoalescedPacket(onlyAck bool, v protocol.VersionNumber) (*coalescedPacket, error)
|
||||
PackPacket(onlyAck bool, now time.Time, v protocol.VersionNumber) (shortHeaderPacket, *packetBuffer, error)
|
||||
MaybePackProbePacket(protocol.EncryptionLevel, protocol.VersionNumber) (*coalescedPacket, error)
|
||||
PackConnectionClose(*qerr.TransportError, protocol.VersionNumber) (*coalescedPacket, error)
|
||||
PackApplicationClose(*qerr.ApplicationError, protocol.VersionNumber) (*coalescedPacket, error)
|
||||
|
||||
SetMaxPacketSize(protocol.ByteCount)
|
||||
PackMTUProbePacket(ping ackhandler.Frame, size protocol.ByteCount, now time.Time, v protocol.VersionNumber) (shortHeaderPacket, *packetBuffer, error)
|
||||
|
||||
HandleTransportParameters(*wire.TransportParameters)
|
||||
SetToken([]byte)
|
||||
}
|
||||
|
||||
|
@ -30,31 +35,26 @@ type sealer interface {
|
|||
}
|
||||
|
||||
type payload struct {
|
||||
streamFrames []ackhandler.StreamFrame
|
||||
frames []ackhandler.Frame
|
||||
ack *wire.AckFrame
|
||||
length protocol.ByteCount
|
||||
}
|
||||
|
||||
type longHeaderPacket struct {
|
||||
header *wire.ExtendedHeader
|
||||
ack *wire.AckFrame
|
||||
frames []ackhandler.Frame
|
||||
streamFrames []ackhandler.StreamFrame // only used for 0-RTT packets
|
||||
|
||||
frames []*ackhandler.Frame
|
||||
ack *wire.AckFrame
|
||||
length protocol.ByteCount
|
||||
}
|
||||
|
||||
type shortHeaderPacket struct {
|
||||
PacketNumber protocol.PacketNumber
|
||||
Frames []ackhandler.Frame
|
||||
StreamFrames []ackhandler.StreamFrame
|
||||
Ack *wire.AckFrame
|
||||
Length protocol.ByteCount
|
||||
IsPathMTUProbePacket bool
|
||||
type longHeaderPacket struct {
|
||||
header *wire.ExtendedHeader
|
||||
ack *wire.AckFrame
|
||||
frames []*ackhandler.Frame
|
||||
|
||||
length protocol.ByteCount
|
||||
|
||||
isMTUProbePacket bool
|
||||
}
|
||||
|
||||
type shortHeaderPacket struct {
|
||||
*ackhandler.Packet
|
||||
// used for logging
|
||||
DestConnID protocol.ConnectionID
|
||||
Ack *wire.AckFrame
|
||||
PacketNumberLen protocol.PacketNumberLen
|
||||
KeyPhase protocol.KeyPhaseBit
|
||||
}
|
||||
|
@ -83,6 +83,52 @@ func (p *longHeaderPacket) EncryptionLevel() protocol.EncryptionLevel {
|
|||
|
||||
func (p *longHeaderPacket) IsAckEliciting() bool { return ackhandler.HasAckElicitingFrames(p.frames) }
|
||||
|
||||
func (p *longHeaderPacket) ToAckHandlerPacket(now time.Time, q *retransmissionQueue) *ackhandler.Packet {
|
||||
largestAcked := protocol.InvalidPacketNumber
|
||||
if p.ack != nil {
|
||||
largestAcked = p.ack.LargestAcked()
|
||||
}
|
||||
encLevel := p.EncryptionLevel()
|
||||
for i := range p.frames {
|
||||
if p.frames[i].OnLost != nil {
|
||||
continue
|
||||
}
|
||||
//nolint:exhaustive // Short header packets are handled separately.
|
||||
switch encLevel {
|
||||
case protocol.EncryptionInitial:
|
||||
p.frames[i].OnLost = q.AddInitial
|
||||
case protocol.EncryptionHandshake:
|
||||
p.frames[i].OnLost = q.AddHandshake
|
||||
case protocol.Encryption0RTT:
|
||||
p.frames[i].OnLost = q.AddAppData
|
||||
}
|
||||
}
|
||||
|
||||
ap := ackhandler.GetPacket()
|
||||
ap.PacketNumber = p.header.PacketNumber
|
||||
ap.LargestAcked = largestAcked
|
||||
ap.Frames = p.frames
|
||||
ap.Length = p.length
|
||||
ap.EncryptionLevel = encLevel
|
||||
ap.SendTime = now
|
||||
ap.IsPathMTUProbePacket = p.isMTUProbePacket
|
||||
return ap
|
||||
}
|
||||
|
||||
func getMaxPacketSize(addr net.Addr) protocol.ByteCount {
|
||||
maxSize := protocol.ByteCount(protocol.MinInitialPacketSize)
|
||||
// If this is not a UDP address, we don't know anything about the MTU.
|
||||
// Use the minimum size of an Initial packet as the max packet size.
|
||||
if udpAddr, ok := addr.(*net.UDPAddr); ok {
|
||||
if utils.IsIPv4(udpAddr.IP) {
|
||||
maxSize = protocol.InitialPacketSizeIPv4
|
||||
} else {
|
||||
maxSize = protocol.InitialPacketSizeIPv6
|
||||
}
|
||||
}
|
||||
return maxSize
|
||||
}
|
||||
|
||||
type packetNumberManager interface {
|
||||
PeekPacketNumber(protocol.EncryptionLevel) (protocol.PacketNumber, protocol.PacketNumberLen)
|
||||
PopPacketNumber(protocol.EncryptionLevel) protocol.PacketNumber
|
||||
|
@ -97,8 +143,8 @@ type sealingManager interface {
|
|||
|
||||
type frameSource interface {
|
||||
HasData() bool
|
||||
AppendStreamFrames([]ackhandler.StreamFrame, protocol.ByteCount, protocol.VersionNumber) ([]ackhandler.StreamFrame, protocol.ByteCount)
|
||||
AppendControlFrames([]ackhandler.Frame, protocol.ByteCount, protocol.VersionNumber) ([]ackhandler.Frame, protocol.ByteCount)
|
||||
AppendStreamFrames([]*ackhandler.Frame, protocol.ByteCount, protocol.VersionNumber) ([]*ackhandler.Frame, protocol.ByteCount)
|
||||
AppendControlFrames([]*ackhandler.Frame, protocol.ByteCount, protocol.VersionNumber) ([]*ackhandler.Frame, protocol.ByteCount)
|
||||
}
|
||||
|
||||
type ackFrameSource interface {
|
||||
|
@ -123,23 +169,13 @@ type packetPacker struct {
|
|||
datagramQueue *datagramQueue
|
||||
retransmissionQueue *retransmissionQueue
|
||||
|
||||
maxPacketSize protocol.ByteCount
|
||||
numNonAckElicitingAcks int
|
||||
}
|
||||
|
||||
var _ packer = &packetPacker{}
|
||||
|
||||
func newPacketPacker(
|
||||
srcConnID protocol.ConnectionID,
|
||||
getDestConnID func() protocol.ConnectionID,
|
||||
initialStream, handshakeStream cryptoStream,
|
||||
packetNumberManager packetNumberManager,
|
||||
retransmissionQueue *retransmissionQueue,
|
||||
cryptoSetup sealingManager,
|
||||
framer frameSource,
|
||||
acks ackFrameSource,
|
||||
datagramQueue *datagramQueue,
|
||||
perspective protocol.Perspective,
|
||||
) *packetPacker {
|
||||
func newPacketPacker(srcConnID protocol.ConnectionID, getDestConnID func() protocol.ConnectionID, initialStream cryptoStream, handshakeStream cryptoStream, packetNumberManager packetNumberManager, retransmissionQueue *retransmissionQueue, remoteAddr net.Addr, cryptoSetup sealingManager, framer frameSource, acks ackFrameSource, datagramQueue *datagramQueue, perspective protocol.Perspective) *packetPacker {
|
||||
return &packetPacker{
|
||||
cryptoSetup: cryptoSetup,
|
||||
getDestConnID: getDestConnID,
|
||||
|
@ -152,22 +188,23 @@ func newPacketPacker(
|
|||
framer: framer,
|
||||
acks: acks,
|
||||
pnManager: packetNumberManager,
|
||||
maxPacketSize: getMaxPacketSize(remoteAddr),
|
||||
}
|
||||
}
|
||||
|
||||
// PackConnectionClose packs a packet that closes the connection with a transport error.
|
||||
func (p *packetPacker) PackConnectionClose(e *qerr.TransportError, maxPacketSize protocol.ByteCount, v protocol.VersionNumber) (*coalescedPacket, error) {
|
||||
func (p *packetPacker) PackConnectionClose(e *qerr.TransportError, v protocol.VersionNumber) (*coalescedPacket, error) {
|
||||
var reason string
|
||||
// don't send details of crypto errors
|
||||
if !e.ErrorCode.IsCryptoError() {
|
||||
reason = e.ErrorMessage
|
||||
}
|
||||
return p.packConnectionClose(false, uint64(e.ErrorCode), e.FrameType, reason, maxPacketSize, v)
|
||||
return p.packConnectionClose(false, uint64(e.ErrorCode), e.FrameType, reason, v)
|
||||
}
|
||||
|
||||
// PackApplicationClose packs a packet that closes the connection with an application error.
|
||||
func (p *packetPacker) PackApplicationClose(e *qerr.ApplicationError, maxPacketSize protocol.ByteCount, v protocol.VersionNumber) (*coalescedPacket, error) {
|
||||
return p.packConnectionClose(true, uint64(e.ErrorCode), 0, e.ErrorMessage, maxPacketSize, v)
|
||||
func (p *packetPacker) PackApplicationClose(e *qerr.ApplicationError, v protocol.VersionNumber) (*coalescedPacket, error) {
|
||||
return p.packConnectionClose(true, uint64(e.ErrorCode), 0, e.ErrorMessage, v)
|
||||
}
|
||||
|
||||
func (p *packetPacker) packConnectionClose(
|
||||
|
@ -175,7 +212,6 @@ func (p *packetPacker) packConnectionClose(
|
|||
errorCode uint64,
|
||||
frameType uint64,
|
||||
reason string,
|
||||
maxPacketSize protocol.ByteCount,
|
||||
v protocol.VersionNumber,
|
||||
) (*coalescedPacket, error) {
|
||||
var sealers [4]sealer
|
||||
|
@ -205,7 +241,7 @@ func (p *packetPacker) packConnectionClose(
|
|||
ccf.ReasonPhrase = ""
|
||||
}
|
||||
pl := payload{
|
||||
frames: []ackhandler.Frame{{Frame: ccf}},
|
||||
frames: []*ackhandler.Frame{{Frame: ccf}},
|
||||
length: ccf.Length(v),
|
||||
}
|
||||
|
||||
|
@ -257,14 +293,20 @@ func (p *packetPacker) packConnectionClose(
|
|||
}
|
||||
var paddingLen protocol.ByteCount
|
||||
if encLevel == protocol.EncryptionInitial {
|
||||
paddingLen = p.initialPaddingLen(payloads[i].frames, size, maxPacketSize)
|
||||
paddingLen = p.initialPaddingLen(payloads[i].frames, size)
|
||||
}
|
||||
if encLevel == protocol.Encryption1RTT {
|
||||
shp, err := p.appendShortHeaderPacket(buffer, connID, oneRTTPacketNumber, oneRTTPacketNumberLen, keyPhase, payloads[i], paddingLen, maxPacketSize, sealers[i], false, v)
|
||||
ap, ack, err := p.appendShortHeaderPacket(buffer, connID, oneRTTPacketNumber, oneRTTPacketNumberLen, keyPhase, payloads[i], paddingLen, sealers[i], false, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packet.shortHdrPacket = &shp
|
||||
packet.shortHdrPacket = &shortHeaderPacket{
|
||||
Packet: ap,
|
||||
DestConnID: connID,
|
||||
Ack: ack,
|
||||
PacketNumberLen: oneRTTPacketNumberLen,
|
||||
KeyPhase: keyPhase,
|
||||
}
|
||||
} else {
|
||||
longHdrPacket, err := p.appendLongHeaderPacket(buffer, hdrs[i], payloads[i], paddingLen, encLevel, sealers[i], v)
|
||||
if err != nil {
|
||||
|
@ -300,21 +342,25 @@ func (p *packetPacker) shortHeaderPacketLength(connID protocol.ConnectionID, pnL
|
|||
}
|
||||
|
||||
// size is the expected size of the packet, if no padding was applied.
|
||||
func (p *packetPacker) initialPaddingLen(frames []ackhandler.Frame, currentSize, maxPacketSize protocol.ByteCount) protocol.ByteCount {
|
||||
func (p *packetPacker) initialPaddingLen(frames []*ackhandler.Frame, size protocol.ByteCount) protocol.ByteCount {
|
||||
// For the server, only ack-eliciting Initial packets need to be padded.
|
||||
if p.perspective == protocol.PerspectiveServer && !ackhandler.HasAckElicitingFrames(frames) {
|
||||
return 0
|
||||
}
|
||||
if currentSize >= maxPacketSize {
|
||||
if size >= p.maxPacketSize {
|
||||
return 0
|
||||
}
|
||||
return maxPacketSize - currentSize
|
||||
return p.maxPacketSize - size
|
||||
}
|
||||
|
||||
// PackCoalescedPacket packs a new packet.
|
||||
// It packs an Initial / Handshake if there is data to send in these packet number spaces.
|
||||
// It should only be called before the handshake is confirmed.
|
||||
func (p *packetPacker) PackCoalescedPacket(onlyAck bool, maxPacketSize protocol.ByteCount, v protocol.VersionNumber) (*coalescedPacket, error) {
|
||||
func (p *packetPacker) PackCoalescedPacket(onlyAck bool, v protocol.VersionNumber) (*coalescedPacket, error) {
|
||||
maxPacketSize := p.maxPacketSize
|
||||
if p.perspective == protocol.PerspectiveClient {
|
||||
maxPacketSize = protocol.MinInitialPacketSize
|
||||
}
|
||||
var (
|
||||
initialHdr, handshakeHdr, zeroRTTHdr *wire.ExtendedHeader
|
||||
initialPayload, handshakePayload, zeroRTTPayload, oneRTTPayload payload
|
||||
|
@ -371,7 +417,7 @@ func (p *packetPacker) PackCoalescedPacket(onlyAck bool, maxPacketSize protocol.
|
|||
if oneRTTPayload.length > 0 {
|
||||
size += p.shortHeaderPacketLength(connID, oneRTTPacketNumberLen, oneRTTPayload) + protocol.ByteCount(oneRTTSealer.Overhead())
|
||||
}
|
||||
} else if p.perspective == protocol.PerspectiveClient && !onlyAck { // 0-RTT packets can't contain ACK frames
|
||||
} else if p.perspective == protocol.PerspectiveClient { // 0-RTT
|
||||
var err error
|
||||
zeroRTTSealer, err = p.cryptoSetup.Get0RTTSealer()
|
||||
if err != nil && err != handshake.ErrKeysDropped && err != handshake.ErrKeysNotYetAvailable {
|
||||
|
@ -396,7 +442,7 @@ func (p *packetPacker) PackCoalescedPacket(onlyAck bool, maxPacketSize protocol.
|
|||
longHdrPackets: make([]*longHeaderPacket, 0, 3),
|
||||
}
|
||||
if initialPayload.length > 0 {
|
||||
padding := p.initialPaddingLen(initialPayload.frames, size, maxPacketSize)
|
||||
padding := p.initialPaddingLen(initialPayload.frames, size)
|
||||
cont, err := p.appendLongHeaderPacket(buffer, initialHdr, initialPayload, padding, protocol.EncryptionInitial, initialSealer, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -417,44 +463,48 @@ func (p *packetPacker) PackCoalescedPacket(onlyAck bool, maxPacketSize protocol.
|
|||
}
|
||||
packet.longHdrPackets = append(packet.longHdrPackets, longHdrPacket)
|
||||
} else if oneRTTPayload.length > 0 {
|
||||
shp, err := p.appendShortHeaderPacket(buffer, connID, oneRTTPacketNumber, oneRTTPacketNumberLen, kp, oneRTTPayload, 0, maxPacketSize, oneRTTSealer, false, v)
|
||||
ap, ack, err := p.appendShortHeaderPacket(buffer, connID, oneRTTPacketNumber, oneRTTPacketNumberLen, kp, oneRTTPayload, 0, oneRTTSealer, false, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packet.shortHdrPacket = &shp
|
||||
packet.shortHdrPacket = &shortHeaderPacket{
|
||||
Packet: ap,
|
||||
DestConnID: connID,
|
||||
Ack: ack,
|
||||
PacketNumberLen: oneRTTPacketNumberLen,
|
||||
KeyPhase: kp,
|
||||
}
|
||||
}
|
||||
return packet, nil
|
||||
}
|
||||
|
||||
// PackAckOnlyPacket packs a packet containing only an ACK in the application data packet number space.
|
||||
// PackPacket packs a packet in the application data packet number space.
|
||||
// It should be called after the handshake is confirmed.
|
||||
func (p *packetPacker) PackAckOnlyPacket(maxPacketSize protocol.ByteCount, v protocol.VersionNumber) (shortHeaderPacket, *packetBuffer, error) {
|
||||
buf := getPacketBuffer()
|
||||
packet, err := p.appendPacket(buf, true, maxPacketSize, v)
|
||||
return packet, buf, err
|
||||
}
|
||||
|
||||
// AppendPacket packs a packet in the application data packet number space.
|
||||
// It should be called after the handshake is confirmed.
|
||||
func (p *packetPacker) AppendPacket(buf *packetBuffer, maxPacketSize protocol.ByteCount, v protocol.VersionNumber) (shortHeaderPacket, error) {
|
||||
return p.appendPacket(buf, false, maxPacketSize, v)
|
||||
}
|
||||
|
||||
func (p *packetPacker) appendPacket(buf *packetBuffer, onlyAck bool, maxPacketSize protocol.ByteCount, v protocol.VersionNumber) (shortHeaderPacket, error) {
|
||||
func (p *packetPacker) PackPacket(onlyAck bool, now time.Time, v protocol.VersionNumber) (shortHeaderPacket, *packetBuffer, error) {
|
||||
sealer, err := p.cryptoSetup.Get1RTTSealer()
|
||||
if err != nil {
|
||||
return shortHeaderPacket{}, err
|
||||
return shortHeaderPacket{}, nil, err
|
||||
}
|
||||
pn, pnLen := p.pnManager.PeekPacketNumber(protocol.Encryption1RTT)
|
||||
connID := p.getDestConnID()
|
||||
hdrLen := wire.ShortHeaderLen(connID, pnLen)
|
||||
pl := p.maybeGetShortHeaderPacket(sealer, hdrLen, maxPacketSize, onlyAck, true, v)
|
||||
pl := p.maybeGetShortHeaderPacket(sealer, hdrLen, p.maxPacketSize, onlyAck, true, v)
|
||||
if pl.length == 0 {
|
||||
return shortHeaderPacket{}, errNothingToPack
|
||||
return shortHeaderPacket{}, nil, errNothingToPack
|
||||
}
|
||||
kp := sealer.KeyPhase()
|
||||
|
||||
return p.appendShortHeaderPacket(buf, connID, pn, pnLen, kp, pl, 0, maxPacketSize, sealer, false, v)
|
||||
buffer := getPacketBuffer()
|
||||
ap, ack, err := p.appendShortHeaderPacket(buffer, connID, pn, pnLen, kp, pl, 0, sealer, false, v)
|
||||
if err != nil {
|
||||
return shortHeaderPacket{}, nil, err
|
||||
}
|
||||
return shortHeaderPacket{
|
||||
Packet: ap,
|
||||
DestConnID: connID,
|
||||
Ack: ack,
|
||||
PacketNumberLen: pnLen,
|
||||
KeyPhase: kp,
|
||||
}, buffer, nil
|
||||
}
|
||||
|
||||
func (p *packetPacker) maybeGetCryptoPacket(maxPacketSize protocol.ByteCount, encLevel protocol.EncryptionLevel, onlyAck, ackAllowed bool, v protocol.VersionNumber) (*wire.ExtendedHeader, payload) {
|
||||
|
@ -469,17 +519,14 @@ func (p *packetPacker) maybeGetCryptoPacket(maxPacketSize protocol.ByteCount, en
|
|||
}
|
||||
|
||||
var s cryptoStream
|
||||
var handler ackhandler.FrameHandler
|
||||
var hasRetransmission bool
|
||||
//nolint:exhaustive // Initial and Handshake are the only two encryption levels here.
|
||||
switch encLevel {
|
||||
case protocol.EncryptionInitial:
|
||||
s = p.initialStream
|
||||
handler = p.retransmissionQueue.InitialAckHandler()
|
||||
hasRetransmission = p.retransmissionQueue.HasInitialData()
|
||||
case protocol.EncryptionHandshake:
|
||||
s = p.handshakeStream
|
||||
handler = p.retransmissionQueue.HandshakeAckHandler()
|
||||
hasRetransmission = p.retransmissionQueue.HasHandshakeData()
|
||||
}
|
||||
|
||||
|
@ -503,27 +550,27 @@ func (p *packetPacker) maybeGetCryptoPacket(maxPacketSize protocol.ByteCount, en
|
|||
maxPacketSize -= hdr.GetLength(v)
|
||||
if hasRetransmission {
|
||||
for {
|
||||
var f ackhandler.Frame
|
||||
var f wire.Frame
|
||||
//nolint:exhaustive // 0-RTT packets can't contain any retransmission.s
|
||||
switch encLevel {
|
||||
case protocol.EncryptionInitial:
|
||||
f.Frame = p.retransmissionQueue.GetInitialFrame(maxPacketSize, v)
|
||||
f.Handler = p.retransmissionQueue.InitialAckHandler()
|
||||
f = p.retransmissionQueue.GetInitialFrame(maxPacketSize, v)
|
||||
case protocol.EncryptionHandshake:
|
||||
f.Frame = p.retransmissionQueue.GetHandshakeFrame(maxPacketSize, v)
|
||||
f.Handler = p.retransmissionQueue.HandshakeAckHandler()
|
||||
f = p.retransmissionQueue.GetHandshakeFrame(maxPacketSize, v)
|
||||
}
|
||||
if f.Frame == nil {
|
||||
if f == nil {
|
||||
break
|
||||
}
|
||||
pl.frames = append(pl.frames, f)
|
||||
frameLen := f.Frame.Length(v)
|
||||
af := ackhandler.GetFrame()
|
||||
af.Frame = f
|
||||
pl.frames = append(pl.frames, af)
|
||||
frameLen := f.Length(v)
|
||||
pl.length += frameLen
|
||||
maxPacketSize -= frameLen
|
||||
}
|
||||
} else if s.HasData() {
|
||||
cf := s.PopCryptoFrame(maxPacketSize)
|
||||
pl.frames = []ackhandler.Frame{{Frame: cf, Handler: handler}}
|
||||
pl.frames = []*ackhandler.Frame{{Frame: cf}}
|
||||
pl.length += cf.Length(v)
|
||||
}
|
||||
return hdr, pl
|
||||
|
@ -548,14 +595,18 @@ func (p *packetPacker) maybeGetAppDataPacket(maxPayloadSize protocol.ByteCount,
|
|||
pl := p.composeNextPacket(maxPayloadSize, onlyAck, ackAllowed, v)
|
||||
|
||||
// check if we have anything to send
|
||||
if len(pl.frames) == 0 && len(pl.streamFrames) == 0 {
|
||||
if len(pl.frames) == 0 {
|
||||
if pl.ack == nil {
|
||||
return payload{}
|
||||
}
|
||||
// the packet only contains an ACK
|
||||
if p.numNonAckElicitingAcks >= protocol.MaxNonAckElicitingAcks {
|
||||
ping := &wire.PingFrame{}
|
||||
pl.frames = append(pl.frames, ackhandler.Frame{Frame: ping})
|
||||
// don't retransmit the PING frame when it is lost
|
||||
af := ackhandler.GetFrame()
|
||||
af.Frame = ping
|
||||
af.OnLost = func(wire.Frame) {}
|
||||
pl.frames = append(pl.frames, af)
|
||||
pl.length += ping.Length(v)
|
||||
p.numNonAckElicitingAcks = 0
|
||||
} else {
|
||||
|
@ -570,12 +621,15 @@ func (p *packetPacker) maybeGetAppDataPacket(maxPayloadSize protocol.ByteCount,
|
|||
func (p *packetPacker) composeNextPacket(maxFrameSize protocol.ByteCount, onlyAck, ackAllowed bool, v protocol.VersionNumber) payload {
|
||||
if onlyAck {
|
||||
if ack := p.acks.GetAckFrame(protocol.Encryption1RTT, true); ack != nil {
|
||||
return payload{ack: ack, length: ack.Length(v)}
|
||||
return payload{
|
||||
ack: ack,
|
||||
length: ack.Length(v),
|
||||
}
|
||||
}
|
||||
return payload{}
|
||||
}
|
||||
|
||||
pl := payload{streamFrames: make([]ackhandler.StreamFrame, 0, 1)}
|
||||
pl := payload{frames: make([]*ackhandler.Frame, 0, 1)}
|
||||
|
||||
hasData := p.framer.HasData()
|
||||
hasRetransmission := p.retransmissionQueue.HasAppData()
|
||||
|
@ -593,7 +647,11 @@ func (p *packetPacker) composeNextPacket(maxFrameSize protocol.ByteCount, onlyAc
|
|||
if f := p.datagramQueue.Peek(); f != nil {
|
||||
size := f.Length(v)
|
||||
if size <= maxFrameSize-pl.length {
|
||||
pl.frames = append(pl.frames, ackhandler.Frame{Frame: f})
|
||||
af := ackhandler.GetFrame()
|
||||
af.Frame = f
|
||||
// set it to a no-op. Then we won't set the default callback, which would retransmit the frame.
|
||||
af.OnLost = func(wire.Frame) {}
|
||||
pl.frames = append(pl.frames, af)
|
||||
pl.length += size
|
||||
p.datagramQueue.Pop()
|
||||
}
|
||||
|
@ -614,28 +672,25 @@ func (p *packetPacker) composeNextPacket(maxFrameSize protocol.ByteCount, onlyAc
|
|||
if f == nil {
|
||||
break
|
||||
}
|
||||
pl.frames = append(pl.frames, ackhandler.Frame{Frame: f, Handler: p.retransmissionQueue.AppDataAckHandler()})
|
||||
af := ackhandler.GetFrame()
|
||||
af.Frame = f
|
||||
pl.frames = append(pl.frames, af)
|
||||
pl.length += f.Length(v)
|
||||
}
|
||||
}
|
||||
|
||||
if hasData {
|
||||
var lengthAdded protocol.ByteCount
|
||||
startLen := len(pl.frames)
|
||||
pl.frames, lengthAdded = p.framer.AppendControlFrames(pl.frames, maxFrameSize-pl.length, v)
|
||||
pl.length += lengthAdded
|
||||
// add handlers for the control frames that were added
|
||||
for i := startLen; i < len(pl.frames); i++ {
|
||||
pl.frames[i].Handler = p.retransmissionQueue.AppDataAckHandler()
|
||||
}
|
||||
|
||||
pl.streamFrames, lengthAdded = p.framer.AppendStreamFrames(pl.streamFrames, maxFrameSize-pl.length, v)
|
||||
pl.frames, lengthAdded = p.framer.AppendStreamFrames(pl.frames, maxFrameSize-pl.length, v)
|
||||
pl.length += lengthAdded
|
||||
}
|
||||
return pl
|
||||
}
|
||||
|
||||
func (p *packetPacker) MaybePackProbePacket(encLevel protocol.EncryptionLevel, maxPacketSize protocol.ByteCount, v protocol.VersionNumber) (*coalescedPacket, error) {
|
||||
func (p *packetPacker) MaybePackProbePacket(encLevel protocol.EncryptionLevel, v protocol.VersionNumber) (*coalescedPacket, error) {
|
||||
if encLevel == protocol.Encryption1RTT {
|
||||
s, err := p.cryptoSetup.Get1RTTSealer()
|
||||
if err != nil {
|
||||
|
@ -645,17 +700,23 @@ func (p *packetPacker) MaybePackProbePacket(encLevel protocol.EncryptionLevel, m
|
|||
connID := p.getDestConnID()
|
||||
pn, pnLen := p.pnManager.PeekPacketNumber(protocol.Encryption1RTT)
|
||||
hdrLen := wire.ShortHeaderLen(connID, pnLen)
|
||||
pl := p.maybeGetAppDataPacket(maxPacketSize-protocol.ByteCount(s.Overhead())-hdrLen, false, true, v)
|
||||
pl := p.maybeGetAppDataPacket(p.maxPacketSize-protocol.ByteCount(s.Overhead())-hdrLen, false, true, v)
|
||||
if pl.length == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
buffer := getPacketBuffer()
|
||||
packet := &coalescedPacket{buffer: buffer}
|
||||
shp, err := p.appendShortHeaderPacket(buffer, connID, pn, pnLen, kp, pl, 0, maxPacketSize, s, false, v)
|
||||
ap, ack, err := p.appendShortHeaderPacket(buffer, connID, pn, pnLen, kp, pl, 0, s, false, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
packet.shortHdrPacket = &shp
|
||||
packet.shortHdrPacket = &shortHeaderPacket{
|
||||
Packet: ap,
|
||||
DestConnID: connID,
|
||||
Ack: ack,
|
||||
PacketNumberLen: pnLen,
|
||||
KeyPhase: kp,
|
||||
}
|
||||
return packet, nil
|
||||
}
|
||||
|
||||
|
@ -670,14 +731,14 @@ func (p *packetPacker) MaybePackProbePacket(encLevel protocol.EncryptionLevel, m
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hdr, pl = p.maybeGetCryptoPacket(maxPacketSize-protocol.ByteCount(sealer.Overhead()), protocol.EncryptionInitial, false, true, v)
|
||||
hdr, pl = p.maybeGetCryptoPacket(p.maxPacketSize-protocol.ByteCount(sealer.Overhead()), protocol.EncryptionInitial, false, true, v)
|
||||
case protocol.EncryptionHandshake:
|
||||
var err error
|
||||
sealer, err = p.cryptoSetup.GetHandshakeSealer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hdr, pl = p.maybeGetCryptoPacket(maxPacketSize-protocol.ByteCount(sealer.Overhead()), protocol.EncryptionHandshake, false, true, v)
|
||||
hdr, pl = p.maybeGetCryptoPacket(p.maxPacketSize-protocol.ByteCount(sealer.Overhead()), protocol.EncryptionHandshake, false, true, v)
|
||||
default:
|
||||
panic("unknown encryption level")
|
||||
}
|
||||
|
@ -690,7 +751,7 @@ func (p *packetPacker) MaybePackProbePacket(encLevel protocol.EncryptionLevel, m
|
|||
size := p.longHeaderPacketLength(hdr, pl, v) + protocol.ByteCount(sealer.Overhead())
|
||||
var padding protocol.ByteCount
|
||||
if encLevel == protocol.EncryptionInitial {
|
||||
padding = p.initialPaddingLen(pl.frames, size, maxPacketSize)
|
||||
padding = p.initialPaddingLen(pl.frames, size)
|
||||
}
|
||||
|
||||
longHdrPacket, err := p.appendLongHeaderPacket(buffer, hdr, pl, padding, encLevel, sealer, v)
|
||||
|
@ -701,10 +762,10 @@ func (p *packetPacker) MaybePackProbePacket(encLevel protocol.EncryptionLevel, m
|
|||
return packet, nil
|
||||
}
|
||||
|
||||
func (p *packetPacker) PackMTUProbePacket(ping ackhandler.Frame, size protocol.ByteCount, v protocol.VersionNumber) (shortHeaderPacket, *packetBuffer, error) {
|
||||
func (p *packetPacker) PackMTUProbePacket(ping ackhandler.Frame, size protocol.ByteCount, now time.Time, v protocol.VersionNumber) (shortHeaderPacket, *packetBuffer, error) {
|
||||
pl := payload{
|
||||
frames: []ackhandler.Frame{ping},
|
||||
length: ping.Frame.Length(v),
|
||||
frames: []*ackhandler.Frame{&ping},
|
||||
length: ping.Length(v),
|
||||
}
|
||||
buffer := getPacketBuffer()
|
||||
s, err := p.cryptoSetup.Get1RTTSealer()
|
||||
|
@ -715,8 +776,17 @@ func (p *packetPacker) PackMTUProbePacket(ping ackhandler.Frame, size protocol.B
|
|||
pn, pnLen := p.pnManager.PeekPacketNumber(protocol.Encryption1RTT)
|
||||
padding := size - p.shortHeaderPacketLength(connID, pnLen, pl) - protocol.ByteCount(s.Overhead())
|
||||
kp := s.KeyPhase()
|
||||
packet, err := p.appendShortHeaderPacket(buffer, connID, pn, pnLen, kp, pl, padding, size, s, true, v)
|
||||
return packet, buffer, err
|
||||
ap, ack, err := p.appendShortHeaderPacket(buffer, connID, pn, pnLen, kp, pl, padding, s, true, v)
|
||||
if err != nil {
|
||||
return shortHeaderPacket{}, nil, err
|
||||
}
|
||||
return shortHeaderPacket{
|
||||
Packet: ap,
|
||||
DestConnID: connID,
|
||||
Ack: ack,
|
||||
PacketNumberLen: pnLen,
|
||||
KeyPhase: kp,
|
||||
}, buffer, nil
|
||||
}
|
||||
|
||||
func (p *packetPacker) getLongHeader(encLevel protocol.EncryptionLevel, v protocol.VersionNumber) *wire.ExtendedHeader {
|
||||
|
@ -759,22 +829,23 @@ func (p *packetPacker) appendLongHeaderPacket(buffer *packetBuffer, header *wire
|
|||
}
|
||||
payloadOffset := protocol.ByteCount(len(raw))
|
||||
|
||||
pn := p.pnManager.PopPacketNumber(encLevel)
|
||||
if pn != header.PacketNumber {
|
||||
return nil, errors.New("packetPacker BUG: Peeked and Popped packet numbers do not match")
|
||||
}
|
||||
|
||||
raw, err = p.appendPacketPayload(raw, pl, paddingLen, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw = p.encryptPacket(raw, sealer, header.PacketNumber, payloadOffset, pnLen)
|
||||
raw = p.encryptPacket(raw, sealer, pn, payloadOffset, pnLen)
|
||||
buffer.Data = buffer.Data[:len(buffer.Data)+len(raw)]
|
||||
|
||||
if pn := p.pnManager.PopPacketNumber(encLevel); pn != header.PacketNumber {
|
||||
return nil, fmt.Errorf("packetPacker BUG: Peeked and Popped packet numbers do not match: expected %d, got %d", pn, header.PacketNumber)
|
||||
}
|
||||
return &longHeaderPacket{
|
||||
header: header,
|
||||
ack: pl.ack,
|
||||
frames: pl.frames,
|
||||
streamFrames: pl.streamFrames,
|
||||
length: protocol.ByteCount(len(raw)),
|
||||
header: header,
|
||||
ack: pl.ack,
|
||||
frames: pl.frames,
|
||||
length: protocol.ByteCount(len(raw)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
@ -785,11 +856,11 @@ func (p *packetPacker) appendShortHeaderPacket(
|
|||
pnLen protocol.PacketNumberLen,
|
||||
kp protocol.KeyPhaseBit,
|
||||
pl payload,
|
||||
padding, maxPacketSize protocol.ByteCount,
|
||||
padding protocol.ByteCount,
|
||||
sealer sealer,
|
||||
isMTUProbePacket bool,
|
||||
v protocol.VersionNumber,
|
||||
) (shortHeaderPacket, error) {
|
||||
) (*ackhandler.Packet, *wire.AckFrame, error) {
|
||||
var paddingLen protocol.ByteCount
|
||||
if pl.length < 4-protocol.ByteCount(pnLen) {
|
||||
paddingLen = 4 - protocol.ByteCount(pnLen) - pl.length
|
||||
|
@ -800,36 +871,48 @@ func (p *packetPacker) appendShortHeaderPacket(
|
|||
raw := buffer.Data[startLen:]
|
||||
raw, err := wire.AppendShortHeader(raw, connID, pn, pnLen, kp)
|
||||
if err != nil {
|
||||
return shortHeaderPacket{}, err
|
||||
return nil, nil, err
|
||||
}
|
||||
payloadOffset := protocol.ByteCount(len(raw))
|
||||
|
||||
if pn != p.pnManager.PopPacketNumber(protocol.Encryption1RTT) {
|
||||
return nil, nil, errors.New("packetPacker BUG: Peeked and Popped packet numbers do not match")
|
||||
}
|
||||
|
||||
raw, err = p.appendPacketPayload(raw, pl, paddingLen, v)
|
||||
if err != nil {
|
||||
return shortHeaderPacket{}, err
|
||||
return nil, nil, err
|
||||
}
|
||||
if !isMTUProbePacket {
|
||||
if size := protocol.ByteCount(len(raw) + sealer.Overhead()); size > maxPacketSize {
|
||||
return shortHeaderPacket{}, fmt.Errorf("PacketPacker BUG: packet too large (%d bytes, allowed %d bytes)", size, maxPacketSize)
|
||||
if size := protocol.ByteCount(len(raw) + sealer.Overhead()); size > p.maxPacketSize {
|
||||
return nil, nil, fmt.Errorf("PacketPacker BUG: packet too large (%d bytes, allowed %d bytes)", size, p.maxPacketSize)
|
||||
}
|
||||
}
|
||||
raw = p.encryptPacket(raw, sealer, pn, payloadOffset, protocol.ByteCount(pnLen))
|
||||
buffer.Data = buffer.Data[:len(buffer.Data)+len(raw)]
|
||||
|
||||
if newPN := p.pnManager.PopPacketNumber(protocol.Encryption1RTT); newPN != pn {
|
||||
return shortHeaderPacket{}, fmt.Errorf("packetPacker BUG: Peeked and Popped packet numbers do not match: expected %d, got %d", pn, newPN)
|
||||
// create the ackhandler.Packet
|
||||
largestAcked := protocol.InvalidPacketNumber
|
||||
if pl.ack != nil {
|
||||
largestAcked = pl.ack.LargestAcked()
|
||||
}
|
||||
return shortHeaderPacket{
|
||||
PacketNumber: pn,
|
||||
PacketNumberLen: pnLen,
|
||||
KeyPhase: kp,
|
||||
StreamFrames: pl.streamFrames,
|
||||
Frames: pl.frames,
|
||||
Ack: pl.ack,
|
||||
Length: protocol.ByteCount(len(raw)),
|
||||
DestConnID: connID,
|
||||
IsPathMTUProbePacket: isMTUProbePacket,
|
||||
}, nil
|
||||
for i := range pl.frames {
|
||||
if pl.frames[i].OnLost != nil {
|
||||
continue
|
||||
}
|
||||
pl.frames[i].OnLost = p.retransmissionQueue.AddAppData
|
||||
}
|
||||
|
||||
ap := ackhandler.GetPacket()
|
||||
ap.PacketNumber = pn
|
||||
ap.LargestAcked = largestAcked
|
||||
ap.Frames = pl.frames
|
||||
ap.Length = protocol.ByteCount(len(raw))
|
||||
ap.EncryptionLevel = protocol.Encryption1RTT
|
||||
ap.SendTime = time.Now()
|
||||
ap.IsPathMTUProbePacket = isMTUProbePacket
|
||||
|
||||
return ap, pl.ack, nil
|
||||
}
|
||||
|
||||
func (p *packetPacker) appendPacketPayload(raw []byte, pl payload, paddingLen protocol.ByteCount, v protocol.VersionNumber) ([]byte, error) {
|
||||
|
@ -844,16 +927,9 @@ func (p *packetPacker) appendPacketPayload(raw []byte, pl payload, paddingLen pr
|
|||
if paddingLen > 0 {
|
||||
raw = append(raw, make([]byte, paddingLen)...)
|
||||
}
|
||||
for _, f := range pl.frames {
|
||||
for _, frame := range pl.frames {
|
||||
var err error
|
||||
raw, err = f.Frame.Append(raw, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, f := range pl.streamFrames {
|
||||
var err error
|
||||
raw, err = f.Frame.Append(raw, v)
|
||||
raw, err = frame.Append(raw, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -877,3 +953,16 @@ func (p *packetPacker) encryptPacket(raw []byte, sealer sealer, pn protocol.Pack
|
|||
func (p *packetPacker) SetToken(token []byte) {
|
||||
p.token = token
|
||||
}
|
||||
|
||||
// When a higher MTU is discovered, use it.
|
||||
func (p *packetPacker) SetMaxPacketSize(s protocol.ByteCount) {
|
||||
p.maxPacketSize = s
|
||||
}
|
||||
|
||||
// If the peer sets a max_packet_size that's smaller than the size we're currently using,
|
||||
// we need to reduce the size of packets we send.
|
||||
func (p *packetPacker) HandleTransportParameters(params *wire.TransportParameters) {
|
||||
if params.MaxUDPPayloadSize != 0 {
|
||||
p.maxPacketSize = utils.Min(p.maxPacketSize, params.MaxUDPPayloadSize)
|
||||
}
|
||||
}
|
||||
|
|
19
vendor/github.com/quic-go/quic-go/quicvarint/varint.go
generated
vendored
19
vendor/github.com/quic-go/quic-go/quicvarint/varint.go
generated
vendored
|
@ -70,6 +70,25 @@ func Read(r io.ByteReader) (uint64, error) {
|
|||
return uint64(b8) + uint64(b7)<<8 + uint64(b6)<<16 + uint64(b5)<<24 + uint64(b4)<<32 + uint64(b3)<<40 + uint64(b2)<<48 + uint64(b1)<<56, nil
|
||||
}
|
||||
|
||||
// Write writes i in the QUIC varint format to w.
|
||||
// Deprecated: use Append instead.
|
||||
func Write(w Writer, i uint64) {
|
||||
if i <= maxVarInt1 {
|
||||
w.WriteByte(uint8(i))
|
||||
} else if i <= maxVarInt2 {
|
||||
w.Write([]byte{uint8(i>>8) | 0x40, uint8(i)})
|
||||
} else if i <= maxVarInt4 {
|
||||
w.Write([]byte{uint8(i>>24) | 0x80, uint8(i >> 16), uint8(i >> 8), uint8(i)})
|
||||
} else if i <= maxVarInt8 {
|
||||
w.Write([]byte{
|
||||
uint8(i>>56) | 0xc0, uint8(i >> 48), uint8(i >> 40), uint8(i >> 32),
|
||||
uint8(i >> 24), uint8(i >> 16), uint8(i >> 8), uint8(i),
|
||||
})
|
||||
} else {
|
||||
panic(fmt.Sprintf("%#x doesn't fit into 62 bits", i))
|
||||
}
|
||||
}
|
||||
|
||||
// Append appends i in the QUIC varint format.
|
||||
func Append(b []byte, i uint64) []byte {
|
||||
if i <= maxVarInt1 {
|
||||
|
|
4
vendor/github.com/quic-go/quic-go/receive_stream.go
generated
vendored
4
vendor/github.com/quic-go/quic-go/receive_stream.go
generated
vendored
|
@ -179,10 +179,6 @@ func (s *receiveStream) readImpl(p []byte) (bool /*stream completed */, int, err
|
|||
|
||||
if s.readPosInFrame >= len(s.currentFrame) && s.currentFrameIsLast {
|
||||
s.finRead = true
|
||||
s.currentFrame = nil
|
||||
if s.currentFrameDone != nil {
|
||||
s.currentFrameDone()
|
||||
}
|
||||
return true, bytesRead, io.EOF
|
||||
}
|
||||
}
|
||||
|
|
57
vendor/github.com/quic-go/quic-go/retransmission_queue.go
generated
vendored
57
vendor/github.com/quic-go/quic-go/retransmission_queue.go
generated
vendored
|
@ -3,8 +3,6 @@ package quic
|
|||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/ackhandler"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
"github.com/quic-go/quic-go/internal/wire"
|
||||
)
|
||||
|
@ -23,23 +21,7 @@ func newRetransmissionQueue() *retransmissionQueue {
|
|||
return &retransmissionQueue{}
|
||||
}
|
||||
|
||||
// AddPing queues a ping.
|
||||
// It is used when a probe packet needs to be sent
|
||||
func (q *retransmissionQueue) AddPing(encLevel protocol.EncryptionLevel) {
|
||||
//nolint:exhaustive // Cannot send probe packets for 0-RTT.
|
||||
switch encLevel {
|
||||
case protocol.EncryptionInitial:
|
||||
q.addInitial(&wire.PingFrame{})
|
||||
case protocol.EncryptionHandshake:
|
||||
q.addHandshake(&wire.PingFrame{})
|
||||
case protocol.Encryption1RTT:
|
||||
q.addAppData(&wire.PingFrame{})
|
||||
default:
|
||||
panic("unexpected encryption level")
|
||||
}
|
||||
}
|
||||
|
||||
func (q *retransmissionQueue) addInitial(f wire.Frame) {
|
||||
func (q *retransmissionQueue) AddInitial(f wire.Frame) {
|
||||
if cf, ok := f.(*wire.CryptoFrame); ok {
|
||||
q.initialCryptoData = append(q.initialCryptoData, cf)
|
||||
return
|
||||
|
@ -47,7 +29,7 @@ func (q *retransmissionQueue) addInitial(f wire.Frame) {
|
|||
q.initial = append(q.initial, f)
|
||||
}
|
||||
|
||||
func (q *retransmissionQueue) addHandshake(f wire.Frame) {
|
||||
func (q *retransmissionQueue) AddHandshake(f wire.Frame) {
|
||||
if cf, ok := f.(*wire.CryptoFrame); ok {
|
||||
q.handshakeCryptoData = append(q.handshakeCryptoData, cf)
|
||||
return
|
||||
|
@ -67,7 +49,7 @@ func (q *retransmissionQueue) HasAppData() bool {
|
|||
return len(q.appData) > 0
|
||||
}
|
||||
|
||||
func (q *retransmissionQueue) addAppData(f wire.Frame) {
|
||||
func (q *retransmissionQueue) AddAppData(f wire.Frame) {
|
||||
if _, ok := f.(*wire.StreamFrame); ok {
|
||||
panic("STREAM frames are handled with their respective streams.")
|
||||
}
|
||||
|
@ -145,36 +127,3 @@ func (q *retransmissionQueue) DropPackets(encLevel protocol.EncryptionLevel) {
|
|||
panic(fmt.Sprintf("unexpected encryption level: %s", encLevel))
|
||||
}
|
||||
}
|
||||
|
||||
func (q *retransmissionQueue) InitialAckHandler() ackhandler.FrameHandler {
|
||||
return (*retransmissionQueueInitialAckHandler)(q)
|
||||
}
|
||||
|
||||
func (q *retransmissionQueue) HandshakeAckHandler() ackhandler.FrameHandler {
|
||||
return (*retransmissionQueueHandshakeAckHandler)(q)
|
||||
}
|
||||
|
||||
func (q *retransmissionQueue) AppDataAckHandler() ackhandler.FrameHandler {
|
||||
return (*retransmissionQueueAppDataAckHandler)(q)
|
||||
}
|
||||
|
||||
type retransmissionQueueInitialAckHandler retransmissionQueue
|
||||
|
||||
func (q *retransmissionQueueInitialAckHandler) OnAcked(wire.Frame) {}
|
||||
func (q *retransmissionQueueInitialAckHandler) OnLost(f wire.Frame) {
|
||||
(*retransmissionQueue)(q).addInitial(f)
|
||||
}
|
||||
|
||||
type retransmissionQueueHandshakeAckHandler retransmissionQueue
|
||||
|
||||
func (q *retransmissionQueueHandshakeAckHandler) OnAcked(wire.Frame) {}
|
||||
func (q *retransmissionQueueHandshakeAckHandler) OnLost(f wire.Frame) {
|
||||
(*retransmissionQueue)(q).addHandshake(f)
|
||||
}
|
||||
|
||||
type retransmissionQueueAppDataAckHandler retransmissionQueue
|
||||
|
||||
func (q *retransmissionQueueAppDataAckHandler) OnAcked(wire.Frame) {}
|
||||
func (q *retransmissionQueueAppDataAckHandler) OnLost(f wire.Frame) {
|
||||
(*retransmissionQueue)(q).addAppData(f)
|
||||
}
|
||||
|
|
64
vendor/github.com/quic-go/quic-go/send_conn.go
generated
vendored
64
vendor/github.com/quic-go/quic-go/send_conn.go
generated
vendored
|
@ -1,65 +1,38 @@
|
|||
package quic
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
)
|
||||
|
||||
// A sendConn allows sending using a simple Write() on a non-connected packet conn.
|
||||
type sendConn interface {
|
||||
Write(b []byte, size protocol.ByteCount) error
|
||||
Write([]byte) error
|
||||
Close() error
|
||||
LocalAddr() net.Addr
|
||||
RemoteAddr() net.Addr
|
||||
|
||||
capabilities() connCapabilities
|
||||
}
|
||||
|
||||
type sconn struct {
|
||||
rawConn
|
||||
|
||||
remoteAddr net.Addr
|
||||
info packetInfo
|
||||
info *packetInfo
|
||||
oob []byte
|
||||
}
|
||||
|
||||
var _ sendConn = &sconn{}
|
||||
|
||||
func newSendConn(c rawConn, remote net.Addr) *sconn {
|
||||
sc := &sconn{
|
||||
rawConn: c,
|
||||
remoteAddr: remote,
|
||||
}
|
||||
if c.capabilities().GSO {
|
||||
// add 32 bytes, so we can add the UDP_SEGMENT msg
|
||||
sc.oob = make([]byte, 0, 32)
|
||||
}
|
||||
return sc
|
||||
}
|
||||
|
||||
func newSendConnWithPacketInfo(c rawConn, remote net.Addr, info packetInfo) *sconn {
|
||||
oob := info.OOB()
|
||||
if c.capabilities().GSO {
|
||||
// add 32 bytes, so we can add the UDP_SEGMENT msg
|
||||
l := len(oob)
|
||||
oob = append(oob, make([]byte, 32)...)
|
||||
oob = oob[:l]
|
||||
}
|
||||
func newSendConn(c rawConn, remote net.Addr, info *packetInfo) sendConn {
|
||||
return &sconn{
|
||||
rawConn: c,
|
||||
remoteAddr: remote,
|
||||
info: info,
|
||||
oob: oob,
|
||||
oob: info.OOB(),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *sconn) Write(p []byte, size protocol.ByteCount) error {
|
||||
if size > math.MaxUint16 {
|
||||
panic("size overflow")
|
||||
}
|
||||
_, err := c.WritePacket(p, uint16(size), c.remoteAddr, c.oob)
|
||||
func (c *sconn) Write(p []byte) error {
|
||||
_, err := c.WritePacket(p, c.remoteAddr, c.oob)
|
||||
return err
|
||||
}
|
||||
|
||||
|
@ -69,12 +42,33 @@ func (c *sconn) RemoteAddr() net.Addr {
|
|||
|
||||
func (c *sconn) LocalAddr() net.Addr {
|
||||
addr := c.rawConn.LocalAddr()
|
||||
if c.info.addr.IsValid() {
|
||||
if c.info != nil {
|
||||
if udpAddr, ok := addr.(*net.UDPAddr); ok {
|
||||
addrCopy := *udpAddr
|
||||
addrCopy.IP = c.info.addr.AsSlice()
|
||||
addrCopy.IP = c.info.addr
|
||||
addr = &addrCopy
|
||||
}
|
||||
}
|
||||
return addr
|
||||
}
|
||||
|
||||
type spconn struct {
|
||||
net.PacketConn
|
||||
|
||||
remoteAddr net.Addr
|
||||
}
|
||||
|
||||
var _ sendConn = &spconn{}
|
||||
|
||||
func newSendPconn(c net.PacketConn, remote net.Addr) sendConn {
|
||||
return &spconn{PacketConn: c, remoteAddr: remote}
|
||||
}
|
||||
|
||||
func (c *spconn) Write(p []byte) error {
|
||||
_, err := c.WriteTo(p, c.remoteAddr)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *spconn) RemoteAddr() net.Addr {
|
||||
return c.remoteAddr
|
||||
}
|
||||
|
|
23
vendor/github.com/quic-go/quic-go/send_queue.go
generated
vendored
23
vendor/github.com/quic-go/quic-go/send_queue.go
generated
vendored
|
@ -1,22 +1,15 @@
|
|||
package quic
|
||||
|
||||
import "github.com/quic-go/quic-go/internal/protocol"
|
||||
|
||||
type sender interface {
|
||||
Send(p *packetBuffer, packetSize protocol.ByteCount)
|
||||
Send(p *packetBuffer)
|
||||
Run() error
|
||||
WouldBlock() bool
|
||||
Available() <-chan struct{}
|
||||
Close()
|
||||
}
|
||||
|
||||
type queueEntry struct {
|
||||
buf *packetBuffer
|
||||
size protocol.ByteCount
|
||||
}
|
||||
|
||||
type sendQueue struct {
|
||||
queue chan queueEntry
|
||||
queue chan *packetBuffer
|
||||
closeCalled chan struct{} // runStopped when Close() is called
|
||||
runStopped chan struct{} // runStopped when the run loop returns
|
||||
available chan struct{}
|
||||
|
@ -33,16 +26,16 @@ func newSendQueue(conn sendConn) sender {
|
|||
runStopped: make(chan struct{}),
|
||||
closeCalled: make(chan struct{}),
|
||||
available: make(chan struct{}, 1),
|
||||
queue: make(chan queueEntry, sendQueueCapacity),
|
||||
queue: make(chan *packetBuffer, sendQueueCapacity),
|
||||
}
|
||||
}
|
||||
|
||||
// Send sends out a packet. It's guaranteed to not block.
|
||||
// Callers need to make sure that there's actually space in the send queue by calling WouldBlock.
|
||||
// Otherwise Send will panic.
|
||||
func (h *sendQueue) Send(p *packetBuffer, size protocol.ByteCount) {
|
||||
func (h *sendQueue) Send(p *packetBuffer) {
|
||||
select {
|
||||
case h.queue <- queueEntry{buf: p, size: size}:
|
||||
case h.queue <- p:
|
||||
// clear available channel if we've reached capacity
|
||||
if len(h.queue) == sendQueueCapacity {
|
||||
select {
|
||||
|
@ -76,8 +69,8 @@ func (h *sendQueue) Run() error {
|
|||
h.closeCalled = nil // prevent this case from being selected again
|
||||
// make sure that all queued packets are actually sent out
|
||||
shouldClose = true
|
||||
case e := <-h.queue:
|
||||
if err := h.conn.Write(e.buf.Data, e.size); err != nil {
|
||||
case p := <-h.queue:
|
||||
if err := h.conn.Write(p.Data); err != nil {
|
||||
// This additional check enables:
|
||||
// 1. Checking for "datagram too large" message from the kernel, as such,
|
||||
// 2. Path MTU discovery,and
|
||||
|
@ -86,7 +79,7 @@ func (h *sendQueue) Run() error {
|
|||
return err
|
||||
}
|
||||
}
|
||||
e.buf.Release()
|
||||
p.Release()
|
||||
select {
|
||||
case h.available <- struct{}{}:
|
||||
default:
|
||||
|
|
95
vendor/github.com/quic-go/quic-go/send_stream.go
generated
vendored
95
vendor/github.com/quic-go/quic-go/send_stream.go
generated
vendored
|
@ -18,7 +18,7 @@ type sendStreamI interface {
|
|||
SendStream
|
||||
handleStopSendingFrame(*wire.StopSendingFrame)
|
||||
hasData() bool
|
||||
popStreamFrame(maxBytes protocol.ByteCount, v protocol.VersionNumber) (frame ackhandler.StreamFrame, ok, hasMore bool)
|
||||
popStreamFrame(maxBytes protocol.ByteCount, v protocol.VersionNumber) (*ackhandler.Frame, bool)
|
||||
closeForShutdown(error)
|
||||
updateSendWindow(protocol.ByteCount)
|
||||
}
|
||||
|
@ -198,7 +198,7 @@ func (s *sendStream) canBufferStreamFrame() bool {
|
|||
|
||||
// popStreamFrame returns the next STREAM frame that is supposed to be sent on this stream
|
||||
// maxBytes is the maximum length this frame (including frame header) will have.
|
||||
func (s *sendStream) popStreamFrame(maxBytes protocol.ByteCount, v protocol.VersionNumber) (af ackhandler.StreamFrame, ok, hasMore bool) {
|
||||
func (s *sendStream) popStreamFrame(maxBytes protocol.ByteCount, v protocol.VersionNumber) (*ackhandler.Frame, bool /* has more data to send */) {
|
||||
s.mutex.Lock()
|
||||
f, hasMoreData := s.popNewOrRetransmittedStreamFrame(maxBytes, v)
|
||||
if f != nil {
|
||||
|
@ -207,12 +207,13 @@ func (s *sendStream) popStreamFrame(maxBytes protocol.ByteCount, v protocol.Vers
|
|||
s.mutex.Unlock()
|
||||
|
||||
if f == nil {
|
||||
return ackhandler.StreamFrame{}, false, hasMoreData
|
||||
return nil, hasMoreData
|
||||
}
|
||||
return ackhandler.StreamFrame{
|
||||
Frame: f,
|
||||
Handler: (*sendStreamAckHandler)(s),
|
||||
}, true, hasMoreData
|
||||
af := ackhandler.GetFrame()
|
||||
af.Frame = f
|
||||
af.OnLost = s.queueRetransmission
|
||||
af.OnAcked = s.frameAcked
|
||||
return af, hasMoreData
|
||||
}
|
||||
|
||||
func (s *sendStream) popNewOrRetransmittedStreamFrame(maxBytes protocol.ByteCount, v protocol.VersionNumber) (*wire.StreamFrame, bool /* has more data to send */) {
|
||||
|
@ -347,6 +348,26 @@ func (s *sendStream) getDataForWriting(f *wire.StreamFrame, maxBytes protocol.By
|
|||
}
|
||||
}
|
||||
|
||||
func (s *sendStream) frameAcked(f wire.Frame) {
|
||||
f.(*wire.StreamFrame).PutBack()
|
||||
|
||||
s.mutex.Lock()
|
||||
if s.cancelWriteErr != nil {
|
||||
s.mutex.Unlock()
|
||||
return
|
||||
}
|
||||
s.numOutstandingFrames--
|
||||
if s.numOutstandingFrames < 0 {
|
||||
panic("numOutStandingFrames negative")
|
||||
}
|
||||
newlyCompleted := s.isNewlyCompleted()
|
||||
s.mutex.Unlock()
|
||||
|
||||
if newlyCompleted {
|
||||
s.sender.onStreamCompleted(s.streamID)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *sendStream) isNewlyCompleted() bool {
|
||||
completed := (s.finSent || s.cancelWriteErr != nil) && s.numOutstandingFrames == 0 && len(s.retransmissionQueue) == 0
|
||||
if completed && !s.completed {
|
||||
|
@ -356,6 +377,24 @@ func (s *sendStream) isNewlyCompleted() bool {
|
|||
return false
|
||||
}
|
||||
|
||||
func (s *sendStream) queueRetransmission(f wire.Frame) {
|
||||
sf := f.(*wire.StreamFrame)
|
||||
sf.DataLenPresent = true
|
||||
s.mutex.Lock()
|
||||
if s.cancelWriteErr != nil {
|
||||
s.mutex.Unlock()
|
||||
return
|
||||
}
|
||||
s.retransmissionQueue = append(s.retransmissionQueue, sf)
|
||||
s.numOutstandingFrames--
|
||||
if s.numOutstandingFrames < 0 {
|
||||
panic("numOutStandingFrames negative")
|
||||
}
|
||||
s.mutex.Unlock()
|
||||
|
||||
s.sender.onHasStreamData(s.streamID)
|
||||
}
|
||||
|
||||
func (s *sendStream) Close() error {
|
||||
s.mutex.Lock()
|
||||
if s.closeForShutdownErr != nil {
|
||||
|
@ -448,45 +487,3 @@ func (s *sendStream) signalWrite() {
|
|||
default:
|
||||
}
|
||||
}
|
||||
|
||||
type sendStreamAckHandler sendStream
|
||||
|
||||
var _ ackhandler.FrameHandler = &sendStreamAckHandler{}
|
||||
|
||||
func (s *sendStreamAckHandler) OnAcked(f wire.Frame) {
|
||||
sf := f.(*wire.StreamFrame)
|
||||
sf.PutBack()
|
||||
s.mutex.Lock()
|
||||
if s.cancelWriteErr != nil {
|
||||
s.mutex.Unlock()
|
||||
return
|
||||
}
|
||||
s.numOutstandingFrames--
|
||||
if s.numOutstandingFrames < 0 {
|
||||
panic("numOutStandingFrames negative")
|
||||
}
|
||||
newlyCompleted := (*sendStream)(s).isNewlyCompleted()
|
||||
s.mutex.Unlock()
|
||||
|
||||
if newlyCompleted {
|
||||
s.sender.onStreamCompleted(s.streamID)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *sendStreamAckHandler) OnLost(f wire.Frame) {
|
||||
sf := f.(*wire.StreamFrame)
|
||||
s.mutex.Lock()
|
||||
if s.cancelWriteErr != nil {
|
||||
s.mutex.Unlock()
|
||||
return
|
||||
}
|
||||
sf.DataLenPresent = true
|
||||
s.retransmissionQueue = append(s.retransmissionQueue, sf)
|
||||
s.numOutstandingFrames--
|
||||
if s.numOutstandingFrames < 0 {
|
||||
panic("numOutStandingFrames negative")
|
||||
}
|
||||
s.mutex.Unlock()
|
||||
|
||||
s.sender.onHasStreamData(s.streamID)
|
||||
}
|
||||
|
|
564
vendor/github.com/quic-go/quic-go/server.go
generated
vendored
564
vendor/github.com/quic-go/quic-go/server.go
generated
vendored
|
@ -20,29 +20,33 @@ import (
|
|||
)
|
||||
|
||||
// ErrServerClosed is returned by the Listener or EarlyListener's Accept method after a call to Close.
|
||||
var ErrServerClosed = errors.New("quic: server closed")
|
||||
var ErrServerClosed = errors.New("quic: Server closed")
|
||||
|
||||
// packetHandler handles packets
|
||||
type packetHandler interface {
|
||||
handlePacket(receivedPacket)
|
||||
handlePacket(*receivedPacket)
|
||||
shutdown()
|
||||
destroy(error)
|
||||
getPerspective() protocol.Perspective
|
||||
}
|
||||
|
||||
type unknownPacketHandler interface {
|
||||
handlePacket(*receivedPacket)
|
||||
setCloseError(error)
|
||||
}
|
||||
|
||||
type packetHandlerManager interface {
|
||||
Get(protocol.ConnectionID) (packetHandler, bool)
|
||||
GetByResetToken(protocol.StatelessResetToken) (packetHandler, bool)
|
||||
AddWithConnID(protocol.ConnectionID, protocol.ConnectionID, func() (packetHandler, bool)) bool
|
||||
Close(error)
|
||||
CloseServer()
|
||||
AddWithConnID(protocol.ConnectionID, protocol.ConnectionID, func() packetHandler) bool
|
||||
Destroy() error
|
||||
connRunner
|
||||
SetServer(unknownPacketHandler)
|
||||
CloseServer()
|
||||
}
|
||||
|
||||
type quicConn interface {
|
||||
EarlyConnection
|
||||
earlyConnReady() <-chan struct{}
|
||||
handlePacket(receivedPacket)
|
||||
handlePacket(*receivedPacket)
|
||||
GetVersion() protocol.VersionNumber
|
||||
getPerspective() protocol.Perspective
|
||||
run() error
|
||||
|
@ -50,11 +54,6 @@ type quicConn interface {
|
|||
shutdown()
|
||||
}
|
||||
|
||||
type zeroRTTQueue struct {
|
||||
packets []receivedPacket
|
||||
expiration time.Time
|
||||
}
|
||||
|
||||
// A Listener of QUIC
|
||||
type baseServer struct {
|
||||
mutex sync.Mutex
|
||||
|
@ -65,17 +64,15 @@ type baseServer struct {
|
|||
config *Config
|
||||
|
||||
conn rawConn
|
||||
// If the server is started with ListenAddr, we create a packet conn.
|
||||
// If it is started with Listen, we take a packet conn as a parameter.
|
||||
createdPacketConn bool
|
||||
|
||||
tokenGenerator *handshake.TokenGenerator
|
||||
|
||||
connIDGenerator ConnectionIDGenerator
|
||||
connHandler packetHandlerManager
|
||||
onClose func()
|
||||
connHandler packetHandlerManager
|
||||
|
||||
receivedPackets chan receivedPacket
|
||||
|
||||
nextZeroRTTCleanup time.Time
|
||||
zeroRTTQueues map[protocol.ConnectionID]*zeroRTTQueue // only initialized if acceptEarlyConns == true
|
||||
receivedPackets chan *receivedPacket
|
||||
|
||||
// set as a member, so they can be set in the tests
|
||||
newConn func(
|
||||
|
@ -86,7 +83,6 @@ type baseServer struct {
|
|||
protocol.ConnectionID, /* client dest connection ID */
|
||||
protocol.ConnectionID, /* destination connection ID */
|
||||
protocol.ConnectionID, /* source connection ID */
|
||||
ConnectionIDGenerator,
|
||||
protocol.StatelessResetToken,
|
||||
*Config,
|
||||
*tls.Config,
|
||||
|
@ -98,164 +94,128 @@ type baseServer struct {
|
|||
protocol.VersionNumber,
|
||||
) quicConn
|
||||
|
||||
serverError error
|
||||
errorChan chan struct{}
|
||||
closed bool
|
||||
running chan struct{} // closed as soon as run() returns
|
||||
versionNegotiationQueue chan receivedPacket
|
||||
invalidTokenQueue chan receivedPacket
|
||||
serverError error
|
||||
errorChan chan struct{}
|
||||
closed bool
|
||||
running chan struct{} // closed as soon as run() returns
|
||||
|
||||
connQueue chan quicConn
|
||||
connQueueLen int32 // to be used as an atomic
|
||||
|
||||
tracer logging.Tracer
|
||||
|
||||
logger utils.Logger
|
||||
}
|
||||
|
||||
// A Listener listens for incoming QUIC connections.
|
||||
// It returns connections once the handshake has completed.
|
||||
type Listener struct {
|
||||
baseServer *baseServer
|
||||
}
|
||||
var (
|
||||
_ Listener = &baseServer{}
|
||||
_ unknownPacketHandler = &baseServer{}
|
||||
)
|
||||
|
||||
// Accept returns new connections. It should be called in a loop.
|
||||
func (l *Listener) Accept(ctx context.Context) (Connection, error) {
|
||||
return l.baseServer.Accept(ctx)
|
||||
}
|
||||
type earlyServer struct{ *baseServer }
|
||||
|
||||
// Close the server. All active connections will be closed.
|
||||
func (l *Listener) Close() error {
|
||||
return l.baseServer.Close()
|
||||
}
|
||||
var _ EarlyListener = &earlyServer{}
|
||||
|
||||
// Addr returns the local network address that the server is listening on.
|
||||
func (l *Listener) Addr() net.Addr {
|
||||
return l.baseServer.Addr()
|
||||
}
|
||||
|
||||
// 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.
|
||||
type EarlyListener struct {
|
||||
baseServer *baseServer
|
||||
}
|
||||
|
||||
// Accept returns a new connections. It should be called in a loop.
|
||||
func (l *EarlyListener) Accept(ctx context.Context) (EarlyConnection, error) {
|
||||
return l.baseServer.accept(ctx)
|
||||
}
|
||||
|
||||
// Close the server. All active connections will be closed.
|
||||
func (l *EarlyListener) Close() error {
|
||||
return l.baseServer.Close()
|
||||
}
|
||||
|
||||
// Addr returns the local network addr that the server is listening on.
|
||||
func (l *EarlyListener) Addr() net.Addr {
|
||||
return l.baseServer.Addr()
|
||||
func (s *earlyServer) Accept(ctx context.Context) (EarlyConnection, error) {
|
||||
return s.baseServer.accept(ctx)
|
||||
}
|
||||
|
||||
// ListenAddr creates a QUIC server listening on a given address.
|
||||
// See Listen for more details.
|
||||
func ListenAddr(addr string, tlsConf *tls.Config, config *Config) (*Listener, error) {
|
||||
conn, err := listenUDP(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return (&Transport{
|
||||
Conn: conn,
|
||||
createdConn: true,
|
||||
isSingleUse: true,
|
||||
}).Listen(tlsConf, config)
|
||||
// The tls.Config must not be nil and must contain a certificate configuration.
|
||||
// The quic.Config may be nil, in that case the default values will be used.
|
||||
func ListenAddr(addr string, tlsConf *tls.Config, config *Config) (Listener, error) {
|
||||
return listenAddr(addr, tlsConf, config, false)
|
||||
}
|
||||
|
||||
// ListenAddrEarly works like ListenAddr, but it returns connections before the handshake completes.
|
||||
func ListenAddrEarly(addr string, tlsConf *tls.Config, config *Config) (*EarlyListener, error) {
|
||||
conn, err := listenUDP(addr)
|
||||
func ListenAddrEarly(addr string, tlsConf *tls.Config, config *Config) (EarlyListener, error) {
|
||||
s, err := listenAddr(addr, tlsConf, config, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return (&Transport{
|
||||
Conn: conn,
|
||||
createdConn: true,
|
||||
isSingleUse: true,
|
||||
}).ListenEarly(tlsConf, config)
|
||||
return &earlyServer{s}, nil
|
||||
}
|
||||
|
||||
func listenUDP(addr string) (*net.UDPConn, error) {
|
||||
func listenAddr(addr string, tlsConf *tls.Config, config *Config, acceptEarly bool) (*baseServer, error) {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return net.ListenUDP("udp", udpAddr)
|
||||
conn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
serv, err := listen(conn, tlsConf, config, acceptEarly)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
serv.createdPacketConn = true
|
||||
return serv, nil
|
||||
}
|
||||
|
||||
// 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, ReadMsgUDP and WriteMsgUDP
|
||||
// will be used instead of ReadFrom and WriteTo to read/write packets.
|
||||
// A single net.PacketConn can only be used for a single call to 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, ReadMsgUDP
|
||||
// and WriteMsgUDP will be used instead of ReadFrom and WriteTo to read/write
|
||||
// packets. A single net.PacketConn only be used for a single call to Listen.
|
||||
// The PacketConn can be used for simultaneous calls to Dial. QUIC connection
|
||||
// IDs are used for demultiplexing the different connections.
|
||||
// The tls.Config must not be nil and must contain a certificate configuration.
|
||||
// Furthermore, it must define an application control (using NextProtos).
|
||||
// The quic.Config may be nil, in that 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.
|
||||
func Listen(conn net.PacketConn, tlsConf *tls.Config, config *Config) (*Listener, error) {
|
||||
tr := &Transport{Conn: conn, isSingleUse: true}
|
||||
return tr.Listen(tlsConf, config)
|
||||
func Listen(conn net.PacketConn, tlsConf *tls.Config, config *Config) (Listener, error) {
|
||||
return listen(conn, tlsConf, config, false)
|
||||
}
|
||||
|
||||
// ListenEarly works like Listen, but it returns connections before the handshake completes.
|
||||
func ListenEarly(conn net.PacketConn, tlsConf *tls.Config, config *Config) (*EarlyListener, error) {
|
||||
tr := &Transport{Conn: conn, isSingleUse: true}
|
||||
return tr.ListenEarly(tlsConf, config)
|
||||
func ListenEarly(conn net.PacketConn, tlsConf *tls.Config, config *Config) (EarlyListener, error) {
|
||||
s, err := listen(conn, tlsConf, config, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &earlyServer{s}, nil
|
||||
}
|
||||
|
||||
func newServer(
|
||||
conn rawConn,
|
||||
connHandler packetHandlerManager,
|
||||
connIDGenerator ConnectionIDGenerator,
|
||||
tlsConf *tls.Config,
|
||||
config *Config,
|
||||
tracer logging.Tracer,
|
||||
onClose func(),
|
||||
acceptEarly bool,
|
||||
) (*baseServer, error) {
|
||||
func listen(conn net.PacketConn, tlsConf *tls.Config, config *Config, acceptEarly bool) (*baseServer, error) {
|
||||
if tlsConf == nil {
|
||||
return nil, errors.New("quic: tls.Config not set")
|
||||
}
|
||||
if err := validateConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config = populateServerConfig(config)
|
||||
for _, v := range config.Versions {
|
||||
if !protocol.IsValidVersion(v) {
|
||||
return nil, fmt.Errorf("%s is not a valid QUIC version", v)
|
||||
}
|
||||
}
|
||||
|
||||
connHandler, err := getMultiplexer().AddConn(conn, config.ConnectionIDGenerator.ConnectionIDLen(), config.StatelessResetKey, config.Tracer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tokenGenerator, err := handshake.NewTokenGenerator(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := &baseServer{
|
||||
conn: conn,
|
||||
tlsConf: tlsConf,
|
||||
config: config,
|
||||
tokenGenerator: tokenGenerator,
|
||||
connIDGenerator: connIDGenerator,
|
||||
connHandler: connHandler,
|
||||
connQueue: make(chan quicConn),
|
||||
errorChan: make(chan struct{}),
|
||||
running: make(chan struct{}),
|
||||
receivedPackets: make(chan receivedPacket, protocol.MaxServerUnprocessedPackets),
|
||||
versionNegotiationQueue: make(chan receivedPacket, 4),
|
||||
invalidTokenQueue: make(chan receivedPacket, 4),
|
||||
newConn: newConnection,
|
||||
tracer: tracer,
|
||||
logger: utils.DefaultLogger.WithPrefix("server"),
|
||||
acceptEarlyConns: acceptEarly,
|
||||
onClose: onClose,
|
||||
c, err := wrapConn(conn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if acceptEarly {
|
||||
s.zeroRTTQueues = map[protocol.ConnectionID]*zeroRTTQueue{}
|
||||
s := &baseServer{
|
||||
conn: c,
|
||||
tlsConf: tlsConf,
|
||||
config: config,
|
||||
tokenGenerator: tokenGenerator,
|
||||
connHandler: connHandler,
|
||||
connQueue: make(chan quicConn),
|
||||
errorChan: make(chan struct{}),
|
||||
running: make(chan struct{}),
|
||||
receivedPackets: make(chan *receivedPacket, protocol.MaxServerUnprocessedPackets),
|
||||
newConn: newConnection,
|
||||
logger: utils.DefaultLogger.WithPrefix("server"),
|
||||
acceptEarlyConns: acceptEarly,
|
||||
}
|
||||
go s.run()
|
||||
go s.runSendQueue()
|
||||
connHandler.SetServer(s)
|
||||
s.logger.Debugf("Listening for %s connections on %s", conn.LocalAddr().Network(), conn.LocalAddr().String())
|
||||
return s, nil
|
||||
}
|
||||
|
@ -279,19 +239,6 @@ func (s *baseServer) run() {
|
|||
}
|
||||
}
|
||||
|
||||
func (s *baseServer) runSendQueue() {
|
||||
for {
|
||||
select {
|
||||
case <-s.running:
|
||||
return
|
||||
case p := <-s.versionNegotiationQueue:
|
||||
s.maybeSendVersionNegotiationPacket(p)
|
||||
case p := <-s.invalidTokenQueue:
|
||||
s.maybeSendInvalidToken(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Accept returns connections that already completed the handshake.
|
||||
// It is only valid if acceptEarlyConns is false.
|
||||
func (s *baseServer) Accept(ctx context.Context) (Connection, error) {
|
||||
|
@ -320,12 +267,18 @@ func (s *baseServer) Close() error {
|
|||
if s.serverError == nil {
|
||||
s.serverError = ErrServerClosed
|
||||
}
|
||||
// If the server was started with ListenAddr, we created the packet conn.
|
||||
// We need to close it in order to make the go routine reading from that conn return.
|
||||
createdPacketConn := s.createdPacketConn
|
||||
s.closed = true
|
||||
close(s.errorChan)
|
||||
s.mutex.Unlock()
|
||||
|
||||
<-s.running
|
||||
s.onClose()
|
||||
s.connHandler.CloseServer()
|
||||
if createdPacketConn {
|
||||
return s.connHandler.Destroy()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -345,26 +298,22 @@ func (s *baseServer) Addr() net.Addr {
|
|||
return s.conn.LocalAddr()
|
||||
}
|
||||
|
||||
func (s *baseServer) handlePacket(p receivedPacket) {
|
||||
func (s *baseServer) handlePacket(p *receivedPacket) {
|
||||
select {
|
||||
case s.receivedPackets <- p:
|
||||
default:
|
||||
s.logger.Debugf("Dropping packet from %s (%d bytes). Server receive queue full.", p.remoteAddr, p.Size())
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropDOSPrevention)
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropDOSPrevention)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer still in use? */ {
|
||||
if !s.nextZeroRTTCleanup.IsZero() && p.rcvTime.After(s.nextZeroRTTCleanup) {
|
||||
defer s.cleanupZeroRTTQueues(p.rcvTime)
|
||||
}
|
||||
|
||||
func (s *baseServer) handlePacketImpl(p *receivedPacket) bool /* is the buffer still in use? */ {
|
||||
if wire.IsVersionNegotiationPacket(p.data) {
|
||||
s.logger.Debugf("Dropping Version Negotiation packet.")
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeVersionNegotiation, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeVersionNegotiation, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
@ -373,54 +322,42 @@ func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer st
|
|||
panic(fmt.Sprintf("misrouted packet: %#v", p.data))
|
||||
}
|
||||
v, err := wire.ParseVersion(p.data)
|
||||
// drop the packet if we failed to parse the protocol version
|
||||
if err != nil {
|
||||
s.logger.Debugf("Dropping a packet with an unknown version")
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
// send a Version Negotiation Packet if the client is speaking a different protocol version
|
||||
if err != nil || !protocol.IsSupportedVersion(s.config.Versions, v) {
|
||||
if err != nil || p.Size() < protocol.MinUnknownVersionPacketSize {
|
||||
s.logger.Debugf("Dropping a packet with an unknown version that is too small (%d bytes)", p.Size())
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
}
|
||||
return false
|
||||
}
|
||||
_, src, dest, err := wire.ParseArbitraryLenConnectionIDs(p.data)
|
||||
if err != nil { // should never happen
|
||||
s.logger.Debugf("Dropping a packet with an unknown version for which we failed to parse connection IDs")
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
}
|
||||
return false
|
||||
}
|
||||
if !s.config.DisableVersionNegotiationPackets {
|
||||
go s.sendVersionNegotiationPacket(p.remoteAddr, src, dest, p.info.OOB(), v)
|
||||
}
|
||||
return false
|
||||
}
|
||||
// send a Version Negotiation Packet if the client is speaking a different protocol version
|
||||
if !protocol.IsSupportedVersion(s.config.Versions, v) {
|
||||
if s.config.DisableVersionNegotiationPackets {
|
||||
return false
|
||||
}
|
||||
|
||||
if p.Size() < protocol.MinUnknownVersionPacketSize {
|
||||
s.logger.Debugf("Dropping a packet with an unsupported version number %d that is too small (%d bytes)", v, p.Size())
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
}
|
||||
return false
|
||||
}
|
||||
return s.enqueueVersionNegotiationPacket(p)
|
||||
}
|
||||
|
||||
if wire.Is0RTTPacket(p.data) {
|
||||
if !s.acceptEarlyConns {
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
}
|
||||
return false
|
||||
}
|
||||
return s.handle0RTTPacket(p)
|
||||
}
|
||||
|
||||
// If we're creating a new connection, the packet will be passed to the connection.
|
||||
// The header will then be parsed again.
|
||||
hdr, _, _, err := wire.ParsePacket(p.data)
|
||||
if err != nil {
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropHeaderParseError)
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropHeaderParseError)
|
||||
}
|
||||
s.logger.Debugf("Error parsing packet: %s", err)
|
||||
return false
|
||||
}
|
||||
if hdr.Type == protocol.PacketTypeInitial && p.Size() < protocol.MinInitialPacketSize {
|
||||
s.logger.Debugf("Dropping a packet that is too small to be a valid Initial (%d bytes)", p.Size())
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
@ -430,8 +367,8 @@ func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer st
|
|||
// There's little point in sending a Stateless Reset, since the client
|
||||
// might not have received the token yet.
|
||||
s.logger.Debugf("Dropping long header packet of type %s (%d bytes)", hdr.Type, len(p.data))
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeFromHeader(hdr), p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeFromHeader(hdr), p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
@ -446,74 +383,6 @@ func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer st
|
|||
return true
|
||||
}
|
||||
|
||||
func (s *baseServer) handle0RTTPacket(p receivedPacket) bool {
|
||||
connID, err := wire.ParseConnectionID(p.data, 0)
|
||||
if err != nil {
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropHeaderParseError)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// check again if we might have a connection now
|
||||
if handler, ok := s.connHandler.Get(connID); ok {
|
||||
handler.handlePacket(p)
|
||||
return true
|
||||
}
|
||||
|
||||
if q, ok := s.zeroRTTQueues[connID]; ok {
|
||||
if len(q.packets) >= protocol.Max0RTTQueueLen {
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropDOSPrevention)
|
||||
}
|
||||
return false
|
||||
}
|
||||
q.packets = append(q.packets, p)
|
||||
return true
|
||||
}
|
||||
|
||||
if len(s.zeroRTTQueues) >= protocol.Max0RTTQueues {
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropDOSPrevention)
|
||||
}
|
||||
return false
|
||||
}
|
||||
queue := &zeroRTTQueue{packets: make([]receivedPacket, 1, 8)}
|
||||
queue.packets[0] = p
|
||||
expiration := p.rcvTime.Add(protocol.Max0RTTQueueingDuration)
|
||||
queue.expiration = expiration
|
||||
if s.nextZeroRTTCleanup.IsZero() || s.nextZeroRTTCleanup.After(expiration) {
|
||||
s.nextZeroRTTCleanup = expiration
|
||||
}
|
||||
s.zeroRTTQueues[connID] = queue
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *baseServer) cleanupZeroRTTQueues(now time.Time) {
|
||||
// Iterate over all queues to find those that are expired.
|
||||
// This is ok since we're placing a pretty low limit on the number of queues.
|
||||
var nextCleanup time.Time
|
||||
for connID, q := range s.zeroRTTQueues {
|
||||
if q.expiration.After(now) {
|
||||
if nextCleanup.IsZero() || nextCleanup.After(q.expiration) {
|
||||
nextCleanup = q.expiration
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, p := range q.packets {
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropDOSPrevention)
|
||||
}
|
||||
p.buffer.Release()
|
||||
}
|
||||
delete(s.zeroRTTQueues, connID)
|
||||
if s.logger.Debug() {
|
||||
s.logger.Debugf("Removing 0-RTT queue for %s.", connID)
|
||||
}
|
||||
}
|
||||
s.nextZeroRTTCleanup = nextCleanup
|
||||
}
|
||||
|
||||
// validateToken returns false if:
|
||||
// - address is invalid
|
||||
// - token is expired
|
||||
|
@ -534,23 +403,15 @@ func (s *baseServer) validateToken(token *handshake.Token, addr net.Addr) bool {
|
|||
return true
|
||||
}
|
||||
|
||||
func (s *baseServer) handleInitialImpl(p receivedPacket, hdr *wire.Header) error {
|
||||
func (s *baseServer) handleInitialImpl(p *receivedPacket, hdr *wire.Header) error {
|
||||
if len(hdr.Token) == 0 && hdr.DestConnectionID.Len() < protocol.MinConnectionIDLenInitial {
|
||||
p.buffer.Release()
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
}
|
||||
return errors.New("too short connection ID")
|
||||
}
|
||||
|
||||
// The server queues packets for a while, and we might already have established a connection by now.
|
||||
// This results in a second check in the connection map.
|
||||
// That's ok since it's not the hot path (it's only taken by some Initial and 0-RTT packets).
|
||||
if handler, ok := s.connHandler.Get(hdr.DestConnectionID); ok {
|
||||
handler.handlePacket(p)
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
token *handshake.Token
|
||||
retrySrcConnID *protocol.ConnectionID
|
||||
|
@ -568,6 +429,7 @@ func (s *baseServer) handleInitialImpl(p receivedPacket, hdr *wire.Header) error
|
|||
}
|
||||
|
||||
clientAddrIsValid := s.validateToken(token, p.remoteAddr)
|
||||
|
||||
if token != nil && !clientAddrIsValid {
|
||||
// For invalid and expired non-retry tokens, we don't send an INVALID_TOKEN error.
|
||||
// We just ignore them, and act as if there was no token on this packet at all.
|
||||
|
@ -578,13 +440,16 @@ func (s *baseServer) handleInitialImpl(p receivedPacket, hdr *wire.Header) error
|
|||
// For Retry tokens, we send an INVALID_ERROR if
|
||||
// * the token is too old, or
|
||||
// * the token is invalid, in case of a retry token.
|
||||
s.enqueueInvalidToken(p)
|
||||
go func() {
|
||||
defer p.buffer.Release()
|
||||
if err := s.maybeSendInvalidToken(p, hdr); err != nil {
|
||||
s.logger.Debugf("Error sending INVALID_TOKEN error: %s", err)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if token == nil && s.config.RequireAddressValidation(p.remoteAddr) {
|
||||
// Retry invalidates all 0-RTT packets sent.
|
||||
delete(s.zeroRTTQueues, hdr.DestConnectionID)
|
||||
go func() {
|
||||
defer p.buffer.Release()
|
||||
if err := s.sendRetry(p.remoteAddr, hdr, p.info); err != nil {
|
||||
|
@ -605,43 +470,37 @@ func (s *baseServer) handleInitialImpl(p receivedPacket, hdr *wire.Header) error
|
|||
return nil
|
||||
}
|
||||
|
||||
connID, err := s.connIDGenerator.GenerateConnectionID()
|
||||
connID, err := s.config.ConnectionIDGenerator.GenerateConnectionID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.logger.Debugf("Changing connection ID to %s.", connID)
|
||||
var conn quicConn
|
||||
tracingID := nextConnTracingID()
|
||||
if added := s.connHandler.AddWithConnID(hdr.DestConnectionID, connID, func() (packetHandler, bool) {
|
||||
config := s.config
|
||||
if s.config.GetConfigForClient != nil {
|
||||
conf, err := s.config.GetConfigForClient(&ClientHelloInfo{RemoteAddr: p.remoteAddr})
|
||||
if err != nil {
|
||||
s.logger.Debugf("Rejecting new connection due to GetConfigForClient callback")
|
||||
return nil, false
|
||||
}
|
||||
config = populateConfig(conf)
|
||||
}
|
||||
if added := s.connHandler.AddWithConnID(hdr.DestConnectionID, connID, func() packetHandler {
|
||||
var tracer logging.ConnectionTracer
|
||||
if config.Tracer != nil {
|
||||
if s.config.Tracer != nil {
|
||||
// Use the same connection ID that is passed to the client's GetLogWriter callback.
|
||||
connID := hdr.DestConnectionID
|
||||
if origDestConnID.Len() > 0 {
|
||||
connID = origDestConnID
|
||||
}
|
||||
tracer = config.Tracer(context.WithValue(context.Background(), ConnectionTracingKey, tracingID), protocol.PerspectiveServer, connID)
|
||||
tracer = s.config.Tracer.TracerForConnection(
|
||||
context.WithValue(context.Background(), ConnectionTracingKey, tracingID),
|
||||
protocol.PerspectiveServer,
|
||||
connID,
|
||||
)
|
||||
}
|
||||
conn = s.newConn(
|
||||
newSendConnWithPacketInfo(s.conn, p.remoteAddr, p.info),
|
||||
newSendConn(s.conn, p.remoteAddr, p.info),
|
||||
s.connHandler,
|
||||
origDestConnID,
|
||||
retrySrcConnID,
|
||||
hdr.DestConnectionID,
|
||||
hdr.SrcConnectionID,
|
||||
connID,
|
||||
s.connIDGenerator,
|
||||
s.connHandler.GetStatelessResetToken(connID),
|
||||
config,
|
||||
s.config,
|
||||
s.tlsConf,
|
||||
s.tokenGenerator,
|
||||
clientAddrIsValid,
|
||||
|
@ -651,22 +510,8 @@ func (s *baseServer) handleInitialImpl(p receivedPacket, hdr *wire.Header) error
|
|||
hdr.Version,
|
||||
)
|
||||
conn.handlePacket(p)
|
||||
|
||||
if q, ok := s.zeroRTTQueues[hdr.DestConnectionID]; ok {
|
||||
for _, p := range q.packets {
|
||||
conn.handlePacket(p)
|
||||
}
|
||||
delete(s.zeroRTTQueues, hdr.DestConnectionID)
|
||||
}
|
||||
|
||||
return conn, true
|
||||
return conn
|
||||
}); !added {
|
||||
go func() {
|
||||
defer p.buffer.Release()
|
||||
if err := s.sendConnectionRefused(p.remoteAddr, hdr, p.info); err != nil {
|
||||
s.logger.Debugf("Error rejecting connection: %s", err)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
go conn.run()
|
||||
|
@ -706,11 +551,11 @@ func (s *baseServer) handleNewConn(conn quicConn) {
|
|||
}
|
||||
}
|
||||
|
||||
func (s *baseServer) sendRetry(remoteAddr net.Addr, hdr *wire.Header, info packetInfo) error {
|
||||
func (s *baseServer) sendRetry(remoteAddr net.Addr, hdr *wire.Header, info *packetInfo) error {
|
||||
// Log the Initial packet now.
|
||||
// If no Retry is sent, the packet will be logged by the connection.
|
||||
(&wire.ExtendedHeader{Header: *hdr}).Log(s.logger)
|
||||
srcConnID, err := s.connIDGenerator.GenerateConnectionID()
|
||||
srcConnID, err := s.config.ConnectionIDGenerator.GenerateConnectionID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -739,69 +584,47 @@ func (s *baseServer) sendRetry(remoteAddr net.Addr, hdr *wire.Header, info packe
|
|||
// append the Retry integrity tag
|
||||
tag := handshake.GetRetryIntegrityTag(buf.Data, hdr.DestConnectionID, hdr.Version)
|
||||
buf.Data = append(buf.Data, tag[:]...)
|
||||
if s.tracer != nil {
|
||||
s.tracer.SentPacket(remoteAddr, &replyHdr.Header, protocol.ByteCount(len(buf.Data)), nil)
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.SentPacket(remoteAddr, &replyHdr.Header, protocol.ByteCount(len(buf.Data)), nil)
|
||||
}
|
||||
_, err = s.conn.WritePacket(buf.Data, uint16(len(buf.Data)), remoteAddr, info.OOB())
|
||||
_, err = s.conn.WritePacket(buf.Data, remoteAddr, info.OOB())
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *baseServer) enqueueInvalidToken(p receivedPacket) {
|
||||
select {
|
||||
case s.invalidTokenQueue <- p:
|
||||
default:
|
||||
// it's fine to drop INVALID_TOKEN packets when we are busy
|
||||
p.buffer.Release()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *baseServer) maybeSendInvalidToken(p receivedPacket) {
|
||||
defer p.buffer.Release()
|
||||
|
||||
hdr, _, _, err := wire.ParsePacket(p.data)
|
||||
if err != nil {
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropHeaderParseError)
|
||||
}
|
||||
s.logger.Debugf("Error parsing packet: %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *baseServer) maybeSendInvalidToken(p *receivedPacket, hdr *wire.Header) error {
|
||||
// Only send INVALID_TOKEN if we can unprotect the packet.
|
||||
// This makes sure that we won't send it for packets that were corrupted.
|
||||
sealer, opener := handshake.NewInitialAEAD(hdr.DestConnectionID, protocol.PerspectiveServer, hdr.Version)
|
||||
data := p.data[:hdr.ParsedLen()+hdr.Length]
|
||||
extHdr, err := unpackLongHeader(opener, hdr, data, hdr.Version)
|
||||
// Only send INVALID_TOKEN if we can unprotect the packet.
|
||||
// This makes sure that we won't send it for packets that were corrupted.
|
||||
if err != nil {
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropHeaderParseError)
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropHeaderParseError)
|
||||
}
|
||||
return
|
||||
// don't return the error here. Just drop the packet.
|
||||
return nil
|
||||
}
|
||||
hdrLen := extHdr.ParsedLen()
|
||||
if _, err := opener.Open(data[hdrLen:hdrLen], data[hdrLen:], extHdr.PacketNumber, data[:hdrLen]); err != nil {
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropPayloadDecryptError)
|
||||
// don't return the error here. Just drop the packet.
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropPayloadDecryptError)
|
||||
}
|
||||
return
|
||||
return nil
|
||||
}
|
||||
if s.logger.Debug() {
|
||||
s.logger.Debugf("Client sent an invalid retry token. Sending INVALID_TOKEN to %s.", p.remoteAddr)
|
||||
}
|
||||
if err := s.sendError(p.remoteAddr, hdr, sealer, qerr.InvalidToken, p.info); err != nil {
|
||||
s.logger.Debugf("Error sending INVALID_TOKEN error: %s", err)
|
||||
}
|
||||
return s.sendError(p.remoteAddr, hdr, sealer, qerr.InvalidToken, p.info)
|
||||
}
|
||||
|
||||
func (s *baseServer) sendConnectionRefused(remoteAddr net.Addr, hdr *wire.Header, info packetInfo) error {
|
||||
func (s *baseServer) sendConnectionRefused(remoteAddr net.Addr, hdr *wire.Header, info *packetInfo) error {
|
||||
sealer, _ := handshake.NewInitialAEAD(hdr.DestConnectionID, protocol.PerspectiveServer, hdr.Version)
|
||||
return s.sendError(remoteAddr, hdr, sealer, qerr.ConnectionRefused, info)
|
||||
}
|
||||
|
||||
// sendError sends the error as a response to the packet received with header hdr
|
||||
func (s *baseServer) sendError(remoteAddr net.Addr, hdr *wire.Header, sealer handshake.LongHeaderSealer, errorCode qerr.TransportErrorCode, info packetInfo) error {
|
||||
func (s *baseServer) sendError(remoteAddr net.Addr, hdr *wire.Header, sealer handshake.LongHeaderSealer, errorCode qerr.TransportErrorCode, info *packetInfo) error {
|
||||
b := getPacketBuffer()
|
||||
defer b.Release()
|
||||
|
||||
|
@ -838,48 +661,21 @@ func (s *baseServer) sendError(remoteAddr net.Addr, hdr *wire.Header, sealer han
|
|||
|
||||
replyHdr.Log(s.logger)
|
||||
wire.LogFrame(s.logger, ccf, true)
|
||||
if s.tracer != nil {
|
||||
s.tracer.SentPacket(remoteAddr, &replyHdr.Header, protocol.ByteCount(len(b.Data)), []logging.Frame{ccf})
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.SentPacket(remoteAddr, &replyHdr.Header, protocol.ByteCount(len(b.Data)), []logging.Frame{ccf})
|
||||
}
|
||||
_, err = s.conn.WritePacket(b.Data, uint16(len(b.Data)), remoteAddr, info.OOB())
|
||||
_, err = s.conn.WritePacket(b.Data, remoteAddr, info.OOB())
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *baseServer) enqueueVersionNegotiationPacket(p receivedPacket) (bufferInUse bool) {
|
||||
select {
|
||||
case s.versionNegotiationQueue <- p:
|
||||
return true
|
||||
default:
|
||||
// it's fine to not send version negotiation packets when we are busy
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *baseServer) maybeSendVersionNegotiationPacket(p receivedPacket) {
|
||||
defer p.buffer.Release()
|
||||
|
||||
v, err := wire.ParseVersion(p.data)
|
||||
if err != nil {
|
||||
s.logger.Debugf("failed to parse version for sending version negotiation packet: %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
_, src, dest, err := wire.ParseArbitraryLenConnectionIDs(p.data)
|
||||
if err != nil { // should never happen
|
||||
s.logger.Debugf("Dropping a packet with an unknown version for which we failed to parse connection IDs")
|
||||
if s.tracer != nil {
|
||||
s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropUnexpectedPacket)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *baseServer) sendVersionNegotiationPacket(remote net.Addr, src, dest protocol.ArbitraryLenConnectionID, oob []byte, v protocol.VersionNumber) {
|
||||
s.logger.Debugf("Client offered version %s, sending Version Negotiation", v)
|
||||
|
||||
data := wire.ComposeVersionNegotiation(dest, src, s.config.Versions)
|
||||
if s.tracer != nil {
|
||||
s.tracer.SentVersionNegotiationPacket(p.remoteAddr, src, dest, s.config.Versions)
|
||||
if s.config.Tracer != nil {
|
||||
s.config.Tracer.SentVersionNegotiationPacket(remote, src, dest, s.config.Versions)
|
||||
}
|
||||
if _, err := s.conn.WritePacket(data, uint16(len(data)), p.remoteAddr, p.info.OOB()); err != nil {
|
||||
if _, err := s.conn.WritePacket(data, remote, oob); err != nil {
|
||||
s.logger.Debugf("Error sending Version Negotiation: %s", err)
|
||||
}
|
||||
}
|
||||
|
|
2
vendor/github.com/quic-go/quic-go/stream.go
generated
vendored
2
vendor/github.com/quic-go/quic-go/stream.go
generated
vendored
|
@ -60,7 +60,7 @@ type streamI interface {
|
|||
// for sending
|
||||
hasData() bool
|
||||
handleStopSendingFrame(*wire.StopSendingFrame)
|
||||
popStreamFrame(maxBytes protocol.ByteCount, v protocol.VersionNumber) (ackhandler.StreamFrame, bool, bool)
|
||||
popStreamFrame(maxBytes protocol.ByteCount, v protocol.VersionNumber) (*ackhandler.Frame, bool)
|
||||
updateSendWindow(protocol.ByteCount)
|
||||
}
|
||||
|
||||
|
|
48
vendor/github.com/quic-go/quic-go/sys_conn.go
generated
vendored
48
vendor/github.com/quic-go/quic-go/sys_conn.go
generated
vendored
|
@ -1,7 +1,6 @@
|
|||
package quic
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"syscall"
|
||||
"time"
|
||||
|
@ -16,38 +15,16 @@ import (
|
|||
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)
|
||||
}
|
||||
|
||||
var _ OOBCapablePacketConn = &net.UDPConn{}
|
||||
|
||||
// OptimizeConn takes a net.PacketConn and attempts to enable various optimizations that will improve QUIC performance:
|
||||
// 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).
|
||||
//
|
||||
// In order for this to work, the connection needs to implement the OOBCapablePacketConn interface (as a *net.UDPConn does).
|
||||
//
|
||||
// It's only necessary to call this function explicitly if the application calls WriteTo
|
||||
// after passing the connection to the Transport.
|
||||
func OptimizeConn(c net.PacketConn) (net.PacketConn, error) {
|
||||
return wrapConn(c)
|
||||
}
|
||||
|
||||
func wrapConn(pc net.PacketConn) (interface {
|
||||
net.PacketConn
|
||||
rawConn
|
||||
}, error,
|
||||
) {
|
||||
func wrapConn(pc net.PacketConn) (rawConn, error) {
|
||||
conn, ok := pc.(interface {
|
||||
SyscallConn() (syscall.RawConn, error)
|
||||
})
|
||||
var supportsDF bool
|
||||
if ok {
|
||||
rawConn, err := conn.SyscallConn()
|
||||
if err != nil {
|
||||
|
@ -56,8 +33,7 @@ func wrapConn(pc net.PacketConn) (interface {
|
|||
|
||||
if _, ok := pc.LocalAddr().(*net.UDPAddr); ok {
|
||||
// Only set DF on sockets that we expect to be able to handle that configuration.
|
||||
var err error
|
||||
supportsDF, err = setDF(rawConn)
|
||||
err = setDF(rawConn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -66,33 +42,32 @@ func wrapConn(pc net.PacketConn) (interface {
|
|||
c, ok := pc.(OOBCapablePacketConn)
|
||||
if !ok {
|
||||
utils.DefaultLogger.Infof("PacketConn is not a net.UDPConn. Disabling optimizations possible on UDP connections.")
|
||||
return &basicConn{PacketConn: pc, supportsDF: supportsDF}, nil
|
||||
return &basicConn{PacketConn: pc}, nil
|
||||
}
|
||||
return newConn(c, supportsDF)
|
||||
return newConn(c)
|
||||
}
|
||||
|
||||
// The basicConn is the most trivial implementation of a rawConn.
|
||||
// The basicConn is the most trivial implementation of a connection.
|
||||
// It reads a single packet from the underlying net.PacketConn.
|
||||
// It is used when
|
||||
// * the net.PacketConn is not a OOBCapablePacketConn, and
|
||||
// * when the OS doesn't support OOB.
|
||||
type basicConn struct {
|
||||
net.PacketConn
|
||||
supportsDF bool
|
||||
}
|
||||
|
||||
var _ rawConn = &basicConn{}
|
||||
|
||||
func (c *basicConn) ReadPacket() (receivedPacket, error) {
|
||||
func (c *basicConn) ReadPacket() (*receivedPacket, error) {
|
||||
buffer := getPacketBuffer()
|
||||
// The packet size should not exceed protocol.MaxPacketBufferSize bytes
|
||||
// If it does, we only read a truncated packet, which will then end up undecryptable
|
||||
buffer.Data = buffer.Data[:protocol.MaxPacketBufferSize]
|
||||
n, addr, err := c.PacketConn.ReadFrom(buffer.Data)
|
||||
if err != nil {
|
||||
return receivedPacket{}, err
|
||||
return nil, err
|
||||
}
|
||||
return receivedPacket{
|
||||
return &receivedPacket{
|
||||
remoteAddr: addr,
|
||||
rcvTime: time.Now(),
|
||||
data: buffer.Data[:n],
|
||||
|
@ -100,11 +75,6 @@ func (c *basicConn) ReadPacket() (receivedPacket, error) {
|
|||
}, nil
|
||||
}
|
||||
|
||||
func (c *basicConn) WritePacket(b []byte, packetSize uint16, addr net.Addr, _ []byte) (n int, err error) {
|
||||
if uint16(len(b)) != packetSize {
|
||||
panic(fmt.Sprintf("inconsistent length. got: %d. expected %d", packetSize, len(b)))
|
||||
}
|
||||
func (c *basicConn) WritePacket(b []byte, addr net.Addr, _ []byte) (n int, err error) {
|
||||
return c.PacketConn.WriteTo(b, addr)
|
||||
}
|
||||
|
||||
func (c *basicConn) capabilities() connCapabilities { return connCapabilities{DF: c.supportsDF} }
|
||||
|
|
68
vendor/github.com/quic-go/quic-go/sys_conn_buffers.go
generated
vendored
68
vendor/github.com/quic-go/quic-go/sys_conn_buffers.go
generated
vendored
|
@ -1,68 +0,0 @@
|
|||
package quic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"syscall"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
"github.com/quic-go/quic-go/internal/utils"
|
||||
)
|
||||
|
||||
//go:generate sh -c "echo '// Code generated by go generate. DO NOT EDIT.\n// Source: sys_conn_buffers.go\n' > sys_conn_buffers_write.go && sed -e 's/SetReadBuffer/SetWriteBuffer/g' -e 's/setReceiveBuffer/setSendBuffer/g' -e 's/inspectReadBuffer/inspectWriteBuffer/g' -e 's/protocol\\.DesiredReceiveBufferSize/protocol\\.DesiredSendBufferSize/g' -e 's/forceSetReceiveBuffer/forceSetSendBuffer/g' -e 's/receive buffer/send buffer/g' sys_conn_buffers.go | sed '/^\\/\\/go:generate/d' >> sys_conn_buffers_write.go"
|
||||
func setReceiveBuffer(c net.PacketConn, logger utils.Logger) error {
|
||||
conn, ok := c.(interface{ SetReadBuffer(int) error })
|
||||
if !ok {
|
||||
return errors.New("connection doesn't allow setting of receive buffer size. Not a *net.UDPConn?")
|
||||
}
|
||||
|
||||
var syscallConn syscall.RawConn
|
||||
if sc, ok := c.(interface {
|
||||
SyscallConn() (syscall.RawConn, error)
|
||||
}); ok {
|
||||
var err error
|
||||
syscallConn, err = sc.SyscallConn()
|
||||
if err != nil {
|
||||
syscallConn = nil
|
||||
}
|
||||
}
|
||||
// The connection has a SetReadBuffer method, but we couldn't obtain a syscall.RawConn.
|
||||
// This shouldn't happen for a net.UDPConn, but is possible if the connection just implements the
|
||||
// net.PacketConn interface and the SetReadBuffer method.
|
||||
// We have no way of checking if increasing the buffer size actually worked.
|
||||
if syscallConn == nil {
|
||||
return conn.SetReadBuffer(protocol.DesiredReceiveBufferSize)
|
||||
}
|
||||
|
||||
size, err := inspectReadBuffer(syscallConn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to determine receive buffer size: %w", err)
|
||||
}
|
||||
if size >= protocol.DesiredReceiveBufferSize {
|
||||
logger.Debugf("Conn has receive buffer of %d kiB (wanted: at least %d kiB)", size/1024, protocol.DesiredReceiveBufferSize/1024)
|
||||
return nil
|
||||
}
|
||||
// Ignore the error. We check if we succeeded by querying the buffer size afterward.
|
||||
_ = conn.SetReadBuffer(protocol.DesiredReceiveBufferSize)
|
||||
newSize, err := inspectReadBuffer(syscallConn)
|
||||
if newSize < protocol.DesiredReceiveBufferSize {
|
||||
// Try again with RCVBUFFORCE on Linux
|
||||
_ = forceSetReceiveBuffer(syscallConn, protocol.DesiredReceiveBufferSize)
|
||||
newSize, err = inspectReadBuffer(syscallConn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to determine receive buffer size: %w", err)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to determine receive buffer size: %w", err)
|
||||
}
|
||||
if newSize == size {
|
||||
return fmt.Errorf("failed to increase receive buffer size (wanted: %d kiB, got %d kiB)", protocol.DesiredReceiveBufferSize/1024, newSize/1024)
|
||||
}
|
||||
if newSize < protocol.DesiredReceiveBufferSize {
|
||||
return fmt.Errorf("failed to sufficiently increase receive buffer size (was: %d kiB, wanted: %d kiB, got: %d kiB)", size/1024, protocol.DesiredReceiveBufferSize/1024, newSize/1024)
|
||||
}
|
||||
logger.Debugf("Increased receive buffer size to %d kiB", newSize/1024)
|
||||
return nil
|
||||
}
|
70
vendor/github.com/quic-go/quic-go/sys_conn_buffers_write.go
generated
vendored
70
vendor/github.com/quic-go/quic-go/sys_conn_buffers_write.go
generated
vendored
|
@ -1,70 +0,0 @@
|
|||
// Code generated by go generate. DO NOT EDIT.
|
||||
// Source: sys_conn_buffers.go
|
||||
|
||||
package quic
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"syscall"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
"github.com/quic-go/quic-go/internal/utils"
|
||||
)
|
||||
|
||||
func setSendBuffer(c net.PacketConn, logger utils.Logger) error {
|
||||
conn, ok := c.(interface{ SetWriteBuffer(int) error })
|
||||
if !ok {
|
||||
return errors.New("connection doesn't allow setting of send buffer size. Not a *net.UDPConn?")
|
||||
}
|
||||
|
||||
var syscallConn syscall.RawConn
|
||||
if sc, ok := c.(interface {
|
||||
SyscallConn() (syscall.RawConn, error)
|
||||
}); ok {
|
||||
var err error
|
||||
syscallConn, err = sc.SyscallConn()
|
||||
if err != nil {
|
||||
syscallConn = nil
|
||||
}
|
||||
}
|
||||
// The connection has a SetWriteBuffer method, but we couldn't obtain a syscall.RawConn.
|
||||
// This shouldn't happen for a net.UDPConn, but is possible if the connection just implements the
|
||||
// net.PacketConn interface and the SetWriteBuffer method.
|
||||
// We have no way of checking if increasing the buffer size actually worked.
|
||||
if syscallConn == nil {
|
||||
return conn.SetWriteBuffer(protocol.DesiredSendBufferSize)
|
||||
}
|
||||
|
||||
size, err := inspectWriteBuffer(syscallConn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to determine send buffer size: %w", err)
|
||||
}
|
||||
if size >= protocol.DesiredSendBufferSize {
|
||||
logger.Debugf("Conn has send buffer of %d kiB (wanted: at least %d kiB)", size/1024, protocol.DesiredSendBufferSize/1024)
|
||||
return nil
|
||||
}
|
||||
// Ignore the error. We check if we succeeded by querying the buffer size afterward.
|
||||
_ = conn.SetWriteBuffer(protocol.DesiredSendBufferSize)
|
||||
newSize, err := inspectWriteBuffer(syscallConn)
|
||||
if newSize < protocol.DesiredSendBufferSize {
|
||||
// Try again with RCVBUFFORCE on Linux
|
||||
_ = forceSetSendBuffer(syscallConn, protocol.DesiredSendBufferSize)
|
||||
newSize, err = inspectWriteBuffer(syscallConn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to determine send buffer size: %w", err)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to determine send buffer size: %w", err)
|
||||
}
|
||||
if newSize == size {
|
||||
return fmt.Errorf("failed to increase send buffer size (wanted: %d kiB, got %d kiB)", protocol.DesiredSendBufferSize/1024, newSize/1024)
|
||||
}
|
||||
if newSize < protocol.DesiredSendBufferSize {
|
||||
return fmt.Errorf("failed to sufficiently increase send buffer size (was: %d kiB, wanted: %d kiB, got: %d kiB)", size/1024, protocol.DesiredSendBufferSize/1024, newSize/1024)
|
||||
}
|
||||
logger.Debugf("Increased send buffer size to %d kiB", newSize/1024)
|
||||
return nil
|
||||
}
|
8
vendor/github.com/quic-go/quic-go/sys_conn_df.go
generated
vendored
8
vendor/github.com/quic-go/quic-go/sys_conn_df.go
generated
vendored
|
@ -2,13 +2,11 @@
|
|||
|
||||
package quic
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
)
|
||||
import "syscall"
|
||||
|
||||
func setDF(syscall.RawConn) (bool, error) {
|
||||
func setDF(rawConn syscall.RawConn) error {
|
||||
// no-op on unsupported platforms
|
||||
return false, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func isMsgSizeErr(err error) bool {
|
||||
|
|
51
vendor/github.com/quic-go/quic-go/sys_conn_df_linux.go
generated
vendored
51
vendor/github.com/quic-go/quic-go/sys_conn_df_linux.go
generated
vendored
|
@ -4,23 +4,14 @@ package quic
|
|||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/utils"
|
||||
)
|
||||
|
||||
// UDP_SEGMENT controls GSO (Generic Segmentation Offload)
|
||||
//
|
||||
//nolint:stylecheck
|
||||
const UDP_SEGMENT = 103
|
||||
|
||||
func setDF(rawConn syscall.RawConn) (bool, error) {
|
||||
func setDF(rawConn syscall.RawConn) error {
|
||||
// Enabling IP_MTU_DISCOVER will force the kernel to return "sendto: message too long"
|
||||
// and the datagram will not be fragmented
|
||||
var errDFIPv4, errDFIPv6 error
|
||||
|
@ -28,7 +19,7 @@ func setDF(rawConn syscall.RawConn) (bool, error) {
|
|||
errDFIPv4 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_MTU_DISCOVER, unix.IP_PMTUDISC_DO)
|
||||
errDFIPv6 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_MTU_DISCOVER, unix.IPV6_PMTUDISC_DO)
|
||||
}); err != nil {
|
||||
return false, err
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case errDFIPv4 == nil && errDFIPv6 == nil:
|
||||
|
@ -38,46 +29,12 @@ func setDF(rawConn syscall.RawConn) (bool, error) {
|
|||
case errDFIPv4 != nil && errDFIPv6 == nil:
|
||||
utils.DefaultLogger.Debugf("Setting DF for IPv6.")
|
||||
case errDFIPv4 != nil && errDFIPv6 != nil:
|
||||
return false, errors.New("setting DF failed for both IPv4 and IPv6")
|
||||
return errors.New("setting DF failed for both IPv4 and IPv6")
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func maybeSetGSO(rawConn syscall.RawConn) bool {
|
||||
disable, _ := strconv.ParseBool(os.Getenv("QUIC_GO_DISABLE_GSO"))
|
||||
if disable {
|
||||
return false
|
||||
}
|
||||
|
||||
var setErr error
|
||||
if err := rawConn.Control(func(fd uintptr) {
|
||||
setErr = unix.SetsockoptInt(int(fd), syscall.IPPROTO_UDP, UDP_SEGMENT, 1)
|
||||
}); err != nil {
|
||||
setErr = err
|
||||
}
|
||||
if setErr != nil {
|
||||
log.Println("failed to enable GSO")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
return nil
|
||||
}
|
||||
|
||||
func isMsgSizeErr(err error) bool {
|
||||
// https://man7.org/linux/man-pages/man7/udp.7.html
|
||||
return errors.Is(err, unix.EMSGSIZE)
|
||||
}
|
||||
|
||||
func appendUDPSegmentSizeMsg(b []byte, size uint16) []byte {
|
||||
startLen := len(b)
|
||||
const dataLen = 2 // payload is a uint16
|
||||
b = append(b, make([]byte, unix.CmsgSpace(dataLen))...)
|
||||
h := (*unix.Cmsghdr)(unsafe.Pointer(&b[startLen]))
|
||||
h.Level = syscall.IPPROTO_UDP
|
||||
h.Type = UDP_SEGMENT
|
||||
h.SetLen(unix.CmsgLen(dataLen))
|
||||
|
||||
// UnixRights uses the private `data` method, but I *think* this achieves the same goal.
|
||||
offset := startLen + unix.CmsgSpace(0)
|
||||
*(*uint16)(unsafe.Pointer(&b[offset])) = size
|
||||
return b
|
||||
}
|
||||
|
|
17
vendor/github.com/quic-go/quic-go/sys_conn_df_windows.go
generated
vendored
17
vendor/github.com/quic-go/quic-go/sys_conn_df_windows.go
generated
vendored
|
@ -12,23 +12,20 @@ import (
|
|||
)
|
||||
|
||||
const (
|
||||
// IP_DONTFRAGMENT controls the Don't Fragment (DF) bit.
|
||||
//
|
||||
// It's the same code point for both IPv4 and IPv6 on Windows.
|
||||
// same for both IPv4 and IPv6 on Windows
|
||||
// https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Networking/WinSock/constant.IP_DONTFRAG.html
|
||||
// https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Networking/WinSock/constant.IPV6_DONTFRAG.html
|
||||
//
|
||||
//nolint:stylecheck
|
||||
IP_DONTFRAGMENT = 14
|
||||
IPV6_DONTFRAG = 14
|
||||
)
|
||||
|
||||
func setDF(rawConn syscall.RawConn) (bool, error) {
|
||||
func setDF(rawConn syscall.RawConn) error {
|
||||
var errDFIPv4, errDFIPv6 error
|
||||
if err := rawConn.Control(func(fd uintptr) {
|
||||
errDFIPv4 = windows.SetsockoptInt(windows.Handle(fd), windows.IPPROTO_IP, IP_DONTFRAGMENT, 1)
|
||||
errDFIPv6 = windows.SetsockoptInt(windows.Handle(fd), windows.IPPROTO_IPV6, IP_DONTFRAGMENT, 1)
|
||||
errDFIPv6 = windows.SetsockoptInt(windows.Handle(fd), windows.IPPROTO_IPV6, IPV6_DONTFRAG, 1)
|
||||
}); err != nil {
|
||||
return false, err
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case errDFIPv4 == nil && errDFIPv6 == nil:
|
||||
|
@ -38,9 +35,9 @@ func setDF(rawConn syscall.RawConn) (bool, error) {
|
|||
case errDFIPv4 != nil && errDFIPv6 == nil:
|
||||
utils.DefaultLogger.Debugf("Setting DF for IPv6.")
|
||||
case errDFIPv4 != nil && errDFIPv6 != nil:
|
||||
return false, errors.New("setting DF failed for both IPv4 and IPv6")
|
||||
return errors.New("setting DF failed for both IPv4 and IPv6")
|
||||
}
|
||||
return true, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func isMsgSizeErr(err error) bool {
|
||||
|
|
26
vendor/github.com/quic-go/quic-go/sys_conn_helper_linux.go
generated
vendored
26
vendor/github.com/quic-go/quic-go/sys_conn_helper_linux.go
generated
vendored
|
@ -2,11 +2,7 @@
|
|||
|
||||
package quic
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
const msgTypeIPTOS = unix.IP_TOS
|
||||
|
||||
|
@ -21,23 +17,3 @@ const (
|
|||
)
|
||||
|
||||
const batchSize = 8 // needs to smaller than MaxUint8 (otherwise the type of oobConn.readPos has to be changed)
|
||||
|
||||
func forceSetReceiveBuffer(c syscall.RawConn, bytes int) error {
|
||||
var serr error
|
||||
if err := c.Control(func(fd uintptr) {
|
||||
serr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_RCVBUFFORCE, bytes)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return serr
|
||||
}
|
||||
|
||||
func forceSetSendBuffer(c syscall.RawConn, bytes int) error {
|
||||
var serr error
|
||||
if err := c.Control(func(fd uintptr) {
|
||||
serr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_SNDBUFFORCE, bytes)
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return serr
|
||||
}
|
||||
|
|
6
vendor/github.com/quic-go/quic-go/sys_conn_helper_nonlinux.go
generated
vendored
6
vendor/github.com/quic-go/quic-go/sys_conn_helper_nonlinux.go
generated
vendored
|
@ -1,6 +0,0 @@
|
|||
//go:build !linux
|
||||
|
||||
package quic
|
||||
|
||||
func forceSetReceiveBuffer(c any, bytes int) error { return nil }
|
||||
func forceSetSendBuffer(c any, bytes int) error { return nil }
|
8
vendor/github.com/quic-go/quic-go/sys_conn_no_gso.go
generated
vendored
8
vendor/github.com/quic-go/quic-go/sys_conn_no_gso.go
generated
vendored
|
@ -1,8 +0,0 @@
|
|||
//go:build darwin || freebsd
|
||||
|
||||
package quic
|
||||
|
||||
import "syscall"
|
||||
|
||||
func maybeSetGSO(_ syscall.RawConn) bool { return false }
|
||||
func appendUDPSegmentSizeMsg(_ []byte, _ uint16) []byte { return nil }
|
16
vendor/github.com/quic-go/quic-go/sys_conn_no_oob.go
generated
vendored
16
vendor/github.com/quic-go/quic-go/sys_conn_no_oob.go
generated
vendored
|
@ -2,20 +2,14 @@
|
|||
|
||||
package quic
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
)
|
||||
import "net"
|
||||
|
||||
func newConn(c net.PacketConn, supportsDF bool) (*basicConn, error) {
|
||||
return &basicConn{PacketConn: c, supportsDF: supportsDF}, nil
|
||||
func newConn(c net.PacketConn) (rawConn, error) {
|
||||
return &basicConn{PacketConn: c}, nil
|
||||
}
|
||||
|
||||
func inspectReadBuffer(any) (int, error) { return 0, nil }
|
||||
func inspectWriteBuffer(any) (int, error) { return 0, nil }
|
||||
|
||||
type packetInfo struct {
|
||||
addr netip.Addr
|
||||
func inspectReadBuffer(interface{}) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (i *packetInfo) OOB() []byte { return nil }
|
||||
|
|
129
vendor/github.com/quic-go/quic-go/sys_conn_oob.go
generated
vendored
129
vendor/github.com/quic-go/quic-go/sys_conn_oob.go
generated
vendored
|
@ -7,7 +7,6 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
|
@ -33,22 +32,21 @@ type batchConn interface {
|
|||
ReadBatch(ms []ipv4.Message, flags int) (int, error)
|
||||
}
|
||||
|
||||
func inspectReadBuffer(c syscall.RawConn) (int, error) {
|
||||
var size int
|
||||
var serr error
|
||||
if err := c.Control(func(fd uintptr) {
|
||||
size, serr = unix.GetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_RCVBUF)
|
||||
}); err != nil {
|
||||
return 0, err
|
||||
func inspectReadBuffer(c interface{}) (int, error) {
|
||||
conn, ok := c.(interface {
|
||||
SyscallConn() (syscall.RawConn, error)
|
||||
})
|
||||
if !ok {
|
||||
return 0, errors.New("doesn't have a SyscallConn")
|
||||
}
|
||||
rawConn, err := conn.SyscallConn()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("couldn't get syscall.RawConn: %w", err)
|
||||
}
|
||||
return size, serr
|
||||
}
|
||||
|
||||
func inspectWriteBuffer(c syscall.RawConn) (int, error) {
|
||||
var size int
|
||||
var serr error
|
||||
if err := c.Control(func(fd uintptr) {
|
||||
size, serr = unix.GetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_SNDBUF)
|
||||
if err := rawConn.Control(func(fd uintptr) {
|
||||
size, serr = unix.GetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_RCVBUF)
|
||||
}); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
@ -63,13 +61,11 @@ type oobConn struct {
|
|||
// Packets received from the kernel, but not yet returned by ReadPacket().
|
||||
messages []ipv4.Message
|
||||
buffers [batchSize]*packetBuffer
|
||||
|
||||
cap connCapabilities
|
||||
}
|
||||
|
||||
var _ rawConn = &oobConn{}
|
||||
|
||||
func newConn(c OOBCapablePacketConn, supportsDF bool) (*oobConn, error) {
|
||||
func newConn(c OOBCapablePacketConn) (*oobConn, error) {
|
||||
rawConn, err := c.SyscallConn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -126,10 +122,6 @@ func newConn(c OOBCapablePacketConn, supportsDF bool) (*oobConn, error) {
|
|||
bc = ipv4.NewPacketConn(c)
|
||||
}
|
||||
|
||||
// Try enabling GSO.
|
||||
// This will only succeed on Linux, and only for kernels > 4.18.
|
||||
supportsGSO := maybeSetGSO(rawConn)
|
||||
|
||||
msgs := make([]ipv4.Message, batchSize)
|
||||
for i := range msgs {
|
||||
// preallocate the [][]byte
|
||||
|
@ -141,15 +133,13 @@ func newConn(c OOBCapablePacketConn, supportsDF bool) (*oobConn, error) {
|
|||
messages: msgs,
|
||||
readPos: batchSize,
|
||||
}
|
||||
oobConn.cap.DF = supportsDF
|
||||
oobConn.cap.GSO = supportsGSO
|
||||
for i := 0; i < batchSize; i++ {
|
||||
oobConn.messages[i].OOB = make([]byte, oobBufferSize)
|
||||
}
|
||||
return oobConn, nil
|
||||
}
|
||||
|
||||
func (c *oobConn) ReadPacket() (receivedPacket, error) {
|
||||
func (c *oobConn) ReadPacket() (*receivedPacket, error) {
|
||||
if len(c.messages) == int(c.readPos) { // all messages read. Read the next batch of messages.
|
||||
c.messages = c.messages[:batchSize]
|
||||
// replace buffers data buffers up to the packet that has been consumed during the last ReadBatch call
|
||||
|
@ -163,7 +153,7 @@ func (c *oobConn) ReadPacket() (receivedPacket, error) {
|
|||
|
||||
n, err := c.batchConn.ReadBatch(c.messages, 0)
|
||||
if n == 0 || err != nil {
|
||||
return receivedPacket{}, err
|
||||
return nil, err
|
||||
}
|
||||
c.messages = c.messages[:n]
|
||||
}
|
||||
|
@ -173,21 +163,18 @@ func (c *oobConn) ReadPacket() (receivedPacket, error) {
|
|||
c.readPos++
|
||||
|
||||
data := msg.OOB[:msg.NN]
|
||||
p := receivedPacket{
|
||||
remoteAddr: msg.Addr,
|
||||
rcvTime: time.Now(),
|
||||
data: msg.Buffers[0][:msg.N],
|
||||
buffer: buffer,
|
||||
}
|
||||
var ecn protocol.ECN
|
||||
var destIP net.IP
|
||||
var ifIndex uint32
|
||||
for len(data) > 0 {
|
||||
hdr, body, remainder, err := unix.ParseOneSocketControlMessage(data)
|
||||
if err != nil {
|
||||
return receivedPacket{}, err
|
||||
return nil, err
|
||||
}
|
||||
if hdr.Level == unix.IPPROTO_IP {
|
||||
switch hdr.Type {
|
||||
case msgTypeIPTOS:
|
||||
p.ecn = protocol.ECN(body[0] & ecnMask)
|
||||
ecn = protocol.ECN(body[0] & ecnMask)
|
||||
case msgTypeIPv4PKTINFO:
|
||||
// struct in_pktinfo {
|
||||
// unsigned int ipi_ifindex; /* Interface index */
|
||||
|
@ -195,94 +182,80 @@ func (c *oobConn) ReadPacket() (receivedPacket, error) {
|
|||
// struct in_addr ipi_addr; /* Header Destination
|
||||
// address */
|
||||
// };
|
||||
var ip [4]byte
|
||||
ip := make([]byte, 4)
|
||||
if len(body) == 12 {
|
||||
copy(ip[:], body[8:12])
|
||||
p.info.ifIndex = binary.LittleEndian.Uint32(body)
|
||||
ifIndex = binary.LittleEndian.Uint32(body)
|
||||
copy(ip, body[8:12])
|
||||
} else if len(body) == 4 {
|
||||
// FreeBSD
|
||||
copy(ip[:], body)
|
||||
copy(ip, body)
|
||||
}
|
||||
p.info.addr = netip.AddrFrom4(ip)
|
||||
destIP = net.IP(ip)
|
||||
}
|
||||
}
|
||||
if hdr.Level == unix.IPPROTO_IPV6 {
|
||||
switch hdr.Type {
|
||||
case unix.IPV6_TCLASS:
|
||||
p.ecn = protocol.ECN(body[0] & ecnMask)
|
||||
ecn = protocol.ECN(body[0] & ecnMask)
|
||||
case msgTypeIPv6PKTINFO:
|
||||
// struct in6_pktinfo {
|
||||
// struct in6_addr ipi6_addr; /* src/dst IPv6 address */
|
||||
// unsigned int ipi6_ifindex; /* send/recv interface index */
|
||||
// };
|
||||
if len(body) == 20 {
|
||||
var ip [16]byte
|
||||
copy(ip[:], body[:16])
|
||||
p.info.addr = netip.AddrFrom16(ip)
|
||||
p.info.ifIndex = binary.LittleEndian.Uint32(body[16:])
|
||||
ip := make([]byte, 16)
|
||||
copy(ip, body[:16])
|
||||
destIP = net.IP(ip)
|
||||
ifIndex = binary.LittleEndian.Uint32(body[16:])
|
||||
}
|
||||
}
|
||||
}
|
||||
data = remainder
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// WriteTo (re)implements the net.PacketConn method.
|
||||
// This is needed for users who call OptimizeConn to be able to send (non-QUIC) packets on the underlying connection.
|
||||
// With GSO enabled, this would otherwise not be needed, as the kernel requires the UDP_SEGMENT message to be set.
|
||||
func (c *oobConn) WriteTo(p []byte, addr net.Addr) (int, error) {
|
||||
return c.WritePacket(p, uint16(len(p)), addr, nil)
|
||||
}
|
||||
|
||||
// WritePacket writes a new packet.
|
||||
// If the connection supports GSO (and we activated GSO support before),
|
||||
// it appends the UDP_SEGMENT size message to oob.
|
||||
// Callers are advised to make sure that oob has a sufficient capacity,
|
||||
// such that appending the UDP_SEGMENT size message doesn't cause an allocation.
|
||||
func (c *oobConn) WritePacket(b []byte, packetSize uint16, addr net.Addr, oob []byte) (n int, err error) {
|
||||
if c.cap.GSO {
|
||||
oob = appendUDPSegmentSizeMsg(oob, packetSize)
|
||||
} else if uint16(len(b)) != packetSize {
|
||||
panic(fmt.Sprintf("inconsistent length. got: %d. expected %d", packetSize, len(b)))
|
||||
var info *packetInfo
|
||||
if destIP != nil {
|
||||
info = &packetInfo{
|
||||
addr: destIP,
|
||||
ifIndex: ifIndex,
|
||||
}
|
||||
}
|
||||
return &receivedPacket{
|
||||
remoteAddr: msg.Addr,
|
||||
rcvTime: time.Now(),
|
||||
data: msg.Buffers[0][:msg.N],
|
||||
ecn: ecn,
|
||||
info: info,
|
||||
buffer: buffer,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *oobConn) WritePacket(b []byte, addr net.Addr, oob []byte) (n int, err error) {
|
||||
n, _, err = c.OOBCapablePacketConn.WriteMsgUDP(b, oob, addr.(*net.UDPAddr))
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (c *oobConn) capabilities() connCapabilities {
|
||||
return c.cap
|
||||
}
|
||||
|
||||
type packetInfo struct {
|
||||
addr netip.Addr
|
||||
ifIndex uint32
|
||||
}
|
||||
|
||||
func (info *packetInfo) OOB() []byte {
|
||||
if info == nil {
|
||||
return nil
|
||||
}
|
||||
if info.addr.Is4() {
|
||||
ip := info.addr.As4()
|
||||
if ip4 := info.addr.To4(); ip4 != nil {
|
||||
// struct in_pktinfo {
|
||||
// unsigned int ipi_ifindex; /* Interface index */
|
||||
// struct in_addr ipi_spec_dst; /* Local address */
|
||||
// struct in_addr ipi_addr; /* Header Destination address */
|
||||
// };
|
||||
cm := ipv4.ControlMessage{
|
||||
Src: ip[:],
|
||||
Src: ip4,
|
||||
IfIndex: int(info.ifIndex),
|
||||
}
|
||||
return cm.Marshal()
|
||||
} else if info.addr.Is6() {
|
||||
ip := info.addr.As16()
|
||||
} else if len(info.addr) == 16 {
|
||||
// struct in6_pktinfo {
|
||||
// struct in6_addr ipi6_addr; /* src/dst IPv6 address */
|
||||
// unsigned int ipi6_ifindex; /* send/recv interface index */
|
||||
// };
|
||||
cm := ipv6.ControlMessage{
|
||||
Src: ip[:],
|
||||
Src: info.addr,
|
||||
IfIndex: int(info.ifIndex),
|
||||
}
|
||||
return cm.Marshal()
|
||||
|
|
37
vendor/github.com/quic-go/quic-go/sys_conn_windows.go
generated
vendored
37
vendor/github.com/quic-go/quic-go/sys_conn_windows.go
generated
vendored
|
@ -3,20 +3,32 @@
|
|||
package quic
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func newConn(c OOBCapablePacketConn, supportsDF bool) (*basicConn, error) {
|
||||
return &basicConn{PacketConn: c, supportsDF: supportsDF}, nil
|
||||
func newConn(c OOBCapablePacketConn) (rawConn, error) {
|
||||
return &basicConn{PacketConn: c}, nil
|
||||
}
|
||||
|
||||
func inspectReadBuffer(c syscall.RawConn) (int, error) {
|
||||
func inspectReadBuffer(c net.PacketConn) (int, error) {
|
||||
conn, ok := c.(interface {
|
||||
SyscallConn() (syscall.RawConn, error)
|
||||
})
|
||||
if !ok {
|
||||
return 0, errors.New("doesn't have a SyscallConn")
|
||||
}
|
||||
rawConn, err := conn.SyscallConn()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("couldn't get syscall.RawConn: %w", err)
|
||||
}
|
||||
var size int
|
||||
var serr error
|
||||
if err := c.Control(func(fd uintptr) {
|
||||
if err := rawConn.Control(func(fd uintptr) {
|
||||
size, serr = windows.GetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_RCVBUF)
|
||||
}); err != nil {
|
||||
return 0, err
|
||||
|
@ -24,19 +36,4 @@ func inspectReadBuffer(c syscall.RawConn) (int, error) {
|
|||
return size, serr
|
||||
}
|
||||
|
||||
func inspectWriteBuffer(c syscall.RawConn) (int, error) {
|
||||
var size int
|
||||
var serr error
|
||||
if err := c.Control(func(fd uintptr) {
|
||||
size, serr = windows.GetsockoptInt(windows.Handle(fd), windows.SOL_SOCKET, windows.SO_SNDBUF)
|
||||
}); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return size, serr
|
||||
}
|
||||
|
||||
type packetInfo struct {
|
||||
addr netip.Addr
|
||||
}
|
||||
|
||||
func (i *packetInfo) OOB() []byte { return nil }
|
||||
|
|
435
vendor/github.com/quic-go/quic-go/transport.go
generated
vendored
435
vendor/github.com/quic-go/quic-go/transport.go
generated
vendored
|
@ -1,435 +0,0 @@
|
|||
package quic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"log"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/wire"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
"github.com/quic-go/quic-go/internal/utils"
|
||||
"github.com/quic-go/quic-go/logging"
|
||||
)
|
||||
|
||||
// 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.
|
||||
type Transport struct {
|
||||
// A single net.PacketConn can only be handled by one Transport.
|
||||
// Bad things will happen if passed to multiple Transports.
|
||||
//
|
||||
// If not done by the user, the connection is passed through OptimizeConn to enable a number of optimizations.
|
||||
// After passing the connection to the Transport, it's invalid to call ReadFrom on the connection.
|
||||
// Calling WriteTo is only valid on the connection returned by OptimizeConn.
|
||||
Conn net.PacketConn
|
||||
|
||||
// The length of the connection ID in bytes.
|
||||
// It can be 0, or any value between 4 and 18.
|
||||
// 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.
|
||||
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
|
||||
|
||||
// A Tracer traces events that don't belong to a single QUIC connection.
|
||||
Tracer logging.Tracer
|
||||
|
||||
handlerMap packetHandlerManager
|
||||
|
||||
mutex sync.Mutex
|
||||
initOnce sync.Once
|
||||
initErr error
|
||||
|
||||
// Set in init.
|
||||
// If no ConnectionIDGenerator is set, this is the ConnectionIDLength.
|
||||
connIDLen int
|
||||
// Set in init.
|
||||
// If no ConnectionIDGenerator is set, this is set to a default.
|
||||
connIDGenerator ConnectionIDGenerator
|
||||
|
||||
server unknownPacketHandler
|
||||
|
||||
conn rawConn
|
||||
|
||||
closeQueue chan closePacket
|
||||
statelessResetQueue chan receivedPacket
|
||||
|
||||
listening chan struct{} // is closed when listen returns
|
||||
closed bool
|
||||
createdConn bool
|
||||
isSingleUse bool // was created for a single server or client, i.e. by calling quic.Listen or quic.Dial
|
||||
|
||||
logger utils.Logger
|
||||
}
|
||||
|
||||
// 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 (t *Transport) Listen(tlsConf *tls.Config, conf *Config) (*Listener, error) {
|
||||
if tlsConf == nil {
|
||||
return nil, errors.New("quic: tls.Config not set")
|
||||
}
|
||||
if err := validateConfig(conf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
t.mutex.Lock()
|
||||
defer t.mutex.Unlock()
|
||||
|
||||
if t.server != nil {
|
||||
return nil, errListenerAlreadySet
|
||||
}
|
||||
conf = populateServerConfig(conf)
|
||||
if err := t.init(true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s, err := newServer(t.conn, t.handlerMap, t.connIDGenerator, tlsConf, conf, t.Tracer, t.closeServer, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.server = s
|
||||
return &Listener{baseServer: s}, nil
|
||||
}
|
||||
|
||||
// ListenEarly 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 (t *Transport) ListenEarly(tlsConf *tls.Config, conf *Config) (*EarlyListener, error) {
|
||||
if tlsConf == nil {
|
||||
return nil, errors.New("quic: tls.Config not set")
|
||||
}
|
||||
if err := validateConfig(conf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
t.mutex.Lock()
|
||||
defer t.mutex.Unlock()
|
||||
|
||||
if t.server != nil {
|
||||
return nil, errListenerAlreadySet
|
||||
}
|
||||
conf = populateServerConfig(conf)
|
||||
if err := t.init(true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s, err := newServer(t.conn, t.handlerMap, t.connIDGenerator, tlsConf, conf, t.Tracer, t.closeServer, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.server = s
|
||||
return &EarlyListener{baseServer: s}, nil
|
||||
}
|
||||
|
||||
// Dial dials a new connection to a remote host (not using 0-RTT).
|
||||
func (t *Transport) Dial(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (Connection, error) {
|
||||
if err := validateConfig(conf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conf = populateConfig(conf)
|
||||
if err := t.init(false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var onClose func()
|
||||
if t.isSingleUse {
|
||||
onClose = func() { t.Close() }
|
||||
}
|
||||
return dial(ctx, newSendConn(t.conn, addr), t.connIDGenerator, t.handlerMap, tlsConf, conf, onClose, false)
|
||||
}
|
||||
|
||||
// DialEarly dials a new connection, attempting to use 0-RTT if possible.
|
||||
func (t *Transport) DialEarly(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (EarlyConnection, error) {
|
||||
if err := validateConfig(conf); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conf = populateConfig(conf)
|
||||
if err := t.init(false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var onClose func()
|
||||
if t.isSingleUse {
|
||||
onClose = func() { t.Close() }
|
||||
}
|
||||
return dial(ctx, newSendConn(t.conn, addr), t.connIDGenerator, t.handlerMap, tlsConf, conf, onClose, true)
|
||||
}
|
||||
|
||||
func (t *Transport) init(isServer bool) error {
|
||||
t.initOnce.Do(func() {
|
||||
getMultiplexer().AddConn(t.Conn)
|
||||
|
||||
var conn rawConn
|
||||
if c, ok := t.Conn.(rawConn); ok {
|
||||
conn = c
|
||||
} else {
|
||||
var err error
|
||||
conn, err = wrapConn(t.Conn)
|
||||
if err != nil {
|
||||
t.initErr = err
|
||||
return
|
||||
}
|
||||
}
|
||||
t.conn = conn
|
||||
|
||||
t.logger = utils.DefaultLogger // TODO: make this configurable
|
||||
t.conn = conn
|
||||
t.handlerMap = newPacketHandlerMap(t.StatelessResetKey, t.enqueueClosePacket, t.logger)
|
||||
t.listening = make(chan struct{})
|
||||
|
||||
t.closeQueue = make(chan closePacket, 4)
|
||||
t.statelessResetQueue = make(chan receivedPacket, 4)
|
||||
|
||||
if t.ConnectionIDGenerator != nil {
|
||||
t.connIDGenerator = t.ConnectionIDGenerator
|
||||
t.connIDLen = t.ConnectionIDGenerator.ConnectionIDLen()
|
||||
} else {
|
||||
connIDLen := t.ConnectionIDLength
|
||||
if t.ConnectionIDLength == 0 && (!t.isSingleUse || isServer) {
|
||||
connIDLen = protocol.DefaultConnectionIDLength
|
||||
}
|
||||
t.connIDLen = connIDLen
|
||||
t.connIDGenerator = &protocol.DefaultConnectionIDGenerator{ConnLen: t.connIDLen}
|
||||
}
|
||||
|
||||
go t.listen(conn)
|
||||
go t.runSendQueue()
|
||||
})
|
||||
return t.initErr
|
||||
}
|
||||
|
||||
func (t *Transport) enqueueClosePacket(p closePacket) {
|
||||
select {
|
||||
case t.closeQueue <- p:
|
||||
default:
|
||||
// Oops, we're backlogged.
|
||||
// Just drop the packet, sending CONNECTION_CLOSE copies is best effort anyway.
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Transport) runSendQueue() {
|
||||
for {
|
||||
select {
|
||||
case <-t.listening:
|
||||
return
|
||||
case p := <-t.closeQueue:
|
||||
t.conn.WritePacket(p.payload, uint16(len(p.payload)), p.addr, p.info.OOB())
|
||||
case p := <-t.statelessResetQueue:
|
||||
t.sendStatelessReset(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close closes the underlying connection and waits until listen has returned.
|
||||
// It is invalid to start new listeners or connections after that.
|
||||
func (t *Transport) Close() error {
|
||||
t.close(errors.New("closing"))
|
||||
if t.createdConn {
|
||||
if err := t.Conn.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if t.conn != nil {
|
||||
t.conn.SetReadDeadline(time.Now())
|
||||
defer func() { t.conn.SetReadDeadline(time.Time{}) }()
|
||||
}
|
||||
if t.listening != nil {
|
||||
<-t.listening // wait until listening returns
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Transport) closeServer() {
|
||||
t.handlerMap.CloseServer()
|
||||
t.mutex.Lock()
|
||||
t.server = nil
|
||||
if t.isSingleUse {
|
||||
t.closed = true
|
||||
}
|
||||
t.mutex.Unlock()
|
||||
if t.createdConn {
|
||||
t.Conn.Close()
|
||||
}
|
||||
if t.isSingleUse {
|
||||
t.conn.SetReadDeadline(time.Now())
|
||||
defer func() { t.conn.SetReadDeadline(time.Time{}) }()
|
||||
<-t.listening // wait until listening returns
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Transport) close(e error) {
|
||||
t.mutex.Lock()
|
||||
defer t.mutex.Unlock()
|
||||
if t.closed {
|
||||
return
|
||||
}
|
||||
|
||||
if t.handlerMap != nil {
|
||||
t.handlerMap.Close(e)
|
||||
}
|
||||
if t.server != nil {
|
||||
t.server.setCloseError(e)
|
||||
}
|
||||
t.closed = true
|
||||
}
|
||||
|
||||
// only print warnings about the UDP receive buffer size once
|
||||
var setBufferWarningOnce sync.Once
|
||||
|
||||
func (t *Transport) listen(conn rawConn) {
|
||||
defer close(t.listening)
|
||||
defer getMultiplexer().RemoveConn(t.Conn)
|
||||
|
||||
if err := setReceiveBuffer(t.Conn, t.logger); err != nil {
|
||||
if !strings.Contains(err.Error(), "use of closed network connection") {
|
||||
setBufferWarningOnce.Do(func() {
|
||||
if disable, _ := strconv.ParseBool(os.Getenv("QUIC_GO_DISABLE_RECEIVE_BUFFER_WARNING")); disable {
|
||||
return
|
||||
}
|
||||
log.Printf("%s. See https://github.com/quic-go/quic-go/wiki/UDP-Receive-Buffer-Size for details.", err)
|
||||
})
|
||||
}
|
||||
}
|
||||
if err := setSendBuffer(t.Conn, t.logger); err != nil {
|
||||
if !strings.Contains(err.Error(), "use of closed network connection") {
|
||||
setBufferWarningOnce.Do(func() {
|
||||
if disable, _ := strconv.ParseBool(os.Getenv("QUIC_GO_DISABLE_RECEIVE_BUFFER_WARNING")); disable {
|
||||
return
|
||||
}
|
||||
log.Printf("%s. See https://github.com/quic-go/quic-go/wiki/UDP-Receive-Buffer-Size for details.", err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
p, err := conn.ReadPacket()
|
||||
//nolint:staticcheck // SA1019 ignore this!
|
||||
// TODO: This code is used to ignore wsa errors on Windows.
|
||||
// Since net.Error.Temporary is deprecated as of Go 1.18, we should find a better solution.
|
||||
// See https://github.com/quic-go/quic-go/issues/1737 for details.
|
||||
if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
|
||||
t.mutex.Lock()
|
||||
closed := t.closed
|
||||
t.mutex.Unlock()
|
||||
if closed {
|
||||
return
|
||||
}
|
||||
t.logger.Debugf("Temporary error reading from conn: %w", err)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
t.close(err)
|
||||
return
|
||||
}
|
||||
t.handlePacket(p)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Transport) handlePacket(p receivedPacket) {
|
||||
connID, err := wire.ParseConnectionID(p.data, t.connIDLen)
|
||||
if err != nil {
|
||||
t.logger.Debugf("error parsing connection ID on packet from %s: %s", p.remoteAddr, err)
|
||||
if t.Tracer != nil {
|
||||
t.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropHeaderParseError)
|
||||
}
|
||||
p.buffer.MaybeRelease()
|
||||
return
|
||||
}
|
||||
|
||||
if isStatelessReset := t.maybeHandleStatelessReset(p.data); isStatelessReset {
|
||||
return
|
||||
}
|
||||
if handler, ok := t.handlerMap.Get(connID); ok {
|
||||
handler.handlePacket(p)
|
||||
return
|
||||
}
|
||||
if !wire.IsLongHeaderPacket(p.data[0]) {
|
||||
t.maybeSendStatelessReset(p)
|
||||
return
|
||||
}
|
||||
|
||||
t.mutex.Lock()
|
||||
defer t.mutex.Unlock()
|
||||
if t.server == nil { // no server set
|
||||
t.logger.Debugf("received a packet with an unexpected connection ID %s", connID)
|
||||
return
|
||||
}
|
||||
t.server.handlePacket(p)
|
||||
}
|
||||
|
||||
func (t *Transport) maybeSendStatelessReset(p receivedPacket) {
|
||||
if t.StatelessResetKey == nil {
|
||||
p.buffer.Release()
|
||||
return
|
||||
}
|
||||
|
||||
// Don't send a stateless reset in response to very small packets.
|
||||
// This includes packets that could be stateless resets.
|
||||
if len(p.data) <= protocol.MinStatelessResetSize {
|
||||
p.buffer.Release()
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case t.statelessResetQueue <- p:
|
||||
default:
|
||||
// it's fine to not send a stateless reset when we're busy
|
||||
p.buffer.Release()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Transport) sendStatelessReset(p receivedPacket) {
|
||||
defer p.buffer.Release()
|
||||
|
||||
connID, err := wire.ParseConnectionID(p.data, t.connIDLen)
|
||||
if err != nil {
|
||||
t.logger.Errorf("error parsing connection ID on packet from %s: %s", p.remoteAddr, err)
|
||||
return
|
||||
}
|
||||
token := t.handlerMap.GetStatelessResetToken(connID)
|
||||
t.logger.Debugf("Sending stateless reset to %s (connection ID: %s). Token: %#x", p.remoteAddr, connID, token)
|
||||
data := make([]byte, protocol.MinStatelessResetSize-16, protocol.MinStatelessResetSize)
|
||||
rand.Read(data)
|
||||
data[0] = (data[0] & 0x7f) | 0x40
|
||||
data = append(data, token[:]...)
|
||||
if _, err := t.conn.WritePacket(data, uint16(len(data)), p.remoteAddr, p.info.OOB()); err != nil {
|
||||
t.logger.Debugf("Error sending Stateless Reset to %s: %s", p.remoteAddr, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Transport) maybeHandleStatelessReset(data []byte) bool {
|
||||
// stateless resets are always short header packets
|
||||
if wire.IsLongHeaderPacket(data[0]) {
|
||||
return false
|
||||
}
|
||||
if len(data) < 17 /* type byte + 16 bytes for the reset token */ {
|
||||
return false
|
||||
}
|
||||
|
||||
token := *(*protocol.StatelessResetToken)(data[len(data)-16:])
|
||||
if conn, ok := t.handlerMap.GetByResetToken(token); ok {
|
||||
t.logger.Debugf("Received a stateless reset with token %#x. Closing connection.", token)
|
||||
go conn.destroy(&StatelessResetError{Token: token})
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
34
vendor/github.com/quic-go/quic-go/zero_rtt_queue.go
generated
vendored
Normal file
34
vendor/github.com/quic-go/quic-go/zero_rtt_queue.go
generated
vendored
Normal file
|
@ -0,0 +1,34 @@
|
|||
package quic
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/quic-go/quic-go/internal/protocol"
|
||||
)
|
||||
|
||||
type zeroRTTQueue struct {
|
||||
queue []*receivedPacket
|
||||
retireTimer *time.Timer
|
||||
}
|
||||
|
||||
var _ packetHandler = &zeroRTTQueue{}
|
||||
|
||||
func (h *zeroRTTQueue) handlePacket(p *receivedPacket) {
|
||||
if len(h.queue) < protocol.Max0RTTQueueLen {
|
||||
h.queue = append(h.queue, p)
|
||||
}
|
||||
}
|
||||
func (h *zeroRTTQueue) shutdown() {}
|
||||
func (h *zeroRTTQueue) destroy(error) {}
|
||||
func (h *zeroRTTQueue) getPerspective() protocol.Perspective { return protocol.PerspectiveClient }
|
||||
func (h *zeroRTTQueue) EnqueueAll(sess packetHandler) {
|
||||
for _, p := range h.queue {
|
||||
sess.handlePacket(p)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *zeroRTTQueue) Clear() {
|
||||
for _, p := range h.queue {
|
||||
p.buffer.Release()
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue