github.com/metacubex/quic-go@v0.44.1-0.20240520163451-20b689a59136/connection.go (about)

     1  package quic
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"crypto/tls"
     7  	"errors"
     8  	"fmt"
     9  	"io"
    10  	"net"
    11  	"reflect"
    12  	"sync"
    13  	"sync/atomic"
    14  	"time"
    15  
    16  	"github.com/metacubex/quic-go/congestion"
    17  	"github.com/metacubex/quic-go/internal/ackhandler"
    18  	"github.com/metacubex/quic-go/internal/flowcontrol"
    19  	"github.com/metacubex/quic-go/internal/handshake"
    20  	"github.com/metacubex/quic-go/internal/logutils"
    21  	"github.com/metacubex/quic-go/internal/protocol"
    22  	"github.com/metacubex/quic-go/internal/qerr"
    23  	"github.com/metacubex/quic-go/internal/utils"
    24  	"github.com/metacubex/quic-go/internal/wire"
    25  	"github.com/metacubex/quic-go/logging"
    26  )
    27  
    28  type unpacker interface {
    29  	UnpackLongHeader(hdr *wire.Header, rcvTime time.Time, data []byte, v protocol.Version) (*unpackedPacket, error)
    30  	UnpackShortHeader(rcvTime time.Time, data []byte) (protocol.PacketNumber, protocol.PacketNumberLen, protocol.KeyPhaseBit, []byte, error)
    31  }
    32  
    33  type streamGetter interface {
    34  	GetOrOpenReceiveStream(protocol.StreamID) (receiveStreamI, error)
    35  	GetOrOpenSendStream(protocol.StreamID) (sendStreamI, error)
    36  }
    37  
    38  type streamManager interface {
    39  	GetOrOpenSendStream(protocol.StreamID) (sendStreamI, error)
    40  	GetOrOpenReceiveStream(protocol.StreamID) (receiveStreamI, error)
    41  	OpenStream() (Stream, error)
    42  	OpenUniStream() (SendStream, error)
    43  	OpenStreamSync(context.Context) (Stream, error)
    44  	OpenUniStreamSync(context.Context) (SendStream, error)
    45  	AcceptStream(context.Context) (Stream, error)
    46  	AcceptUniStream(context.Context) (ReceiveStream, error)
    47  	DeleteStream(protocol.StreamID) error
    48  	UpdateLimits(*wire.TransportParameters)
    49  	HandleMaxStreamsFrame(*wire.MaxStreamsFrame)
    50  	CloseWithError(error)
    51  	ResetFor0RTT()
    52  	UseResetMaps()
    53  }
    54  
    55  type cryptoStreamHandler interface {
    56  	StartHandshake() error
    57  	ChangeConnectionID(protocol.ConnectionID)
    58  	SetLargest1RTTAcked(protocol.PacketNumber) error
    59  	SetHandshakeConfirmed()
    60  	GetSessionTicket() ([]byte, error)
    61  	NextEvent() handshake.Event
    62  	DiscardInitialKeys()
    63  	io.Closer
    64  	ConnectionState() handshake.ConnectionState
    65  }
    66  
    67  type receivedPacket struct {
    68  	buffer *packetBuffer
    69  
    70  	remoteAddr net.Addr
    71  	rcvTime    time.Time
    72  	data       []byte
    73  
    74  	ecn protocol.ECN
    75  
    76  	info packetInfo // only valid if the contained IP address is valid
    77  }
    78  
    79  func (p *receivedPacket) Size() protocol.ByteCount { return protocol.ByteCount(len(p.data)) }
    80  
    81  func (p *receivedPacket) Clone() *receivedPacket {
    82  	return &receivedPacket{
    83  		remoteAddr: p.remoteAddr,
    84  		rcvTime:    p.rcvTime,
    85  		data:       p.data,
    86  		buffer:     p.buffer,
    87  		ecn:        p.ecn,
    88  		info:       p.info,
    89  	}
    90  }
    91  
    92  type connRunner interface {
    93  	Add(protocol.ConnectionID, packetHandler) bool
    94  	GetStatelessResetToken(protocol.ConnectionID) protocol.StatelessResetToken
    95  	Retire(protocol.ConnectionID)
    96  	Remove(protocol.ConnectionID)
    97  	ReplaceWithClosed([]protocol.ConnectionID, []byte)
    98  	AddResetToken(protocol.StatelessResetToken, packetHandler)
    99  	RemoveResetToken(protocol.StatelessResetToken)
   100  }
   101  
   102  type closeError struct {
   103  	err       error
   104  	remote    bool
   105  	immediate bool
   106  }
   107  
   108  type errCloseForRecreating struct {
   109  	nextPacketNumber protocol.PacketNumber
   110  	nextVersion      protocol.Version
   111  }
   112  
   113  func (e *errCloseForRecreating) Error() string {
   114  	return "closing connection in order to recreate it"
   115  }
   116  
   117  var connTracingID atomic.Uint64              // to be accessed atomically
   118  func nextConnTracingID() ConnectionTracingID { return ConnectionTracingID(connTracingID.Add(1)) }
   119  
   120  // A Connection is a QUIC connection
   121  type connection struct {
   122  	// Destination connection ID used during the handshake.
   123  	// Used to check source connection ID on incoming packets.
   124  	handshakeDestConnID protocol.ConnectionID
   125  	// Set for the client. Destination connection ID used on the first Initial sent.
   126  	origDestConnID protocol.ConnectionID
   127  	retrySrcConnID *protocol.ConnectionID // only set for the client (and if a Retry was performed)
   128  
   129  	srcConnIDLen int
   130  
   131  	perspective protocol.Perspective
   132  	version     protocol.Version
   133  	config      *Config
   134  
   135  	conn      sendConn
   136  	sendQueue sender
   137  
   138  	streamsMap      streamManager
   139  	connIDManager   *connIDManager
   140  	connIDGenerator *connIDGenerator
   141  
   142  	rttStats *utils.RTTStats
   143  
   144  	cryptoStreamManager   *cryptoStreamManager
   145  	sentPacketHandler     ackhandler.SentPacketHandler
   146  	receivedPacketHandler ackhandler.ReceivedPacketHandler
   147  	retransmissionQueue   *retransmissionQueue
   148  	framer                framer
   149  	windowUpdateQueue     *windowUpdateQueue
   150  	connFlowController    flowcontrol.ConnectionFlowController
   151  	tokenStoreKey         string                    // only set for the client
   152  	tokenGenerator        *handshake.TokenGenerator // only set for the server
   153  
   154  	unpacker      unpacker
   155  	frameParser   wire.FrameParser
   156  	packer        packer
   157  	mtuDiscoverer mtuDiscoverer // initialized when the transport parameters are received
   158  
   159  	maxPayloadSizeEstimate atomic.Uint32
   160  
   161  	initialStream       cryptoStream
   162  	handshakeStream     cryptoStream
   163  	oneRTTStream        cryptoStream // only set for the server
   164  	cryptoStreamHandler cryptoStreamHandler
   165  
   166  	receivedPackets  chan receivedPacket
   167  	sendingScheduled chan struct{}
   168  
   169  	closeOnce sync.Once
   170  	// closeChan is used to notify the run loop that it should terminate
   171  	closeChan chan closeError
   172  
   173  	ctx                context.Context
   174  	ctxCancel          context.CancelCauseFunc
   175  	handshakeCtx       context.Context
   176  	handshakeCtxCancel context.CancelFunc
   177  
   178  	undecryptablePackets          []receivedPacket // undecryptable packets, waiting for a change in encryption level
   179  	undecryptablePacketsToProcess []receivedPacket
   180  
   181  	earlyConnReadyChan chan struct{}
   182  	sentFirstPacket    bool
   183  	droppedInitialKeys bool
   184  	handshakeComplete  bool
   185  	handshakeConfirmed bool
   186  
   187  	receivedRetry       bool
   188  	versionNegotiated   bool
   189  	receivedFirstPacket bool
   190  
   191  	// the minimum of the max_idle_timeout values advertised by both endpoints
   192  	idleTimeout  time.Duration
   193  	creationTime time.Time
   194  	// The idle timeout is set based on the max of the time we received the last packet...
   195  	lastPacketReceivedTime time.Time
   196  	// ... and the time we sent a new ack-eliciting packet after receiving a packet.
   197  	firstAckElicitingPacketAfterIdleSentTime time.Time
   198  	// pacingDeadline is the time when the next packet should be sent
   199  	pacingDeadline time.Time
   200  
   201  	peerParams *wire.TransportParameters
   202  
   203  	timer connectionTimer
   204  	// keepAlivePingSent stores whether a keep alive PING is in flight.
   205  	// It is reset as soon as we receive a packet from the peer.
   206  	keepAlivePingSent bool
   207  	keepAliveInterval time.Duration
   208  
   209  	datagramQueue        *datagramQueue
   210  	maxDatagramFrameSize protocol.ByteCount
   211  
   212  	connStateMutex sync.Mutex
   213  	connState      ConnectionState
   214  
   215  	logID  string
   216  	tracer *logging.ConnectionTracer
   217  	logger utils.Logger
   218  }
   219  
   220  var (
   221  	_ Connection      = &connection{}
   222  	_ EarlyConnection = &connection{}
   223  	_ streamSender    = &connection{}
   224  )
   225  
   226  var newConnection = func(
   227  	conn sendConn,
   228  	runner connRunner,
   229  	origDestConnID protocol.ConnectionID,
   230  	retrySrcConnID *protocol.ConnectionID,
   231  	clientDestConnID protocol.ConnectionID,
   232  	destConnID protocol.ConnectionID,
   233  	srcConnID protocol.ConnectionID,
   234  	connIDGenerator ConnectionIDGenerator,
   235  	statelessResetToken protocol.StatelessResetToken,
   236  	conf *Config,
   237  	tlsConf *tls.Config,
   238  	tokenGenerator *handshake.TokenGenerator,
   239  	clientAddressValidated bool,
   240  	tracer *logging.ConnectionTracer,
   241  	tracingID ConnectionTracingID,
   242  	logger utils.Logger,
   243  	v protocol.Version,
   244  ) quicConn {
   245  	s := &connection{
   246  		conn:                conn,
   247  		config:              conf,
   248  		handshakeDestConnID: destConnID,
   249  		srcConnIDLen:        srcConnID.Len(),
   250  		tokenGenerator:      tokenGenerator,
   251  		oneRTTStream:        newCryptoStream(),
   252  		perspective:         protocol.PerspectiveServer,
   253  		tracer:              tracer,
   254  		logger:              logger,
   255  		version:             v,
   256  	}
   257  	if origDestConnID.Len() > 0 {
   258  		s.logID = origDestConnID.String()
   259  	} else {
   260  		s.logID = destConnID.String()
   261  	}
   262  	s.connIDManager = newConnIDManager(
   263  		destConnID,
   264  		func(token protocol.StatelessResetToken) { runner.AddResetToken(token, s) },
   265  		runner.RemoveResetToken,
   266  		s.queueControlFrame,
   267  	)
   268  	s.connIDGenerator = newConnIDGenerator(
   269  		srcConnID,
   270  		&clientDestConnID,
   271  		func(connID protocol.ConnectionID) { runner.Add(connID, s) },
   272  		runner.GetStatelessResetToken,
   273  		runner.Remove,
   274  		runner.Retire,
   275  		runner.ReplaceWithClosed,
   276  		s.queueControlFrame,
   277  		connIDGenerator,
   278  	)
   279  	s.ctx, s.ctxCancel = context.WithCancelCause(context.WithValue(context.Background(), ConnectionTracingKey, tracingID))
   280  	s.preSetup()
   281  	s.sentPacketHandler, s.receivedPacketHandler = ackhandler.NewAckHandler(
   282  		0,
   283  		protocol.ByteCount(s.config.InitialPacketSize),
   284  		s.rttStats,
   285  		clientAddressValidated,
   286  		s.conn.capabilities().ECN,
   287  		s.perspective,
   288  		s.tracer,
   289  		s.logger,
   290  	)
   291  	s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(protocol.ByteCount(s.config.InitialPacketSize))))
   292  	params := &wire.TransportParameters{
   293  		InitialMaxStreamDataBidiLocal:   protocol.ByteCount(s.config.InitialStreamReceiveWindow),
   294  		InitialMaxStreamDataBidiRemote:  protocol.ByteCount(s.config.InitialStreamReceiveWindow),
   295  		InitialMaxStreamDataUni:         protocol.ByteCount(s.config.InitialStreamReceiveWindow),
   296  		InitialMaxData:                  protocol.ByteCount(s.config.InitialConnectionReceiveWindow),
   297  		MaxIdleTimeout:                  s.config.MaxIdleTimeout,
   298  		MaxBidiStreamNum:                protocol.StreamNum(s.config.MaxIncomingStreams),
   299  		MaxUniStreamNum:                 protocol.StreamNum(s.config.MaxIncomingUniStreams),
   300  		MaxAckDelay:                     protocol.MaxAckDelayInclGranularity,
   301  		AckDelayExponent:                protocol.AckDelayExponent,
   302  		MaxUDPPayloadSize:               protocol.MaxPacketBufferSize,
   303  		DisableActiveMigration:          true,
   304  		StatelessResetToken:             &statelessResetToken,
   305  		OriginalDestinationConnectionID: origDestConnID,
   306  		// For interoperability with quic-go versions before May 2023, this value must be set to a value
   307  		// different from protocol.DefaultActiveConnectionIDLimit.
   308  		// If set to the default value, it will be omitted from the transport parameters, which will make
   309  		// old quic-go versions interpret it as 0, instead of the default value of 2.
   310  		// See https://github.com/metacubex/quic-go/pull/3806.
   311  		ActiveConnectionIDLimit:   protocol.MaxActiveConnectionIDs,
   312  		InitialSourceConnectionID: srcConnID,
   313  		RetrySourceConnectionID:   retrySrcConnID,
   314  	}
   315  	if s.config.EnableDatagrams {
   316  		params.MaxDatagramFrameSize = wire.MaxDatagramSize
   317  		if s.config.MaxDatagramFrameSize != 0 {
   318  			params.MaxDatagramFrameSize = protocol.ByteCount(s.config.MaxDatagramFrameSize)
   319  		}
   320  	} else {
   321  		params.MaxDatagramFrameSize = protocol.InvalidByteCount
   322  	}
   323  	s.maxDatagramFrameSize = params.MaxDatagramFrameSize
   324  	if s.tracer != nil && s.tracer.SentTransportParameters != nil {
   325  		s.tracer.SentTransportParameters(params)
   326  	}
   327  	cs := handshake.NewCryptoSetupServer(
   328  		clientDestConnID,
   329  		conn.LocalAddr(),
   330  		conn.RemoteAddr(),
   331  		params,
   332  		tlsConf,
   333  		conf.Allow0RTT,
   334  		s.rttStats,
   335  		tracer,
   336  		logger,
   337  		s.version,
   338  	)
   339  	s.cryptoStreamHandler = cs
   340  	s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective)
   341  	s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen)
   342  	s.cryptoStreamManager = newCryptoStreamManager(cs, s.initialStream, s.handshakeStream, s.oneRTTStream)
   343  	return s
   344  }
   345  
   346  // declare this as a variable, such that we can it mock it in the tests
   347  var newClientConnection = func(
   348  	conn sendConn,
   349  	runner connRunner,
   350  	destConnID protocol.ConnectionID,
   351  	srcConnID protocol.ConnectionID,
   352  	connIDGenerator ConnectionIDGenerator,
   353  	conf *Config,
   354  	tlsConf *tls.Config,
   355  	initialPacketNumber protocol.PacketNumber,
   356  	enable0RTT bool,
   357  	hasNegotiatedVersion bool,
   358  	tracer *logging.ConnectionTracer,
   359  	tracingID ConnectionTracingID,
   360  	logger utils.Logger,
   361  	v protocol.Version,
   362  ) quicConn {
   363  	s := &connection{
   364  		conn:                conn,
   365  		config:              conf,
   366  		origDestConnID:      destConnID,
   367  		handshakeDestConnID: destConnID,
   368  		srcConnIDLen:        srcConnID.Len(),
   369  		perspective:         protocol.PerspectiveClient,
   370  		logID:               destConnID.String(),
   371  		logger:              logger,
   372  		tracer:              tracer,
   373  		versionNegotiated:   hasNegotiatedVersion,
   374  		version:             v,
   375  	}
   376  	s.connIDManager = newConnIDManager(
   377  		destConnID,
   378  		func(token protocol.StatelessResetToken) { runner.AddResetToken(token, s) },
   379  		runner.RemoveResetToken,
   380  		s.queueControlFrame,
   381  	)
   382  	s.connIDGenerator = newConnIDGenerator(
   383  		srcConnID,
   384  		nil,
   385  		func(connID protocol.ConnectionID) { runner.Add(connID, s) },
   386  		runner.GetStatelessResetToken,
   387  		runner.Remove,
   388  		runner.Retire,
   389  		runner.ReplaceWithClosed,
   390  		s.queueControlFrame,
   391  		connIDGenerator,
   392  	)
   393  	s.ctx, s.ctxCancel = context.WithCancelCause(context.WithValue(context.Background(), ConnectionTracingKey, tracingID))
   394  	s.preSetup()
   395  	s.sentPacketHandler, s.receivedPacketHandler = ackhandler.NewAckHandler(
   396  		initialPacketNumber,
   397  		protocol.ByteCount(s.config.InitialPacketSize),
   398  		s.rttStats,
   399  		false, // has no effect
   400  		s.conn.capabilities().ECN,
   401  		s.perspective,
   402  		s.tracer,
   403  		s.logger,
   404  	)
   405  	s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(protocol.ByteCount(s.config.InitialPacketSize))))
   406  	oneRTTStream := newCryptoStream()
   407  	params := &wire.TransportParameters{
   408  		InitialMaxStreamDataBidiRemote: protocol.ByteCount(s.config.InitialStreamReceiveWindow),
   409  		InitialMaxStreamDataBidiLocal:  protocol.ByteCount(s.config.InitialStreamReceiveWindow),
   410  		InitialMaxStreamDataUni:        protocol.ByteCount(s.config.InitialStreamReceiveWindow),
   411  		InitialMaxData:                 protocol.ByteCount(s.config.InitialConnectionReceiveWindow),
   412  		MaxIdleTimeout:                 s.config.MaxIdleTimeout,
   413  		MaxBidiStreamNum:               protocol.StreamNum(s.config.MaxIncomingStreams),
   414  		MaxUniStreamNum:                protocol.StreamNum(s.config.MaxIncomingUniStreams),
   415  		MaxAckDelay:                    protocol.MaxAckDelayInclGranularity,
   416  		MaxUDPPayloadSize:              protocol.MaxPacketBufferSize,
   417  		AckDelayExponent:               protocol.AckDelayExponent,
   418  		DisableActiveMigration:         true,
   419  		// For interoperability with quic-go versions before May 2023, this value must be set to a value
   420  		// different from protocol.DefaultActiveConnectionIDLimit.
   421  		// If set to the default value, it will be omitted from the transport parameters, which will make
   422  		// old quic-go versions interpret it as 0, instead of the default value of 2.
   423  		// See https://github.com/metacubex/quic-go/pull/3806.
   424  		ActiveConnectionIDLimit:   protocol.MaxActiveConnectionIDs,
   425  		InitialSourceConnectionID: srcConnID,
   426  	}
   427  	if s.config.EnableDatagrams {
   428  		params.MaxDatagramFrameSize = wire.MaxDatagramSize
   429  		if s.config.MaxDatagramFrameSize != 0 {
   430  			params.MaxDatagramFrameSize = protocol.ByteCount(s.config.MaxDatagramFrameSize)
   431  		}
   432  	} else {
   433  		params.MaxDatagramFrameSize = protocol.InvalidByteCount
   434  	}
   435  	s.maxDatagramFrameSize = params.MaxDatagramFrameSize
   436  	if s.tracer != nil && s.tracer.SentTransportParameters != nil {
   437  		s.tracer.SentTransportParameters(params)
   438  	}
   439  	cs := handshake.NewCryptoSetupClient(
   440  		destConnID,
   441  		params,
   442  		tlsConf,
   443  		enable0RTT,
   444  		s.rttStats,
   445  		tracer,
   446  		logger,
   447  		s.version,
   448  	)
   449  	s.cryptoStreamHandler = cs
   450  	s.cryptoStreamManager = newCryptoStreamManager(cs, s.initialStream, s.handshakeStream, oneRTTStream)
   451  	s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen)
   452  	s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective)
   453  	if len(tlsConf.ServerName) > 0 {
   454  		s.tokenStoreKey = tlsConf.ServerName
   455  	} else {
   456  		s.tokenStoreKey = conn.RemoteAddr().String()
   457  	}
   458  	if s.config.TokenStore != nil {
   459  		if token := s.config.TokenStore.Pop(s.tokenStoreKey); token != nil {
   460  			s.packer.SetToken(token.data)
   461  		}
   462  	}
   463  	return s
   464  }
   465  
   466  func (s *connection) preSetup() {
   467  	s.initialStream = newCryptoStream()
   468  	s.handshakeStream = newCryptoStream()
   469  	s.sendQueue = newSendQueue(s.conn)
   470  	s.retransmissionQueue = newRetransmissionQueue()
   471  	s.frameParser = *wire.NewFrameParser(s.config.EnableDatagrams)
   472  	s.rttStats = &utils.RTTStats{}
   473  	s.connFlowController = flowcontrol.NewConnectionFlowController(
   474  		protocol.ByteCount(s.config.InitialConnectionReceiveWindow),
   475  		protocol.ByteCount(s.config.MaxConnectionReceiveWindow),
   476  		s.onHasConnectionWindowUpdate,
   477  		func(size protocol.ByteCount) bool {
   478  			if s.config.AllowConnectionWindowIncrease == nil {
   479  				return true
   480  			}
   481  			return s.config.AllowConnectionWindowIncrease(s, uint64(size))
   482  		},
   483  		s.rttStats,
   484  		s.logger,
   485  	)
   486  	s.earlyConnReadyChan = make(chan struct{})
   487  	s.streamsMap = newStreamsMap(
   488  		s.ctx,
   489  		s,
   490  		s.newFlowController,
   491  		uint64(s.config.MaxIncomingStreams),
   492  		uint64(s.config.MaxIncomingUniStreams),
   493  		s.perspective,
   494  	)
   495  	s.framer = newFramer(s.streamsMap)
   496  	s.receivedPackets = make(chan receivedPacket, protocol.MaxConnUnprocessedPackets)
   497  	s.closeChan = make(chan closeError, 1)
   498  	s.sendingScheduled = make(chan struct{}, 1)
   499  	s.handshakeCtx, s.handshakeCtxCancel = context.WithCancel(context.Background())
   500  
   501  	now := time.Now()
   502  	s.lastPacketReceivedTime = now
   503  	s.creationTime = now
   504  
   505  	s.windowUpdateQueue = newWindowUpdateQueue(s.streamsMap, s.connFlowController, s.framer.QueueControlFrame)
   506  	s.datagramQueue = newDatagramQueue(s.scheduleSending, s.logger)
   507  	s.connState.Version = s.version
   508  }
   509  
   510  // run the connection main loop
   511  func (s *connection) run() error {
   512  	var closeErr closeError
   513  	defer func() {
   514  		s.ctxCancel(closeErr.err)
   515  	}()
   516  
   517  	s.timer = *newTimer()
   518  
   519  	if err := s.cryptoStreamHandler.StartHandshake(); err != nil {
   520  		return err
   521  	}
   522  	if err := s.handleHandshakeEvents(); err != nil {
   523  		return err
   524  	}
   525  	go func() {
   526  		if err := s.sendQueue.Run(); err != nil {
   527  			s.destroyImpl(err)
   528  		}
   529  	}()
   530  
   531  	if s.perspective == protocol.PerspectiveClient {
   532  		s.scheduleSending() // so the ClientHello actually gets sent
   533  	}
   534  
   535  	var sendQueueAvailable <-chan struct{}
   536  
   537  runLoop:
   538  	for {
   539  		if s.framer.QueuedTooManyControlFrames() {
   540  			s.closeLocal(&qerr.TransportError{ErrorCode: InternalError})
   541  		}
   542  		// Close immediately if requested
   543  		select {
   544  		case closeErr = <-s.closeChan:
   545  			break runLoop
   546  		default:
   547  		}
   548  
   549  		s.maybeResetTimer()
   550  
   551  		var processedUndecryptablePacket bool
   552  		if len(s.undecryptablePacketsToProcess) > 0 {
   553  			queue := s.undecryptablePacketsToProcess
   554  			s.undecryptablePacketsToProcess = nil
   555  			for _, p := range queue {
   556  				if processed := s.handlePacketImpl(p); processed {
   557  					processedUndecryptablePacket = true
   558  				}
   559  				// Don't set timers and send packets if the packet made us close the connection.
   560  				select {
   561  				case closeErr = <-s.closeChan:
   562  					break runLoop
   563  				default:
   564  				}
   565  			}
   566  		}
   567  		// If we processed any undecryptable packets, jump to the resetting of the timers directly.
   568  		if !processedUndecryptablePacket {
   569  			select {
   570  			case closeErr = <-s.closeChan:
   571  				break runLoop
   572  			case <-s.timer.Chan():
   573  				s.timer.SetRead()
   574  				// We do all the interesting stuff after the switch statement, so
   575  				// nothing to see here.
   576  			case <-s.sendingScheduled:
   577  				// We do all the interesting stuff after the switch statement, so
   578  				// nothing to see here.
   579  			case <-sendQueueAvailable:
   580  			case firstPacket := <-s.receivedPackets:
   581  				wasProcessed := s.handlePacketImpl(firstPacket)
   582  				// Don't set timers and send packets if the packet made us close the connection.
   583  				select {
   584  				case closeErr = <-s.closeChan:
   585  					break runLoop
   586  				default:
   587  				}
   588  				if s.handshakeComplete {
   589  					// Now process all packets in the receivedPackets channel.
   590  					// Limit the number of packets to the length of the receivedPackets channel,
   591  					// so we eventually get a chance to send out an ACK when receiving a lot of packets.
   592  					numPackets := len(s.receivedPackets)
   593  				receiveLoop:
   594  					for i := 0; i < numPackets; i++ {
   595  						select {
   596  						case p := <-s.receivedPackets:
   597  							if processed := s.handlePacketImpl(p); processed {
   598  								wasProcessed = true
   599  							}
   600  							select {
   601  							case closeErr = <-s.closeChan:
   602  								break runLoop
   603  							default:
   604  							}
   605  						default:
   606  							break receiveLoop
   607  						}
   608  					}
   609  				}
   610  				// Only reset the timers if this packet was actually processed.
   611  				// This avoids modifying any state when handling undecryptable packets,
   612  				// which could be injected by an attacker.
   613  				if !wasProcessed {
   614  					continue
   615  				}
   616  			}
   617  		}
   618  
   619  		now := time.Now()
   620  		if timeout := s.sentPacketHandler.GetLossDetectionTimeout(); !timeout.IsZero() && timeout.Before(now) {
   621  			// This could cause packets to be retransmitted.
   622  			// Check it before trying to send packets.
   623  			if err := s.sentPacketHandler.OnLossDetectionTimeout(); err != nil {
   624  				s.closeLocal(err)
   625  			}
   626  		}
   627  
   628  		if keepAliveTime := s.nextKeepAliveTime(); !keepAliveTime.IsZero() && !now.Before(keepAliveTime) {
   629  			// send a PING frame since there is no activity in the connection
   630  			s.logger.Debugf("Sending a keep-alive PING to keep the connection alive.")
   631  			s.framer.QueueControlFrame(&wire.PingFrame{})
   632  			s.keepAlivePingSent = true
   633  		} else if !s.handshakeComplete && now.Sub(s.creationTime) >= s.config.handshakeTimeout() {
   634  			s.destroyImpl(qerr.ErrHandshakeTimeout)
   635  			continue
   636  		} else {
   637  			idleTimeoutStartTime := s.idleTimeoutStartTime()
   638  			if (!s.handshakeComplete && now.Sub(idleTimeoutStartTime) >= s.config.HandshakeIdleTimeout) ||
   639  				(s.handshakeComplete && now.After(s.nextIdleTimeoutTime())) {
   640  				s.destroyImpl(qerr.ErrIdleTimeout)
   641  				continue
   642  			}
   643  		}
   644  
   645  		if s.sendQueue.WouldBlock() {
   646  			// The send queue is still busy sending out packets.
   647  			// Wait until there's space to enqueue new packets.
   648  			sendQueueAvailable = s.sendQueue.Available()
   649  			continue
   650  		}
   651  		if err := s.triggerSending(now); err != nil {
   652  			s.closeLocal(err)
   653  		}
   654  		if s.sendQueue.WouldBlock() {
   655  			sendQueueAvailable = s.sendQueue.Available()
   656  		} else {
   657  			sendQueueAvailable = nil
   658  		}
   659  	}
   660  
   661  	s.cryptoStreamHandler.Close()
   662  	s.sendQueue.Close() // close the send queue before sending the CONNECTION_CLOSE
   663  	s.handleCloseError(&closeErr)
   664  	if s.tracer != nil && s.tracer.Close != nil {
   665  		if e := (&errCloseForRecreating{}); !errors.As(closeErr.err, &e) {
   666  			s.tracer.Close()
   667  		}
   668  	}
   669  	s.logger.Infof("Connection %s closed.", s.logID)
   670  	s.timer.Stop()
   671  	return closeErr.err
   672  }
   673  
   674  // blocks until the early connection can be used
   675  func (s *connection) earlyConnReady() <-chan struct{} {
   676  	return s.earlyConnReadyChan
   677  }
   678  
   679  func (s *connection) HandshakeComplete() <-chan struct{} {
   680  	return s.handshakeCtx.Done()
   681  }
   682  
   683  func (s *connection) Context() context.Context {
   684  	return s.ctx
   685  }
   686  
   687  func (s *connection) supportsDatagrams() bool {
   688  	return s.peerParams.MaxDatagramFrameSize > 0
   689  }
   690  
   691  func (s *connection) ConnectionState() ConnectionState {
   692  	s.connStateMutex.Lock()
   693  	defer s.connStateMutex.Unlock()
   694  	cs := s.cryptoStreamHandler.ConnectionState()
   695  	s.connState.TLS = cs.ConnectionState
   696  	s.connState.Used0RTT = cs.Used0RTT
   697  	s.connState.GSO = s.conn.capabilities().GSO
   698  	return s.connState
   699  }
   700  
   701  // Time when the connection should time out
   702  func (s *connection) nextIdleTimeoutTime() time.Time {
   703  	idleTimeout := utils.Max(s.idleTimeout, s.rttStats.PTO(true)*3)
   704  	return s.idleTimeoutStartTime().Add(idleTimeout)
   705  }
   706  
   707  // Time when the next keep-alive packet should be sent.
   708  // It returns a zero time if no keep-alive should be sent.
   709  func (s *connection) nextKeepAliveTime() time.Time {
   710  	if s.config.KeepAlivePeriod == 0 || s.keepAlivePingSent || !s.firstAckElicitingPacketAfterIdleSentTime.IsZero() {
   711  		return time.Time{}
   712  	}
   713  	keepAliveInterval := utils.Max(s.keepAliveInterval, s.rttStats.PTO(true)*3/2)
   714  	return s.lastPacketReceivedTime.Add(keepAliveInterval)
   715  }
   716  
   717  func (s *connection) maybeResetTimer() {
   718  	var deadline time.Time
   719  	if !s.handshakeComplete {
   720  		deadline = utils.MinTime(
   721  			s.creationTime.Add(s.config.handshakeTimeout()),
   722  			s.idleTimeoutStartTime().Add(s.config.HandshakeIdleTimeout),
   723  		)
   724  	} else {
   725  		if keepAliveTime := s.nextKeepAliveTime(); !keepAliveTime.IsZero() {
   726  			deadline = keepAliveTime
   727  		} else {
   728  			deadline = s.nextIdleTimeoutTime()
   729  		}
   730  	}
   731  
   732  	s.timer.SetTimer(
   733  		deadline,
   734  		s.receivedPacketHandler.GetAlarmTimeout(),
   735  		s.sentPacketHandler.GetLossDetectionTimeout(),
   736  		s.pacingDeadline,
   737  	)
   738  }
   739  
   740  func (s *connection) idleTimeoutStartTime() time.Time {
   741  	return utils.MaxTime(s.lastPacketReceivedTime, s.firstAckElicitingPacketAfterIdleSentTime)
   742  }
   743  
   744  func (s *connection) handleHandshakeComplete() error {
   745  	defer s.handshakeCtxCancel()
   746  	// Once the handshake completes, we have derived 1-RTT keys.
   747  	// There's no point in queueing undecryptable packets for later decryption anymore.
   748  	s.undecryptablePackets = nil
   749  
   750  	s.connIDManager.SetHandshakeComplete()
   751  	s.connIDGenerator.SetHandshakeComplete()
   752  
   753  	if s.tracer != nil && s.tracer.ChoseALPN != nil {
   754  		s.tracer.ChoseALPN(s.cryptoStreamHandler.ConnectionState().NegotiatedProtocol)
   755  	}
   756  
   757  	// The server applies transport parameters right away, but the client side has to wait for handshake completion.
   758  	// During a 0-RTT connection, the client is only allowed to use the new transport parameters for 1-RTT packets.
   759  	if s.perspective == protocol.PerspectiveClient {
   760  		s.applyTransportParameters()
   761  		return nil
   762  	}
   763  
   764  	// All these only apply to the server side.
   765  	if err := s.handleHandshakeConfirmed(); err != nil {
   766  		return err
   767  	}
   768  
   769  	ticket, err := s.cryptoStreamHandler.GetSessionTicket()
   770  	if err != nil {
   771  		return err
   772  	}
   773  	if ticket != nil { // may be nil if session tickets are disabled via tls.Config.SessionTicketsDisabled
   774  		s.oneRTTStream.Write(ticket)
   775  		for s.oneRTTStream.HasData() {
   776  			s.queueControlFrame(s.oneRTTStream.PopCryptoFrame(protocol.MaxPostHandshakeCryptoFrameSize))
   777  		}
   778  	}
   779  	token, err := s.tokenGenerator.NewToken(s.conn.RemoteAddr())
   780  	if err != nil {
   781  		return err
   782  	}
   783  	s.queueControlFrame(&wire.NewTokenFrame{Token: token})
   784  	s.queueControlFrame(&wire.HandshakeDoneFrame{})
   785  	return nil
   786  }
   787  
   788  func (s *connection) handleHandshakeConfirmed() error {
   789  	if err := s.dropEncryptionLevel(protocol.EncryptionHandshake); err != nil {
   790  		return err
   791  	}
   792  
   793  	s.handshakeConfirmed = true
   794  	s.sentPacketHandler.SetHandshakeConfirmed()
   795  	s.cryptoStreamHandler.SetHandshakeConfirmed()
   796  
   797  	if !s.config.DisablePathMTUDiscovery && s.conn.capabilities().DF {
   798  		s.mtuDiscoverer.Start()
   799  	}
   800  	return nil
   801  }
   802  
   803  func (s *connection) handlePacketImpl(rp receivedPacket) bool {
   804  	s.sentPacketHandler.ReceivedBytes(rp.Size())
   805  
   806  	if wire.IsVersionNegotiationPacket(rp.data) {
   807  		s.handleVersionNegotiationPacket(rp)
   808  		return false
   809  	}
   810  
   811  	var counter uint8
   812  	var lastConnID protocol.ConnectionID
   813  	var processed bool
   814  	data := rp.data
   815  	p := rp
   816  	for len(data) > 0 {
   817  		var destConnID protocol.ConnectionID
   818  		if counter > 0 {
   819  			p = *(p.Clone())
   820  			p.data = data
   821  
   822  			var err error
   823  			destConnID, err = wire.ParseConnectionID(p.data, s.srcConnIDLen)
   824  			if err != nil {
   825  				if s.tracer != nil && s.tracer.DroppedPacket != nil {
   826  					s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropHeaderParseError)
   827  				}
   828  				s.logger.Debugf("error parsing packet, couldn't parse connection ID: %s", err)
   829  				break
   830  			}
   831  			if destConnID != lastConnID {
   832  				if s.tracer != nil && s.tracer.DroppedPacket != nil {
   833  					s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnknownConnectionID)
   834  				}
   835  				s.logger.Debugf("coalesced packet has different destination connection ID: %s, expected %s", destConnID, lastConnID)
   836  				break
   837  			}
   838  		}
   839  
   840  		if wire.IsLongHeaderPacket(p.data[0]) {
   841  			hdr, packetData, rest, err := wire.ParsePacket(p.data)
   842  			if err != nil {
   843  				if s.tracer != nil && s.tracer.DroppedPacket != nil {
   844  					dropReason := logging.PacketDropHeaderParseError
   845  					if err == wire.ErrUnsupportedVersion {
   846  						dropReason = logging.PacketDropUnsupportedVersion
   847  					}
   848  					s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), dropReason)
   849  				}
   850  				s.logger.Debugf("error parsing packet: %s", err)
   851  				break
   852  			}
   853  			lastConnID = hdr.DestConnectionID
   854  
   855  			if hdr.Version != s.version {
   856  				if s.tracer != nil && s.tracer.DroppedPacket != nil {
   857  					s.tracer.DroppedPacket(logging.PacketTypeFromHeader(hdr), protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedVersion)
   858  				}
   859  				s.logger.Debugf("Dropping packet with version %x. Expected %x.", hdr.Version, s.version)
   860  				break
   861  			}
   862  
   863  			if counter > 0 {
   864  				p.buffer.Split()
   865  			}
   866  			counter++
   867  
   868  			// only log if this actually a coalesced packet
   869  			if s.logger.Debug() && (counter > 1 || len(rest) > 0) {
   870  				s.logger.Debugf("Parsed a coalesced packet. Part %d: %d bytes. Remaining: %d bytes.", counter, len(packetData), len(rest))
   871  			}
   872  
   873  			p.data = packetData
   874  
   875  			if wasProcessed := s.handleLongHeaderPacket(p, hdr); wasProcessed {
   876  				processed = true
   877  			}
   878  			data = rest
   879  		} else {
   880  			if counter > 0 {
   881  				p.buffer.Split()
   882  			}
   883  			processed = s.handleShortHeaderPacket(p, destConnID)
   884  			break
   885  		}
   886  	}
   887  
   888  	// Hysteria connection migration
   889  	// Set remote address to the address of the last received valid packet
   890  	if s.perspective == protocol.PerspectiveServer && processed {
   891  		// Connection migration
   892  		s.conn.SetRemoteAddr(rp.remoteAddr)
   893  	}
   894  
   895  	p.buffer.MaybeRelease()
   896  	return processed
   897  }
   898  
   899  func (s *connection) handleShortHeaderPacket(p receivedPacket, destConnID protocol.ConnectionID) bool {
   900  	var wasQueued bool
   901  
   902  	defer func() {
   903  		// Put back the packet buffer if the packet wasn't queued for later decryption.
   904  		if !wasQueued {
   905  			p.buffer.Decrement()
   906  		}
   907  	}()
   908  
   909  	pn, pnLen, keyPhase, data, err := s.unpacker.UnpackShortHeader(p.rcvTime, p.data)
   910  	if err != nil {
   911  		wasQueued = s.handleUnpackError(err, p, logging.PacketType1RTT)
   912  		return false
   913  	}
   914  
   915  	if s.logger.Debug() {
   916  		s.logger.Debugf("<- Reading packet %d (%d bytes) for connection %s, 1-RTT", pn, p.Size(), destConnID)
   917  		wire.LogShortHeader(s.logger, destConnID, pn, pnLen, keyPhase)
   918  	}
   919  
   920  	if s.receivedPacketHandler.IsPotentiallyDuplicate(pn, protocol.Encryption1RTT) {
   921  		s.logger.Debugf("Dropping (potentially) duplicate packet.")
   922  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
   923  			s.tracer.DroppedPacket(logging.PacketType1RTT, pn, p.Size(), logging.PacketDropDuplicate)
   924  		}
   925  		return false
   926  	}
   927  
   928  	var log func([]logging.Frame)
   929  	if s.tracer != nil && s.tracer.ReceivedShortHeaderPacket != nil {
   930  		log = func(frames []logging.Frame) {
   931  			s.tracer.ReceivedShortHeaderPacket(
   932  				&logging.ShortHeader{
   933  					DestConnectionID: destConnID,
   934  					PacketNumber:     pn,
   935  					PacketNumberLen:  pnLen,
   936  					KeyPhase:         keyPhase,
   937  				},
   938  				p.Size(),
   939  				p.ecn,
   940  				frames,
   941  			)
   942  		}
   943  	}
   944  	if err := s.handleUnpackedShortHeaderPacket(destConnID, pn, data, p.ecn, p.rcvTime, log); err != nil {
   945  		s.closeLocal(err)
   946  		return false
   947  	}
   948  	return true
   949  }
   950  
   951  func (s *connection) handleLongHeaderPacket(p receivedPacket, hdr *wire.Header) bool /* was the packet successfully processed */ {
   952  	var wasQueued bool
   953  
   954  	defer func() {
   955  		// Put back the packet buffer if the packet wasn't queued for later decryption.
   956  		if !wasQueued {
   957  			p.buffer.Decrement()
   958  		}
   959  	}()
   960  
   961  	if hdr.Type == protocol.PacketTypeRetry {
   962  		return s.handleRetryPacket(hdr, p.data, p.rcvTime)
   963  	}
   964  
   965  	// The server can change the source connection ID with the first Handshake packet.
   966  	// After this, all packets with a different source connection have to be ignored.
   967  	if s.receivedFirstPacket && hdr.Type == protocol.PacketTypeInitial && hdr.SrcConnectionID != s.handshakeDestConnID {
   968  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
   969  			s.tracer.DroppedPacket(logging.PacketTypeInitial, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropUnknownConnectionID)
   970  		}
   971  		s.logger.Debugf("Dropping Initial packet (%d bytes) with unexpected source connection ID: %s (expected %s)", p.Size(), hdr.SrcConnectionID, s.handshakeDestConnID)
   972  		return false
   973  	}
   974  	// drop 0-RTT packets, if we are a client
   975  	if s.perspective == protocol.PerspectiveClient && hdr.Type == protocol.PacketType0RTT {
   976  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
   977  			s.tracer.DroppedPacket(logging.PacketType0RTT, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropKeyUnavailable)
   978  		}
   979  		return false
   980  	}
   981  
   982  	packet, err := s.unpacker.UnpackLongHeader(hdr, p.rcvTime, p.data, s.version)
   983  	if err != nil {
   984  		wasQueued = s.handleUnpackError(err, p, logging.PacketTypeFromHeader(hdr))
   985  		return false
   986  	}
   987  
   988  	if s.logger.Debug() {
   989  		s.logger.Debugf("<- Reading packet %d (%d bytes) for connection %s, %s", packet.hdr.PacketNumber, p.Size(), hdr.DestConnectionID, packet.encryptionLevel)
   990  		packet.hdr.Log(s.logger)
   991  	}
   992  
   993  	if pn := packet.hdr.PacketNumber; s.receivedPacketHandler.IsPotentiallyDuplicate(pn, packet.encryptionLevel) {
   994  		s.logger.Debugf("Dropping (potentially) duplicate packet.")
   995  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
   996  			s.tracer.DroppedPacket(logging.PacketTypeFromHeader(hdr), pn, p.Size(), logging.PacketDropDuplicate)
   997  		}
   998  		return false
   999  	}
  1000  
  1001  	if err := s.handleUnpackedLongHeaderPacket(packet, p.ecn, p.rcvTime, p.Size()); err != nil {
  1002  		s.closeLocal(err)
  1003  		return false
  1004  	}
  1005  	return true
  1006  }
  1007  
  1008  func (s *connection) handleUnpackError(err error, p receivedPacket, pt logging.PacketType) (wasQueued bool) {
  1009  	switch err {
  1010  	case handshake.ErrKeysDropped:
  1011  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1012  			s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropKeyUnavailable)
  1013  		}
  1014  		s.logger.Debugf("Dropping %s packet (%d bytes) because we already dropped the keys.", pt, p.Size())
  1015  	case handshake.ErrKeysNotYetAvailable:
  1016  		// Sealer for this encryption level not yet available.
  1017  		// Try again later.
  1018  		s.tryQueueingUndecryptablePacket(p, pt)
  1019  		return true
  1020  	case wire.ErrInvalidReservedBits:
  1021  		s.closeLocal(&qerr.TransportError{
  1022  			ErrorCode:    qerr.ProtocolViolation,
  1023  			ErrorMessage: err.Error(),
  1024  		})
  1025  	case handshake.ErrDecryptionFailed:
  1026  		// This might be a packet injected by an attacker. Drop it.
  1027  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1028  			s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropPayloadDecryptError)
  1029  		}
  1030  		s.logger.Debugf("Dropping %s packet (%d bytes) that could not be unpacked. Error: %s", pt, p.Size(), err)
  1031  	default:
  1032  		var headerErr *headerParseError
  1033  		if errors.As(err, &headerErr) {
  1034  			// This might be a packet injected by an attacker. Drop it.
  1035  			if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1036  				s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropHeaderParseError)
  1037  			}
  1038  			s.logger.Debugf("Dropping %s packet (%d bytes) for which we couldn't unpack the header. Error: %s", pt, p.Size(), err)
  1039  		} else {
  1040  			// This is an error returned by the AEAD (other than ErrDecryptionFailed).
  1041  			// For example, a PROTOCOL_VIOLATION due to key updates.
  1042  			s.closeLocal(err)
  1043  		}
  1044  	}
  1045  	return false
  1046  }
  1047  
  1048  func (s *connection) handleRetryPacket(hdr *wire.Header, data []byte, rcvTime time.Time) bool /* was this a valid Retry */ {
  1049  	if s.perspective == protocol.PerspectiveServer {
  1050  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1051  			s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket)
  1052  		}
  1053  		s.logger.Debugf("Ignoring Retry.")
  1054  		return false
  1055  	}
  1056  	if s.receivedFirstPacket {
  1057  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1058  			s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket)
  1059  		}
  1060  		s.logger.Debugf("Ignoring Retry, since we already received a packet.")
  1061  		return false
  1062  	}
  1063  	destConnID := s.connIDManager.Get()
  1064  	if hdr.SrcConnectionID == destConnID {
  1065  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1066  			s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket)
  1067  		}
  1068  		s.logger.Debugf("Ignoring Retry, since the server didn't change the Source Connection ID.")
  1069  		return false
  1070  	}
  1071  	// If a token is already set, this means that we already received a Retry from the server.
  1072  	// Ignore this Retry packet.
  1073  	if s.receivedRetry {
  1074  		s.logger.Debugf("Ignoring Retry, since a Retry was already received.")
  1075  		return false
  1076  	}
  1077  
  1078  	tag := handshake.GetRetryIntegrityTag(data[:len(data)-16], destConnID, hdr.Version)
  1079  	if !bytes.Equal(data[len(data)-16:], tag[:]) {
  1080  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1081  			s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.InvalidPacketNumber, protocol.ByteCount(len(data)), logging.PacketDropPayloadDecryptError)
  1082  		}
  1083  		s.logger.Debugf("Ignoring spoofed Retry. Integrity Tag doesn't match.")
  1084  		return false
  1085  	}
  1086  
  1087  	if s.logger.Debug() {
  1088  		s.logger.Debugf("<- Received Retry:")
  1089  		(&wire.ExtendedHeader{Header: *hdr}).Log(s.logger)
  1090  		s.logger.Debugf("Switching destination connection ID to: %s", hdr.SrcConnectionID)
  1091  	}
  1092  	if s.tracer != nil && s.tracer.ReceivedRetry != nil {
  1093  		s.tracer.ReceivedRetry(hdr)
  1094  	}
  1095  	newDestConnID := hdr.SrcConnectionID
  1096  	s.receivedRetry = true
  1097  	if err := s.sentPacketHandler.ResetForRetry(rcvTime); err != nil {
  1098  		s.closeLocal(err)
  1099  		return false
  1100  	}
  1101  	s.handshakeDestConnID = newDestConnID
  1102  	s.retrySrcConnID = &newDestConnID
  1103  	s.cryptoStreamHandler.ChangeConnectionID(newDestConnID)
  1104  	s.packer.SetToken(hdr.Token)
  1105  	s.connIDManager.ChangeInitialConnID(newDestConnID)
  1106  	s.scheduleSending()
  1107  	return true
  1108  }
  1109  
  1110  func (s *connection) handleVersionNegotiationPacket(p receivedPacket) {
  1111  	if s.perspective == protocol.PerspectiveServer || // servers never receive version negotiation packets
  1112  		s.receivedFirstPacket || s.versionNegotiated { // ignore delayed / duplicated version negotiation packets
  1113  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1114  			s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropUnexpectedPacket)
  1115  		}
  1116  		return
  1117  	}
  1118  
  1119  	src, dest, supportedVersions, err := wire.ParseVersionNegotiationPacket(p.data)
  1120  	if err != nil {
  1121  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1122  			s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropHeaderParseError)
  1123  		}
  1124  		s.logger.Debugf("Error parsing Version Negotiation packet: %s", err)
  1125  		return
  1126  	}
  1127  
  1128  	for _, v := range supportedVersions {
  1129  		if v == s.version {
  1130  			if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1131  				s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropUnexpectedVersion)
  1132  			}
  1133  			// The Version Negotiation packet contains the version that we offered.
  1134  			// This might be a packet sent by an attacker, or it was corrupted.
  1135  			return
  1136  		}
  1137  	}
  1138  
  1139  	s.logger.Infof("Received a Version Negotiation packet. Supported Versions: %s", supportedVersions)
  1140  	if s.tracer != nil && s.tracer.ReceivedVersionNegotiationPacket != nil {
  1141  		s.tracer.ReceivedVersionNegotiationPacket(dest, src, supportedVersions)
  1142  	}
  1143  	newVersion, ok := protocol.ChooseSupportedVersion(s.config.Versions, supportedVersions)
  1144  	if !ok {
  1145  		s.destroyImpl(&VersionNegotiationError{
  1146  			Ours:   s.config.Versions,
  1147  			Theirs: supportedVersions,
  1148  		})
  1149  		s.logger.Infof("No compatible QUIC version found.")
  1150  		return
  1151  	}
  1152  	if s.tracer != nil && s.tracer.NegotiatedVersion != nil {
  1153  		s.tracer.NegotiatedVersion(newVersion, s.config.Versions, supportedVersions)
  1154  	}
  1155  
  1156  	s.logger.Infof("Switching to QUIC version %s.", newVersion)
  1157  	nextPN, _ := s.sentPacketHandler.PeekPacketNumber(protocol.EncryptionInitial)
  1158  	s.destroyImpl(&errCloseForRecreating{
  1159  		nextPacketNumber: nextPN,
  1160  		nextVersion:      newVersion,
  1161  	})
  1162  }
  1163  
  1164  func (s *connection) handleUnpackedLongHeaderPacket(
  1165  	packet *unpackedPacket,
  1166  	ecn protocol.ECN,
  1167  	rcvTime time.Time,
  1168  	packetSize protocol.ByteCount, // only for logging
  1169  ) error {
  1170  	if !s.receivedFirstPacket {
  1171  		s.receivedFirstPacket = true
  1172  		if !s.versionNegotiated && s.tracer != nil && s.tracer.NegotiatedVersion != nil {
  1173  			var clientVersions, serverVersions []protocol.Version
  1174  			switch s.perspective {
  1175  			case protocol.PerspectiveClient:
  1176  				clientVersions = s.config.Versions
  1177  			case protocol.PerspectiveServer:
  1178  				serverVersions = s.config.Versions
  1179  			}
  1180  			s.tracer.NegotiatedVersion(s.version, clientVersions, serverVersions)
  1181  		}
  1182  		// The server can change the source connection ID with the first Handshake packet.
  1183  		if s.perspective == protocol.PerspectiveClient && packet.hdr.SrcConnectionID != s.handshakeDestConnID {
  1184  			cid := packet.hdr.SrcConnectionID
  1185  			s.logger.Debugf("Received first packet. Switching destination connection ID to: %s", cid)
  1186  			s.handshakeDestConnID = cid
  1187  			s.connIDManager.ChangeInitialConnID(cid)
  1188  		}
  1189  		// We create the connection as soon as we receive the first packet from the client.
  1190  		// We do that before authenticating the packet.
  1191  		// That means that if the source connection ID was corrupted,
  1192  		// we might have created a connection with an incorrect source connection ID.
  1193  		// Once we authenticate the first packet, we need to update it.
  1194  		if s.perspective == protocol.PerspectiveServer {
  1195  			if packet.hdr.SrcConnectionID != s.handshakeDestConnID {
  1196  				s.handshakeDestConnID = packet.hdr.SrcConnectionID
  1197  				s.connIDManager.ChangeInitialConnID(packet.hdr.SrcConnectionID)
  1198  			}
  1199  			if s.tracer != nil && s.tracer.StartedConnection != nil {
  1200  				s.tracer.StartedConnection(
  1201  					s.conn.LocalAddr(),
  1202  					s.conn.RemoteAddr(),
  1203  					packet.hdr.SrcConnectionID,
  1204  					packet.hdr.DestConnectionID,
  1205  				)
  1206  			}
  1207  		}
  1208  	}
  1209  
  1210  	if s.perspective == protocol.PerspectiveServer && packet.encryptionLevel == protocol.EncryptionHandshake &&
  1211  		!s.droppedInitialKeys {
  1212  		// On the server side, Initial keys are dropped as soon as the first Handshake packet is received.
  1213  		// See Section 4.9.1 of RFC 9001.
  1214  		if err := s.dropEncryptionLevel(protocol.EncryptionInitial); err != nil {
  1215  			return err
  1216  		}
  1217  	}
  1218  
  1219  	s.lastPacketReceivedTime = rcvTime
  1220  	s.firstAckElicitingPacketAfterIdleSentTime = time.Time{}
  1221  	s.keepAlivePingSent = false
  1222  
  1223  	var log func([]logging.Frame)
  1224  	if s.tracer != nil && s.tracer.ReceivedLongHeaderPacket != nil {
  1225  		log = func(frames []logging.Frame) {
  1226  			s.tracer.ReceivedLongHeaderPacket(packet.hdr, packetSize, ecn, frames)
  1227  		}
  1228  	}
  1229  	isAckEliciting, err := s.handleFrames(packet.data, packet.hdr.DestConnectionID, packet.encryptionLevel, log)
  1230  	if err != nil {
  1231  		return err
  1232  	}
  1233  	return s.receivedPacketHandler.ReceivedPacket(packet.hdr.PacketNumber, ecn, packet.encryptionLevel, rcvTime, isAckEliciting)
  1234  }
  1235  
  1236  func (s *connection) handleUnpackedShortHeaderPacket(
  1237  	destConnID protocol.ConnectionID,
  1238  	pn protocol.PacketNumber,
  1239  	data []byte,
  1240  	ecn protocol.ECN,
  1241  	rcvTime time.Time,
  1242  	log func([]logging.Frame),
  1243  ) error {
  1244  	s.lastPacketReceivedTime = rcvTime
  1245  	s.firstAckElicitingPacketAfterIdleSentTime = time.Time{}
  1246  	s.keepAlivePingSent = false
  1247  
  1248  	isAckEliciting, err := s.handleFrames(data, destConnID, protocol.Encryption1RTT, log)
  1249  	if err != nil {
  1250  		return err
  1251  	}
  1252  	return s.receivedPacketHandler.ReceivedPacket(pn, ecn, protocol.Encryption1RTT, rcvTime, isAckEliciting)
  1253  }
  1254  
  1255  func (s *connection) handleFrames(
  1256  	data []byte,
  1257  	destConnID protocol.ConnectionID,
  1258  	encLevel protocol.EncryptionLevel,
  1259  	log func([]logging.Frame),
  1260  ) (isAckEliciting bool, _ error) {
  1261  	// Only used for tracing.
  1262  	// If we're not tracing, this slice will always remain empty.
  1263  	var frames []logging.Frame
  1264  	if log != nil {
  1265  		frames = make([]logging.Frame, 0, 4)
  1266  	}
  1267  	handshakeWasComplete := s.handshakeComplete
  1268  	var handleErr error
  1269  	for len(data) > 0 {
  1270  		l, frame, err := s.frameParser.ParseNext(data, encLevel, s.version)
  1271  		if err != nil {
  1272  			return false, err
  1273  		}
  1274  		data = data[l:]
  1275  		if frame == nil {
  1276  			break
  1277  		}
  1278  		if ackhandler.IsFrameAckEliciting(frame) {
  1279  			isAckEliciting = true
  1280  		}
  1281  		if log != nil {
  1282  			frames = append(frames, logutils.ConvertFrame(frame))
  1283  		}
  1284  		// An error occurred handling a previous frame.
  1285  		// Don't handle the current frame.
  1286  		if handleErr != nil {
  1287  			continue
  1288  		}
  1289  		if err := s.handleFrame(frame, encLevel, destConnID); err != nil {
  1290  			if log == nil {
  1291  				return false, err
  1292  			}
  1293  			// If we're logging, we need to keep parsing (but not handling) all frames.
  1294  			handleErr = err
  1295  		}
  1296  	}
  1297  
  1298  	if log != nil {
  1299  		log(frames)
  1300  		if handleErr != nil {
  1301  			return false, handleErr
  1302  		}
  1303  	}
  1304  
  1305  	// Handle completion of the handshake after processing all the frames.
  1306  	// This ensures that we correctly handle the following case on the server side:
  1307  	// We receive a Handshake packet that contains the CRYPTO frame that allows us to complete the handshake,
  1308  	// and an ACK serialized after that CRYPTO frame. In this case, we still want to process the ACK frame.
  1309  	if !handshakeWasComplete && s.handshakeComplete {
  1310  		if err := s.handleHandshakeComplete(); err != nil {
  1311  			return false, err
  1312  		}
  1313  	}
  1314  
  1315  	return
  1316  }
  1317  
  1318  func (s *connection) handleFrame(f wire.Frame, encLevel protocol.EncryptionLevel, destConnID protocol.ConnectionID) error {
  1319  	var err error
  1320  	wire.LogFrame(s.logger, f, false)
  1321  	switch frame := f.(type) {
  1322  	case *wire.CryptoFrame:
  1323  		err = s.handleCryptoFrame(frame, encLevel)
  1324  	case *wire.StreamFrame:
  1325  		err = s.handleStreamFrame(frame)
  1326  	case *wire.AckFrame:
  1327  		err = s.handleAckFrame(frame, encLevel)
  1328  	case *wire.ConnectionCloseFrame:
  1329  		s.handleConnectionCloseFrame(frame)
  1330  	case *wire.ResetStreamFrame:
  1331  		err = s.handleResetStreamFrame(frame)
  1332  	case *wire.MaxDataFrame:
  1333  		s.handleMaxDataFrame(frame)
  1334  	case *wire.MaxStreamDataFrame:
  1335  		err = s.handleMaxStreamDataFrame(frame)
  1336  	case *wire.MaxStreamsFrame:
  1337  		s.handleMaxStreamsFrame(frame)
  1338  	case *wire.DataBlockedFrame:
  1339  	case *wire.StreamDataBlockedFrame:
  1340  	case *wire.StreamsBlockedFrame:
  1341  	case *wire.StopSendingFrame:
  1342  		err = s.handleStopSendingFrame(frame)
  1343  	case *wire.PingFrame:
  1344  	case *wire.PathChallengeFrame:
  1345  		s.handlePathChallengeFrame(frame)
  1346  	case *wire.PathResponseFrame:
  1347  		// since we don't send PATH_CHALLENGEs, we don't expect PATH_RESPONSEs
  1348  		err = errors.New("unexpected PATH_RESPONSE frame")
  1349  	case *wire.NewTokenFrame:
  1350  		err = s.handleNewTokenFrame(frame)
  1351  	case *wire.NewConnectionIDFrame:
  1352  		err = s.handleNewConnectionIDFrame(frame)
  1353  	case *wire.RetireConnectionIDFrame:
  1354  		err = s.handleRetireConnectionIDFrame(frame, destConnID)
  1355  	case *wire.HandshakeDoneFrame:
  1356  		err = s.handleHandshakeDoneFrame()
  1357  	case *wire.DatagramFrame:
  1358  		err = s.handleDatagramFrame(frame)
  1359  	default:
  1360  		err = fmt.Errorf("unexpected frame type: %s", reflect.ValueOf(&frame).Elem().Type().Name())
  1361  	}
  1362  	return err
  1363  }
  1364  
  1365  // handlePacket is called by the server with a new packet
  1366  func (s *connection) handlePacket(p receivedPacket) {
  1367  	// Discard packets once the amount of queued packets is larger than
  1368  	// the channel size, protocol.MaxConnUnprocessedPackets
  1369  	select {
  1370  	case s.receivedPackets <- p:
  1371  	default:
  1372  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
  1373  			s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropDOSPrevention)
  1374  		}
  1375  	}
  1376  }
  1377  
  1378  func (s *connection) handleConnectionCloseFrame(frame *wire.ConnectionCloseFrame) {
  1379  	if frame.IsApplicationError {
  1380  		s.closeRemote(&qerr.ApplicationError{
  1381  			Remote:       true,
  1382  			ErrorCode:    qerr.ApplicationErrorCode(frame.ErrorCode),
  1383  			ErrorMessage: frame.ReasonPhrase,
  1384  		})
  1385  		return
  1386  	}
  1387  	s.closeRemote(&qerr.TransportError{
  1388  		Remote:       true,
  1389  		ErrorCode:    qerr.TransportErrorCode(frame.ErrorCode),
  1390  		FrameType:    frame.FrameType,
  1391  		ErrorMessage: frame.ReasonPhrase,
  1392  	})
  1393  }
  1394  
  1395  func (s *connection) handleCryptoFrame(frame *wire.CryptoFrame, encLevel protocol.EncryptionLevel) error {
  1396  	if err := s.cryptoStreamManager.HandleCryptoFrame(frame, encLevel); err != nil {
  1397  		return err
  1398  	}
  1399  	return s.handleHandshakeEvents()
  1400  }
  1401  
  1402  func (s *connection) handleHandshakeEvents() error {
  1403  	for {
  1404  		ev := s.cryptoStreamHandler.NextEvent()
  1405  		var err error
  1406  		switch ev.Kind {
  1407  		case handshake.EventNoEvent:
  1408  			return nil
  1409  		case handshake.EventHandshakeComplete:
  1410  			// Don't call handleHandshakeComplete yet.
  1411  			// It's advantageous to process ACK frames that might be serialized after the CRYPTO frame first.
  1412  			s.handshakeComplete = true
  1413  		case handshake.EventReceivedTransportParameters:
  1414  			err = s.handleTransportParameters(ev.TransportParameters)
  1415  		case handshake.EventRestoredTransportParameters:
  1416  			s.restoreTransportParameters(ev.TransportParameters)
  1417  			close(s.earlyConnReadyChan)
  1418  		case handshake.EventReceivedReadKeys:
  1419  			// Queue all packets for decryption that have been undecryptable so far.
  1420  			s.undecryptablePacketsToProcess = s.undecryptablePackets
  1421  			s.undecryptablePackets = nil
  1422  		case handshake.EventDiscard0RTTKeys:
  1423  			err = s.dropEncryptionLevel(protocol.Encryption0RTT)
  1424  		case handshake.EventWriteInitialData:
  1425  			_, err = s.initialStream.Write(ev.Data)
  1426  		case handshake.EventWriteHandshakeData:
  1427  			_, err = s.handshakeStream.Write(ev.Data)
  1428  		}
  1429  		if err != nil {
  1430  			return err
  1431  		}
  1432  	}
  1433  }
  1434  
  1435  func (s *connection) handleStreamFrame(frame *wire.StreamFrame) error {
  1436  	str, err := s.streamsMap.GetOrOpenReceiveStream(frame.StreamID)
  1437  	if err != nil {
  1438  		return err
  1439  	}
  1440  	if str == nil {
  1441  		// Stream is closed and already garbage collected
  1442  		// ignore this StreamFrame
  1443  		return nil
  1444  	}
  1445  	return str.handleStreamFrame(frame)
  1446  }
  1447  
  1448  func (s *connection) handleMaxDataFrame(frame *wire.MaxDataFrame) {
  1449  	s.connFlowController.UpdateSendWindow(frame.MaximumData)
  1450  }
  1451  
  1452  func (s *connection) handleMaxStreamDataFrame(frame *wire.MaxStreamDataFrame) error {
  1453  	str, err := s.streamsMap.GetOrOpenSendStream(frame.StreamID)
  1454  	if err != nil {
  1455  		return err
  1456  	}
  1457  	if str == nil {
  1458  		// stream is closed and already garbage collected
  1459  		return nil
  1460  	}
  1461  	str.updateSendWindow(frame.MaximumStreamData)
  1462  	return nil
  1463  }
  1464  
  1465  func (s *connection) handleMaxStreamsFrame(frame *wire.MaxStreamsFrame) {
  1466  	s.streamsMap.HandleMaxStreamsFrame(frame)
  1467  }
  1468  
  1469  func (s *connection) handleResetStreamFrame(frame *wire.ResetStreamFrame) error {
  1470  	str, err := s.streamsMap.GetOrOpenReceiveStream(frame.StreamID)
  1471  	if err != nil {
  1472  		return err
  1473  	}
  1474  	if str == nil {
  1475  		// stream is closed and already garbage collected
  1476  		return nil
  1477  	}
  1478  	return str.handleResetStreamFrame(frame)
  1479  }
  1480  
  1481  func (s *connection) handleStopSendingFrame(frame *wire.StopSendingFrame) error {
  1482  	str, err := s.streamsMap.GetOrOpenSendStream(frame.StreamID)
  1483  	if err != nil {
  1484  		return err
  1485  	}
  1486  	if str == nil {
  1487  		// stream is closed and already garbage collected
  1488  		return nil
  1489  	}
  1490  	str.handleStopSendingFrame(frame)
  1491  	return nil
  1492  }
  1493  
  1494  func (s *connection) handlePathChallengeFrame(frame *wire.PathChallengeFrame) {
  1495  	s.queueControlFrame(&wire.PathResponseFrame{Data: frame.Data})
  1496  }
  1497  
  1498  func (s *connection) handleNewTokenFrame(frame *wire.NewTokenFrame) error {
  1499  	if s.perspective == protocol.PerspectiveServer {
  1500  		return &qerr.TransportError{
  1501  			ErrorCode:    qerr.ProtocolViolation,
  1502  			ErrorMessage: "received NEW_TOKEN frame from the client",
  1503  		}
  1504  	}
  1505  	if s.config.TokenStore != nil {
  1506  		s.config.TokenStore.Put(s.tokenStoreKey, &ClientToken{data: frame.Token})
  1507  	}
  1508  	return nil
  1509  }
  1510  
  1511  func (s *connection) handleNewConnectionIDFrame(f *wire.NewConnectionIDFrame) error {
  1512  	return s.connIDManager.Add(f)
  1513  }
  1514  
  1515  func (s *connection) handleRetireConnectionIDFrame(f *wire.RetireConnectionIDFrame, destConnID protocol.ConnectionID) error {
  1516  	return s.connIDGenerator.Retire(f.SequenceNumber, destConnID)
  1517  }
  1518  
  1519  func (s *connection) handleHandshakeDoneFrame() error {
  1520  	if s.perspective == protocol.PerspectiveServer {
  1521  		return &qerr.TransportError{
  1522  			ErrorCode:    qerr.ProtocolViolation,
  1523  			ErrorMessage: "received a HANDSHAKE_DONE frame",
  1524  		}
  1525  	}
  1526  	if !s.handshakeConfirmed {
  1527  		return s.handleHandshakeConfirmed()
  1528  	}
  1529  	return nil
  1530  }
  1531  
  1532  func (s *connection) handleAckFrame(frame *wire.AckFrame, encLevel protocol.EncryptionLevel) error {
  1533  	acked1RTTPacket, err := s.sentPacketHandler.ReceivedAck(frame, encLevel, s.lastPacketReceivedTime)
  1534  	if err != nil {
  1535  		return err
  1536  	}
  1537  	if !acked1RTTPacket {
  1538  		return nil
  1539  	}
  1540  	// On the client side: If the packet acknowledged a 1-RTT packet, this confirms the handshake.
  1541  	// This is only possible if the ACK was sent in a 1-RTT packet.
  1542  	// This is an optimization over simply waiting for a HANDSHAKE_DONE frame, see section 4.1.2 of RFC 9001.
  1543  	if s.perspective == protocol.PerspectiveClient && !s.handshakeConfirmed {
  1544  		if err := s.handleHandshakeConfirmed(); err != nil {
  1545  			return err
  1546  		}
  1547  	}
  1548  	return s.cryptoStreamHandler.SetLargest1RTTAcked(frame.LargestAcked())
  1549  }
  1550  
  1551  func (s *connection) handleDatagramFrame(f *wire.DatagramFrame) error {
  1552  	if f.Length(s.version) > s.maxDatagramFrameSize {
  1553  		return &qerr.TransportError{
  1554  			ErrorCode:    qerr.ProtocolViolation,
  1555  			ErrorMessage: "DATAGRAM frame too large",
  1556  		}
  1557  	}
  1558  	s.datagramQueue.HandleDatagramFrame(f)
  1559  	return nil
  1560  }
  1561  
  1562  // closeLocal closes the connection and send a CONNECTION_CLOSE containing the error
  1563  func (s *connection) closeLocal(e error) {
  1564  	s.closeOnce.Do(func() {
  1565  		if e == nil {
  1566  			s.logger.Infof("Closing connection.")
  1567  		} else {
  1568  			s.logger.Errorf("Closing connection with error: %s", e)
  1569  		}
  1570  		s.closeChan <- closeError{err: e, immediate: false, remote: false}
  1571  	})
  1572  }
  1573  
  1574  // destroy closes the connection without sending the error on the wire
  1575  func (s *connection) destroy(e error) {
  1576  	s.destroyImpl(e)
  1577  	<-s.ctx.Done()
  1578  }
  1579  
  1580  func (s *connection) destroyImpl(e error) {
  1581  	s.closeOnce.Do(func() {
  1582  		if nerr, ok := e.(net.Error); ok && nerr.Timeout() {
  1583  			s.logger.Errorf("Destroying connection: %s", e)
  1584  		} else {
  1585  			s.logger.Errorf("Destroying connection with error: %s", e)
  1586  		}
  1587  		s.closeChan <- closeError{err: e, immediate: true, remote: false}
  1588  	})
  1589  }
  1590  
  1591  func (s *connection) closeRemote(e error) {
  1592  	s.closeOnce.Do(func() {
  1593  		s.logger.Errorf("Peer closed connection with error: %s", e)
  1594  		s.closeChan <- closeError{err: e, immediate: true, remote: true}
  1595  	})
  1596  }
  1597  
  1598  func (s *connection) CloseWithError(code ApplicationErrorCode, desc string) error {
  1599  	s.closeLocal(&qerr.ApplicationError{
  1600  		ErrorCode:    code,
  1601  		ErrorMessage: desc,
  1602  	})
  1603  	<-s.ctx.Done()
  1604  	return nil
  1605  }
  1606  
  1607  func (s *connection) closeWithTransportError(code TransportErrorCode) {
  1608  	s.closeLocal(&qerr.TransportError{ErrorCode: code})
  1609  	<-s.ctx.Done()
  1610  }
  1611  
  1612  func (s *connection) handleCloseError(closeErr *closeError) {
  1613  	e := closeErr.err
  1614  	if e == nil {
  1615  		e = &qerr.ApplicationError{}
  1616  	} else {
  1617  		defer func() {
  1618  			closeErr.err = e
  1619  		}()
  1620  	}
  1621  
  1622  	var (
  1623  		statelessResetErr     *StatelessResetError
  1624  		versionNegotiationErr *VersionNegotiationError
  1625  		recreateErr           *errCloseForRecreating
  1626  		applicationErr        *ApplicationError
  1627  		transportErr          *TransportError
  1628  	)
  1629  	switch {
  1630  	case errors.Is(e, qerr.ErrIdleTimeout),
  1631  		errors.Is(e, qerr.ErrHandshakeTimeout),
  1632  		errors.As(e, &statelessResetErr),
  1633  		errors.As(e, &versionNegotiationErr),
  1634  		errors.As(e, &recreateErr),
  1635  		errors.As(e, &applicationErr),
  1636  		errors.As(e, &transportErr):
  1637  	default:
  1638  		e = &qerr.TransportError{
  1639  			ErrorCode:    qerr.InternalError,
  1640  			ErrorMessage: e.Error(),
  1641  		}
  1642  	}
  1643  
  1644  	s.streamsMap.CloseWithError(e)
  1645  	s.connIDManager.Close()
  1646  	if s.datagramQueue != nil {
  1647  		s.datagramQueue.CloseWithError(e)
  1648  	}
  1649  
  1650  	if s.tracer != nil && s.tracer.ClosedConnection != nil && !errors.As(e, &recreateErr) {
  1651  		s.tracer.ClosedConnection(e)
  1652  	}
  1653  
  1654  	// If this is a remote close we're done here
  1655  	if closeErr.remote {
  1656  		s.connIDGenerator.ReplaceWithClosed(nil)
  1657  		return
  1658  	}
  1659  	if closeErr.immediate {
  1660  		s.connIDGenerator.RemoveAll()
  1661  		return
  1662  	}
  1663  	// Don't send out any CONNECTION_CLOSE if this is an error that occurred
  1664  	// before we even sent out the first packet.
  1665  	if s.perspective == protocol.PerspectiveClient && !s.sentFirstPacket {
  1666  		s.connIDGenerator.RemoveAll()
  1667  		return
  1668  	}
  1669  	connClosePacket, err := s.sendConnectionClose(e)
  1670  	if err != nil {
  1671  		s.logger.Debugf("Error sending CONNECTION_CLOSE: %s", err)
  1672  	}
  1673  	s.connIDGenerator.ReplaceWithClosed(connClosePacket)
  1674  }
  1675  
  1676  func (s *connection) dropEncryptionLevel(encLevel protocol.EncryptionLevel) error {
  1677  	if s.tracer != nil && s.tracer.DroppedEncryptionLevel != nil {
  1678  		s.tracer.DroppedEncryptionLevel(encLevel)
  1679  	}
  1680  	s.sentPacketHandler.DropPackets(encLevel)
  1681  	s.receivedPacketHandler.DropPackets(encLevel)
  1682  	//nolint:exhaustive // only Initial and 0-RTT need special treatment
  1683  	switch encLevel {
  1684  	case protocol.EncryptionInitial:
  1685  		s.droppedInitialKeys = true
  1686  		s.cryptoStreamHandler.DiscardInitialKeys()
  1687  	case protocol.Encryption0RTT:
  1688  		s.streamsMap.ResetFor0RTT()
  1689  		if err := s.connFlowController.Reset(); err != nil {
  1690  			return err
  1691  		}
  1692  		return s.framer.Handle0RTTRejection()
  1693  	}
  1694  	return s.cryptoStreamManager.Drop(encLevel)
  1695  }
  1696  
  1697  // is called for the client, when restoring transport parameters saved for 0-RTT
  1698  func (s *connection) restoreTransportParameters(params *wire.TransportParameters) {
  1699  	if s.logger.Debug() {
  1700  		s.logger.Debugf("Restoring Transport Parameters: %s", params)
  1701  	}
  1702  
  1703  	s.peerParams = params
  1704  	s.connIDGenerator.SetMaxActiveConnIDs(params.ActiveConnectionIDLimit)
  1705  	s.connFlowController.UpdateSendWindow(params.InitialMaxData)
  1706  	s.streamsMap.UpdateLimits(params)
  1707  	s.connStateMutex.Lock()
  1708  	s.connState.SupportsDatagrams = s.supportsDatagrams()
  1709  	s.connStateMutex.Unlock()
  1710  }
  1711  
  1712  func (s *connection) handleTransportParameters(params *wire.TransportParameters) error {
  1713  	if s.tracer != nil && s.tracer.ReceivedTransportParameters != nil {
  1714  		s.tracer.ReceivedTransportParameters(params)
  1715  	}
  1716  	if err := s.checkTransportParameters(params); err != nil {
  1717  		return &qerr.TransportError{
  1718  			ErrorCode:    qerr.TransportParameterError,
  1719  			ErrorMessage: err.Error(),
  1720  		}
  1721  	}
  1722  
  1723  	if s.perspective == protocol.PerspectiveClient && s.peerParams != nil && s.ConnectionState().Used0RTT && !params.ValidForUpdate(s.peerParams) {
  1724  		return &qerr.TransportError{
  1725  			ErrorCode:    qerr.ProtocolViolation,
  1726  			ErrorMessage: "server sent reduced limits after accepting 0-RTT data",
  1727  		}
  1728  	}
  1729  
  1730  	s.peerParams = params
  1731  	// On the client side we have to wait for handshake completion.
  1732  	// During a 0-RTT connection, we are only allowed to use the new transport parameters for 1-RTT packets.
  1733  	if s.perspective == protocol.PerspectiveServer {
  1734  		s.applyTransportParameters()
  1735  		// On the server side, the early connection is ready as soon as we processed
  1736  		// the client's transport parameters.
  1737  		close(s.earlyConnReadyChan)
  1738  	}
  1739  
  1740  	s.connStateMutex.Lock()
  1741  	s.connState.SupportsDatagrams = s.supportsDatagrams()
  1742  	s.connStateMutex.Unlock()
  1743  	return nil
  1744  }
  1745  
  1746  func (s *connection) checkTransportParameters(params *wire.TransportParameters) error {
  1747  	if s.logger.Debug() {
  1748  		s.logger.Debugf("Processed Transport Parameters: %s", params)
  1749  	}
  1750  
  1751  	// check the initial_source_connection_id
  1752  	if params.InitialSourceConnectionID != s.handshakeDestConnID {
  1753  		return fmt.Errorf("expected initial_source_connection_id to equal %s, is %s", s.handshakeDestConnID, params.InitialSourceConnectionID)
  1754  	}
  1755  
  1756  	if s.perspective == protocol.PerspectiveServer {
  1757  		return nil
  1758  	}
  1759  	// check the original_destination_connection_id
  1760  	if params.OriginalDestinationConnectionID != s.origDestConnID {
  1761  		return fmt.Errorf("expected original_destination_connection_id to equal %s, is %s", s.origDestConnID, params.OriginalDestinationConnectionID)
  1762  	}
  1763  	if s.retrySrcConnID != nil { // a Retry was performed
  1764  		if params.RetrySourceConnectionID == nil {
  1765  			return errors.New("missing retry_source_connection_id")
  1766  		}
  1767  		if *params.RetrySourceConnectionID != *s.retrySrcConnID {
  1768  			return fmt.Errorf("expected retry_source_connection_id to equal %s, is %s", s.retrySrcConnID, *params.RetrySourceConnectionID)
  1769  		}
  1770  	} else if params.RetrySourceConnectionID != nil {
  1771  		return errors.New("received retry_source_connection_id, although no Retry was performed")
  1772  	}
  1773  	return nil
  1774  }
  1775  
  1776  func (s *connection) applyTransportParameters() {
  1777  	params := s.peerParams
  1778  	// Our local idle timeout will always be > 0.
  1779  	s.idleTimeout = utils.MinNonZeroDuration(s.config.MaxIdleTimeout, params.MaxIdleTimeout)
  1780  	s.keepAliveInterval = utils.Min(s.config.KeepAlivePeriod, utils.Min(s.idleTimeout/2, protocol.MaxKeepAliveInterval))
  1781  	s.streamsMap.UpdateLimits(params)
  1782  	s.frameParser.SetAckDelayExponent(params.AckDelayExponent)
  1783  	s.connFlowController.UpdateSendWindow(params.InitialMaxData)
  1784  	s.rttStats.SetMaxAckDelay(params.MaxAckDelay)
  1785  	s.connIDGenerator.SetMaxActiveConnIDs(params.ActiveConnectionIDLimit)
  1786  	if params.StatelessResetToken != nil {
  1787  		s.connIDManager.SetStatelessResetToken(*params.StatelessResetToken)
  1788  	}
  1789  	// We don't support connection migration yet, so we don't have any use for the preferred_address.
  1790  	if params.PreferredAddress != nil {
  1791  		// Retire the connection ID.
  1792  		s.connIDManager.AddFromPreferredAddress(params.PreferredAddress.ConnectionID, params.PreferredAddress.StatelessResetToken)
  1793  	}
  1794  	maxPacketSize := protocol.ByteCount(protocol.MaxPacketBufferSize)
  1795  	if params.MaxUDPPayloadSize > 0 && params.MaxUDPPayloadSize < maxPacketSize {
  1796  		maxPacketSize = params.MaxUDPPayloadSize
  1797  	}
  1798  	s.mtuDiscoverer = newMTUDiscoverer(
  1799  		s.rttStats,
  1800  		protocol.ByteCount(s.config.InitialPacketSize),
  1801  		maxPacketSize,
  1802  		s.onMTUIncreased,
  1803  		s.tracer,
  1804  	)
  1805  }
  1806  
  1807  func (s *connection) triggerSending(now time.Time) error {
  1808  	s.pacingDeadline = time.Time{}
  1809  
  1810  	sendMode := s.sentPacketHandler.SendMode(now)
  1811  	//nolint:exhaustive // No need to handle pacing limited here.
  1812  	switch sendMode {
  1813  	case ackhandler.SendAny:
  1814  		return s.sendPackets(now)
  1815  	case ackhandler.SendNone:
  1816  		return nil
  1817  	case ackhandler.SendPacingLimited:
  1818  		deadline := s.sentPacketHandler.TimeUntilSend()
  1819  		if deadline.IsZero() {
  1820  			deadline = deadlineSendImmediately
  1821  		}
  1822  		s.pacingDeadline = deadline
  1823  		// Allow sending of an ACK if we're pacing limit.
  1824  		// This makes sure that a peer that is mostly receiving data (and thus has an inaccurate cwnd estimate)
  1825  		// sends enough ACKs to allow its peer to utilize the bandwidth.
  1826  		fallthrough
  1827  	case ackhandler.SendAck:
  1828  		// We can at most send a single ACK only packet.
  1829  		// There will only be a new ACK after receiving new packets.
  1830  		// SendAck is only returned when we're congestion limited, so we don't need to set the pacinggs timer.
  1831  		return s.maybeSendAckOnlyPacket(now)
  1832  	case ackhandler.SendPTOInitial:
  1833  		if err := s.sendProbePacket(protocol.EncryptionInitial, now); err != nil {
  1834  			return err
  1835  		}
  1836  		if s.sendQueue.WouldBlock() {
  1837  			s.scheduleSending()
  1838  			return nil
  1839  		}
  1840  		return s.triggerSending(now)
  1841  	case ackhandler.SendPTOHandshake:
  1842  		if err := s.sendProbePacket(protocol.EncryptionHandshake, now); err != nil {
  1843  			return err
  1844  		}
  1845  		if s.sendQueue.WouldBlock() {
  1846  			s.scheduleSending()
  1847  			return nil
  1848  		}
  1849  		return s.triggerSending(now)
  1850  	case ackhandler.SendPTOAppData:
  1851  		if err := s.sendProbePacket(protocol.Encryption1RTT, now); err != nil {
  1852  			return err
  1853  		}
  1854  		if s.sendQueue.WouldBlock() {
  1855  			s.scheduleSending()
  1856  			return nil
  1857  		}
  1858  		return s.triggerSending(now)
  1859  	default:
  1860  		return fmt.Errorf("BUG: invalid send mode %d", sendMode)
  1861  	}
  1862  }
  1863  
  1864  func (s *connection) sendPackets(now time.Time) error {
  1865  	// Path MTU Discovery
  1866  	// Can't use GSO, since we need to send a single packet that's larger than our current maximum size.
  1867  	// Performance-wise, this doesn't matter, since we only send a very small (<10) number of
  1868  	// MTU probe packets per connection.
  1869  	if s.handshakeConfirmed && s.mtuDiscoverer != nil && s.mtuDiscoverer.ShouldSendProbe(now) {
  1870  		ping, size := s.mtuDiscoverer.GetPing()
  1871  		p, buf, err := s.packer.PackMTUProbePacket(ping, size, s.version)
  1872  		if err != nil {
  1873  			return err
  1874  		}
  1875  		ecn := s.sentPacketHandler.ECNMode(true)
  1876  		s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, buf.Len(), false)
  1877  		s.registerPackedShortHeaderPacket(p, ecn, now)
  1878  		s.sendQueue.Send(buf, 0, ecn)
  1879  		// This is kind of a hack. We need to trigger sending again somehow.
  1880  		s.pacingDeadline = deadlineSendImmediately
  1881  		return nil
  1882  	}
  1883  
  1884  	if isBlocked, offset := s.connFlowController.IsNewlyBlocked(); isBlocked {
  1885  		s.framer.QueueControlFrame(&wire.DataBlockedFrame{MaximumData: offset})
  1886  	}
  1887  	s.windowUpdateQueue.QueueAll()
  1888  	if cf := s.cryptoStreamManager.GetPostHandshakeData(protocol.MaxPostHandshakeCryptoFrameSize); cf != nil {
  1889  		s.queueControlFrame(cf)
  1890  	}
  1891  
  1892  	if !s.handshakeConfirmed {
  1893  		packet, err := s.packer.PackCoalescedPacket(false, s.maxPacketSize(), s.version)
  1894  		if err != nil || packet == nil {
  1895  			return err
  1896  		}
  1897  		s.sentFirstPacket = true
  1898  		if err := s.sendPackedCoalescedPacket(packet, s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket()), now); err != nil {
  1899  			return err
  1900  		}
  1901  		sendMode := s.sentPacketHandler.SendMode(now)
  1902  		if sendMode == ackhandler.SendPacingLimited {
  1903  			s.resetPacingDeadline()
  1904  		} else if sendMode == ackhandler.SendAny {
  1905  			s.pacingDeadline = deadlineSendImmediately
  1906  		}
  1907  		return nil
  1908  	}
  1909  
  1910  	if s.conn.capabilities().GSO {
  1911  		return s.sendPacketsWithGSO(now)
  1912  	}
  1913  	return s.sendPacketsWithoutGSO(now)
  1914  }
  1915  
  1916  func (s *connection) sendPacketsWithoutGSO(now time.Time) error {
  1917  	for {
  1918  		buf := getPacketBuffer()
  1919  		ecn := s.sentPacketHandler.ECNMode(true)
  1920  		if _, err := s.appendOneShortHeaderPacket(buf, s.maxPacketSize(), ecn, now); err != nil {
  1921  			if err == errNothingToPack {
  1922  				buf.Release()
  1923  				return nil
  1924  			}
  1925  			return err
  1926  		}
  1927  
  1928  		s.sendQueue.Send(buf, 0, ecn)
  1929  
  1930  		if s.sendQueue.WouldBlock() {
  1931  			return nil
  1932  		}
  1933  		sendMode := s.sentPacketHandler.SendMode(now)
  1934  		if sendMode == ackhandler.SendPacingLimited {
  1935  			s.resetPacingDeadline()
  1936  			return nil
  1937  		}
  1938  		if sendMode != ackhandler.SendAny {
  1939  			return nil
  1940  		}
  1941  		// Prioritize receiving of packets over sending out more packets.
  1942  		if len(s.receivedPackets) > 0 {
  1943  			s.pacingDeadline = deadlineSendImmediately
  1944  			return nil
  1945  		}
  1946  	}
  1947  }
  1948  
  1949  func (s *connection) sendPacketsWithGSO(now time.Time) error {
  1950  	buf := getLargePacketBuffer()
  1951  	maxSize := s.maxPacketSize()
  1952  
  1953  	ecn := s.sentPacketHandler.ECNMode(true)
  1954  	for {
  1955  		var dontSendMore bool
  1956  		size, err := s.appendOneShortHeaderPacket(buf, maxSize, ecn, now)
  1957  		if err != nil {
  1958  			if err != errNothingToPack {
  1959  				return err
  1960  			}
  1961  			if buf.Len() == 0 {
  1962  				buf.Release()
  1963  				return nil
  1964  			}
  1965  			dontSendMore = true
  1966  		}
  1967  
  1968  		if !dontSendMore {
  1969  			sendMode := s.sentPacketHandler.SendMode(now)
  1970  			if sendMode == ackhandler.SendPacingLimited {
  1971  				s.resetPacingDeadline()
  1972  			}
  1973  			if sendMode != ackhandler.SendAny {
  1974  				dontSendMore = true
  1975  			}
  1976  		}
  1977  
  1978  		// Don't send more packets in this batch if they require a different ECN marking than the previous ones.
  1979  		nextECN := s.sentPacketHandler.ECNMode(true)
  1980  
  1981  		// Append another packet if
  1982  		// 1. The congestion controller and pacer allow sending more
  1983  		// 2. The last packet appended was a full-size packet
  1984  		// 3. The next packet will have the same ECN marking
  1985  		// 4. We still have enough space for another full-size packet in the buffer
  1986  		if !dontSendMore && size == maxSize && nextECN == ecn && buf.Len()+maxSize <= buf.Cap() {
  1987  			continue
  1988  		}
  1989  
  1990  		s.sendQueue.Send(buf, uint16(maxSize), ecn)
  1991  
  1992  		if dontSendMore {
  1993  			return nil
  1994  		}
  1995  		if s.sendQueue.WouldBlock() {
  1996  			return nil
  1997  		}
  1998  
  1999  		// Prioritize receiving of packets over sending out more packets.
  2000  		if len(s.receivedPackets) > 0 {
  2001  			s.pacingDeadline = deadlineSendImmediately
  2002  			return nil
  2003  		}
  2004  
  2005  		buf = getLargePacketBuffer()
  2006  	}
  2007  }
  2008  
  2009  func (s *connection) resetPacingDeadline() {
  2010  	deadline := s.sentPacketHandler.TimeUntilSend()
  2011  	if deadline.IsZero() {
  2012  		deadline = deadlineSendImmediately
  2013  	}
  2014  	s.pacingDeadline = deadline
  2015  }
  2016  
  2017  func (s *connection) maybeSendAckOnlyPacket(now time.Time) error {
  2018  	if !s.handshakeConfirmed {
  2019  		ecn := s.sentPacketHandler.ECNMode(false)
  2020  		packet, err := s.packer.PackCoalescedPacket(true, s.maxPacketSize(), s.version)
  2021  		if err != nil {
  2022  			return err
  2023  		}
  2024  		if packet == nil {
  2025  			return nil
  2026  		}
  2027  		return s.sendPackedCoalescedPacket(packet, ecn, now)
  2028  	}
  2029  
  2030  	ecn := s.sentPacketHandler.ECNMode(true)
  2031  	p, buf, err := s.packer.PackAckOnlyPacket(s.maxPacketSize(), s.version)
  2032  	if err != nil {
  2033  		if err == errNothingToPack {
  2034  			return nil
  2035  		}
  2036  		return err
  2037  	}
  2038  	s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, buf.Len(), false)
  2039  	s.registerPackedShortHeaderPacket(p, ecn, now)
  2040  	s.sendQueue.Send(buf, 0, ecn)
  2041  	return nil
  2042  }
  2043  
  2044  func (s *connection) sendProbePacket(encLevel protocol.EncryptionLevel, now time.Time) error {
  2045  	// Queue probe packets until we actually send out a packet,
  2046  	// or until there are no more packets to queue.
  2047  	var packet *coalescedPacket
  2048  	for {
  2049  		if wasQueued := s.sentPacketHandler.QueueProbePacket(encLevel); !wasQueued {
  2050  			break
  2051  		}
  2052  		var err error
  2053  		packet, err = s.packer.MaybePackProbePacket(encLevel, s.maxPacketSize(), s.version)
  2054  		if err != nil {
  2055  			return err
  2056  		}
  2057  		if packet != nil {
  2058  			break
  2059  		}
  2060  	}
  2061  	if packet == nil {
  2062  		s.retransmissionQueue.AddPing(encLevel)
  2063  		var err error
  2064  		packet, err = s.packer.MaybePackProbePacket(encLevel, s.maxPacketSize(), s.version)
  2065  		if err != nil {
  2066  			return err
  2067  		}
  2068  	}
  2069  	if packet == nil || (len(packet.longHdrPackets) == 0 && packet.shortHdrPacket == nil) {
  2070  		return fmt.Errorf("connection BUG: couldn't pack %s probe packet", encLevel)
  2071  	}
  2072  	return s.sendPackedCoalescedPacket(packet, s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket()), now)
  2073  }
  2074  
  2075  // appendOneShortHeaderPacket appends a new packet to the given packetBuffer.
  2076  // If there was nothing to pack, the returned size is 0.
  2077  func (s *connection) appendOneShortHeaderPacket(buf *packetBuffer, maxSize protocol.ByteCount, ecn protocol.ECN, now time.Time) (protocol.ByteCount, error) {
  2078  	startLen := buf.Len()
  2079  	p, err := s.packer.AppendPacket(buf, maxSize, s.version)
  2080  	if err != nil {
  2081  		return 0, err
  2082  	}
  2083  	size := buf.Len() - startLen
  2084  	s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, size, false)
  2085  	s.registerPackedShortHeaderPacket(p, ecn, now)
  2086  	return size, nil
  2087  }
  2088  
  2089  func (s *connection) registerPackedShortHeaderPacket(p shortHeaderPacket, ecn protocol.ECN, now time.Time) {
  2090  	if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && (len(p.StreamFrames) > 0 || ackhandler.HasAckElicitingFrames(p.Frames)) {
  2091  		s.firstAckElicitingPacketAfterIdleSentTime = now
  2092  	}
  2093  
  2094  	largestAcked := protocol.InvalidPacketNumber
  2095  	if p.Ack != nil {
  2096  		largestAcked = p.Ack.LargestAcked()
  2097  	}
  2098  	s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, ecn, p.Length, p.IsPathMTUProbePacket)
  2099  	s.connIDManager.SentPacket()
  2100  }
  2101  
  2102  func (s *connection) sendPackedCoalescedPacket(packet *coalescedPacket, ecn protocol.ECN, now time.Time) error {
  2103  	s.logCoalescedPacket(packet, ecn)
  2104  	for _, p := range packet.longHdrPackets {
  2105  		if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && p.IsAckEliciting() {
  2106  			s.firstAckElicitingPacketAfterIdleSentTime = now
  2107  		}
  2108  		largestAcked := protocol.InvalidPacketNumber
  2109  		if p.ack != nil {
  2110  			largestAcked = p.ack.LargestAcked()
  2111  		}
  2112  		s.sentPacketHandler.SentPacket(now, p.header.PacketNumber, largestAcked, p.streamFrames, p.frames, p.EncryptionLevel(), ecn, p.length, false)
  2113  		if s.perspective == protocol.PerspectiveClient && p.EncryptionLevel() == protocol.EncryptionHandshake &&
  2114  			!s.droppedInitialKeys {
  2115  			// On the client side, Initial keys are dropped as soon as the first Handshake packet is sent.
  2116  			// See Section 4.9.1 of RFC 9001.
  2117  			if err := s.dropEncryptionLevel(protocol.EncryptionInitial); err != nil {
  2118  				return err
  2119  			}
  2120  		}
  2121  	}
  2122  	if p := packet.shortHdrPacket; p != nil {
  2123  		if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && p.IsAckEliciting() {
  2124  			s.firstAckElicitingPacketAfterIdleSentTime = now
  2125  		}
  2126  		largestAcked := protocol.InvalidPacketNumber
  2127  		if p.Ack != nil {
  2128  			largestAcked = p.Ack.LargestAcked()
  2129  		}
  2130  		s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, ecn, p.Length, p.IsPathMTUProbePacket)
  2131  	}
  2132  	s.connIDManager.SentPacket()
  2133  	s.sendQueue.Send(packet.buffer, 0, ecn)
  2134  	return nil
  2135  }
  2136  
  2137  func (s *connection) sendConnectionClose(e error) ([]byte, error) {
  2138  	var packet *coalescedPacket
  2139  	var err error
  2140  	var transportErr *qerr.TransportError
  2141  	var applicationErr *qerr.ApplicationError
  2142  	if errors.As(e, &transportErr) {
  2143  		packet, err = s.packer.PackConnectionClose(transportErr, s.maxPacketSize(), s.version)
  2144  	} else if errors.As(e, &applicationErr) {
  2145  		packet, err = s.packer.PackApplicationClose(applicationErr, s.maxPacketSize(), s.version)
  2146  	} else {
  2147  		packet, err = s.packer.PackConnectionClose(&qerr.TransportError{
  2148  			ErrorCode:    qerr.InternalError,
  2149  			ErrorMessage: fmt.Sprintf("connection BUG: unspecified error type (msg: %s)", e.Error()),
  2150  		}, s.maxPacketSize(), s.version)
  2151  	}
  2152  	if err != nil {
  2153  		return nil, err
  2154  	}
  2155  	ecn := s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket())
  2156  	s.logCoalescedPacket(packet, ecn)
  2157  	return packet.buffer.Data, s.conn.Write(packet.buffer.Data, 0, ecn)
  2158  }
  2159  
  2160  func (s *connection) maxPacketSize() protocol.ByteCount {
  2161  	if s.mtuDiscoverer == nil {
  2162  		// Use the configured packet size on the client side.
  2163  		// If the server sends a max_udp_payload_size that's smaller than this size, we can ignore this:
  2164  		// Apparently the server still processed the (fully padded) Initial packet anyway.
  2165  		if s.perspective == protocol.PerspectiveClient {
  2166  			return protocol.ByteCount(s.config.InitialPacketSize)
  2167  		}
  2168  		// On the server side, there's no downside to using 1200 bytes until we received the client's transport
  2169  		// parameters:
  2170  		// * If the first packet didn't contain the entire ClientHello, all we can do is ACK that packet. We don't
  2171  		//   need a lot of bytes for that.
  2172  		// * If it did, we will have processed the transport parameters and initialized the MTU discoverer.
  2173  		return protocol.MinInitialPacketSize
  2174  	}
  2175  	return s.mtuDiscoverer.CurrentSize()
  2176  }
  2177  
  2178  func (s *connection) logLongHeaderPacket(p *longHeaderPacket, ecn protocol.ECN) {
  2179  	// quic-go logging
  2180  	if s.logger.Debug() {
  2181  		p.header.Log(s.logger)
  2182  		if p.ack != nil {
  2183  			wire.LogFrame(s.logger, p.ack, true)
  2184  		}
  2185  		for _, frame := range p.frames {
  2186  			wire.LogFrame(s.logger, frame.Frame, true)
  2187  		}
  2188  		for _, frame := range p.streamFrames {
  2189  			wire.LogFrame(s.logger, frame.Frame, true)
  2190  		}
  2191  	}
  2192  
  2193  	// tracing
  2194  	if s.tracer != nil && s.tracer.SentLongHeaderPacket != nil {
  2195  		frames := make([]logging.Frame, 0, len(p.frames))
  2196  		for _, f := range p.frames {
  2197  			frames = append(frames, logutils.ConvertFrame(f.Frame))
  2198  		}
  2199  		for _, f := range p.streamFrames {
  2200  			frames = append(frames, logutils.ConvertFrame(f.Frame))
  2201  		}
  2202  		var ack *logging.AckFrame
  2203  		if p.ack != nil {
  2204  			ack = logutils.ConvertAckFrame(p.ack)
  2205  		}
  2206  		s.tracer.SentLongHeaderPacket(p.header, p.length, ecn, ack, frames)
  2207  	}
  2208  }
  2209  
  2210  func (s *connection) logShortHeaderPacket(
  2211  	destConnID protocol.ConnectionID,
  2212  	ackFrame *wire.AckFrame,
  2213  	frames []ackhandler.Frame,
  2214  	streamFrames []ackhandler.StreamFrame,
  2215  	pn protocol.PacketNumber,
  2216  	pnLen protocol.PacketNumberLen,
  2217  	kp protocol.KeyPhaseBit,
  2218  	ecn protocol.ECN,
  2219  	size protocol.ByteCount,
  2220  	isCoalesced bool,
  2221  ) {
  2222  	if s.logger.Debug() && !isCoalesced {
  2223  		s.logger.Debugf("-> Sending packet %d (%d bytes) for connection %s, 1-RTT (ECN: %s)", pn, size, s.logID, ecn)
  2224  	}
  2225  	// quic-go logging
  2226  	if s.logger.Debug() {
  2227  		wire.LogShortHeader(s.logger, destConnID, pn, pnLen, kp)
  2228  		if ackFrame != nil {
  2229  			wire.LogFrame(s.logger, ackFrame, true)
  2230  		}
  2231  		for _, f := range frames {
  2232  			wire.LogFrame(s.logger, f.Frame, true)
  2233  		}
  2234  		for _, f := range streamFrames {
  2235  			wire.LogFrame(s.logger, f.Frame, true)
  2236  		}
  2237  	}
  2238  
  2239  	// tracing
  2240  	if s.tracer != nil && s.tracer.SentShortHeaderPacket != nil {
  2241  		fs := make([]logging.Frame, 0, len(frames)+len(streamFrames))
  2242  		for _, f := range frames {
  2243  			fs = append(fs, logutils.ConvertFrame(f.Frame))
  2244  		}
  2245  		for _, f := range streamFrames {
  2246  			fs = append(fs, logutils.ConvertFrame(f.Frame))
  2247  		}
  2248  		var ack *logging.AckFrame
  2249  		if ackFrame != nil {
  2250  			ack = logutils.ConvertAckFrame(ackFrame)
  2251  		}
  2252  		s.tracer.SentShortHeaderPacket(
  2253  			&logging.ShortHeader{
  2254  				DestConnectionID: destConnID,
  2255  				PacketNumber:     pn,
  2256  				PacketNumberLen:  pnLen,
  2257  				KeyPhase:         kp,
  2258  			},
  2259  			size,
  2260  			ecn,
  2261  			ack,
  2262  			fs,
  2263  		)
  2264  	}
  2265  }
  2266  
  2267  func (s *connection) logCoalescedPacket(packet *coalescedPacket, ecn protocol.ECN) {
  2268  	if s.logger.Debug() {
  2269  		// There's a short period between dropping both Initial and Handshake keys and completion of the handshake,
  2270  		// during which we might call PackCoalescedPacket but just pack a short header packet.
  2271  		if len(packet.longHdrPackets) == 0 && packet.shortHdrPacket != nil {
  2272  			s.logShortHeaderPacket(
  2273  				packet.shortHdrPacket.DestConnID,
  2274  				packet.shortHdrPacket.Ack,
  2275  				packet.shortHdrPacket.Frames,
  2276  				packet.shortHdrPacket.StreamFrames,
  2277  				packet.shortHdrPacket.PacketNumber,
  2278  				packet.shortHdrPacket.PacketNumberLen,
  2279  				packet.shortHdrPacket.KeyPhase,
  2280  				ecn,
  2281  				packet.shortHdrPacket.Length,
  2282  				false,
  2283  			)
  2284  			return
  2285  		}
  2286  		if len(packet.longHdrPackets) > 1 {
  2287  			s.logger.Debugf("-> Sending coalesced packet (%d parts, %d bytes) for connection %s", len(packet.longHdrPackets), packet.buffer.Len(), s.logID)
  2288  		} else {
  2289  			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())
  2290  		}
  2291  	}
  2292  	for _, p := range packet.longHdrPackets {
  2293  		s.logLongHeaderPacket(p, ecn)
  2294  	}
  2295  	if p := packet.shortHdrPacket; p != nil {
  2296  		s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, p.Length, true)
  2297  	}
  2298  }
  2299  
  2300  // AcceptStream returns the next stream openend by the peer
  2301  func (s *connection) AcceptStream(ctx context.Context) (Stream, error) {
  2302  	return s.streamsMap.AcceptStream(ctx)
  2303  }
  2304  
  2305  func (s *connection) AcceptUniStream(ctx context.Context) (ReceiveStream, error) {
  2306  	return s.streamsMap.AcceptUniStream(ctx)
  2307  }
  2308  
  2309  // OpenStream opens a stream
  2310  func (s *connection) OpenStream() (Stream, error) {
  2311  	return s.streamsMap.OpenStream()
  2312  }
  2313  
  2314  func (s *connection) OpenStreamSync(ctx context.Context) (Stream, error) {
  2315  	return s.streamsMap.OpenStreamSync(ctx)
  2316  }
  2317  
  2318  func (s *connection) OpenUniStream() (SendStream, error) {
  2319  	return s.streamsMap.OpenUniStream()
  2320  }
  2321  
  2322  func (s *connection) OpenUniStreamSync(ctx context.Context) (SendStream, error) {
  2323  	return s.streamsMap.OpenUniStreamSync(ctx)
  2324  }
  2325  
  2326  func (s *connection) newFlowController(id protocol.StreamID) flowcontrol.StreamFlowController {
  2327  	initialSendWindow := s.peerParams.InitialMaxStreamDataUni
  2328  	if id.Type() == protocol.StreamTypeBidi {
  2329  		if id.InitiatedBy() == s.perspective {
  2330  			initialSendWindow = s.peerParams.InitialMaxStreamDataBidiRemote
  2331  		} else {
  2332  			initialSendWindow = s.peerParams.InitialMaxStreamDataBidiLocal
  2333  		}
  2334  	}
  2335  	return flowcontrol.NewStreamFlowController(
  2336  		id,
  2337  		s.connFlowController,
  2338  		protocol.ByteCount(s.config.InitialStreamReceiveWindow),
  2339  		protocol.ByteCount(s.config.MaxStreamReceiveWindow),
  2340  		initialSendWindow,
  2341  		s.onHasStreamWindowUpdate,
  2342  		s.rttStats,
  2343  		s.logger,
  2344  	)
  2345  }
  2346  
  2347  // scheduleSending signals that we have data for sending
  2348  func (s *connection) scheduleSending() {
  2349  	select {
  2350  	case s.sendingScheduled <- struct{}{}:
  2351  	default:
  2352  	}
  2353  }
  2354  
  2355  // tryQueueingUndecryptablePacket queues a packet for which we're missing the decryption keys.
  2356  // The logging.PacketType is only used for logging purposes.
  2357  func (s *connection) tryQueueingUndecryptablePacket(p receivedPacket, pt logging.PacketType) {
  2358  	if s.handshakeComplete {
  2359  		panic("shouldn't queue undecryptable packets after handshake completion")
  2360  	}
  2361  	if len(s.undecryptablePackets)+1 > protocol.MaxUndecryptablePackets {
  2362  		if s.tracer != nil && s.tracer.DroppedPacket != nil {
  2363  			s.tracer.DroppedPacket(pt, protocol.InvalidPacketNumber, p.Size(), logging.PacketDropDOSPrevention)
  2364  		}
  2365  		s.logger.Infof("Dropping undecryptable packet (%d bytes). Undecryptable packet queue full.", p.Size())
  2366  		return
  2367  	}
  2368  	s.logger.Infof("Queueing packet (%d bytes) for later decryption", p.Size())
  2369  	if s.tracer != nil && s.tracer.BufferedPacket != nil {
  2370  		s.tracer.BufferedPacket(pt, p.Size())
  2371  	}
  2372  	s.undecryptablePackets = append(s.undecryptablePackets, p)
  2373  }
  2374  
  2375  func (s *connection) queueControlFrame(f wire.Frame) {
  2376  	s.framer.QueueControlFrame(f)
  2377  	s.scheduleSending()
  2378  }
  2379  
  2380  func (s *connection) onHasStreamWindowUpdate(id protocol.StreamID) {
  2381  	s.windowUpdateQueue.AddStream(id)
  2382  	s.scheduleSending()
  2383  }
  2384  
  2385  func (s *connection) onHasConnectionWindowUpdate() {
  2386  	s.windowUpdateQueue.AddConnection()
  2387  	s.scheduleSending()
  2388  }
  2389  
  2390  func (s *connection) onHasStreamData(id protocol.StreamID) {
  2391  	s.framer.AddActiveStream(id)
  2392  	s.scheduleSending()
  2393  }
  2394  
  2395  func (s *connection) onStreamCompleted(id protocol.StreamID) {
  2396  	if err := s.streamsMap.DeleteStream(id); err != nil {
  2397  		s.closeLocal(err)
  2398  	}
  2399  }
  2400  
  2401  func (s *connection) onMTUIncreased(mtu protocol.ByteCount) {
  2402  	s.maxPayloadSizeEstimate.Store(uint32(estimateMaxPayloadSize(mtu)))
  2403  	s.sentPacketHandler.SetMaxDatagramSize(mtu)
  2404  }
  2405  
  2406  func (s *connection) SendDatagram(p []byte) error {
  2407  	if !s.supportsDatagrams() {
  2408  		return errors.New("datagram support disabled")
  2409  	}
  2410  
  2411  	f := &wire.DatagramFrame{DataLenPresent: true}
  2412  	// The payload size estimate is conservative.
  2413  	// Under many circumstances we could send a few more bytes.
  2414  	maxDataLen := utils.Max(
  2415  		f.MaxDataLen(s.peerParams.MaxDatagramFrameSize, s.version),
  2416  		protocol.ByteCount(s.maxPayloadSizeEstimate.Load()),
  2417  	)
  2418  	if protocol.ByteCount(len(p)) > maxDataLen {
  2419  		return &DatagramTooLargeError{MaxDatagramPayloadSize: int64(maxDataLen)}
  2420  	}
  2421  	f.Data = make([]byte, len(p))
  2422  	copy(f.Data, p)
  2423  	return s.datagramQueue.Add(f)
  2424  }
  2425  
  2426  func (s *connection) ReceiveDatagram(ctx context.Context) ([]byte, error) {
  2427  	if !s.config.EnableDatagrams {
  2428  		return nil, errors.New("datagram support disabled")
  2429  	}
  2430  	return s.datagramQueue.Receive(ctx)
  2431  }
  2432  
  2433  func (s *connection) LocalAddr() net.Addr {
  2434  	return s.conn.LocalAddr()
  2435  }
  2436  
  2437  func (s *connection) RemoteAddr() net.Addr {
  2438  	return s.conn.RemoteAddr()
  2439  }
  2440  
  2441  func (s *connection) GetVersion() protocol.Version {
  2442  	return s.version
  2443  }
  2444  
  2445  func (s *connection) NextConnection() Connection {
  2446  	<-s.HandshakeComplete()
  2447  	s.streamsMap.UseResetMaps()
  2448  	return s
  2449  }
  2450  
  2451  func (s *connection) SetCongestionControl(cc congestion.CongestionControl) {
  2452  	s.sentPacketHandler.SetCongestionControl(cc)
  2453  }
  2454  
  2455  func (s *connection) SetRemoteAddr(addr net.Addr) {
  2456  	s.conn.SetRemoteAddr(addr)
  2457  }
  2458  
  2459  func (s *connection) Config() *Config {
  2460  	return s.config
  2461  }
  2462  
  2463  // estimateMaxPayloadSize estimates the maximum payload size for short header packets.
  2464  // It is not very sophisticated: it just subtracts the size of header (assuming the maximum
  2465  // connection ID length), and the size of the encryption tag.
  2466  func estimateMaxPayloadSize(mtu protocol.ByteCount) protocol.ByteCount {
  2467  	return mtu - 1 /* type byte */ - 20 /* maximum connection ID length */ - 16 /* tag size */
  2468  }