github.com/TugasAkhir-QUIC/quic-go@v0.0.2-0.20240215011318-d20e25a9054c/connection.go (about)

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