github.com/sagernet/quic-go@v0.43.1-beta.1/ech/connection.go (about)

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