github.com/apernet/quic-go@v0.43.1-0.20240515053213-5e9e635fd9f0/connection.go (about)

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