2021-08-03 09:04:02 +00:00
|
|
|
package quic
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"crypto/tls"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
"reflect"
|
|
|
|
"sync"
|
2021-08-27 11:26:00 +00:00
|
|
|
"sync/atomic"
|
2021-08-03 09:04:02 +00:00
|
|
|
"time"
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
"github.com/quic-go/quic-go/internal/ackhandler"
|
|
|
|
"github.com/quic-go/quic-go/internal/flowcontrol"
|
|
|
|
"github.com/quic-go/quic-go/internal/handshake"
|
|
|
|
"github.com/quic-go/quic-go/internal/logutils"
|
|
|
|
"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"
|
|
|
|
"github.com/quic-go/quic-go/logging"
|
2021-08-03 09:04:02 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type unpacker interface {
|
2024-04-18 17:26:01 +00:00
|
|
|
UnpackLongHeader(hdr *wire.Header, rcvTime time.Time, data []byte, v protocol.Version) (*unpackedPacket, error)
|
2023-05-06 00:42:41 +00:00
|
|
|
UnpackShortHeader(rcvTime time.Time, data []byte) (protocol.PacketNumber, protocol.PacketNumberLen, protocol.KeyPhaseBit, []byte, error)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type streamGetter interface {
|
|
|
|
GetOrOpenReceiveStream(protocol.StreamID) (receiveStreamI, error)
|
|
|
|
GetOrOpenSendStream(protocol.StreamID) (sendStreamI, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type streamManager interface {
|
|
|
|
GetOrOpenSendStream(protocol.StreamID) (sendStreamI, error)
|
|
|
|
GetOrOpenReceiveStream(protocol.StreamID) (receiveStreamI, error)
|
|
|
|
OpenStream() (Stream, error)
|
|
|
|
OpenUniStream() (SendStream, error)
|
|
|
|
OpenStreamSync(context.Context) (Stream, error)
|
|
|
|
OpenUniStreamSync(context.Context) (SendStream, error)
|
|
|
|
AcceptStream(context.Context) (Stream, error)
|
|
|
|
AcceptUniStream(context.Context) (ReceiveStream, error)
|
|
|
|
DeleteStream(protocol.StreamID) error
|
|
|
|
UpdateLimits(*wire.TransportParameters)
|
|
|
|
HandleMaxStreamsFrame(*wire.MaxStreamsFrame)
|
|
|
|
CloseWithError(error)
|
|
|
|
ResetFor0RTT()
|
|
|
|
UseResetMaps()
|
|
|
|
}
|
|
|
|
|
|
|
|
type cryptoStreamHandler interface {
|
2024-06-07 15:24:19 +00:00
|
|
|
StartHandshake(context.Context) error
|
2021-08-03 09:04:02 +00:00
|
|
|
ChangeConnectionID(protocol.ConnectionID)
|
|
|
|
SetLargest1RTTAcked(protocol.PacketNumber) error
|
|
|
|
SetHandshakeConfirmed()
|
|
|
|
GetSessionTicket() ([]byte, error)
|
2023-12-04 09:49:00 +00:00
|
|
|
NextEvent() handshake.Event
|
|
|
|
DiscardInitialKeys()
|
2021-08-03 09:04:02 +00:00
|
|
|
io.Closer
|
|
|
|
ConnectionState() handshake.ConnectionState
|
|
|
|
}
|
|
|
|
|
|
|
|
type receivedPacket struct {
|
|
|
|
buffer *packetBuffer
|
|
|
|
|
|
|
|
remoteAddr net.Addr
|
|
|
|
rcvTime time.Time
|
|
|
|
data []byte
|
|
|
|
|
|
|
|
ecn protocol.ECN
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
info packetInfo // only valid if the contained IP address is valid
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (p *receivedPacket) Size() protocol.ByteCount { return protocol.ByteCount(len(p.data)) }
|
|
|
|
|
|
|
|
func (p *receivedPacket) Clone() *receivedPacket {
|
|
|
|
return &receivedPacket{
|
|
|
|
remoteAddr: p.remoteAddr,
|
|
|
|
rcvTime: p.rcvTime,
|
|
|
|
data: p.data,
|
|
|
|
buffer: p.buffer,
|
|
|
|
ecn: p.ecn,
|
|
|
|
info: p.info,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
type connRunner interface {
|
2021-08-03 09:04:02 +00:00
|
|
|
Add(protocol.ConnectionID, packetHandler) bool
|
|
|
|
GetStatelessResetToken(protocol.ConnectionID) protocol.StatelessResetToken
|
|
|
|
Retire(protocol.ConnectionID)
|
|
|
|
Remove(protocol.ConnectionID)
|
2024-04-18 17:26:01 +00:00
|
|
|
ReplaceWithClosed([]protocol.ConnectionID, []byte)
|
2021-08-03 09:04:02 +00:00
|
|
|
AddResetToken(protocol.StatelessResetToken, packetHandler)
|
|
|
|
RemoveResetToken(protocol.StatelessResetToken)
|
|
|
|
}
|
|
|
|
|
|
|
|
type closeError struct {
|
|
|
|
err error
|
|
|
|
remote bool
|
|
|
|
immediate bool
|
|
|
|
}
|
|
|
|
|
|
|
|
type errCloseForRecreating struct {
|
|
|
|
nextPacketNumber protocol.PacketNumber
|
2024-04-18 17:26:01 +00:00
|
|
|
nextVersion protocol.Version
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2021-08-27 11:26:00 +00:00
|
|
|
func (e *errCloseForRecreating) Error() string {
|
2022-06-06 13:15:35 +00:00
|
|
|
return "closing connection in order to recreate it"
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2024-06-07 15:24:19 +00:00
|
|
|
var connTracingID atomic.Uint64 // to be accessed atomically
|
|
|
|
func nextConnTracingID() ConnectionTracingID { return ConnectionTracingID(connTracingID.Add(1)) }
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
// A Connection is a QUIC connection
|
|
|
|
type connection struct {
|
2021-08-03 09:04:02 +00:00
|
|
|
// Destination connection ID used during the handshake.
|
|
|
|
// Used to check source connection ID on incoming packets.
|
|
|
|
handshakeDestConnID protocol.ConnectionID
|
|
|
|
// Set for the client. Destination connection ID used on the first Initial sent.
|
|
|
|
origDestConnID protocol.ConnectionID
|
|
|
|
retrySrcConnID *protocol.ConnectionID // only set for the client (and if a Retry was performed)
|
|
|
|
|
|
|
|
srcConnIDLen int
|
|
|
|
|
|
|
|
perspective protocol.Perspective
|
2024-04-18 17:26:01 +00:00
|
|
|
version protocol.Version
|
2021-08-03 09:04:02 +00:00
|
|
|
config *Config
|
|
|
|
|
|
|
|
conn sendConn
|
|
|
|
sendQueue sender
|
|
|
|
|
|
|
|
streamsMap streamManager
|
|
|
|
connIDManager *connIDManager
|
|
|
|
connIDGenerator *connIDGenerator
|
|
|
|
|
|
|
|
rttStats *utils.RTTStats
|
|
|
|
|
|
|
|
cryptoStreamManager *cryptoStreamManager
|
|
|
|
sentPacketHandler ackhandler.SentPacketHandler
|
|
|
|
receivedPacketHandler ackhandler.ReceivedPacketHandler
|
|
|
|
retransmissionQueue *retransmissionQueue
|
|
|
|
framer framer
|
|
|
|
windowUpdateQueue *windowUpdateQueue
|
|
|
|
connFlowController flowcontrol.ConnectionFlowController
|
|
|
|
tokenStoreKey string // only set for the client
|
|
|
|
tokenGenerator *handshake.TokenGenerator // only set for the server
|
|
|
|
|
|
|
|
unpacker unpacker
|
|
|
|
frameParser wire.FrameParser
|
|
|
|
packer packer
|
2024-06-07 15:24:19 +00:00
|
|
|
mtuDiscoverer mtuDiscoverer // initialized when the transport parameters are received
|
|
|
|
|
|
|
|
maxPayloadSizeEstimate atomic.Uint32
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
initialStream cryptoStream
|
|
|
|
handshakeStream cryptoStream
|
2021-08-03 09:04:02 +00:00
|
|
|
oneRTTStream cryptoStream // only set for the server
|
|
|
|
cryptoStreamHandler cryptoStreamHandler
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
receivedPackets chan receivedPacket
|
2021-08-03 09:04:02 +00:00
|
|
|
sendingScheduled chan struct{}
|
|
|
|
|
|
|
|
closeOnce sync.Once
|
|
|
|
// closeChan is used to notify the run loop that it should terminate
|
|
|
|
closeChan chan closeError
|
|
|
|
|
2024-06-07 15:24:19 +00:00
|
|
|
ctx context.Context
|
|
|
|
ctxCancel context.CancelCauseFunc
|
|
|
|
handshakeCompleteChan chan struct{}
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
undecryptablePackets []receivedPacket // undecryptable packets, waiting for a change in encryption level
|
|
|
|
undecryptablePacketsToProcess []receivedPacket
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
earlyConnReadyChan chan struct{}
|
|
|
|
sentFirstPacket bool
|
2024-04-18 17:26:01 +00:00
|
|
|
droppedInitialKeys bool
|
2023-12-04 09:49:00 +00:00
|
|
|
handshakeComplete bool
|
|
|
|
handshakeConfirmed bool
|
2021-08-03 09:04:02 +00:00
|
|
|
|
|
|
|
receivedRetry bool
|
|
|
|
versionNegotiated bool
|
|
|
|
receivedFirstPacket bool
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
// the minimum of the max_idle_timeout values advertised by both endpoints
|
2022-06-06 13:15:35 +00:00
|
|
|
idleTimeout time.Duration
|
|
|
|
creationTime time.Time
|
2021-08-03 09:04:02 +00:00
|
|
|
// The idle timeout is set based on the max of the time we received the last packet...
|
|
|
|
lastPacketReceivedTime time.Time
|
|
|
|
// ... and the time we sent a new ack-eliciting packet after receiving a packet.
|
|
|
|
firstAckElicitingPacketAfterIdleSentTime time.Time
|
|
|
|
// pacingDeadline is the time when the next packet should be sent
|
|
|
|
pacingDeadline time.Time
|
|
|
|
|
|
|
|
peerParams *wire.TransportParameters
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
timer connectionTimer
|
2021-08-03 09:04:02 +00:00
|
|
|
// keepAlivePingSent stores whether a keep alive PING is in flight.
|
|
|
|
// It is reset as soon as we receive a packet from the peer.
|
|
|
|
keepAlivePingSent bool
|
|
|
|
keepAliveInterval time.Duration
|
|
|
|
|
|
|
|
datagramQueue *datagramQueue
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
connStateMutex sync.Mutex
|
|
|
|
connState ConnectionState
|
|
|
|
|
2021-08-03 09:04:02 +00:00
|
|
|
logID string
|
2023-12-04 09:49:00 +00:00
|
|
|
tracer *logging.ConnectionTracer
|
2021-08-03 09:04:02 +00:00
|
|
|
logger utils.Logger
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
2023-05-06 00:42:41 +00:00
|
|
|
_ Connection = &connection{}
|
|
|
|
_ EarlyConnection = &connection{}
|
|
|
|
_ streamSender = &connection{}
|
2021-08-03 09:04:02 +00:00
|
|
|
)
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
var newConnection = func(
|
2024-06-07 15:24:19 +00:00
|
|
|
ctx context.Context,
|
|
|
|
ctxCancel context.CancelCauseFunc,
|
2021-08-03 09:04:02 +00:00
|
|
|
conn sendConn,
|
2022-06-06 13:15:35 +00:00
|
|
|
runner connRunner,
|
2021-08-03 09:04:02 +00:00
|
|
|
origDestConnID protocol.ConnectionID,
|
|
|
|
retrySrcConnID *protocol.ConnectionID,
|
|
|
|
clientDestConnID protocol.ConnectionID,
|
|
|
|
destConnID protocol.ConnectionID,
|
|
|
|
srcConnID protocol.ConnectionID,
|
2023-05-06 00:42:41 +00:00
|
|
|
connIDGenerator ConnectionIDGenerator,
|
2021-08-03 09:04:02 +00:00
|
|
|
statelessResetToken protocol.StatelessResetToken,
|
|
|
|
conf *Config,
|
|
|
|
tlsConf *tls.Config,
|
|
|
|
tokenGenerator *handshake.TokenGenerator,
|
2023-05-06 00:42:41 +00:00
|
|
|
clientAddressValidated bool,
|
2023-12-04 09:49:00 +00:00
|
|
|
tracer *logging.ConnectionTracer,
|
2021-08-03 09:04:02 +00:00
|
|
|
logger utils.Logger,
|
2024-04-18 17:26:01 +00:00
|
|
|
v protocol.Version,
|
2022-06-06 13:15:35 +00:00
|
|
|
) quicConn {
|
|
|
|
s := &connection{
|
2024-06-07 15:24:19 +00:00
|
|
|
ctx: ctx,
|
|
|
|
ctxCancel: ctxCancel,
|
2023-12-04 09:49:00 +00:00
|
|
|
conn: conn,
|
|
|
|
config: conf,
|
|
|
|
handshakeDestConnID: destConnID,
|
|
|
|
srcConnIDLen: srcConnID.Len(),
|
|
|
|
tokenGenerator: tokenGenerator,
|
|
|
|
oneRTTStream: newCryptoStream(),
|
|
|
|
perspective: protocol.PerspectiveServer,
|
|
|
|
tracer: tracer,
|
|
|
|
logger: logger,
|
|
|
|
version: v,
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
if origDestConnID.Len() > 0 {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.logID = origDestConnID.String()
|
|
|
|
} else {
|
|
|
|
s.logID = destConnID.String()
|
|
|
|
}
|
|
|
|
s.connIDManager = newConnIDManager(
|
|
|
|
destConnID,
|
|
|
|
func(token protocol.StatelessResetToken) { runner.AddResetToken(token, s) },
|
|
|
|
runner.RemoveResetToken,
|
|
|
|
s.queueControlFrame,
|
|
|
|
)
|
|
|
|
s.connIDGenerator = newConnIDGenerator(
|
|
|
|
srcConnID,
|
2023-05-06 00:42:41 +00:00
|
|
|
&clientDestConnID,
|
2021-08-03 09:04:02 +00:00
|
|
|
func(connID protocol.ConnectionID) { runner.Add(connID, s) },
|
|
|
|
runner.GetStatelessResetToken,
|
|
|
|
runner.Remove,
|
|
|
|
runner.Retire,
|
|
|
|
runner.ReplaceWithClosed,
|
|
|
|
s.queueControlFrame,
|
2023-05-06 00:42:41 +00:00
|
|
|
connIDGenerator,
|
2021-08-03 09:04:02 +00:00
|
|
|
)
|
|
|
|
s.preSetup()
|
|
|
|
s.sentPacketHandler, s.receivedPacketHandler = ackhandler.NewAckHandler(
|
|
|
|
0,
|
2024-06-07 15:24:19 +00:00
|
|
|
protocol.ByteCount(s.config.InitialPacketSize),
|
2021-08-03 09:04:02 +00:00
|
|
|
s.rttStats,
|
2023-05-06 00:42:41 +00:00
|
|
|
clientAddressValidated,
|
2023-12-04 09:49:00 +00:00
|
|
|
s.conn.capabilities().ECN,
|
2021-08-03 09:04:02 +00:00
|
|
|
s.perspective,
|
|
|
|
s.tracer,
|
|
|
|
s.logger,
|
|
|
|
)
|
2024-06-07 15:24:19 +00:00
|
|
|
s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(protocol.ByteCount(s.config.InitialPacketSize))))
|
2021-08-03 09:04:02 +00:00
|
|
|
params := &wire.TransportParameters{
|
|
|
|
InitialMaxStreamDataBidiLocal: protocol.ByteCount(s.config.InitialStreamReceiveWindow),
|
|
|
|
InitialMaxStreamDataBidiRemote: protocol.ByteCount(s.config.InitialStreamReceiveWindow),
|
|
|
|
InitialMaxStreamDataUni: protocol.ByteCount(s.config.InitialStreamReceiveWindow),
|
|
|
|
InitialMaxData: protocol.ByteCount(s.config.InitialConnectionReceiveWindow),
|
|
|
|
MaxIdleTimeout: s.config.MaxIdleTimeout,
|
|
|
|
MaxBidiStreamNum: protocol.StreamNum(s.config.MaxIncomingStreams),
|
|
|
|
MaxUniStreamNum: protocol.StreamNum(s.config.MaxIncomingUniStreams),
|
|
|
|
MaxAckDelay: protocol.MaxAckDelayInclGranularity,
|
|
|
|
AckDelayExponent: protocol.AckDelayExponent,
|
2024-06-07 15:24:19 +00:00
|
|
|
MaxUDPPayloadSize: protocol.MaxPacketBufferSize,
|
2021-08-03 09:04:02 +00:00
|
|
|
DisableActiveMigration: true,
|
|
|
|
StatelessResetToken: &statelessResetToken,
|
|
|
|
OriginalDestinationConnectionID: origDestConnID,
|
2023-12-04 09:49:00 +00:00
|
|
|
// 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,
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
if s.config.EnableDatagrams {
|
2023-12-04 09:49:00 +00:00
|
|
|
params.MaxDatagramFrameSize = wire.MaxDatagramSize
|
2023-05-06 00:42:41 +00:00
|
|
|
} else {
|
|
|
|
params.MaxDatagramFrameSize = protocol.InvalidByteCount
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.SentTransportParameters != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.tracer.SentTransportParameters(params)
|
|
|
|
}
|
|
|
|
cs := handshake.NewCryptoSetupServer(
|
|
|
|
clientDestConnID,
|
|
|
|
conn.LocalAddr(),
|
|
|
|
conn.RemoteAddr(),
|
|
|
|
params,
|
|
|
|
tlsConf,
|
2023-05-06 00:42:41 +00:00
|
|
|
conf.Allow0RTT,
|
2021-08-03 09:04:02 +00:00
|
|
|
s.rttStats,
|
|
|
|
tracer,
|
|
|
|
logger,
|
|
|
|
s.version,
|
|
|
|
)
|
|
|
|
s.cryptoStreamHandler = cs
|
2023-12-04 09:49:00 +00:00
|
|
|
s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective)
|
2023-05-06 00:42:41 +00:00
|
|
|
s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen)
|
2023-12-04 09:49:00 +00:00
|
|
|
s.cryptoStreamManager = newCryptoStreamManager(cs, s.initialStream, s.handshakeStream, s.oneRTTStream)
|
2021-08-03 09:04:02 +00:00
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
// declare this as a variable, such that we can it mock it in the tests
|
2022-06-06 13:15:35 +00:00
|
|
|
var newClientConnection = func(
|
2024-06-07 15:24:19 +00:00
|
|
|
ctx context.Context,
|
2021-08-03 09:04:02 +00:00
|
|
|
conn sendConn,
|
2022-06-06 13:15:35 +00:00
|
|
|
runner connRunner,
|
2021-08-03 09:04:02 +00:00
|
|
|
destConnID protocol.ConnectionID,
|
|
|
|
srcConnID protocol.ConnectionID,
|
2023-05-06 00:42:41 +00:00
|
|
|
connIDGenerator ConnectionIDGenerator,
|
2021-08-03 09:04:02 +00:00
|
|
|
conf *Config,
|
|
|
|
tlsConf *tls.Config,
|
|
|
|
initialPacketNumber protocol.PacketNumber,
|
|
|
|
enable0RTT bool,
|
|
|
|
hasNegotiatedVersion bool,
|
2023-12-04 09:49:00 +00:00
|
|
|
tracer *logging.ConnectionTracer,
|
2021-08-03 09:04:02 +00:00
|
|
|
logger utils.Logger,
|
2024-04-18 17:26:01 +00:00
|
|
|
v protocol.Version,
|
2022-06-06 13:15:35 +00:00
|
|
|
) quicConn {
|
|
|
|
s := &connection{
|
2023-12-04 09:49:00 +00:00
|
|
|
conn: conn,
|
|
|
|
config: conf,
|
|
|
|
origDestConnID: destConnID,
|
|
|
|
handshakeDestConnID: destConnID,
|
|
|
|
srcConnIDLen: srcConnID.Len(),
|
|
|
|
perspective: protocol.PerspectiveClient,
|
|
|
|
logID: destConnID.String(),
|
|
|
|
logger: logger,
|
|
|
|
tracer: tracer,
|
|
|
|
versionNegotiated: hasNegotiatedVersion,
|
|
|
|
version: v,
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.connIDManager = newConnIDManager(
|
|
|
|
destConnID,
|
|
|
|
func(token protocol.StatelessResetToken) { runner.AddResetToken(token, s) },
|
|
|
|
runner.RemoveResetToken,
|
|
|
|
s.queueControlFrame,
|
|
|
|
)
|
|
|
|
s.connIDGenerator = newConnIDGenerator(
|
|
|
|
srcConnID,
|
|
|
|
nil,
|
|
|
|
func(connID protocol.ConnectionID) { runner.Add(connID, s) },
|
|
|
|
runner.GetStatelessResetToken,
|
|
|
|
runner.Remove,
|
|
|
|
runner.Retire,
|
|
|
|
runner.ReplaceWithClosed,
|
|
|
|
s.queueControlFrame,
|
2023-05-06 00:42:41 +00:00
|
|
|
connIDGenerator,
|
2021-08-03 09:04:02 +00:00
|
|
|
)
|
2024-06-07 15:24:19 +00:00
|
|
|
s.ctx, s.ctxCancel = context.WithCancelCause(ctx)
|
2021-08-03 09:04:02 +00:00
|
|
|
s.preSetup()
|
|
|
|
s.sentPacketHandler, s.receivedPacketHandler = ackhandler.NewAckHandler(
|
|
|
|
initialPacketNumber,
|
2024-06-07 15:24:19 +00:00
|
|
|
protocol.ByteCount(s.config.InitialPacketSize),
|
2021-08-03 09:04:02 +00:00
|
|
|
s.rttStats,
|
2023-12-04 09:49:00 +00:00
|
|
|
false, // has no effect
|
|
|
|
s.conn.capabilities().ECN,
|
2021-08-03 09:04:02 +00:00
|
|
|
s.perspective,
|
|
|
|
s.tracer,
|
|
|
|
s.logger,
|
|
|
|
)
|
2024-06-07 15:24:19 +00:00
|
|
|
s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(protocol.ByteCount(s.config.InitialPacketSize))))
|
2023-12-04 09:49:00 +00:00
|
|
|
oneRTTStream := newCryptoStream()
|
2021-08-03 09:04:02 +00:00
|
|
|
params := &wire.TransportParameters{
|
|
|
|
InitialMaxStreamDataBidiRemote: protocol.ByteCount(s.config.InitialStreamReceiveWindow),
|
|
|
|
InitialMaxStreamDataBidiLocal: protocol.ByteCount(s.config.InitialStreamReceiveWindow),
|
|
|
|
InitialMaxStreamDataUni: protocol.ByteCount(s.config.InitialStreamReceiveWindow),
|
|
|
|
InitialMaxData: protocol.ByteCount(s.config.InitialConnectionReceiveWindow),
|
|
|
|
MaxIdleTimeout: s.config.MaxIdleTimeout,
|
|
|
|
MaxBidiStreamNum: protocol.StreamNum(s.config.MaxIncomingStreams),
|
|
|
|
MaxUniStreamNum: protocol.StreamNum(s.config.MaxIncomingUniStreams),
|
|
|
|
MaxAckDelay: protocol.MaxAckDelayInclGranularity,
|
2024-06-07 15:24:19 +00:00
|
|
|
MaxUDPPayloadSize: protocol.MaxPacketBufferSize,
|
2021-08-03 09:04:02 +00:00
|
|
|
AckDelayExponent: protocol.AckDelayExponent,
|
|
|
|
DisableActiveMigration: true,
|
2023-12-04 09:49:00 +00:00
|
|
|
// 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,
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
if s.config.EnableDatagrams {
|
2023-12-04 09:49:00 +00:00
|
|
|
params.MaxDatagramFrameSize = wire.MaxDatagramSize
|
2023-05-06 00:42:41 +00:00
|
|
|
} else {
|
|
|
|
params.MaxDatagramFrameSize = protocol.InvalidByteCount
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.SentTransportParameters != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.tracer.SentTransportParameters(params)
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
cs := handshake.NewCryptoSetupClient(
|
2021-08-03 09:04:02 +00:00
|
|
|
destConnID,
|
|
|
|
params,
|
|
|
|
tlsConf,
|
|
|
|
enable0RTT,
|
|
|
|
s.rttStats,
|
|
|
|
tracer,
|
|
|
|
logger,
|
|
|
|
s.version,
|
|
|
|
)
|
|
|
|
s.cryptoStreamHandler = cs
|
2023-12-04 09:49:00 +00:00
|
|
|
s.cryptoStreamManager = newCryptoStreamManager(cs, s.initialStream, s.handshakeStream, oneRTTStream)
|
2023-05-06 00:42:41 +00:00
|
|
|
s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen)
|
2023-12-04 09:49:00 +00:00
|
|
|
s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective)
|
2021-08-03 09:04:02 +00:00
|
|
|
if len(tlsConf.ServerName) > 0 {
|
|
|
|
s.tokenStoreKey = tlsConf.ServerName
|
|
|
|
} else {
|
|
|
|
s.tokenStoreKey = conn.RemoteAddr().String()
|
|
|
|
}
|
|
|
|
if s.config.TokenStore != nil {
|
|
|
|
if token := s.config.TokenStore.Pop(s.tokenStoreKey); token != nil {
|
|
|
|
s.packer.SetToken(token.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) preSetup() {
|
2023-12-04 09:49:00 +00:00
|
|
|
s.initialStream = newCryptoStream()
|
|
|
|
s.handshakeStream = newCryptoStream()
|
2021-08-03 09:04:02 +00:00
|
|
|
s.sendQueue = newSendQueue(s.conn)
|
2023-05-06 00:42:41 +00:00
|
|
|
s.retransmissionQueue = newRetransmissionQueue()
|
2024-04-18 17:26:01 +00:00
|
|
|
s.frameParser = *wire.NewFrameParser(s.config.EnableDatagrams)
|
2021-08-03 09:04:02 +00:00
|
|
|
s.rttStats = &utils.RTTStats{}
|
|
|
|
s.connFlowController = flowcontrol.NewConnectionFlowController(
|
|
|
|
protocol.ByteCount(s.config.InitialConnectionReceiveWindow),
|
|
|
|
protocol.ByteCount(s.config.MaxConnectionReceiveWindow),
|
|
|
|
s.onHasConnectionWindowUpdate,
|
2022-06-06 13:15:35 +00:00
|
|
|
func(size protocol.ByteCount) bool {
|
|
|
|
if s.config.AllowConnectionWindowIncrease == nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return s.config.AllowConnectionWindowIncrease(s, uint64(size))
|
|
|
|
},
|
2021-08-03 09:04:02 +00:00
|
|
|
s.rttStats,
|
|
|
|
s.logger,
|
|
|
|
)
|
2022-06-06 13:15:35 +00:00
|
|
|
s.earlyConnReadyChan = make(chan struct{})
|
2021-08-03 09:04:02 +00:00
|
|
|
s.streamsMap = newStreamsMap(
|
2024-06-07 15:24:19 +00:00
|
|
|
s.ctx,
|
2021-08-03 09:04:02 +00:00
|
|
|
s,
|
|
|
|
s.newFlowController,
|
|
|
|
uint64(s.config.MaxIncomingStreams),
|
|
|
|
uint64(s.config.MaxIncomingUniStreams),
|
|
|
|
s.perspective,
|
|
|
|
)
|
2023-05-06 00:42:41 +00:00
|
|
|
s.framer = newFramer(s.streamsMap)
|
2023-12-04 09:49:00 +00:00
|
|
|
s.receivedPackets = make(chan receivedPacket, protocol.MaxConnUnprocessedPackets)
|
2021-08-03 09:04:02 +00:00
|
|
|
s.closeChan = make(chan closeError, 1)
|
|
|
|
s.sendingScheduled = make(chan struct{}, 1)
|
2024-06-07 15:24:19 +00:00
|
|
|
s.handshakeCompleteChan = make(chan struct{})
|
2021-08-03 09:04:02 +00:00
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
s.lastPacketReceivedTime = now
|
2022-06-06 13:15:35 +00:00
|
|
|
s.creationTime = now
|
2021-08-03 09:04:02 +00:00
|
|
|
|
|
|
|
s.windowUpdateQueue = newWindowUpdateQueue(s.streamsMap, s.connFlowController, s.framer.QueueControlFrame)
|
2023-05-06 00:42:41 +00:00
|
|
|
s.datagramQueue = newDatagramQueue(s.scheduleSending, s.logger)
|
|
|
|
s.connState.Version = s.version
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
// run the connection main loop
|
|
|
|
func (s *connection) run() error {
|
2023-12-04 09:49:00 +00:00
|
|
|
var closeErr closeError
|
2024-06-07 15:24:19 +00:00
|
|
|
defer func() { s.ctxCancel(closeErr.err) }()
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
s.timer = *newTimer()
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2024-06-07 15:24:19 +00:00
|
|
|
if err := s.cryptoStreamHandler.StartHandshake(s.ctx); err != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if err := s.handleHandshakeEvents(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
go func() {
|
|
|
|
if err := s.sendQueue.Run(); err != nil {
|
|
|
|
s.destroyImpl(err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
if s.perspective == protocol.PerspectiveClient {
|
2023-12-04 09:49:00 +00:00
|
|
|
s.scheduleSending() // so the ClientHello actually gets sent
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
var sendQueueAvailable <-chan struct{}
|
2021-08-03 09:04:02 +00:00
|
|
|
|
|
|
|
runLoop:
|
|
|
|
for {
|
2024-04-18 17:26:01 +00:00
|
|
|
if s.framer.QueuedTooManyControlFrames() {
|
|
|
|
s.closeLocal(&qerr.TransportError{ErrorCode: InternalError})
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
// Close immediately if requested
|
|
|
|
select {
|
|
|
|
case closeErr = <-s.closeChan:
|
|
|
|
break runLoop
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
|
|
|
s.maybeResetTimer()
|
|
|
|
|
|
|
|
var processedUndecryptablePacket bool
|
|
|
|
if len(s.undecryptablePacketsToProcess) > 0 {
|
|
|
|
queue := s.undecryptablePacketsToProcess
|
|
|
|
s.undecryptablePacketsToProcess = nil
|
|
|
|
for _, p := range queue {
|
|
|
|
if processed := s.handlePacketImpl(p); processed {
|
|
|
|
processedUndecryptablePacket = true
|
|
|
|
}
|
2022-06-06 13:15:35 +00:00
|
|
|
// Don't set timers and send packets if the packet made us close the connection.
|
2021-08-03 09:04:02 +00:00
|
|
|
select {
|
|
|
|
case closeErr = <-s.closeChan:
|
|
|
|
break runLoop
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
2021-11-10 18:45:26 +00:00
|
|
|
}
|
|
|
|
// If we processed any undecryptable packets, jump to the resetting of the timers directly.
|
|
|
|
if !processedUndecryptablePacket {
|
2021-08-03 09:04:02 +00:00
|
|
|
select {
|
|
|
|
case closeErr = <-s.closeChan:
|
|
|
|
break runLoop
|
|
|
|
case <-s.timer.Chan():
|
|
|
|
s.timer.SetRead()
|
|
|
|
// We do all the interesting stuff after the switch statement, so
|
|
|
|
// nothing to see here.
|
|
|
|
case <-s.sendingScheduled:
|
|
|
|
// We do all the interesting stuff after the switch statement, so
|
|
|
|
// nothing to see here.
|
|
|
|
case <-sendQueueAvailable:
|
|
|
|
case firstPacket := <-s.receivedPackets:
|
|
|
|
wasProcessed := s.handlePacketImpl(firstPacket)
|
2022-06-06 13:15:35 +00:00
|
|
|
// Don't set timers and send packets if the packet made us close the connection.
|
2021-08-03 09:04:02 +00:00
|
|
|
select {
|
|
|
|
case closeErr = <-s.closeChan:
|
|
|
|
break runLoop
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
if s.handshakeComplete {
|
|
|
|
// Now process all packets in the receivedPackets channel.
|
|
|
|
// Limit the number of packets to the length of the receivedPackets channel,
|
|
|
|
// so we eventually get a chance to send out an ACK when receiving a lot of packets.
|
|
|
|
numPackets := len(s.receivedPackets)
|
|
|
|
receiveLoop:
|
|
|
|
for i := 0; i < numPackets; i++ {
|
|
|
|
select {
|
|
|
|
case p := <-s.receivedPackets:
|
|
|
|
if processed := s.handlePacketImpl(p); processed {
|
|
|
|
wasProcessed = true
|
|
|
|
}
|
|
|
|
select {
|
|
|
|
case closeErr = <-s.closeChan:
|
|
|
|
break runLoop
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
break receiveLoop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Only reset the timers if this packet was actually processed.
|
|
|
|
// This avoids modifying any state when handling undecryptable packets,
|
|
|
|
// which could be injected by an attacker.
|
|
|
|
if !wasProcessed {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
if timeout := s.sentPacketHandler.GetLossDetectionTimeout(); !timeout.IsZero() && timeout.Before(now) {
|
|
|
|
// This could cause packets to be retransmitted.
|
|
|
|
// Check it before trying to send packets.
|
|
|
|
if err := s.sentPacketHandler.OnLossDetectionTimeout(); err != nil {
|
|
|
|
s.closeLocal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if keepAliveTime := s.nextKeepAliveTime(); !keepAliveTime.IsZero() && !now.Before(keepAliveTime) {
|
2022-06-06 13:15:35 +00:00
|
|
|
// send a PING frame since there is no activity in the connection
|
2021-08-03 09:04:02 +00:00
|
|
|
s.logger.Debugf("Sending a keep-alive PING to keep the connection alive.")
|
|
|
|
s.framer.QueueControlFrame(&wire.PingFrame{})
|
|
|
|
s.keepAlivePingSent = true
|
2022-06-06 13:15:35 +00:00
|
|
|
} else if !s.handshakeComplete && now.Sub(s.creationTime) >= s.config.handshakeTimeout() {
|
2021-08-27 11:26:00 +00:00
|
|
|
s.destroyImpl(qerr.ErrHandshakeTimeout)
|
2021-08-03 09:04:02 +00:00
|
|
|
continue
|
|
|
|
} else {
|
|
|
|
idleTimeoutStartTime := s.idleTimeoutStartTime()
|
|
|
|
if (!s.handshakeComplete && now.Sub(idleTimeoutStartTime) >= s.config.HandshakeIdleTimeout) ||
|
2023-12-04 09:49:00 +00:00
|
|
|
(s.handshakeComplete && now.After(s.nextIdleTimeoutTime())) {
|
2021-08-27 11:26:00 +00:00
|
|
|
s.destroyImpl(qerr.ErrIdleTimeout)
|
2021-08-03 09:04:02 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.sendQueue.WouldBlock() {
|
|
|
|
// The send queue is still busy sending out packets.
|
|
|
|
// Wait until there's space to enqueue new packets.
|
|
|
|
sendQueueAvailable = s.sendQueue.Available()
|
|
|
|
continue
|
|
|
|
}
|
2024-01-01 09:43:25 +00:00
|
|
|
if err := s.triggerSending(now); err != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.closeLocal(err)
|
|
|
|
}
|
|
|
|
if s.sendQueue.WouldBlock() {
|
|
|
|
sendQueueAvailable = s.sendQueue.Available()
|
|
|
|
} else {
|
|
|
|
sendQueueAvailable = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
s.cryptoStreamHandler.Close()
|
2023-12-04 09:49:00 +00:00
|
|
|
s.sendQueue.Close() // close the send queue before sending the CONNECTION_CLOSE
|
2021-08-27 11:26:00 +00:00
|
|
|
s.handleCloseError(&closeErr)
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.Close != nil {
|
|
|
|
if e := (&errCloseForRecreating{}); !errors.As(closeErr.err, &e) {
|
|
|
|
s.tracer.Close()
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.logger.Infof("Connection %s closed.", s.logID)
|
|
|
|
s.timer.Stop()
|
|
|
|
return closeErr.err
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
// blocks until the early connection can be used
|
|
|
|
func (s *connection) earlyConnReady() <-chan struct{} {
|
|
|
|
return s.earlyConnReadyChan
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
func (s *connection) HandshakeComplete() <-chan struct{} {
|
2024-06-07 15:24:19 +00:00
|
|
|
return s.handshakeCompleteChan
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) Context() context.Context {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.ctx
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) supportsDatagrams() bool {
|
2023-05-06 00:42:41 +00:00
|
|
|
return s.peerParams.MaxDatagramFrameSize > 0
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) ConnectionState() ConnectionState {
|
2023-05-06 00:42:41 +00:00
|
|
|
s.connStateMutex.Lock()
|
|
|
|
defer s.connStateMutex.Unlock()
|
2023-12-04 09:49:00 +00:00
|
|
|
cs := s.cryptoStreamHandler.ConnectionState()
|
|
|
|
s.connState.TLS = cs.ConnectionState
|
|
|
|
s.connState.Used0RTT = cs.Used0RTT
|
|
|
|
s.connState.GSO = s.conn.capabilities().GSO
|
2023-05-06 00:42:41 +00:00
|
|
|
return s.connState
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
// Time when the connection should time out
|
|
|
|
func (s *connection) nextIdleTimeoutTime() time.Time {
|
2024-01-01 09:43:25 +00:00
|
|
|
idleTimeout := max(s.idleTimeout, s.rttStats.PTO(true)*3)
|
2023-12-04 09:49:00 +00:00
|
|
|
return s.idleTimeoutStartTime().Add(idleTimeout)
|
|
|
|
}
|
|
|
|
|
2021-08-03 09:04:02 +00:00
|
|
|
// Time when the next keep-alive packet should be sent.
|
|
|
|
// It returns a zero time if no keep-alive should be sent.
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) nextKeepAliveTime() time.Time {
|
|
|
|
if s.config.KeepAlivePeriod == 0 || s.keepAlivePingSent || !s.firstAckElicitingPacketAfterIdleSentTime.IsZero() {
|
2021-08-03 09:04:02 +00:00
|
|
|
return time.Time{}
|
|
|
|
}
|
2024-01-01 09:43:25 +00:00
|
|
|
keepAliveInterval := max(s.keepAliveInterval, s.rttStats.PTO(true)*3/2)
|
2023-12-04 09:49:00 +00:00
|
|
|
return s.lastPacketReceivedTime.Add(keepAliveInterval)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) maybeResetTimer() {
|
2021-08-03 09:04:02 +00:00
|
|
|
var deadline time.Time
|
|
|
|
if !s.handshakeComplete {
|
2021-08-27 11:26:00 +00:00
|
|
|
deadline = utils.MinTime(
|
2022-06-06 13:15:35 +00:00
|
|
|
s.creationTime.Add(s.config.handshakeTimeout()),
|
2021-08-27 11:26:00 +00:00
|
|
|
s.idleTimeoutStartTime().Add(s.config.HandshakeIdleTimeout),
|
|
|
|
)
|
2021-08-03 09:04:02 +00:00
|
|
|
} else {
|
|
|
|
if keepAliveTime := s.nextKeepAliveTime(); !keepAliveTime.IsZero() {
|
|
|
|
deadline = keepAliveTime
|
|
|
|
} else {
|
2023-12-04 09:49:00 +00:00
|
|
|
deadline = s.nextIdleTimeoutTime()
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2021-08-27 11:26:00 +00:00
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
s.timer.SetTimer(
|
|
|
|
deadline,
|
|
|
|
s.receivedPacketHandler.GetAlarmTimeout(),
|
|
|
|
s.sentPacketHandler.GetLossDetectionTimeout(),
|
|
|
|
s.pacingDeadline,
|
|
|
|
)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) idleTimeoutStartTime() time.Time {
|
2021-08-03 09:04:02 +00:00
|
|
|
return utils.MaxTime(s.lastPacketReceivedTime, s.firstAckElicitingPacketAfterIdleSentTime)
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) handleHandshakeComplete() error {
|
2024-06-07 15:24:19 +00:00
|
|
|
defer close(s.handshakeCompleteChan)
|
2021-08-03 09:04:02 +00:00
|
|
|
// Once the handshake completes, we have derived 1-RTT keys.
|
2023-12-04 09:49:00 +00:00
|
|
|
// There's no point in queueing undecryptable packets for later decryption anymore.
|
2021-08-03 09:04:02 +00:00
|
|
|
s.undecryptablePackets = nil
|
|
|
|
|
|
|
|
s.connIDManager.SetHandshakeComplete()
|
|
|
|
s.connIDGenerator.SetHandshakeComplete()
|
|
|
|
|
2024-01-01 09:43:25 +00:00
|
|
|
if s.tracer != nil && s.tracer.ChoseALPN != nil {
|
|
|
|
s.tracer.ChoseALPN(s.cryptoStreamHandler.ConnectionState().NegotiatedProtocol)
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
// The server applies transport parameters right away, but the client side has to wait for handshake completion.
|
|
|
|
// During a 0-RTT connection, the client is only allowed to use the new transport parameters for 1-RTT packets.
|
2021-08-03 09:04:02 +00:00
|
|
|
if s.perspective == protocol.PerspectiveClient {
|
|
|
|
s.applyTransportParameters()
|
2023-12-04 09:49:00 +00:00
|
|
|
return nil
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
// All these only apply to the server side.
|
|
|
|
if err := s.handleHandshakeConfirmed(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-08-27 11:26:00 +00:00
|
|
|
|
2021-08-03 09:04:02 +00:00
|
|
|
ticket, err := s.cryptoStreamHandler.GetSessionTicket()
|
|
|
|
if err != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
return err
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
if ticket != nil { // may be nil if session tickets are disabled via tls.Config.SessionTicketsDisabled
|
2021-08-03 09:04:02 +00:00
|
|
|
s.oneRTTStream.Write(ticket)
|
|
|
|
for s.oneRTTStream.HasData() {
|
|
|
|
s.queueControlFrame(s.oneRTTStream.PopCryptoFrame(protocol.MaxPostHandshakeCryptoFrameSize))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
token, err := s.tokenGenerator.NewToken(s.conn.RemoteAddr())
|
|
|
|
if err != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
return err
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.queueControlFrame(&wire.NewTokenFrame{Token: token})
|
2021-08-13 14:45:13 +00:00
|
|
|
s.queueControlFrame(&wire.HandshakeDoneFrame{})
|
2023-12-04 09:49:00 +00:00
|
|
|
return nil
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) handleHandshakeConfirmed() error {
|
|
|
|
if err := s.dropEncryptionLevel(protocol.EncryptionHandshake); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-08-27 11:26:00 +00:00
|
|
|
s.handshakeConfirmed = true
|
|
|
|
s.sentPacketHandler.SetHandshakeConfirmed()
|
|
|
|
s.cryptoStreamHandler.SetHandshakeConfirmed()
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
if !s.config.DisablePathMTUDiscovery && s.conn.capabilities().DF {
|
2024-06-07 15:24:19 +00:00
|
|
|
s.mtuDiscoverer.Start()
|
2021-08-27 11:26:00 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
return nil
|
2021-08-27 11:26:00 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) handlePacketImpl(rp receivedPacket) bool {
|
2021-08-27 11:26:00 +00:00
|
|
|
s.sentPacketHandler.ReceivedBytes(rp.Size())
|
|
|
|
|
2021-08-03 09:04:02 +00:00
|
|
|
if wire.IsVersionNegotiationPacket(rp.data) {
|
|
|
|
s.handleVersionNegotiationPacket(rp)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
var counter uint8
|
|
|
|
var lastConnID protocol.ConnectionID
|
|
|
|
var processed bool
|
|
|
|
data := rp.data
|
|
|
|
p := rp
|
|
|
|
for len(data) > 0 {
|
2023-05-06 00:42:41 +00:00
|
|
|
var destConnID protocol.ConnectionID
|
2021-08-03 09:04:02 +00:00
|
|
|
if counter > 0 {
|
2023-12-04 09:49:00 +00:00
|
|
|
p = *(p.Clone())
|
2021-08-03 09:04:02 +00:00
|
|
|
p.data = data
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
var err error
|
|
|
|
destConnID, err = wire.ParseConnectionID(p.data, s.srcConnIDLen)
|
|
|
|
if err != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropHeaderParseError)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
s.logger.Debugf("error parsing packet, couldn't parse connection ID: %s", err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if destConnID != lastConnID {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnknownConnectionID)
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("coalesced packet has different destination connection ID: %s, expected %s", destConnID, lastConnID)
|
|
|
|
break
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
if wire.IsLongHeaderPacket(p.data[0]) {
|
|
|
|
hdr, packetData, rest, err := wire.ParsePacket(p.data)
|
|
|
|
if err != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
2023-05-06 00:42:41 +00:00
|
|
|
dropReason := logging.PacketDropHeaderParseError
|
|
|
|
if err == wire.ErrUnsupportedVersion {
|
|
|
|
dropReason = logging.PacketDropUnsupportedVersion
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), dropReason)
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("error parsing packet: %s", err)
|
|
|
|
break
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
lastConnID = hdr.DestConnectionID
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
if hdr.Version != s.version {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeFromHeader(hdr), protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedVersion)
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("Dropping packet with version %x. Expected %x.", hdr.Version, s.version)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
if counter > 0 {
|
|
|
|
p.buffer.Split()
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
counter++
|
|
|
|
|
|
|
|
// only log if this actually a coalesced packet
|
|
|
|
if s.logger.Debug() && (counter > 1 || len(rest) > 0) {
|
|
|
|
s.logger.Debugf("Parsed a coalesced packet. Part %d: %d bytes. Remaining: %d bytes.", counter, len(packetData), len(rest))
|
|
|
|
}
|
|
|
|
|
|
|
|
p.data = packetData
|
|
|
|
|
|
|
|
if wasProcessed := s.handleLongHeaderPacket(p, hdr); wasProcessed {
|
|
|
|
processed = true
|
|
|
|
}
|
|
|
|
data = rest
|
|
|
|
} else {
|
|
|
|
if counter > 0 {
|
|
|
|
p.buffer.Split()
|
|
|
|
}
|
|
|
|
processed = s.handleShortHeaderPacket(p, destConnID)
|
2021-08-03 09:04:02 +00:00
|
|
|
break
|
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
p.buffer.MaybeRelease()
|
|
|
|
return processed
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) handleShortHeaderPacket(p receivedPacket, destConnID protocol.ConnectionID) bool {
|
2023-05-06 00:42:41 +00:00
|
|
|
var wasQueued bool
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
defer func() {
|
|
|
|
// Put back the packet buffer if the packet wasn't queued for later decryption.
|
|
|
|
if !wasQueued {
|
|
|
|
p.buffer.Decrement()
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
pn, pnLen, keyPhase, data, err := s.unpacker.UnpackShortHeader(p.rcvTime, p.data)
|
|
|
|
if err != nil {
|
|
|
|
wasQueued = s.handleUnpackError(err, p, logging.PacketType1RTT)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.logger.Debug() {
|
|
|
|
s.logger.Debugf("<- Reading packet %d (%d bytes) for connection %s, 1-RTT", pn, p.Size(), destConnID)
|
|
|
|
wire.LogShortHeader(s.logger, destConnID, pn, pnLen, keyPhase)
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.receivedPacketHandler.IsPotentiallyDuplicate(pn, protocol.Encryption1RTT) {
|
|
|
|
s.logger.Debugf("Dropping (potentially) duplicate packet.")
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketType1RTT, pn, p.Size(), logging.PacketDropDuplicate)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
return false
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
|
|
|
|
var log func([]logging.Frame)
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.ReceivedShortHeaderPacket != nil {
|
2023-05-06 00:42:41 +00:00
|
|
|
log = func(frames []logging.Frame) {
|
|
|
|
s.tracer.ReceivedShortHeaderPacket(
|
|
|
|
&logging.ShortHeader{
|
|
|
|
DestConnectionID: destConnID,
|
|
|
|
PacketNumber: pn,
|
|
|
|
PacketNumberLen: pnLen,
|
|
|
|
KeyPhase: keyPhase,
|
|
|
|
},
|
|
|
|
p.Size(),
|
2023-12-04 09:49:00 +00:00
|
|
|
p.ecn,
|
2023-05-06 00:42:41 +00:00
|
|
|
frames,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err := s.handleUnpackedShortHeaderPacket(destConnID, pn, data, p.ecn, p.rcvTime, log); err != nil {
|
|
|
|
s.closeLocal(err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) handleLongHeaderPacket(p receivedPacket, hdr *wire.Header) bool /* was the packet successfully processed */ {
|
2021-08-03 09:04:02 +00:00
|
|
|
var wasQueued bool
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
// Put back the packet buffer if the packet wasn't queued for later decryption.
|
|
|
|
if !wasQueued {
|
|
|
|
p.buffer.Decrement()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
if hdr.Type == protocol.PacketTypeRetry {
|
2023-12-04 09:49:00 +00:00
|
|
|
return s.handleRetryPacket(hdr, p.data, p.rcvTime)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// The server can change the source connection ID with the first Handshake packet.
|
|
|
|
// After this, all packets with a different source connection have to be ignored.
|
2023-05-06 00:42:41 +00:00
|
|
|
if s.receivedFirstPacket && hdr.Type == protocol.PacketTypeInitial && hdr.SrcConnectionID != s.handshakeDestConnID {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeInitial, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropUnknownConnectionID)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("Dropping Initial packet (%d bytes) with unexpected source connection ID: %s (expected %s)", p.Size(), hdr.SrcConnectionID, s.handshakeDestConnID)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// drop 0-RTT packets, if we are a client
|
|
|
|
if s.perspective == protocol.PerspectiveClient && hdr.Type == protocol.PacketType0RTT {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketType0RTT, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropKeyUnavailable)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
packet, err := s.unpacker.UnpackLongHeader(hdr, p.rcvTime, p.data, s.version)
|
2021-08-03 09:04:02 +00:00
|
|
|
if err != nil {
|
2023-05-06 00:42:41 +00:00
|
|
|
wasQueued = s.handleUnpackError(err, p, logging.PacketTypeFromHeader(hdr))
|
2021-08-03 09:04:02 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.logger.Debug() {
|
2023-05-06 00:42:41 +00:00
|
|
|
s.logger.Debugf("<- Reading packet %d (%d bytes) for connection %s, %s", packet.hdr.PacketNumber, p.Size(), hdr.DestConnectionID, packet.encryptionLevel)
|
2021-08-03 09:04:02 +00:00
|
|
|
packet.hdr.Log(s.logger)
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
if pn := packet.hdr.PacketNumber; s.receivedPacketHandler.IsPotentiallyDuplicate(pn, packet.encryptionLevel) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.logger.Debugf("Dropping (potentially) duplicate packet.")
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeFromHeader(hdr), pn, p.Size(), logging.PacketDropDuplicate)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
if err := s.handleUnpackedLongHeaderPacket(packet, p.ecn, p.rcvTime, p.Size()); err != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.closeLocal(err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) handleUnpackError(err error, p receivedPacket, pt logging.PacketType) (wasQueued bool) {
|
2023-05-06 00:42:41 +00:00
|
|
|
switch err {
|
|
|
|
case handshake.ErrKeysDropped:
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropKeyUnavailable)
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("Dropping %s packet (%d bytes) because we already dropped the keys.", pt, p.Size())
|
|
|
|
case handshake.ErrKeysNotYetAvailable:
|
|
|
|
// Sealer for this encryption level not yet available.
|
|
|
|
// Try again later.
|
|
|
|
s.tryQueueingUndecryptablePacket(p, pt)
|
|
|
|
return true
|
|
|
|
case wire.ErrInvalidReservedBits:
|
|
|
|
s.closeLocal(&qerr.TransportError{
|
|
|
|
ErrorCode: qerr.ProtocolViolation,
|
|
|
|
ErrorMessage: err.Error(),
|
|
|
|
})
|
|
|
|
case handshake.ErrDecryptionFailed:
|
|
|
|
// This might be a packet injected by an attacker. Drop it.
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropPayloadDecryptError)
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("Dropping %s packet (%d bytes) that could not be unpacked. Error: %s", pt, p.Size(), err)
|
|
|
|
default:
|
|
|
|
var headerErr *headerParseError
|
|
|
|
if errors.As(err, &headerErr) {
|
|
|
|
// This might be a packet injected by an attacker. Drop it.
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropHeaderParseError)
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("Dropping %s packet (%d bytes) for which we couldn't unpack the header. Error: %s", pt, p.Size(), err)
|
|
|
|
} else {
|
|
|
|
// This is an error returned by the AEAD (other than ErrDecryptionFailed).
|
|
|
|
// For example, a PROTOCOL_VIOLATION due to key updates.
|
|
|
|
s.closeLocal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) handleRetryPacket(hdr *wire.Header, data []byte, rcvTime time.Time) bool /* was this a valid Retry */ {
|
2021-08-03 09:04:02 +00:00
|
|
|
if s.perspective == protocol.PerspectiveServer {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("Ignoring Retry.")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if s.receivedFirstPacket {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("Ignoring Retry, since we already received a packet.")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
destConnID := s.connIDManager.Get()
|
2023-05-06 00:42:41 +00:00
|
|
|
if hdr.SrcConnectionID == destConnID {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("Ignoring Retry, since the server didn't change the Source Connection ID.")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
// If a token is already set, this means that we already received a Retry from the server.
|
|
|
|
// Ignore this Retry packet.
|
|
|
|
if s.receivedRetry {
|
|
|
|
s.logger.Debugf("Ignoring Retry, since a Retry was already received.")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
tag := handshake.GetRetryIntegrityTag(data[:len(data)-16], destConnID, hdr.Version)
|
|
|
|
if !bytes.Equal(data[len(data)-16:], tag[:]) {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropPayloadDecryptError)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("Ignoring spoofed Retry. Integrity Tag doesn't match.")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
if s.logger.Debug() {
|
|
|
|
s.logger.Debugf("<- Received Retry:")
|
|
|
|
(&wire.ExtendedHeader{Header: *hdr}).Log(s.logger)
|
|
|
|
s.logger.Debugf("Switching destination connection ID to: %s", hdr.SrcConnectionID)
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.ReceivedRetry != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.tracer.ReceivedRetry(hdr)
|
|
|
|
}
|
|
|
|
newDestConnID := hdr.SrcConnectionID
|
|
|
|
s.receivedRetry = true
|
2023-12-04 09:49:00 +00:00
|
|
|
if err := s.sentPacketHandler.ResetForRetry(rcvTime); err != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.closeLocal(err)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
s.handshakeDestConnID = newDestConnID
|
|
|
|
s.retrySrcConnID = &newDestConnID
|
|
|
|
s.cryptoStreamHandler.ChangeConnectionID(newDestConnID)
|
|
|
|
s.packer.SetToken(hdr.Token)
|
|
|
|
s.connIDManager.ChangeInitialConnID(newDestConnID)
|
|
|
|
s.scheduleSending()
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) handleVersionNegotiationPacket(p receivedPacket) {
|
2021-08-03 09:04:02 +00:00
|
|
|
if s.perspective == protocol.PerspectiveServer || // servers never receive version negotiation packets
|
|
|
|
s.receivedFirstPacket || s.versionNegotiated { // ignore delayed / duplicated version negotiation packets
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropUnexpectedPacket)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
src, dest, supportedVersions, err := wire.ParseVersionNegotiationPacket(p.data)
|
2021-08-03 09:04:02 +00:00
|
|
|
if err != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropHeaderParseError)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.logger.Debugf("Error parsing Version Negotiation packet: %s", err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, v := range supportedVersions {
|
|
|
|
if v == s.version {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropUnexpectedVersion)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
// The Version Negotiation packet contains the version that we offered.
|
|
|
|
// This might be a packet sent by an attacker, or it was corrupted.
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
s.logger.Infof("Received a Version Negotiation packet. Supported Versions: %s", supportedVersions)
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.ReceivedVersionNegotiationPacket != nil {
|
2023-05-06 00:42:41 +00:00
|
|
|
s.tracer.ReceivedVersionNegotiationPacket(dest, src, supportedVersions)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
newVersion, ok := protocol.ChooseSupportedVersion(s.config.Versions, supportedVersions)
|
|
|
|
if !ok {
|
2021-08-27 11:26:00 +00:00
|
|
|
s.destroyImpl(&VersionNegotiationError{
|
|
|
|
Ours: s.config.Versions,
|
|
|
|
Theirs: supportedVersions,
|
2021-08-03 09:04:02 +00:00
|
|
|
})
|
|
|
|
s.logger.Infof("No compatible QUIC version found.")
|
|
|
|
return
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.NegotiatedVersion != nil {
|
2021-08-27 11:26:00 +00:00
|
|
|
s.tracer.NegotiatedVersion(newVersion, s.config.Versions, supportedVersions)
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
|
|
|
|
s.logger.Infof("Switching to QUIC version %s.", newVersion)
|
|
|
|
nextPN, _ := s.sentPacketHandler.PeekPacketNumber(protocol.EncryptionInitial)
|
|
|
|
s.destroyImpl(&errCloseForRecreating{
|
|
|
|
nextPacketNumber: nextPN,
|
|
|
|
nextVersion: newVersion,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
func (s *connection) handleUnpackedLongHeaderPacket(
|
2021-08-03 09:04:02 +00:00
|
|
|
packet *unpackedPacket,
|
|
|
|
ecn protocol.ECN,
|
|
|
|
rcvTime time.Time,
|
|
|
|
packetSize protocol.ByteCount, // only for logging
|
|
|
|
) error {
|
|
|
|
if !s.receivedFirstPacket {
|
|
|
|
s.receivedFirstPacket = true
|
2023-12-04 09:49:00 +00:00
|
|
|
if !s.versionNegotiated && s.tracer != nil && s.tracer.NegotiatedVersion != nil {
|
2024-04-18 17:26:01 +00:00
|
|
|
var clientVersions, serverVersions []protocol.Version
|
2021-08-27 11:26:00 +00:00
|
|
|
switch s.perspective {
|
|
|
|
case protocol.PerspectiveClient:
|
|
|
|
clientVersions = s.config.Versions
|
|
|
|
case protocol.PerspectiveServer:
|
|
|
|
serverVersions = s.config.Versions
|
|
|
|
}
|
|
|
|
s.tracer.NegotiatedVersion(s.version, clientVersions, serverVersions)
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
// The server can change the source connection ID with the first Handshake packet.
|
2023-05-06 00:42:41 +00:00
|
|
|
if s.perspective == protocol.PerspectiveClient && packet.hdr.SrcConnectionID != s.handshakeDestConnID {
|
2021-08-03 09:04:02 +00:00
|
|
|
cid := packet.hdr.SrcConnectionID
|
|
|
|
s.logger.Debugf("Received first packet. Switching destination connection ID to: %s", cid)
|
|
|
|
s.handshakeDestConnID = cid
|
|
|
|
s.connIDManager.ChangeInitialConnID(cid)
|
|
|
|
}
|
2022-06-06 13:15:35 +00:00
|
|
|
// We create the connection as soon as we receive the first packet from the client.
|
2021-08-03 09:04:02 +00:00
|
|
|
// We do that before authenticating the packet.
|
|
|
|
// That means that if the source connection ID was corrupted,
|
2023-05-06 00:42:41 +00:00
|
|
|
// we might have created a connection with an incorrect source connection ID.
|
2021-08-03 09:04:02 +00:00
|
|
|
// Once we authenticate the first packet, we need to update it.
|
|
|
|
if s.perspective == protocol.PerspectiveServer {
|
2023-05-06 00:42:41 +00:00
|
|
|
if packet.hdr.SrcConnectionID != s.handshakeDestConnID {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.handshakeDestConnID = packet.hdr.SrcConnectionID
|
|
|
|
s.connIDManager.ChangeInitialConnID(packet.hdr.SrcConnectionID)
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.StartedConnection != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.tracer.StartedConnection(
|
|
|
|
s.conn.LocalAddr(),
|
|
|
|
s.conn.RemoteAddr(),
|
|
|
|
packet.hdr.SrcConnectionID,
|
|
|
|
packet.hdr.DestConnectionID,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-18 17:26:01 +00:00
|
|
|
if s.perspective == protocol.PerspectiveServer && packet.encryptionLevel == protocol.EncryptionHandshake &&
|
|
|
|
!s.droppedInitialKeys {
|
2023-12-04 09:49:00 +00:00
|
|
|
// On the server side, Initial keys are dropped as soon as the first Handshake packet is received.
|
|
|
|
// See Section 4.9.1 of RFC 9001.
|
|
|
|
if err := s.dropEncryptionLevel(protocol.EncryptionInitial); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-03 09:04:02 +00:00
|
|
|
s.lastPacketReceivedTime = rcvTime
|
|
|
|
s.firstAckElicitingPacketAfterIdleSentTime = time.Time{}
|
|
|
|
s.keepAlivePingSent = false
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
var log func([]logging.Frame)
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.ReceivedLongHeaderPacket != nil {
|
2023-05-06 00:42:41 +00:00
|
|
|
log = func(frames []logging.Frame) {
|
2023-12-04 09:49:00 +00:00
|
|
|
s.tracer.ReceivedLongHeaderPacket(packet.hdr, packetSize, ecn, frames)
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
isAckEliciting, err := s.handleFrames(packet.data, packet.hdr.DestConnectionID, packet.encryptionLevel, log)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return s.receivedPacketHandler.ReceivedPacket(packet.hdr.PacketNumber, ecn, packet.encryptionLevel, rcvTime, isAckEliciting)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *connection) handleUnpackedShortHeaderPacket(
|
|
|
|
destConnID protocol.ConnectionID,
|
|
|
|
pn protocol.PacketNumber,
|
|
|
|
data []byte,
|
|
|
|
ecn protocol.ECN,
|
|
|
|
rcvTime time.Time,
|
|
|
|
log func([]logging.Frame),
|
|
|
|
) error {
|
|
|
|
s.lastPacketReceivedTime = rcvTime
|
|
|
|
s.firstAckElicitingPacketAfterIdleSentTime = time.Time{}
|
|
|
|
s.keepAlivePingSent = false
|
|
|
|
|
|
|
|
isAckEliciting, err := s.handleFrames(data, destConnID, protocol.Encryption1RTT, log)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return s.receivedPacketHandler.ReceivedPacket(pn, ecn, protocol.Encryption1RTT, rcvTime, isAckEliciting)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *connection) handleFrames(
|
|
|
|
data []byte,
|
|
|
|
destConnID protocol.ConnectionID,
|
|
|
|
encLevel protocol.EncryptionLevel,
|
|
|
|
log func([]logging.Frame),
|
|
|
|
) (isAckEliciting bool, _ error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
// Only used for tracing.
|
|
|
|
// If we're not tracing, this slice will always remain empty.
|
2023-12-04 09:49:00 +00:00
|
|
|
var frames []logging.Frame
|
|
|
|
if log != nil {
|
|
|
|
frames = make([]logging.Frame, 0, 4)
|
|
|
|
}
|
|
|
|
handshakeWasComplete := s.handshakeComplete
|
|
|
|
var handleErr error
|
2023-05-06 00:42:41 +00:00
|
|
|
for len(data) > 0 {
|
|
|
|
l, frame, err := s.frameParser.ParseNext(data, encLevel, s.version)
|
2021-08-03 09:04:02 +00:00
|
|
|
if err != nil {
|
2023-05-06 00:42:41 +00:00
|
|
|
return false, err
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
data = data[l:]
|
2021-08-03 09:04:02 +00:00
|
|
|
if frame == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if ackhandler.IsFrameAckEliciting(frame) {
|
|
|
|
isAckEliciting = true
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
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 {
|
2023-05-06 00:42:41 +00:00
|
|
|
return false, err
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
// If we're logging, we need to keep parsing (but not handling) all frames.
|
|
|
|
handleErr = err
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
if log != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
log(frames)
|
|
|
|
if handleErr != nil {
|
|
|
|
return false, handleErr
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Handle completion of the handshake after processing all the frames.
|
|
|
|
// This ensures that we correctly handle the following case on the server side:
|
|
|
|
// We receive a Handshake packet that contains the CRYPTO frame that allows us to complete the handshake,
|
|
|
|
// and an ACK serialized after that CRYPTO frame. In this case, we still want to process the ACK frame.
|
|
|
|
if !handshakeWasComplete && s.handshakeComplete {
|
|
|
|
if err := s.handleHandshakeComplete(); err != nil {
|
|
|
|
return false, err
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
return
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleFrame(f wire.Frame, encLevel protocol.EncryptionLevel, destConnID protocol.ConnectionID) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
var err error
|
|
|
|
wire.LogFrame(s.logger, f, false)
|
|
|
|
switch frame := f.(type) {
|
|
|
|
case *wire.CryptoFrame:
|
|
|
|
err = s.handleCryptoFrame(frame, encLevel)
|
|
|
|
case *wire.StreamFrame:
|
|
|
|
err = s.handleStreamFrame(frame)
|
|
|
|
case *wire.AckFrame:
|
|
|
|
err = s.handleAckFrame(frame, encLevel)
|
|
|
|
case *wire.ConnectionCloseFrame:
|
|
|
|
s.handleConnectionCloseFrame(frame)
|
|
|
|
case *wire.ResetStreamFrame:
|
|
|
|
err = s.handleResetStreamFrame(frame)
|
|
|
|
case *wire.MaxDataFrame:
|
|
|
|
s.handleMaxDataFrame(frame)
|
|
|
|
case *wire.MaxStreamDataFrame:
|
|
|
|
err = s.handleMaxStreamDataFrame(frame)
|
|
|
|
case *wire.MaxStreamsFrame:
|
|
|
|
s.handleMaxStreamsFrame(frame)
|
|
|
|
case *wire.DataBlockedFrame:
|
|
|
|
case *wire.StreamDataBlockedFrame:
|
|
|
|
case *wire.StreamsBlockedFrame:
|
|
|
|
case *wire.StopSendingFrame:
|
|
|
|
err = s.handleStopSendingFrame(frame)
|
|
|
|
case *wire.PingFrame:
|
|
|
|
case *wire.PathChallengeFrame:
|
|
|
|
s.handlePathChallengeFrame(frame)
|
|
|
|
case *wire.PathResponseFrame:
|
|
|
|
// since we don't send PATH_CHALLENGEs, we don't expect PATH_RESPONSEs
|
|
|
|
err = errors.New("unexpected PATH_RESPONSE frame")
|
|
|
|
case *wire.NewTokenFrame:
|
|
|
|
err = s.handleNewTokenFrame(frame)
|
|
|
|
case *wire.NewConnectionIDFrame:
|
|
|
|
err = s.handleNewConnectionIDFrame(frame)
|
|
|
|
case *wire.RetireConnectionIDFrame:
|
|
|
|
err = s.handleRetireConnectionIDFrame(frame, destConnID)
|
|
|
|
case *wire.HandshakeDoneFrame:
|
|
|
|
err = s.handleHandshakeDoneFrame()
|
|
|
|
case *wire.DatagramFrame:
|
|
|
|
err = s.handleDatagramFrame(frame)
|
|
|
|
default:
|
|
|
|
err = fmt.Errorf("unexpected frame type: %s", reflect.ValueOf(&frame).Elem().Type().Name())
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// handlePacket is called by the server with a new packet
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) handlePacket(p receivedPacket) {
|
2021-08-03 09:04:02 +00:00
|
|
|
// Discard packets once the amount of queued packets is larger than
|
2022-06-06 13:15:35 +00:00
|
|
|
// the channel size, protocol.MaxConnUnprocessedPackets
|
2021-08-03 09:04:02 +00:00
|
|
|
select {
|
|
|
|
case s.receivedPackets <- p:
|
|
|
|
default:
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropDOSPrevention)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleConnectionCloseFrame(frame *wire.ConnectionCloseFrame) {
|
2021-08-03 09:04:02 +00:00
|
|
|
if frame.IsApplicationError {
|
2021-08-27 11:26:00 +00:00
|
|
|
s.closeRemote(&qerr.ApplicationError{
|
|
|
|
Remote: true,
|
|
|
|
ErrorCode: qerr.ApplicationErrorCode(frame.ErrorCode),
|
|
|
|
ErrorMessage: frame.ReasonPhrase,
|
|
|
|
})
|
|
|
|
return
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2021-08-27 11:26:00 +00:00
|
|
|
s.closeRemote(&qerr.TransportError{
|
|
|
|
Remote: true,
|
|
|
|
ErrorCode: qerr.TransportErrorCode(frame.ErrorCode),
|
|
|
|
FrameType: frame.FrameType,
|
|
|
|
ErrorMessage: frame.ReasonPhrase,
|
|
|
|
})
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleCryptoFrame(frame *wire.CryptoFrame, encLevel protocol.EncryptionLevel) error {
|
2023-12-04 09:49:00 +00:00
|
|
|
if err := s.cryptoStreamManager.HandleCryptoFrame(frame, encLevel); err != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
return err
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
return s.handleHandshakeEvents()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *connection) handleHandshakeEvents() error {
|
|
|
|
for {
|
|
|
|
ev := s.cryptoStreamHandler.NextEvent()
|
|
|
|
var err error
|
|
|
|
switch ev.Kind {
|
|
|
|
case handshake.EventNoEvent:
|
|
|
|
return nil
|
|
|
|
case handshake.EventHandshakeComplete:
|
|
|
|
// Don't call handleHandshakeComplete yet.
|
|
|
|
// It's advantageous to process ACK frames that might be serialized after the CRYPTO frame first.
|
|
|
|
s.handshakeComplete = true
|
|
|
|
case handshake.EventReceivedTransportParameters:
|
|
|
|
err = s.handleTransportParameters(ev.TransportParameters)
|
|
|
|
case handshake.EventRestoredTransportParameters:
|
|
|
|
s.restoreTransportParameters(ev.TransportParameters)
|
|
|
|
close(s.earlyConnReadyChan)
|
|
|
|
case handshake.EventReceivedReadKeys:
|
|
|
|
// Queue all packets for decryption that have been undecryptable so far.
|
|
|
|
s.undecryptablePacketsToProcess = s.undecryptablePackets
|
|
|
|
s.undecryptablePackets = nil
|
|
|
|
case handshake.EventDiscard0RTTKeys:
|
|
|
|
err = s.dropEncryptionLevel(protocol.Encryption0RTT)
|
|
|
|
case handshake.EventWriteInitialData:
|
|
|
|
_, err = s.initialStream.Write(ev.Data)
|
|
|
|
case handshake.EventWriteHandshakeData:
|
|
|
|
_, err = s.handshakeStream.Write(ev.Data)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleStreamFrame(frame *wire.StreamFrame) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
str, err := s.streamsMap.GetOrOpenReceiveStream(frame.StreamID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if str == nil {
|
|
|
|
// Stream is closed and already garbage collected
|
|
|
|
// ignore this StreamFrame
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return str.handleStreamFrame(frame)
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleMaxDataFrame(frame *wire.MaxDataFrame) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.connFlowController.UpdateSendWindow(frame.MaximumData)
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleMaxStreamDataFrame(frame *wire.MaxStreamDataFrame) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
str, err := s.streamsMap.GetOrOpenSendStream(frame.StreamID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if str == nil {
|
|
|
|
// stream is closed and already garbage collected
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
str.updateSendWindow(frame.MaximumStreamData)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleMaxStreamsFrame(frame *wire.MaxStreamsFrame) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.streamsMap.HandleMaxStreamsFrame(frame)
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleResetStreamFrame(frame *wire.ResetStreamFrame) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
str, err := s.streamsMap.GetOrOpenReceiveStream(frame.StreamID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if str == nil {
|
|
|
|
// stream is closed and already garbage collected
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return str.handleResetStreamFrame(frame)
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleStopSendingFrame(frame *wire.StopSendingFrame) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
str, err := s.streamsMap.GetOrOpenSendStream(frame.StreamID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if str == nil {
|
|
|
|
// stream is closed and already garbage collected
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
str.handleStopSendingFrame(frame)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handlePathChallengeFrame(frame *wire.PathChallengeFrame) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.queueControlFrame(&wire.PathResponseFrame{Data: frame.Data})
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleNewTokenFrame(frame *wire.NewTokenFrame) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
if s.perspective == protocol.PerspectiveServer {
|
2021-08-27 11:26:00 +00:00
|
|
|
return &qerr.TransportError{
|
|
|
|
ErrorCode: qerr.ProtocolViolation,
|
|
|
|
ErrorMessage: "received NEW_TOKEN frame from the client",
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
if s.config.TokenStore != nil {
|
|
|
|
s.config.TokenStore.Put(s.tokenStoreKey, &ClientToken{data: frame.Token})
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleNewConnectionIDFrame(f *wire.NewConnectionIDFrame) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.connIDManager.Add(f)
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleRetireConnectionIDFrame(f *wire.RetireConnectionIDFrame, destConnID protocol.ConnectionID) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.connIDGenerator.Retire(f.SequenceNumber, destConnID)
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleHandshakeDoneFrame() error {
|
2021-08-03 09:04:02 +00:00
|
|
|
if s.perspective == protocol.PerspectiveServer {
|
2021-08-27 11:26:00 +00:00
|
|
|
return &qerr.TransportError{
|
|
|
|
ErrorCode: qerr.ProtocolViolation,
|
|
|
|
ErrorMessage: "received a HANDSHAKE_DONE frame",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !s.handshakeConfirmed {
|
2023-12-04 09:49:00 +00:00
|
|
|
return s.handleHandshakeConfirmed()
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleAckFrame(frame *wire.AckFrame, encLevel protocol.EncryptionLevel) error {
|
2021-08-27 11:26:00 +00:00
|
|
|
acked1RTTPacket, err := s.sentPacketHandler.ReceivedAck(frame, encLevel, s.lastPacketReceivedTime)
|
|
|
|
if err != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
return err
|
|
|
|
}
|
2021-08-27 11:26:00 +00:00
|
|
|
if !acked1RTTPacket {
|
2021-08-03 09:04:02 +00:00
|
|
|
return nil
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
// On the client side: If the packet acknowledged a 1-RTT packet, this confirms the handshake.
|
|
|
|
// This is only possible if the ACK was sent in a 1-RTT packet.
|
|
|
|
// This is an optimization over simply waiting for a HANDSHAKE_DONE frame, see section 4.1.2 of RFC 9001.
|
2021-08-27 11:26:00 +00:00
|
|
|
if s.perspective == protocol.PerspectiveClient && !s.handshakeConfirmed {
|
2023-12-04 09:49:00 +00:00
|
|
|
if err := s.handleHandshakeConfirmed(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-08-27 11:26:00 +00:00
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.cryptoStreamHandler.SetLargest1RTTAcked(frame.LargestAcked())
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleDatagramFrame(f *wire.DatagramFrame) error {
|
2023-12-04 09:49:00 +00:00
|
|
|
if f.Length(s.version) > wire.MaxDatagramSize {
|
2021-08-27 11:26:00 +00:00
|
|
|
return &qerr.TransportError{
|
|
|
|
ErrorCode: qerr.ProtocolViolation,
|
|
|
|
ErrorMessage: "DATAGRAM frame too large",
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.datagramQueue.HandleDatagramFrame(f)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
// closeLocal closes the connection and send a CONNECTION_CLOSE containing the error
|
|
|
|
func (s *connection) closeLocal(e error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.closeOnce.Do(func() {
|
|
|
|
if e == nil {
|
2022-06-06 13:15:35 +00:00
|
|
|
s.logger.Infof("Closing connection.")
|
2021-08-03 09:04:02 +00:00
|
|
|
} else {
|
2022-06-06 13:15:35 +00:00
|
|
|
s.logger.Errorf("Closing connection with error: %s", e)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.closeChan <- closeError{err: e, immediate: false, remote: false}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
// destroy closes the connection without sending the error on the wire
|
|
|
|
func (s *connection) destroy(e error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.destroyImpl(e)
|
|
|
|
<-s.ctx.Done()
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) destroyImpl(e error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.closeOnce.Do(func() {
|
|
|
|
if nerr, ok := e.(net.Error); ok && nerr.Timeout() {
|
2022-06-06 13:15:35 +00:00
|
|
|
s.logger.Errorf("Destroying connection: %s", e)
|
2021-08-03 09:04:02 +00:00
|
|
|
} else {
|
2022-06-06 13:15:35 +00:00
|
|
|
s.logger.Errorf("Destroying connection with error: %s", e)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.closeChan <- closeError{err: e, immediate: true, remote: false}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) closeRemote(e error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.closeOnce.Do(func() {
|
2022-06-06 13:15:35 +00:00
|
|
|
s.logger.Errorf("Peer closed connection with error: %s", e)
|
2021-08-03 09:04:02 +00:00
|
|
|
s.closeChan <- closeError{err: e, immediate: true, remote: true}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) CloseWithError(code ApplicationErrorCode, desc string) error {
|
2021-08-27 11:26:00 +00:00
|
|
|
s.closeLocal(&qerr.ApplicationError{
|
|
|
|
ErrorCode: code,
|
|
|
|
ErrorMessage: desc,
|
|
|
|
})
|
2021-08-03 09:04:02 +00:00
|
|
|
<-s.ctx.Done()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-04-18 17:26:01 +00:00
|
|
|
func (s *connection) closeWithTransportError(code TransportErrorCode) {
|
|
|
|
s.closeLocal(&qerr.TransportError{ErrorCode: code})
|
|
|
|
<-s.ctx.Done()
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) handleCloseError(closeErr *closeError) {
|
2021-08-27 11:26:00 +00:00
|
|
|
e := closeErr.err
|
|
|
|
if e == nil {
|
|
|
|
e = &qerr.ApplicationError{}
|
|
|
|
} else {
|
|
|
|
defer func() {
|
|
|
|
closeErr.err = e
|
|
|
|
}()
|
2021-08-13 14:45:13 +00:00
|
|
|
}
|
|
|
|
|
2021-08-27 11:26:00 +00:00
|
|
|
var (
|
|
|
|
statelessResetErr *StatelessResetError
|
|
|
|
versionNegotiationErr *VersionNegotiationError
|
|
|
|
recreateErr *errCloseForRecreating
|
|
|
|
applicationErr *ApplicationError
|
|
|
|
transportErr *TransportError
|
|
|
|
)
|
|
|
|
switch {
|
|
|
|
case errors.Is(e, qerr.ErrIdleTimeout),
|
|
|
|
errors.Is(e, qerr.ErrHandshakeTimeout),
|
|
|
|
errors.As(e, &statelessResetErr),
|
|
|
|
errors.As(e, &versionNegotiationErr),
|
|
|
|
errors.As(e, &recreateErr),
|
|
|
|
errors.As(e, &applicationErr),
|
|
|
|
errors.As(e, &transportErr):
|
|
|
|
default:
|
|
|
|
e = &qerr.TransportError{
|
|
|
|
ErrorCode: qerr.InternalError,
|
|
|
|
ErrorMessage: e.Error(),
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2021-08-27 11:26:00 +00:00
|
|
|
s.streamsMap.CloseWithError(e)
|
2021-08-03 09:04:02 +00:00
|
|
|
s.connIDManager.Close()
|
|
|
|
if s.datagramQueue != nil {
|
2021-08-27 11:26:00 +00:00
|
|
|
s.datagramQueue.CloseWithError(e)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.ClosedConnection != nil && !errors.As(e, &recreateErr) {
|
2021-08-27 11:26:00 +00:00
|
|
|
s.tracer.ClosedConnection(e)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// If this is a remote close we're done here
|
|
|
|
if closeErr.remote {
|
2024-04-18 17:26:01 +00:00
|
|
|
s.connIDGenerator.ReplaceWithClosed(nil)
|
2021-08-03 09:04:02 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if closeErr.immediate {
|
|
|
|
s.connIDGenerator.RemoveAll()
|
|
|
|
return
|
|
|
|
}
|
2022-08-08 14:49:10 +00:00
|
|
|
// Don't send out any CONNECTION_CLOSE if this is an error that occurred
|
|
|
|
// before we even sent out the first packet.
|
|
|
|
if s.perspective == protocol.PerspectiveClient && !s.sentFirstPacket {
|
|
|
|
s.connIDGenerator.RemoveAll()
|
|
|
|
return
|
|
|
|
}
|
2021-08-27 11:26:00 +00:00
|
|
|
connClosePacket, err := s.sendConnectionClose(e)
|
2021-08-03 09:04:02 +00:00
|
|
|
if err != nil {
|
|
|
|
s.logger.Debugf("Error sending CONNECTION_CLOSE: %s", err)
|
|
|
|
}
|
2024-04-18 17:26:01 +00:00
|
|
|
s.connIDGenerator.ReplaceWithClosed(connClosePacket)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) dropEncryptionLevel(encLevel protocol.EncryptionLevel) error {
|
|
|
|
if s.tracer != nil && s.tracer.DroppedEncryptionLevel != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.tracer.DroppedEncryptionLevel(encLevel)
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
s.sentPacketHandler.DropPackets(encLevel)
|
|
|
|
s.receivedPacketHandler.DropPackets(encLevel)
|
|
|
|
//nolint:exhaustive // only Initial and 0-RTT need special treatment
|
|
|
|
switch encLevel {
|
|
|
|
case protocol.EncryptionInitial:
|
2024-04-18 17:26:01 +00:00
|
|
|
s.droppedInitialKeys = true
|
2023-12-04 09:49:00 +00:00
|
|
|
s.cryptoStreamHandler.DiscardInitialKeys()
|
|
|
|
case protocol.Encryption0RTT:
|
2021-08-03 09:04:02 +00:00
|
|
|
s.streamsMap.ResetFor0RTT()
|
|
|
|
if err := s.connFlowController.Reset(); err != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
return err
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
return s.framer.Handle0RTTRejection()
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
return s.cryptoStreamManager.Drop(encLevel)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// is called for the client, when restoring transport parameters saved for 0-RTT
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) restoreTransportParameters(params *wire.TransportParameters) {
|
2021-08-03 09:04:02 +00:00
|
|
|
if s.logger.Debug() {
|
|
|
|
s.logger.Debugf("Restoring Transport Parameters: %s", params)
|
|
|
|
}
|
|
|
|
|
|
|
|
s.peerParams = params
|
|
|
|
s.connIDGenerator.SetMaxActiveConnIDs(params.ActiveConnectionIDLimit)
|
|
|
|
s.connFlowController.UpdateSendWindow(params.InitialMaxData)
|
|
|
|
s.streamsMap.UpdateLimits(params)
|
2023-05-06 00:42:41 +00:00
|
|
|
s.connStateMutex.Lock()
|
|
|
|
s.connState.SupportsDatagrams = s.supportsDatagrams()
|
|
|
|
s.connStateMutex.Unlock()
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) handleTransportParameters(params *wire.TransportParameters) error {
|
|
|
|
if s.tracer != nil && s.tracer.ReceivedTransportParameters != nil {
|
|
|
|
s.tracer.ReceivedTransportParameters(params)
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
if err := s.checkTransportParameters(params); err != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
return &qerr.TransportError{
|
2021-08-27 11:26:00 +00:00
|
|
|
ErrorCode: qerr.TransportParameterError,
|
|
|
|
ErrorMessage: err.Error(),
|
2023-12-04 09:49:00 +00:00
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
|
|
|
|
if s.perspective == protocol.PerspectiveClient && s.peerParams != nil && s.ConnectionState().Used0RTT && !params.ValidForUpdate(s.peerParams) {
|
|
|
|
return &qerr.TransportError{
|
|
|
|
ErrorCode: qerr.ProtocolViolation,
|
|
|
|
ErrorMessage: "server sent reduced limits after accepting 0-RTT data",
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-03 09:04:02 +00:00
|
|
|
s.peerParams = params
|
|
|
|
// On the client side we have to wait for handshake completion.
|
|
|
|
// During a 0-RTT connection, we are only allowed to use the new transport parameters for 1-RTT packets.
|
|
|
|
if s.perspective == protocol.PerspectiveServer {
|
|
|
|
s.applyTransportParameters()
|
2022-06-06 13:15:35 +00:00
|
|
|
// On the server side, the early connection is ready as soon as we processed
|
2021-08-03 09:04:02 +00:00
|
|
|
// the client's transport parameters.
|
2022-06-06 13:15:35 +00:00
|
|
|
close(s.earlyConnReadyChan)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
|
|
|
|
s.connStateMutex.Lock()
|
|
|
|
s.connState.SupportsDatagrams = s.supportsDatagrams()
|
|
|
|
s.connStateMutex.Unlock()
|
2023-12-04 09:49:00 +00:00
|
|
|
return nil
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) checkTransportParameters(params *wire.TransportParameters) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
if s.logger.Debug() {
|
|
|
|
s.logger.Debugf("Processed Transport Parameters: %s", params)
|
|
|
|
}
|
|
|
|
|
|
|
|
// check the initial_source_connection_id
|
2023-05-06 00:42:41 +00:00
|
|
|
if params.InitialSourceConnectionID != s.handshakeDestConnID {
|
2021-08-27 11:26:00 +00:00
|
|
|
return fmt.Errorf("expected initial_source_connection_id to equal %s, is %s", s.handshakeDestConnID, params.InitialSourceConnectionID)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if s.perspective == protocol.PerspectiveServer {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
// check the original_destination_connection_id
|
2023-05-06 00:42:41 +00:00
|
|
|
if params.OriginalDestinationConnectionID != s.origDestConnID {
|
2021-08-27 11:26:00 +00:00
|
|
|
return fmt.Errorf("expected original_destination_connection_id to equal %s, is %s", s.origDestConnID, params.OriginalDestinationConnectionID)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
if s.retrySrcConnID != nil { // a Retry was performed
|
|
|
|
if params.RetrySourceConnectionID == nil {
|
2021-08-27 11:26:00 +00:00
|
|
|
return errors.New("missing retry_source_connection_id")
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
if *params.RetrySourceConnectionID != *s.retrySrcConnID {
|
2021-08-27 11:26:00 +00:00
|
|
|
return fmt.Errorf("expected retry_source_connection_id to equal %s, is %s", s.retrySrcConnID, *params.RetrySourceConnectionID)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
} else if params.RetrySourceConnectionID != nil {
|
2021-08-27 11:26:00 +00:00
|
|
|
return errors.New("received retry_source_connection_id, although no Retry was performed")
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) applyTransportParameters() {
|
2021-08-03 09:04:02 +00:00
|
|
|
params := s.peerParams
|
|
|
|
// Our local idle timeout will always be > 0.
|
|
|
|
s.idleTimeout = utils.MinNonZeroDuration(s.config.MaxIdleTimeout, params.MaxIdleTimeout)
|
2024-01-01 09:43:25 +00:00
|
|
|
s.keepAliveInterval = min(s.config.KeepAlivePeriod, min(s.idleTimeout/2, protocol.MaxKeepAliveInterval))
|
2021-08-03 09:04:02 +00:00
|
|
|
s.streamsMap.UpdateLimits(params)
|
|
|
|
s.frameParser.SetAckDelayExponent(params.AckDelayExponent)
|
|
|
|
s.connFlowController.UpdateSendWindow(params.InitialMaxData)
|
|
|
|
s.rttStats.SetMaxAckDelay(params.MaxAckDelay)
|
|
|
|
s.connIDGenerator.SetMaxActiveConnIDs(params.ActiveConnectionIDLimit)
|
|
|
|
if params.StatelessResetToken != nil {
|
|
|
|
s.connIDManager.SetStatelessResetToken(*params.StatelessResetToken)
|
|
|
|
}
|
|
|
|
// We don't support connection migration yet, so we don't have any use for the preferred_address.
|
|
|
|
if params.PreferredAddress != nil {
|
|
|
|
// Retire the connection ID.
|
|
|
|
s.connIDManager.AddFromPreferredAddress(params.PreferredAddress.ConnectionID, params.PreferredAddress.StatelessResetToken)
|
|
|
|
}
|
2024-06-07 15:24:19 +00:00
|
|
|
maxPacketSize := protocol.ByteCount(protocol.MaxPacketBufferSize)
|
|
|
|
if params.MaxUDPPayloadSize > 0 && params.MaxUDPPayloadSize < maxPacketSize {
|
|
|
|
maxPacketSize = params.MaxUDPPayloadSize
|
|
|
|
}
|
|
|
|
s.mtuDiscoverer = newMTUDiscoverer(
|
|
|
|
s.rttStats,
|
|
|
|
protocol.ByteCount(s.config.InitialPacketSize),
|
|
|
|
maxPacketSize,
|
|
|
|
s.onMTUIncreased,
|
|
|
|
s.tracer,
|
|
|
|
)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2024-01-01 09:43:25 +00:00
|
|
|
func (s *connection) triggerSending(now time.Time) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.pacingDeadline = time.Time{}
|
2023-12-04 09:49:00 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
2024-01-01 09:43:25 +00:00
|
|
|
return s.triggerSending(now)
|
2023-12-04 09:49:00 +00:00
|
|
|
case ackhandler.SendPTOHandshake:
|
|
|
|
if err := s.sendProbePacket(protocol.EncryptionHandshake, now); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if s.sendQueue.WouldBlock() {
|
|
|
|
s.scheduleSending()
|
|
|
|
return nil
|
|
|
|
}
|
2024-01-01 09:43:25 +00:00
|
|
|
return s.triggerSending(now)
|
2023-12-04 09:49:00 +00:00
|
|
|
case ackhandler.SendPTOAppData:
|
|
|
|
if err := s.sendProbePacket(protocol.Encryption1RTT, now); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if s.sendQueue.WouldBlock() {
|
|
|
|
s.scheduleSending()
|
|
|
|
return nil
|
|
|
|
}
|
2024-01-01 09:43:25 +00:00
|
|
|
return s.triggerSending(now)
|
2023-12-04 09:49:00 +00:00
|
|
|
default:
|
|
|
|
return fmt.Errorf("BUG: invalid send mode %d", sendMode)
|
|
|
|
}
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
ecn := s.sentPacketHandler.ECNMode(true)
|
|
|
|
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, buf.Len(), false)
|
|
|
|
s.registerPackedShortHeaderPacket(p, ecn, now)
|
|
|
|
s.sendQueue.Send(buf, 0, ecn)
|
|
|
|
// 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 cf := s.cryptoStreamManager.GetPostHandshakeData(protocol.MaxPostHandshakeCryptoFrameSize); cf != nil {
|
|
|
|
s.queueControlFrame(cf)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !s.handshakeConfirmed {
|
2024-06-07 15:24:19 +00:00
|
|
|
packet, err := s.packer.PackCoalescedPacket(false, s.maxPacketSize(), s.version)
|
2023-12-04 09:49:00 +00:00
|
|
|
if err != nil || packet == nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
s.sentFirstPacket = true
|
|
|
|
if err := s.sendPackedCoalescedPacket(packet, s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket()), now); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
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 {
|
2021-08-03 09:04:02 +00:00
|
|
|
for {
|
2023-12-04 09:49:00 +00:00
|
|
|
buf := getPacketBuffer()
|
|
|
|
ecn := s.sentPacketHandler.ECNMode(true)
|
2024-06-07 15:24:19 +00:00
|
|
|
if _, err := s.appendOneShortHeaderPacket(buf, s.maxPacketSize(), ecn, now); err != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
if err == errNothingToPack {
|
|
|
|
buf.Release()
|
2021-08-03 09:04:02 +00:00
|
|
|
return nil
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
return err
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
|
|
|
|
s.sendQueue.Send(buf, 0, ecn)
|
|
|
|
|
|
|
|
if s.sendQueue.WouldBlock() {
|
2021-08-03 09:04:02 +00:00
|
|
|
return nil
|
2023-12-04 09:49:00 +00:00
|
|
|
}
|
|
|
|
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()
|
2024-06-07 15:24:19 +00:00
|
|
|
maxSize := s.maxPacketSize()
|
2023-12-04 09:49:00 +00:00
|
|
|
|
|
|
|
ecn := s.sentPacketHandler.ECNMode(true)
|
|
|
|
for {
|
|
|
|
var dontSendMore bool
|
|
|
|
size, err := s.appendOneShortHeaderPacket(buf, maxSize, ecn, now)
|
|
|
|
if err != nil {
|
|
|
|
if err != errNothingToPack {
|
2021-08-03 09:04:02 +00:00
|
|
|
return err
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
if buf.Len() == 0 {
|
|
|
|
buf.Release()
|
|
|
|
return nil
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
dontSendMore = true
|
|
|
|
}
|
|
|
|
|
|
|
|
if !dontSendMore {
|
|
|
|
sendMode := s.sentPacketHandler.SendMode(now)
|
|
|
|
if sendMode == ackhandler.SendPacingLimited {
|
|
|
|
s.resetPacingDeadline()
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
if sendMode != ackhandler.SendAny {
|
|
|
|
dontSendMore = true
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
|
|
|
|
// Don't send more packets in this batch if they require a different ECN marking than the previous ones.
|
|
|
|
nextECN := s.sentPacketHandler.ECNMode(true)
|
|
|
|
|
|
|
|
// Append another packet if
|
|
|
|
// 1. The congestion controller and pacer allow sending more
|
|
|
|
// 2. The last packet appended was a full-size packet
|
|
|
|
// 3. The next packet will have the same ECN marking
|
|
|
|
// 4. We still have enough space for another full-size packet in the buffer
|
|
|
|
if !dontSendMore && size == maxSize && nextECN == ecn && buf.Len()+maxSize <= buf.Cap() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
s.sendQueue.Send(buf, uint16(maxSize), ecn)
|
|
|
|
|
|
|
|
if dontSendMore {
|
2021-08-03 09:04:02 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if s.sendQueue.WouldBlock() {
|
|
|
|
return nil
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
|
|
|
|
// Prioritize receiving of packets over sending out more packets.
|
|
|
|
if len(s.receivedPackets) > 0 {
|
|
|
|
s.pacingDeadline = deadlineSendImmediately
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
buf = getLargePacketBuffer()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *connection) resetPacingDeadline() {
|
|
|
|
deadline := s.sentPacketHandler.TimeUntilSend()
|
|
|
|
if deadline.IsZero() {
|
|
|
|
deadline = deadlineSendImmediately
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
s.pacingDeadline = deadline
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) maybeSendAckOnlyPacket(now time.Time) error {
|
2023-05-06 00:42:41 +00:00
|
|
|
if !s.handshakeConfirmed {
|
2023-12-04 09:49:00 +00:00
|
|
|
ecn := s.sentPacketHandler.ECNMode(false)
|
2024-06-07 15:24:19 +00:00
|
|
|
packet, err := s.packer.PackCoalescedPacket(true, s.maxPacketSize(), s.version)
|
2023-05-06 00:42:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if packet == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2024-01-01 09:43:25 +00:00
|
|
|
return s.sendPackedCoalescedPacket(packet, ecn, now)
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
ecn := s.sentPacketHandler.ECNMode(true)
|
2024-06-07 15:24:19 +00:00
|
|
|
p, buf, err := s.packer.PackAckOnlyPacket(s.maxPacketSize(), s.version)
|
2021-08-03 09:04:02 +00:00
|
|
|
if err != nil {
|
2023-05-06 00:42:41 +00:00
|
|
|
if err == errNothingToPack {
|
|
|
|
return nil
|
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
return err
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, buf.Len(), false)
|
|
|
|
s.registerPackedShortHeaderPacket(p, ecn, now)
|
|
|
|
s.sendQueue.Send(buf, 0, ecn)
|
2021-08-03 09:04:02 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) sendProbePacket(encLevel protocol.EncryptionLevel, now time.Time) error {
|
2021-08-03 09:04:02 +00:00
|
|
|
// Queue probe packets until we actually send out a packet,
|
|
|
|
// or until there are no more packets to queue.
|
2023-05-06 00:42:41 +00:00
|
|
|
var packet *coalescedPacket
|
2021-08-03 09:04:02 +00:00
|
|
|
for {
|
|
|
|
if wasQueued := s.sentPacketHandler.QueueProbePacket(encLevel); !wasQueued {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
var err error
|
2024-06-07 15:24:19 +00:00
|
|
|
packet, err = s.packer.MaybePackProbePacket(encLevel, s.maxPacketSize(), s.version)
|
2021-08-03 09:04:02 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if packet != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if packet == nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
s.retransmissionQueue.AddPing(encLevel)
|
2021-08-03 09:04:02 +00:00
|
|
|
var err error
|
2024-06-07 15:24:19 +00:00
|
|
|
packet, err = s.packer.MaybePackProbePacket(encLevel, s.maxPacketSize(), s.version)
|
2021-08-03 09:04:02 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
if packet == nil || (len(packet.longHdrPackets) == 0 && packet.shortHdrPacket == nil) {
|
2022-06-06 13:15:35 +00:00
|
|
|
return fmt.Errorf("connection BUG: couldn't pack %s probe packet", encLevel)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
return s.sendPackedCoalescedPacket(packet, s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket()), now)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
// appendOneShortHeaderPacket appends a new packet to the given packetBuffer.
|
|
|
|
// If there was nothing to pack, the returned size is 0.
|
|
|
|
func (s *connection) appendOneShortHeaderPacket(buf *packetBuffer, maxSize protocol.ByteCount, ecn protocol.ECN, now time.Time) (protocol.ByteCount, error) {
|
|
|
|
startLen := buf.Len()
|
|
|
|
p, err := s.packer.AppendPacket(buf, maxSize, s.version)
|
2023-05-06 00:42:41 +00:00
|
|
|
if err != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
return 0, err
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
size := buf.Len() - startLen
|
|
|
|
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, size, false)
|
|
|
|
s.registerPackedShortHeaderPacket(p, ecn, now)
|
|
|
|
return size, nil
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) registerPackedShortHeaderPacket(p shortHeaderPacket, ecn protocol.ECN, now time.Time) {
|
|
|
|
if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && (len(p.StreamFrames) > 0 || ackhandler.HasAckElicitingFrames(p.Frames)) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.firstAckElicitingPacketAfterIdleSentTime = now
|
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
largestAcked := protocol.InvalidPacketNumber
|
|
|
|
if p.Ack != nil {
|
|
|
|
largestAcked = p.Ack.LargestAcked()
|
|
|
|
}
|
|
|
|
s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, ecn, p.Length, p.IsPathMTUProbePacket)
|
2023-05-06 00:42:41 +00:00
|
|
|
s.connIDManager.SentPacket()
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) sendPackedCoalescedPacket(packet *coalescedPacket, ecn protocol.ECN, now time.Time) error {
|
|
|
|
s.logCoalescedPacket(packet, ecn)
|
2023-05-06 00:42:41 +00:00
|
|
|
for _, p := range packet.longHdrPackets {
|
|
|
|
if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && p.IsAckEliciting() {
|
|
|
|
s.firstAckElicitingPacketAfterIdleSentTime = now
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
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(), ecn, p.length, false)
|
2024-04-18 17:26:01 +00:00
|
|
|
if s.perspective == protocol.PerspectiveClient && p.EncryptionLevel() == protocol.EncryptionHandshake &&
|
|
|
|
!s.droppedInitialKeys {
|
2023-12-04 09:49:00 +00:00
|
|
|
// On the client side, Initial keys are dropped as soon as the first Handshake packet is sent.
|
|
|
|
// See Section 4.9.1 of RFC 9001.
|
|
|
|
if err := s.dropEncryptionLevel(protocol.EncryptionInitial); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
|
|
|
if p := packet.shortHdrPacket; p != nil {
|
|
|
|
if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && p.IsAckEliciting() {
|
|
|
|
s.firstAckElicitingPacketAfterIdleSentTime = now
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
largestAcked := protocol.InvalidPacketNumber
|
|
|
|
if p.Ack != nil {
|
|
|
|
largestAcked = p.Ack.LargestAcked()
|
|
|
|
}
|
|
|
|
s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, ecn, p.Length, p.IsPathMTUProbePacket)
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
s.connIDManager.SentPacket()
|
2023-12-04 09:49:00 +00:00
|
|
|
s.sendQueue.Send(packet.buffer, 0, ecn)
|
|
|
|
return nil
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) sendConnectionClose(e error) ([]byte, error) {
|
2021-08-27 11:26:00 +00:00
|
|
|
var packet *coalescedPacket
|
|
|
|
var err error
|
|
|
|
var transportErr *qerr.TransportError
|
|
|
|
var applicationErr *qerr.ApplicationError
|
|
|
|
if errors.As(e, &transportErr) {
|
2024-06-07 15:24:19 +00:00
|
|
|
packet, err = s.packer.PackConnectionClose(transportErr, s.maxPacketSize(), s.version)
|
2021-08-27 11:26:00 +00:00
|
|
|
} else if errors.As(e, &applicationErr) {
|
2024-06-07 15:24:19 +00:00
|
|
|
packet, err = s.packer.PackApplicationClose(applicationErr, s.maxPacketSize(), s.version)
|
2021-08-27 11:26:00 +00:00
|
|
|
} else {
|
|
|
|
packet, err = s.packer.PackConnectionClose(&qerr.TransportError{
|
|
|
|
ErrorCode: qerr.InternalError,
|
2022-06-06 13:15:35 +00:00
|
|
|
ErrorMessage: fmt.Sprintf("connection BUG: unspecified error type (msg: %s)", e.Error()),
|
2024-06-07 15:24:19 +00:00
|
|
|
}, s.maxPacketSize(), s.version)
|
2021-08-27 11:26:00 +00:00
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
ecn := s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket())
|
|
|
|
s.logCoalescedPacket(packet, ecn)
|
|
|
|
return packet.buffer.Data, s.conn.Write(packet.buffer.Data, 0, ecn)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2024-06-07 15:24:19 +00:00
|
|
|
func (s *connection) maxPacketSize() protocol.ByteCount {
|
|
|
|
if s.mtuDiscoverer == nil {
|
|
|
|
// Use the configured packet size on the client side.
|
|
|
|
// If the server sends a max_udp_payload_size that's smaller than this size, we can ignore this:
|
|
|
|
// Apparently the server still processed the (fully padded) Initial packet anyway.
|
|
|
|
if s.perspective == protocol.PerspectiveClient {
|
|
|
|
return protocol.ByteCount(s.config.InitialPacketSize)
|
|
|
|
}
|
|
|
|
// On the server side, there's no downside to using 1200 bytes until we received the client's transport
|
|
|
|
// parameters:
|
|
|
|
// * If the first packet didn't contain the entire ClientHello, all we can do is ACK that packet. We don't
|
|
|
|
// need a lot of bytes for that.
|
|
|
|
// * If it did, we will have processed the transport parameters and initialized the MTU discoverer.
|
|
|
|
return protocol.MinInitialPacketSize
|
|
|
|
}
|
|
|
|
return s.mtuDiscoverer.CurrentSize()
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) logLongHeaderPacket(p *longHeaderPacket, ecn protocol.ECN) {
|
2023-05-06 00:42:41 +00:00
|
|
|
// quic-go logging
|
|
|
|
if s.logger.Debug() {
|
|
|
|
p.header.Log(s.logger)
|
|
|
|
if p.ack != nil {
|
|
|
|
wire.LogFrame(s.logger, p.ack, true)
|
|
|
|
}
|
|
|
|
for _, frame := range p.frames {
|
|
|
|
wire.LogFrame(s.logger, frame.Frame, true)
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
for _, frame := range p.streamFrames {
|
|
|
|
wire.LogFrame(s.logger, frame.Frame, true)
|
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
|
|
|
|
2021-08-03 09:04:02 +00:00
|
|
|
// tracing
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.SentLongHeaderPacket != nil {
|
2021-08-03 09:04:02 +00:00
|
|
|
frames := make([]logging.Frame, 0, len(p.frames))
|
|
|
|
for _, f := range p.frames {
|
|
|
|
frames = append(frames, logutils.ConvertFrame(f.Frame))
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
for _, f := range p.streamFrames {
|
|
|
|
frames = append(frames, logutils.ConvertFrame(f.Frame))
|
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
var ack *logging.AckFrame
|
|
|
|
if p.ack != nil {
|
|
|
|
ack = logutils.ConvertAckFrame(p.ack)
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
s.tracer.SentLongHeaderPacket(p.header, p.length, ecn, ack, frames)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
func (s *connection) logShortHeaderPacket(
|
|
|
|
destConnID protocol.ConnectionID,
|
|
|
|
ackFrame *wire.AckFrame,
|
2023-12-04 09:49:00 +00:00
|
|
|
frames []ackhandler.Frame,
|
|
|
|
streamFrames []ackhandler.StreamFrame,
|
2023-05-06 00:42:41 +00:00
|
|
|
pn protocol.PacketNumber,
|
|
|
|
pnLen protocol.PacketNumberLen,
|
|
|
|
kp protocol.KeyPhaseBit,
|
2023-12-04 09:49:00 +00:00
|
|
|
ecn protocol.ECN,
|
2023-05-06 00:42:41 +00:00
|
|
|
size protocol.ByteCount,
|
|
|
|
isCoalesced bool,
|
|
|
|
) {
|
|
|
|
if s.logger.Debug() && !isCoalesced {
|
2023-12-04 09:49:00 +00:00
|
|
|
s.logger.Debugf("-> Sending packet %d (%d bytes) for connection %s, 1-RTT (ECN: %s)", pn, size, s.logID, ecn)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
// quic-go logging
|
|
|
|
if s.logger.Debug() {
|
|
|
|
wire.LogShortHeader(s.logger, destConnID, pn, pnLen, kp)
|
|
|
|
if ackFrame != nil {
|
|
|
|
wire.LogFrame(s.logger, ackFrame, true)
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
for _, f := range frames {
|
|
|
|
wire.LogFrame(s.logger, f.Frame, true)
|
|
|
|
}
|
|
|
|
for _, f := range streamFrames {
|
|
|
|
wire.LogFrame(s.logger, f.Frame, true)
|
2023-05-06 00:42:41 +00:00
|
|
|
}
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
|
|
|
|
// tracing
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.SentShortHeaderPacket != nil {
|
|
|
|
fs := make([]logging.Frame, 0, len(frames)+len(streamFrames))
|
2023-05-06 00:42:41 +00:00
|
|
|
for _, f := range frames {
|
|
|
|
fs = append(fs, logutils.ConvertFrame(f.Frame))
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
for _, f := range streamFrames {
|
|
|
|
fs = append(fs, logutils.ConvertFrame(f.Frame))
|
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
var ack *logging.AckFrame
|
|
|
|
if ackFrame != nil {
|
|
|
|
ack = logutils.ConvertAckFrame(ackFrame)
|
|
|
|
}
|
|
|
|
s.tracer.SentShortHeaderPacket(
|
|
|
|
&logging.ShortHeader{
|
|
|
|
DestConnectionID: destConnID,
|
|
|
|
PacketNumber: pn,
|
|
|
|
PacketNumberLen: pnLen,
|
|
|
|
KeyPhase: kp,
|
|
|
|
},
|
|
|
|
size,
|
2023-12-04 09:49:00 +00:00
|
|
|
ecn,
|
2023-05-06 00:42:41 +00:00
|
|
|
ack,
|
|
|
|
fs,
|
|
|
|
)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) logCoalescedPacket(packet *coalescedPacket, ecn protocol.ECN) {
|
2021-08-03 09:04:02 +00:00
|
|
|
if s.logger.Debug() {
|
2023-05-06 00:42:41 +00:00
|
|
|
// There's a short period between dropping both Initial and Handshake keys and completion of the handshake,
|
|
|
|
// during which we might call PackCoalescedPacket but just pack a short header packet.
|
|
|
|
if len(packet.longHdrPackets) == 0 && packet.shortHdrPacket != nil {
|
|
|
|
s.logShortHeaderPacket(
|
|
|
|
packet.shortHdrPacket.DestConnID,
|
|
|
|
packet.shortHdrPacket.Ack,
|
|
|
|
packet.shortHdrPacket.Frames,
|
2023-12-04 09:49:00 +00:00
|
|
|
packet.shortHdrPacket.StreamFrames,
|
2023-05-06 00:42:41 +00:00
|
|
|
packet.shortHdrPacket.PacketNumber,
|
|
|
|
packet.shortHdrPacket.PacketNumberLen,
|
|
|
|
packet.shortHdrPacket.KeyPhase,
|
2023-12-04 09:49:00 +00:00
|
|
|
ecn,
|
2023-05-06 00:42:41 +00:00
|
|
|
packet.shortHdrPacket.Length,
|
|
|
|
false,
|
|
|
|
)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if len(packet.longHdrPackets) > 1 {
|
|
|
|
s.logger.Debugf("-> Sending coalesced packet (%d parts, %d bytes) for connection %s", len(packet.longHdrPackets), packet.buffer.Len(), s.logID)
|
2021-08-03 09:04:02 +00:00
|
|
|
} else {
|
2023-05-06 00:42:41 +00:00
|
|
|
s.logger.Debugf("-> Sending packet %d (%d bytes) for connection %s, %s", packet.longHdrPackets[0].header.PacketNumber, packet.buffer.Len(), s.logID, packet.longHdrPackets[0].EncryptionLevel())
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
for _, p := range packet.longHdrPackets {
|
2023-12-04 09:49:00 +00:00
|
|
|
s.logLongHeaderPacket(p, ecn)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
2023-05-06 00:42:41 +00:00
|
|
|
if p := packet.shortHdrPacket; p != nil {
|
2023-12-04 09:49:00 +00:00
|
|
|
s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, p.Length, true)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// AcceptStream returns the next stream openend by the peer
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) AcceptStream(ctx context.Context) (Stream, error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.streamsMap.AcceptStream(ctx)
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) AcceptUniStream(ctx context.Context) (ReceiveStream, error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.streamsMap.AcceptUniStream(ctx)
|
|
|
|
}
|
|
|
|
|
|
|
|
// OpenStream opens a stream
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) OpenStream() (Stream, error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.streamsMap.OpenStream()
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) OpenStreamSync(ctx context.Context) (Stream, error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.streamsMap.OpenStreamSync(ctx)
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) OpenUniStream() (SendStream, error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.streamsMap.OpenUniStream()
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) OpenUniStreamSync(ctx context.Context) (SendStream, error) {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.streamsMap.OpenUniStreamSync(ctx)
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) newFlowController(id protocol.StreamID) flowcontrol.StreamFlowController {
|
2021-08-03 09:04:02 +00:00
|
|
|
initialSendWindow := s.peerParams.InitialMaxStreamDataUni
|
|
|
|
if id.Type() == protocol.StreamTypeBidi {
|
|
|
|
if id.InitiatedBy() == s.perspective {
|
|
|
|
initialSendWindow = s.peerParams.InitialMaxStreamDataBidiRemote
|
|
|
|
} else {
|
|
|
|
initialSendWindow = s.peerParams.InitialMaxStreamDataBidiLocal
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return flowcontrol.NewStreamFlowController(
|
|
|
|
id,
|
|
|
|
s.connFlowController,
|
|
|
|
protocol.ByteCount(s.config.InitialStreamReceiveWindow),
|
|
|
|
protocol.ByteCount(s.config.MaxStreamReceiveWindow),
|
|
|
|
initialSendWindow,
|
|
|
|
s.onHasStreamWindowUpdate,
|
|
|
|
s.rttStats,
|
|
|
|
s.logger,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
// scheduleSending signals that we have data for sending
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) scheduleSending() {
|
2021-08-03 09:04:02 +00:00
|
|
|
select {
|
|
|
|
case s.sendingScheduled <- struct{}{}:
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-06 00:42:41 +00:00
|
|
|
// tryQueueingUndecryptablePacket queues a packet for which we're missing the decryption keys.
|
|
|
|
// The logging.PacketType is only used for logging purposes.
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) tryQueueingUndecryptablePacket(p receivedPacket, pt logging.PacketType) {
|
2021-08-03 09:04:02 +00:00
|
|
|
if s.handshakeComplete {
|
|
|
|
panic("shouldn't queue undecryptable packets after handshake completion")
|
|
|
|
}
|
|
|
|
if len(s.undecryptablePackets)+1 > protocol.MaxUndecryptablePackets {
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.DroppedPacket != nil {
|
|
|
|
s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropDOSPrevention)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.logger.Infof("Dropping undecryptable packet (%d bytes). Undecryptable packet queue full.", p.Size())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
s.logger.Infof("Queueing packet (%d bytes) for later decryption", p.Size())
|
2023-12-04 09:49:00 +00:00
|
|
|
if s.tracer != nil && s.tracer.BufferedPacket != nil {
|
2023-05-06 00:42:41 +00:00
|
|
|
s.tracer.BufferedPacket(pt, p.Size())
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
s.undecryptablePackets = append(s.undecryptablePackets, p)
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) queueControlFrame(f wire.Frame) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.framer.QueueControlFrame(f)
|
|
|
|
s.scheduleSending()
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) onHasStreamWindowUpdate(id protocol.StreamID) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.windowUpdateQueue.AddStream(id)
|
|
|
|
s.scheduleSending()
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) onHasConnectionWindowUpdate() {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.windowUpdateQueue.AddConnection()
|
|
|
|
s.scheduleSending()
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) onHasStreamData(id protocol.StreamID) {
|
2021-08-03 09:04:02 +00:00
|
|
|
s.framer.AddActiveStream(id)
|
|
|
|
s.scheduleSending()
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) onStreamCompleted(id protocol.StreamID) {
|
2021-08-03 09:04:02 +00:00
|
|
|
if err := s.streamsMap.DeleteStream(id); err != nil {
|
|
|
|
s.closeLocal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-07 15:24:19 +00:00
|
|
|
func (s *connection) onMTUIncreased(mtu protocol.ByteCount) {
|
|
|
|
s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(mtu)))
|
|
|
|
s.sentPacketHandler.SetMaxDatagramSize(mtu)
|
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) SendDatagram(p []byte) error {
|
2023-05-06 00:42:41 +00:00
|
|
|
if !s.supportsDatagrams() {
|
|
|
|
return errors.New("datagram support disabled")
|
|
|
|
}
|
|
|
|
|
2021-08-03 09:04:02 +00:00
|
|
|
f := &wire.DatagramFrame{DataLenPresent: true}
|
2024-06-07 15:24:19 +00:00
|
|
|
// The payload size estimate is conservative.
|
|
|
|
// Under many circumstances we could send a few more bytes.
|
|
|
|
maxDataLen := min(
|
|
|
|
f.MaxDataLen(s.peerParams.MaxDatagramFrameSize, s.version),
|
|
|
|
protocol.ByteCount(s.maxPayloadSizeEstimate.Load()),
|
|
|
|
)
|
|
|
|
if protocol.ByteCount(len(p)) > maxDataLen {
|
|
|
|
return &DatagramTooLargeError{MaxDatagramPayloadSize: int64(maxDataLen)}
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
f.Data = make([]byte, len(p))
|
|
|
|
copy(f.Data, p)
|
2024-01-01 09:43:25 +00:00
|
|
|
return s.datagramQueue.Add(f)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2023-12-04 09:49:00 +00:00
|
|
|
func (s *connection) ReceiveDatagram(ctx context.Context) ([]byte, error) {
|
2023-05-06 00:42:41 +00:00
|
|
|
if !s.config.EnableDatagrams {
|
|
|
|
return nil, errors.New("datagram support disabled")
|
|
|
|
}
|
2023-12-04 09:49:00 +00:00
|
|
|
return s.datagramQueue.Receive(ctx)
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) LocalAddr() net.Addr {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.conn.LocalAddr()
|
|
|
|
}
|
|
|
|
|
2022-06-06 13:15:35 +00:00
|
|
|
func (s *connection) RemoteAddr() net.Addr {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.conn.RemoteAddr()
|
|
|
|
}
|
|
|
|
|
2024-04-18 17:26:01 +00:00
|
|
|
func (s *connection) GetVersion() protocol.Version {
|
2021-08-03 09:04:02 +00:00
|
|
|
return s.version
|
|
|
|
}
|
|
|
|
|
2024-06-07 15:24:19 +00:00
|
|
|
func (s *connection) NextConnection(ctx context.Context) (Connection, error) {
|
|
|
|
// The handshake might fail after the server rejected 0-RTT.
|
|
|
|
// This could happen if the Finished message is malformed or never received.
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil, context.Cause(ctx)
|
|
|
|
case <-s.Context().Done():
|
|
|
|
case <-s.HandshakeComplete():
|
|
|
|
s.streamsMap.UseResetMaps()
|
|
|
|
}
|
|
|
|
return s, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// estimateMaxPayloadSize estimates the maximum payload size for short header packets.
|
|
|
|
// It is not very sophisticated: it just subtracts the size of header (assuming the maximum
|
|
|
|
// connection ID length), and the size of the encryption tag.
|
|
|
|
func estimateMaxPayloadSize(mtu protocol.ByteCount) protocol.ByteCount {
|
|
|
|
return mtu - 1 /* type byte */ - 20 /* maximum connection ID length */ - 16 /* tag size */
|
2021-08-03 09:04:02 +00:00
|
|
|
}
|