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