github.com/psiphon-Labs/psiphon-tunnel-core@v2.0.28+incompatible/psiphon/common/quic/gquic-go/session.go (about)

     1  package gquic
     2  
     3  import (
     4  	"context"
     5  	"crypto/rand"
     6  	"crypto/tls"
     7  	"errors"
     8  	"fmt"
     9  	"net"
    10  	"sync"
    11  	"time"
    12  
    13  	"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/ackhandler"
    14  	"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/congestion"
    15  	"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/flowcontrol"
    16  	"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/handshake"
    17  	"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/protocol"
    18  	"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/utils"
    19  	"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/internal/wire"
    20  	"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/quic/gquic-go/qerr"
    21  	"github.com/bifurcation/mint"
    22  )
    23  
    24  type unpacker interface {
    25  	Unpack(headerBinary []byte, hdr *wire.Header, data []byte) (*unpackedPacket, error)
    26  }
    27  
    28  type streamGetter interface {
    29  	GetOrOpenReceiveStream(protocol.StreamID) (receiveStreamI, error)
    30  	GetOrOpenSendStream(protocol.StreamID) (sendStreamI, error)
    31  }
    32  
    33  type streamManager interface {
    34  	GetOrOpenSendStream(protocol.StreamID) (sendStreamI, error)
    35  	GetOrOpenReceiveStream(protocol.StreamID) (receiveStreamI, error)
    36  	OpenStream() (Stream, error)
    37  	OpenUniStream() (SendStream, error)
    38  	OpenStreamSync() (Stream, error)
    39  	OpenUniStreamSync() (SendStream, error)
    40  	AcceptStream() (Stream, error)
    41  	AcceptUniStream() (ReceiveStream, error)
    42  	DeleteStream(protocol.StreamID) error
    43  	UpdateLimits(*handshake.TransportParameters)
    44  	HandleMaxStreamIDFrame(*wire.MaxStreamIDFrame) error
    45  	CloseWithError(error)
    46  }
    47  
    48  type cryptoStreamHandler interface {
    49  	HandleCryptoStream() error
    50  	ConnectionState() handshake.ConnectionState
    51  }
    52  
    53  type divNonceSetter interface {
    54  	SetDiversificationNonce([]byte) error
    55  }
    56  
    57  type receivedPacket struct {
    58  	remoteAddr net.Addr
    59  	header     *wire.Header
    60  	data       []byte
    61  	rcvTime    time.Time
    62  }
    63  
    64  var (
    65  	newCryptoSetup       = handshake.NewCryptoSetup
    66  	newCryptoSetupClient = handshake.NewCryptoSetupClient
    67  )
    68  
    69  type closeError struct {
    70  	err       error
    71  	remote    bool
    72  	sendClose bool
    73  }
    74  
    75  // A Session is a QUIC session
    76  type session struct {
    77  	sessionRunner sessionRunner
    78  
    79  	destConnID protocol.ConnectionID
    80  	srcConnID  protocol.ConnectionID
    81  
    82  	perspective protocol.Perspective
    83  	version     protocol.VersionNumber
    84  	config      *Config
    85  
    86  	conn connection
    87  
    88  	streamsMap   streamManager
    89  	cryptoStream cryptoStream
    90  
    91  	rttStats *congestion.RTTStats
    92  
    93  	sentPacketHandler     ackhandler.SentPacketHandler
    94  	receivedPacketHandler ackhandler.ReceivedPacketHandler
    95  	framer                *framer
    96  	windowUpdateQueue     *windowUpdateQueue
    97  	connFlowController    flowcontrol.ConnectionFlowController
    98  
    99  	unpacker unpacker
   100  	packer   packer
   101  
   102  	cryptoStreamHandler cryptoStreamHandler
   103  
   104  	receivedPackets  chan *receivedPacket
   105  	sendingScheduled chan struct{}
   106  	// closeChan is used to notify the run loop that it should terminate.
   107  	closeChan chan closeError
   108  	closeOnce sync.Once
   109  
   110  	ctx       context.Context
   111  	ctxCancel context.CancelFunc
   112  
   113  	// when we receive too many undecryptable packets during the handshake, we send a Public reset
   114  	// but only after a time of protocol.PublicResetTimeout has passed
   115  	undecryptablePackets                   []*receivedPacket
   116  	receivedTooManyUndecrytablePacketsTime time.Time
   117  
   118  	// this channel is passed to the CryptoSetup and receives the transport parameters, as soon as the peer sends them
   119  	paramsChan <-chan handshake.TransportParameters
   120  	// the handshakeEvent channel is passed to the CryptoSetup.
   121  	// It receives when it makes sense to try decrypting undecryptable packets.
   122  	handshakeEvent    <-chan struct{}
   123  	handshakeComplete bool
   124  
   125  	receivedFirstPacket              bool // since packet numbers start at 0, we can't use largestRcvdPacketNumber != 0 for this
   126  	receivedFirstForwardSecurePacket bool
   127  	lastRcvdPacketNumber             protocol.PacketNumber
   128  	// Used to calculate the next packet number from the truncated wire
   129  	// representation, and sent back in public reset packets
   130  	largestRcvdPacketNumber protocol.PacketNumber
   131  
   132  	sessionCreationTime     time.Time
   133  	lastNetworkActivityTime time.Time
   134  	// pacingDeadline is the time when the next packet should be sent
   135  	pacingDeadline time.Time
   136  
   137  	peerParams *handshake.TransportParameters
   138  
   139  	timer *utils.Timer
   140  	// keepAlivePingSent stores whether a Ping frame was sent to the peer or not
   141  	// it is reset as soon as we receive a packet from the peer
   142  	keepAlivePingSent bool
   143  
   144  	logger utils.Logger
   145  }
   146  
   147  var _ Session = &session{}
   148  var _ streamSender = &session{}
   149  
   150  // newSession makes a new session
   151  func newSession(
   152  	conn connection,
   153  	sessionRunner sessionRunner,
   154  	v protocol.VersionNumber,
   155  	destConnID protocol.ConnectionID,
   156  	srcConnID protocol.ConnectionID,
   157  	scfg *handshake.ServerConfig,
   158  	tlsConf *tls.Config,
   159  	config *Config,
   160  	logger utils.Logger,
   161  ) (quicSession, error) {
   162  	logger.Debugf("Creating new session. Destination Connection ID: %s, Source Connection ID: %s", destConnID, srcConnID)
   163  	paramsChan := make(chan handshake.TransportParameters)
   164  	handshakeEvent := make(chan struct{}, 1)
   165  	s := &session{
   166  		conn:           conn,
   167  		sessionRunner:  sessionRunner,
   168  		srcConnID:      srcConnID,
   169  		destConnID:     destConnID,
   170  		perspective:    protocol.PerspectiveServer,
   171  		version:        v,
   172  		config:         config,
   173  		handshakeEvent: handshakeEvent,
   174  		paramsChan:     paramsChan,
   175  		logger:         logger,
   176  	}
   177  	s.preSetup()
   178  	transportParams := &handshake.TransportParameters{
   179  		StreamFlowControlWindow:     protocol.ReceiveStreamFlowControlWindow,
   180  		ConnectionFlowControlWindow: protocol.ReceiveConnectionFlowControlWindow,
   181  		MaxStreams:                  uint32(s.config.MaxIncomingStreams),
   182  		IdleTimeout:                 s.config.IdleTimeout,
   183  	}
   184  	divNonce := make([]byte, 32)
   185  	if _, err := rand.Read(divNonce); err != nil {
   186  		return nil, err
   187  	}
   188  	cs, err := newCryptoSetup(
   189  		s.cryptoStream,
   190  		srcConnID,
   191  		s.conn.RemoteAddr(),
   192  		s.version,
   193  		divNonce,
   194  		scfg,
   195  		transportParams,
   196  		s.config.Versions,
   197  		s.config.AcceptCookie,
   198  		paramsChan,
   199  		handshakeEvent,
   200  		s.logger,
   201  	)
   202  	if err != nil {
   203  		return nil, err
   204  	}
   205  	s.cryptoStreamHandler = cs
   206  	s.unpacker = newPacketUnpackerGQUIC(cs, s.version)
   207  	s.streamsMap = newStreamsMapLegacy(s.newStream, s.config.MaxIncomingStreams, s.perspective)
   208  	s.framer = newFramer(s.cryptoStream, s.streamsMap, s.version)
   209  	s.packer = newPacketPackerLegacy(
   210  		destConnID,
   211  		srcConnID,
   212  		s.sentPacketHandler.GetPacketNumberLen,
   213  		s.RemoteAddr(),
   214  		divNonce,
   215  		s.cryptoStream,
   216  		cs,
   217  		s.framer,
   218  		sentAndReceivedPacketManager{s.sentPacketHandler, s.receivedPacketHandler},
   219  		s.perspective,
   220  		s.version,
   221  	)
   222  	return s, s.postSetup()
   223  }
   224  
   225  // declare this as a variable, so that we can it mock it in the tests
   226  var newClientSession = func(
   227  	conn connection,
   228  	sessionRunner sessionRunner,
   229  	v protocol.VersionNumber,
   230  	destConnID protocol.ConnectionID,
   231  	srcConnID protocol.ConnectionID,
   232  	tlsConf *tls.Config,
   233  	config *Config,
   234  	initialVersion protocol.VersionNumber,
   235  	negotiatedVersions []protocol.VersionNumber, // needed for validation of the GQUIC version negotiation
   236  	logger utils.Logger,
   237  ) (quicSession, error) {
   238  	logger.Debugf("Creating new session. Destination Connection ID: %s, Source Connection ID: %s", destConnID, srcConnID)
   239  	paramsChan := make(chan handshake.TransportParameters)
   240  	handshakeEvent := make(chan struct{}, 1)
   241  	s := &session{
   242  		conn:           conn,
   243  		sessionRunner:  sessionRunner,
   244  		srcConnID:      srcConnID,
   245  		destConnID:     destConnID,
   246  		perspective:    protocol.PerspectiveClient,
   247  		version:        v,
   248  		config:         config,
   249  		handshakeEvent: handshakeEvent,
   250  		paramsChan:     paramsChan,
   251  		logger:         logger,
   252  	}
   253  	s.preSetup()
   254  	transportParams := &handshake.TransportParameters{
   255  		StreamFlowControlWindow:     protocol.ReceiveStreamFlowControlWindow,
   256  		ConnectionFlowControlWindow: protocol.ReceiveConnectionFlowControlWindow,
   257  		MaxStreams:                  uint32(s.config.MaxIncomingStreams),
   258  		IdleTimeout:                 s.config.IdleTimeout,
   259  		OmitConnectionID:            s.config.RequestConnectionIDOmission,
   260  	}
   261  	cs, err := newCryptoSetupClient(
   262  		s.cryptoStream,
   263  		destConnID,
   264  		s.version,
   265  		tlsConf,
   266  		transportParams,
   267  		paramsChan,
   268  		handshakeEvent,
   269  		initialVersion,
   270  		negotiatedVersions,
   271  		s.logger,
   272  	)
   273  	if err != nil {
   274  		return nil, err
   275  	}
   276  	s.cryptoStreamHandler = cs
   277  	s.unpacker = newPacketUnpackerGQUIC(cs, s.version)
   278  	s.streamsMap = newStreamsMapLegacy(s.newStream, s.config.MaxIncomingStreams, s.perspective)
   279  	s.framer = newFramer(s.cryptoStream, s.streamsMap, s.version)
   280  	s.packer = newPacketPackerLegacy(
   281  		destConnID,
   282  		srcConnID,
   283  		s.sentPacketHandler.GetPacketNumberLen,
   284  		s.RemoteAddr(),
   285  		nil, // no diversification nonce
   286  		s.cryptoStream,
   287  		cs,
   288  		s.framer,
   289  		sentAndReceivedPacketManager{s.sentPacketHandler, s.receivedPacketHandler},
   290  		s.perspective,
   291  		s.version,
   292  	)
   293  	return s, s.postSetup()
   294  }
   295  
   296  func newTLSServerSession(
   297  	conn connection,
   298  	runner sessionRunner,
   299  	origConnID protocol.ConnectionID,
   300  	destConnID protocol.ConnectionID,
   301  	srcConnID protocol.ConnectionID,
   302  	initialPacketNumber protocol.PacketNumber,
   303  	config *Config,
   304  	mintConf *mint.Config,
   305  	paramsChan <-chan handshake.TransportParameters,
   306  	logger utils.Logger,
   307  	v protocol.VersionNumber,
   308  ) (quicSession, error) {
   309  	handshakeEvent := make(chan struct{}, 1)
   310  	s := &session{
   311  		conn:           conn,
   312  		sessionRunner:  runner,
   313  		config:         config,
   314  		srcConnID:      srcConnID,
   315  		destConnID:     destConnID,
   316  		perspective:    protocol.PerspectiveServer,
   317  		version:        v,
   318  		handshakeEvent: handshakeEvent,
   319  		paramsChan:     paramsChan,
   320  		logger:         logger,
   321  	}
   322  	s.preSetup()
   323  	cs, err := handshake.NewCryptoSetupTLSServer(
   324  		s.cryptoStream,
   325  		origConnID,
   326  		mintConf,
   327  		handshakeEvent,
   328  		v,
   329  	)
   330  	if err != nil {
   331  		return nil, err
   332  	}
   333  	s.cryptoStreamHandler = cs
   334  	s.streamsMap = newStreamsMap(s, s.newFlowController, s.config.MaxIncomingStreams, s.config.MaxIncomingUniStreams, s.perspective, s.version)
   335  	s.framer = newFramer(s.cryptoStream, s.streamsMap, s.version)
   336  	s.packer = newPacketPacker(
   337  		s.destConnID,
   338  		s.srcConnID,
   339  		initialPacketNumber,
   340  		s.sentPacketHandler.GetPacketNumberLen,
   341  		s.RemoteAddr(),
   342  		nil, // no token
   343  		s.cryptoStream,
   344  		cs,
   345  		s.framer,
   346  		sentAndReceivedPacketManager{s.sentPacketHandler, s.receivedPacketHandler},
   347  		s.perspective,
   348  		s.version,
   349  	)
   350  	if err := s.postSetup(); err != nil {
   351  		return nil, err
   352  	}
   353  	s.unpacker = newPacketUnpacker(cs, s.version)
   354  	return s, nil
   355  }
   356  
   357  // declare this as a variable, such that we can it mock it in the tests
   358  var newTLSClientSession = func(
   359  	conn connection,
   360  	runner sessionRunner,
   361  	token []byte,
   362  	destConnID protocol.ConnectionID,
   363  	srcConnID protocol.ConnectionID,
   364  	conf *Config,
   365  	mintConf *mint.Config,
   366  	paramsChan <-chan handshake.TransportParameters,
   367  	initialPacketNumber protocol.PacketNumber,
   368  	logger utils.Logger,
   369  	v protocol.VersionNumber,
   370  ) (quicSession, error) {
   371  	handshakeEvent := make(chan struct{}, 1)
   372  	s := &session{
   373  		conn:           conn,
   374  		sessionRunner:  runner,
   375  		config:         conf,
   376  		srcConnID:      srcConnID,
   377  		destConnID:     destConnID,
   378  		perspective:    protocol.PerspectiveClient,
   379  		version:        v,
   380  		handshakeEvent: handshakeEvent,
   381  		paramsChan:     paramsChan,
   382  		logger:         logger,
   383  	}
   384  	s.preSetup()
   385  	cs, err := handshake.NewCryptoSetupTLSClient(
   386  		s.cryptoStream,
   387  		s.destConnID,
   388  		mintConf,
   389  		handshakeEvent,
   390  		v,
   391  	)
   392  	if err != nil {
   393  		return nil, err
   394  	}
   395  	s.cryptoStreamHandler = cs
   396  	s.unpacker = newPacketUnpacker(cs, s.version)
   397  	s.streamsMap = newStreamsMap(s, s.newFlowController, s.config.MaxIncomingStreams, s.config.MaxIncomingUniStreams, s.perspective, s.version)
   398  	s.framer = newFramer(s.cryptoStream, s.streamsMap, s.version)
   399  	s.packer = newPacketPacker(
   400  		s.destConnID,
   401  		s.srcConnID,
   402  		initialPacketNumber,
   403  		s.sentPacketHandler.GetPacketNumberLen,
   404  		s.RemoteAddr(),
   405  		token,
   406  		s.cryptoStream,
   407  		cs,
   408  		s.framer,
   409  		sentAndReceivedPacketManager{s.sentPacketHandler, s.receivedPacketHandler},
   410  		s.perspective,
   411  		s.version,
   412  	)
   413  	return s, s.postSetup()
   414  }
   415  
   416  func (s *session) preSetup() {
   417  	s.rttStats = &congestion.RTTStats{}
   418  	s.sentPacketHandler = ackhandler.NewSentPacketHandler(s.rttStats, s.logger, s.version)
   419  	s.receivedPacketHandler = ackhandler.NewReceivedPacketHandler(s.rttStats, s.logger, s.version)
   420  	s.connFlowController = flowcontrol.NewConnectionFlowController(
   421  		protocol.ReceiveConnectionFlowControlWindow,
   422  		protocol.ByteCount(s.config.MaxReceiveConnectionFlowControlWindow),
   423  		s.onHasConnectionWindowUpdate,
   424  		s.rttStats,
   425  		s.logger,
   426  	)
   427  	s.cryptoStream = s.newCryptoStream()
   428  }
   429  
   430  func (s *session) postSetup() error {
   431  	s.receivedPackets = make(chan *receivedPacket, protocol.MaxSessionUnprocessedPackets)
   432  	s.closeChan = make(chan closeError, 1)
   433  	s.sendingScheduled = make(chan struct{}, 1)
   434  	s.undecryptablePackets = make([]*receivedPacket, 0, protocol.MaxUndecryptablePackets)
   435  	s.ctx, s.ctxCancel = context.WithCancel(context.Background())
   436  
   437  	s.timer = utils.NewTimer()
   438  	now := time.Now()
   439  	s.lastNetworkActivityTime = now
   440  	s.sessionCreationTime = now
   441  
   442  	s.windowUpdateQueue = newWindowUpdateQueue(s.streamsMap, s.connFlowController, s.framer.QueueControlFrame)
   443  	return nil
   444  }
   445  
   446  // run the session main loop
   447  func (s *session) run() error {
   448  	defer s.ctxCancel()
   449  
   450  	go func() {
   451  		if err := s.cryptoStreamHandler.HandleCryptoStream(); err != nil {
   452  			s.closeLocal(err)
   453  		}
   454  	}()
   455  
   456  	var closeErr closeError
   457  
   458  runLoop:
   459  	for {
   460  
   461  		// Close immediately if requested
   462  		select {
   463  		case closeErr = <-s.closeChan:
   464  			break runLoop
   465  		case _, ok := <-s.handshakeEvent:
   466  			// when the handshake is completed, the channel will be closed
   467  			s.handleHandshakeEvent(!ok)
   468  		default:
   469  		}
   470  
   471  		s.maybeResetTimer()
   472  
   473  		select {
   474  		case closeErr = <-s.closeChan:
   475  			break runLoop
   476  		case <-s.timer.Chan():
   477  			s.timer.SetRead()
   478  			// We do all the interesting stuff after the switch statement, so
   479  			// nothing to see here.
   480  		case <-s.sendingScheduled:
   481  			// We do all the interesting stuff after the switch statement, so
   482  			// nothing to see here.
   483  		case p := <-s.receivedPackets:
   484  			err := s.handlePacketImpl(p)
   485  			if err != nil {
   486  				if qErr, ok := err.(*qerr.QuicError); ok && qErr.ErrorCode == qerr.DecryptionFailure {
   487  					s.tryQueueingUndecryptablePacket(p)
   488  					continue
   489  				}
   490  				s.closeLocal(err)
   491  				continue
   492  			}
   493  			// This is a bit unclean, but works properly, since the packet always
   494  			// begins with the public header and we never copy it.
   495  			putPacketBuffer(&p.header.Raw)
   496  		case p := <-s.paramsChan:
   497  			s.processTransportParameters(&p)
   498  			continue
   499  		case _, ok := <-s.handshakeEvent:
   500  			// when the handshake is completed, the channel will be closed
   501  			s.handleHandshakeEvent(!ok)
   502  		}
   503  
   504  		now := time.Now()
   505  		if timeout := s.sentPacketHandler.GetAlarmTimeout(); !timeout.IsZero() && timeout.Before(now) {
   506  			// This could cause packets to be retransmitted.
   507  			// Check it before trying to send packets.
   508  			if err := s.sentPacketHandler.OnAlarm(); err != nil {
   509  				s.closeLocal(err)
   510  			}
   511  		}
   512  
   513  		var pacingDeadline time.Time
   514  		if s.pacingDeadline.IsZero() { // the timer didn't have a pacing deadline set
   515  			pacingDeadline = s.sentPacketHandler.TimeUntilSend()
   516  		}
   517  		if s.config.KeepAlive && !s.keepAlivePingSent && s.handshakeComplete && time.Since(s.lastNetworkActivityTime) >= s.peerParams.IdleTimeout/2 {
   518  			// send a PING frame since there is no activity in the session
   519  			s.logger.Debugf("Sending a keep-alive ping to keep the connection alive.")
   520  			s.framer.QueueControlFrame(&wire.PingFrame{})
   521  			s.keepAlivePingSent = true
   522  		} else if !pacingDeadline.IsZero() && now.Before(pacingDeadline) {
   523  			// If we get to this point before the pacing deadline, we should wait until that deadline.
   524  			// This can happen when scheduleSending is called, or a packet is received.
   525  			// Set the timer and restart the run loop.
   526  			s.pacingDeadline = pacingDeadline
   527  			continue
   528  		}
   529  
   530  		if !s.receivedTooManyUndecrytablePacketsTime.IsZero() && s.receivedTooManyUndecrytablePacketsTime.Add(protocol.PublicResetTimeout).Before(now) && len(s.undecryptablePackets) != 0 {
   531  			s.closeLocal(qerr.Error(qerr.DecryptionFailure, "too many undecryptable packets received"))
   532  			continue
   533  		}
   534  		if !s.handshakeComplete && now.Sub(s.sessionCreationTime) >= s.config.HandshakeTimeout {
   535  			s.closeLocal(qerr.Error(qerr.HandshakeTimeout, "Crypto handshake did not complete in time."))
   536  			continue
   537  		}
   538  		if s.handshakeComplete && now.Sub(s.lastNetworkActivityTime) >= s.config.IdleTimeout {
   539  			s.closeLocal(qerr.Error(qerr.NetworkIdleTimeout, "No recent network activity."))
   540  			continue
   541  		}
   542  
   543  		if err := s.sendPackets(); err != nil {
   544  			s.closeLocal(err)
   545  		}
   546  	}
   547  
   548  	// [Psiphon]
   549  	// Stop timer to immediately release resources
   550  	s.timer.Reset(time.Time{})
   551  
   552  	if err := s.handleCloseError(closeErr); err != nil {
   553  		s.logger.Infof("Handling close error failed: %s", err)
   554  	}
   555  	s.logger.Infof("Connection %s closed.", s.srcConnID)
   556  	s.sessionRunner.removeConnectionID(s.srcConnID)
   557  	return closeErr.err
   558  }
   559  
   560  func (s *session) Context() context.Context {
   561  	return s.ctx
   562  }
   563  
   564  func (s *session) ConnectionState() ConnectionState {
   565  	return s.cryptoStreamHandler.ConnectionState()
   566  }
   567  
   568  func (s *session) maybeResetTimer() {
   569  	var deadline time.Time
   570  	if s.config.KeepAlive && s.handshakeComplete && !s.keepAlivePingSent {
   571  		deadline = s.lastNetworkActivityTime.Add(s.peerParams.IdleTimeout / 2)
   572  	} else {
   573  		deadline = s.lastNetworkActivityTime.Add(s.config.IdleTimeout)
   574  	}
   575  
   576  	if ackAlarm := s.receivedPacketHandler.GetAlarmTimeout(); !ackAlarm.IsZero() {
   577  		deadline = utils.MinTime(deadline, ackAlarm)
   578  	}
   579  	if lossTime := s.sentPacketHandler.GetAlarmTimeout(); !lossTime.IsZero() {
   580  		deadline = utils.MinTime(deadline, lossTime)
   581  	}
   582  	if !s.handshakeComplete {
   583  		handshakeDeadline := s.sessionCreationTime.Add(s.config.HandshakeTimeout)
   584  		deadline = utils.MinTime(deadline, handshakeDeadline)
   585  	}
   586  	if !s.receivedTooManyUndecrytablePacketsTime.IsZero() {
   587  		deadline = utils.MinTime(deadline, s.receivedTooManyUndecrytablePacketsTime.Add(protocol.PublicResetTimeout))
   588  	}
   589  	if !s.pacingDeadline.IsZero() {
   590  		deadline = utils.MinTime(deadline, s.pacingDeadline)
   591  	}
   592  
   593  	s.timer.Reset(deadline)
   594  }
   595  
   596  func (s *session) handleHandshakeEvent(completed bool) {
   597  	if !completed {
   598  		s.tryDecryptingQueuedPackets()
   599  		return
   600  	}
   601  	s.handshakeComplete = true
   602  	s.handshakeEvent = nil // prevent this case from ever being selected again
   603  	s.sessionRunner.onHandshakeComplete(s)
   604  
   605  	// In gQUIC, the server completes the handshake first (after sending the SHLO).
   606  	// In TLS 1.3, the client completes the handshake first (after sending the CFIN).
   607  	// We need to make sure they learn about the peer completing the handshake,
   608  	// in order to stop retransmitting handshake packets.
   609  	// They will stop retransmitting handshake packets when receiving the first forward-secure packet.
   610  	// We need to make sure that a retransmittable forward-secure packet is sent,
   611  	// independent from the application protocol.
   612  	if (!s.version.UsesTLS() && s.perspective == protocol.PerspectiveClient) ||
   613  		(s.version.UsesTLS() && s.perspective == protocol.PerspectiveServer) {
   614  		s.queueControlFrame(&wire.PingFrame{})
   615  		s.sentPacketHandler.SetHandshakeComplete()
   616  	}
   617  }
   618  
   619  func (s *session) handlePacketImpl(p *receivedPacket) error {
   620  	hdr := p.header
   621  	// The server can change the source connection ID with the first Handshake packet.
   622  	// After this, all packets with a different source connection have to be ignored.
   623  	if s.receivedFirstPacket && hdr.IsLongHeader && !hdr.SrcConnectionID.Equal(s.destConnID) {
   624  		s.logger.Debugf("Dropping packet with unexpected source connection ID: %s (expected %s)", p.header.SrcConnectionID, s.destConnID)
   625  		return nil
   626  	}
   627  	if s.perspective == protocol.PerspectiveClient {
   628  		if divNonce := p.header.DiversificationNonce; len(divNonce) > 0 {
   629  			if err := s.cryptoStreamHandler.(divNonceSetter).SetDiversificationNonce(divNonce); err != nil {
   630  				return err
   631  			}
   632  		}
   633  	}
   634  
   635  	if p.rcvTime.IsZero() {
   636  		// To simplify testing
   637  		p.rcvTime = time.Now()
   638  	}
   639  
   640  	// Calculate packet number
   641  	hdr.PacketNumber = protocol.InferPacketNumber(
   642  		hdr.PacketNumberLen,
   643  		s.largestRcvdPacketNumber,
   644  		hdr.PacketNumber,
   645  		s.version,
   646  	)
   647  
   648  	packet, err := s.unpacker.Unpack(hdr.Raw, hdr, p.data)
   649  	if s.logger.Debug() {
   650  		if err != nil {
   651  			s.logger.Debugf("<- Reading packet 0x%x (%d bytes) for connection %s", hdr.PacketNumber, len(p.data)+len(hdr.Raw), hdr.DestConnectionID)
   652  		} else {
   653  			s.logger.Debugf("<- Reading packet 0x%x (%d bytes) for connection %s, %s", hdr.PacketNumber, len(p.data)+len(hdr.Raw), hdr.DestConnectionID, packet.encryptionLevel)
   654  		}
   655  		hdr.Log(s.logger)
   656  	}
   657  	// if the decryption failed, this might be a packet sent by an attacker
   658  	if err != nil {
   659  		return err
   660  	}
   661  
   662  	// The server can change the source connection ID with the first Handshake packet.
   663  	if s.perspective == protocol.PerspectiveClient && !s.receivedFirstPacket && hdr.IsLongHeader && !hdr.SrcConnectionID.Equal(s.destConnID) {
   664  		s.logger.Debugf("Received first packet. Switching destination connection ID to: %s", hdr.SrcConnectionID)
   665  		s.destConnID = hdr.SrcConnectionID
   666  		err = s.packer.ChangeDestConnectionID(s.destConnID)
   667  		// [Psiphon]
   668  		// - Check error return value.
   669  		if err != nil {
   670  			return err
   671  		}
   672  		// [Psiphon]
   673  	}
   674  
   675  	s.receivedFirstPacket = true
   676  	s.lastNetworkActivityTime = p.rcvTime
   677  	s.keepAlivePingSent = false
   678  
   679  	// In gQUIC, the server completes the handshake first (after sending the SHLO).
   680  	// In TLS 1.3, the client completes the handshake first (after sending the CFIN).
   681  	// We know that the peer completed the handshake as soon as we receive a forward-secure packet.
   682  	if (!s.version.UsesTLS() && s.perspective == protocol.PerspectiveServer) ||
   683  		(s.version.UsesTLS() && s.perspective == protocol.PerspectiveClient) {
   684  		if !s.receivedFirstForwardSecurePacket && packet.encryptionLevel == protocol.EncryptionForwardSecure {
   685  			s.receivedFirstForwardSecurePacket = true
   686  			s.sentPacketHandler.SetHandshakeComplete()
   687  		}
   688  	}
   689  
   690  	s.lastRcvdPacketNumber = hdr.PacketNumber
   691  	// Only do this after decrypting, so we are sure the packet is not attacker-controlled
   692  	s.largestRcvdPacketNumber = utils.MaxPacketNumber(s.largestRcvdPacketNumber, hdr.PacketNumber)
   693  
   694  	// If this is a Retry packet, there's no need to send an ACK.
   695  	// The session will be closed and recreated as soon as the crypto setup processed the HRR.
   696  	if hdr.Type != protocol.PacketTypeRetry {
   697  		isRetransmittable := ackhandler.HasRetransmittableFrames(packet.frames)
   698  		if err := s.receivedPacketHandler.ReceivedPacket(hdr.PacketNumber, p.rcvTime, isRetransmittable); err != nil {
   699  			return err
   700  		}
   701  	}
   702  
   703  	return s.handleFrames(packet.frames, packet.encryptionLevel)
   704  }
   705  
   706  func (s *session) handleFrames(fs []wire.Frame, encLevel protocol.EncryptionLevel) error {
   707  	for _, ff := range fs {
   708  		var err error
   709  		wire.LogFrame(s.logger, ff, false)
   710  		switch frame := ff.(type) {
   711  		case *wire.StreamFrame:
   712  			err = s.handleStreamFrame(frame, encLevel)
   713  		case *wire.AckFrame:
   714  			err = s.handleAckFrame(frame, encLevel)
   715  		case *wire.ConnectionCloseFrame:
   716  			s.closeRemote(qerr.Error(frame.ErrorCode, frame.ReasonPhrase))
   717  		case *wire.GoawayFrame:
   718  			err = errors.New("unimplemented: handling GOAWAY frames")
   719  		case *wire.StopWaitingFrame: // ignore STOP_WAITINGs
   720  		case *wire.RstStreamFrame:
   721  			err = s.handleRstStreamFrame(frame)
   722  		case *wire.MaxDataFrame:
   723  			s.handleMaxDataFrame(frame)
   724  		case *wire.MaxStreamDataFrame:
   725  			err = s.handleMaxStreamDataFrame(frame)
   726  		case *wire.MaxStreamIDFrame:
   727  			err = s.handleMaxStreamIDFrame(frame)
   728  		case *wire.BlockedFrame:
   729  		case *wire.StreamBlockedFrame:
   730  		case *wire.StreamIDBlockedFrame:
   731  		case *wire.StopSendingFrame:
   732  			err = s.handleStopSendingFrame(frame)
   733  		case *wire.PingFrame:
   734  		case *wire.PathChallengeFrame:
   735  			s.handlePathChallengeFrame(frame)
   736  		case *wire.PathResponseFrame:
   737  			// since we don't send PATH_CHALLENGEs, we don't expect PATH_RESPONSEs
   738  			err = errors.New("unexpected PATH_RESPONSE frame")
   739  		default:
   740  			return errors.New("Session BUG: unexpected frame type")
   741  		}
   742  
   743  		if err != nil {
   744  			return err
   745  		}
   746  	}
   747  	return nil
   748  }
   749  
   750  // handlePacket is called by the server with a new packet
   751  func (s *session) handlePacket(p *receivedPacket) {
   752  	// Discard packets once the amount of queued packets is larger than
   753  	// the channel size, protocol.MaxSessionUnprocessedPackets
   754  	select {
   755  	case s.receivedPackets <- p:
   756  	default:
   757  	}
   758  }
   759  
   760  func (s *session) handleStreamFrame(frame *wire.StreamFrame, encLevel protocol.EncryptionLevel) error {
   761  	if frame.StreamID == s.version.CryptoStreamID() {
   762  		if frame.FinBit {
   763  			return errors.New("Received STREAM frame with FIN bit for the crypto stream")
   764  		}
   765  		return s.cryptoStream.handleStreamFrame(frame)
   766  	} else if encLevel <= protocol.EncryptionUnencrypted {
   767  		return qerr.Error(qerr.UnencryptedStreamData, fmt.Sprintf("received unencrypted stream data on stream %d", frame.StreamID))
   768  	}
   769  	str, err := s.streamsMap.GetOrOpenReceiveStream(frame.StreamID)
   770  	if err != nil {
   771  		return err
   772  	}
   773  	if str == nil {
   774  		// Stream is closed and already garbage collected
   775  		// ignore this StreamFrame
   776  		return nil
   777  	}
   778  	return str.handleStreamFrame(frame)
   779  }
   780  
   781  func (s *session) handleMaxDataFrame(frame *wire.MaxDataFrame) {
   782  	s.connFlowController.UpdateSendWindow(frame.ByteOffset)
   783  }
   784  
   785  func (s *session) handleMaxStreamDataFrame(frame *wire.MaxStreamDataFrame) error {
   786  	if frame.StreamID == s.version.CryptoStreamID() {
   787  		s.cryptoStream.handleMaxStreamDataFrame(frame)
   788  		return nil
   789  	}
   790  	str, err := s.streamsMap.GetOrOpenSendStream(frame.StreamID)
   791  	if err != nil {
   792  		return err
   793  	}
   794  	if str == nil {
   795  		// stream is closed and already garbage collected
   796  		return nil
   797  	}
   798  	str.handleMaxStreamDataFrame(frame)
   799  	return nil
   800  }
   801  
   802  func (s *session) handleMaxStreamIDFrame(frame *wire.MaxStreamIDFrame) error {
   803  	return s.streamsMap.HandleMaxStreamIDFrame(frame)
   804  }
   805  
   806  func (s *session) handleRstStreamFrame(frame *wire.RstStreamFrame) error {
   807  	if frame.StreamID == s.version.CryptoStreamID() {
   808  		return errors.New("Received RST_STREAM frame for the crypto stream")
   809  	}
   810  	str, err := s.streamsMap.GetOrOpenReceiveStream(frame.StreamID)
   811  	if err != nil {
   812  		return err
   813  	}
   814  	if str == nil {
   815  		// stream is closed and already garbage collected
   816  		return nil
   817  	}
   818  	return str.handleRstStreamFrame(frame)
   819  }
   820  
   821  func (s *session) handleStopSendingFrame(frame *wire.StopSendingFrame) error {
   822  	if frame.StreamID == s.version.CryptoStreamID() {
   823  		return errors.New("Received a STOP_SENDING frame for the crypto stream")
   824  	}
   825  	str, err := s.streamsMap.GetOrOpenSendStream(frame.StreamID)
   826  	if err != nil {
   827  		return err
   828  	}
   829  	if str == nil {
   830  		// stream is closed and already garbage collected
   831  		return nil
   832  	}
   833  	str.handleStopSendingFrame(frame)
   834  	return nil
   835  }
   836  
   837  func (s *session) handlePathChallengeFrame(frame *wire.PathChallengeFrame) {
   838  	s.queueControlFrame(&wire.PathResponseFrame{Data: frame.Data})
   839  }
   840  
   841  func (s *session) handleAckFrame(frame *wire.AckFrame, encLevel protocol.EncryptionLevel) error {
   842  	if err := s.sentPacketHandler.ReceivedAck(frame, s.lastRcvdPacketNumber, encLevel, s.lastNetworkActivityTime); err != nil {
   843  		return err
   844  	}
   845  	s.receivedPacketHandler.IgnoreBelow(s.sentPacketHandler.GetLowestPacketNotConfirmedAcked())
   846  	return nil
   847  }
   848  
   849  // closeLocal closes the session and send a CONNECTION_CLOSE containing the error
   850  func (s *session) closeLocal(e error) {
   851  	s.closeOnce.Do(func() {
   852  		s.closeChan <- closeError{err: e, sendClose: true, remote: false}
   853  	})
   854  }
   855  
   856  // destroy closes the session without sending the error on the wire
   857  func (s *session) destroy(e error) {
   858  	s.closeOnce.Do(func() {
   859  		s.closeChan <- closeError{err: e, sendClose: false, remote: false}
   860  	})
   861  }
   862  
   863  func (s *session) closeRemote(e error) {
   864  	s.closeOnce.Do(func() {
   865  		s.closeChan <- closeError{err: e, remote: true}
   866  	})
   867  }
   868  
   869  // Close the connection. It sends a qerr.PeerGoingAway.
   870  // It waits until the run loop has stopped before returning
   871  func (s *session) Close() error {
   872  	s.closeLocal(nil)
   873  	<-s.ctx.Done()
   874  	return nil
   875  }
   876  
   877  func (s *session) CloseWithError(code protocol.ApplicationErrorCode, e error) error {
   878  	s.closeLocal(qerr.Error(qerr.ErrorCode(code), e.Error()))
   879  	<-s.ctx.Done()
   880  	return nil
   881  }
   882  
   883  func (s *session) handleCloseError(closeErr closeError) error {
   884  	if closeErr.err == nil {
   885  		closeErr.err = qerr.PeerGoingAway
   886  	}
   887  
   888  	var quicErr *qerr.QuicError
   889  	var ok bool
   890  	if quicErr, ok = closeErr.err.(*qerr.QuicError); !ok {
   891  		quicErr = qerr.ToQuicError(closeErr.err)
   892  	}
   893  	// Don't log 'normal' reasons
   894  	if quicErr.ErrorCode == qerr.PeerGoingAway || quicErr.ErrorCode == qerr.NetworkIdleTimeout {
   895  		s.logger.Infof("Closing connection %s.", s.srcConnID)
   896  	} else {
   897  		s.logger.Errorf("Closing session with error: %s", closeErr.err.Error())
   898  	}
   899  
   900  	s.cryptoStream.closeForShutdown(quicErr)
   901  	s.streamsMap.CloseWithError(quicErr)
   902  
   903  	if !closeErr.sendClose {
   904  		return nil
   905  	}
   906  
   907  	// If this is a remote close we're done here
   908  	if closeErr.remote {
   909  		return nil
   910  	}
   911  
   912  	if quicErr.ErrorCode == qerr.DecryptionFailure ||
   913  		quicErr == handshake.ErrNSTPExperiment {
   914  		return s.sendPublicReset(s.lastRcvdPacketNumber)
   915  	}
   916  	return s.sendConnectionClose(quicErr)
   917  }
   918  
   919  func (s *session) processTransportParameters(params *handshake.TransportParameters) {
   920  	s.peerParams = params
   921  	s.streamsMap.UpdateLimits(params)
   922  	s.packer.HandleTransportParameters(params)
   923  	s.connFlowController.UpdateSendWindow(params.ConnectionFlowControlWindow)
   924  	// the crypto stream is the only open stream at this moment
   925  	// so we don't need to update stream flow control windows
   926  }
   927  
   928  func (s *session) sendPackets() error {
   929  	s.pacingDeadline = time.Time{}
   930  
   931  	sendMode := s.sentPacketHandler.SendMode()
   932  	if sendMode == ackhandler.SendNone { // shortcut: return immediately if there's nothing to send
   933  		return nil
   934  	}
   935  
   936  	numPackets := s.sentPacketHandler.ShouldSendNumPackets()
   937  	var numPacketsSent int
   938  sendLoop:
   939  	for {
   940  		switch sendMode {
   941  		case ackhandler.SendNone:
   942  			break sendLoop
   943  		case ackhandler.SendAck:
   944  			// If we already sent packets, and the send mode switches to SendAck,
   945  			// we've just become congestion limited.
   946  			// There's no need to try to send an ACK at this moment.
   947  			if numPacketsSent > 0 {
   948  				return nil
   949  			}
   950  			// We can at most send a single ACK only packet.
   951  			// There will only be a new ACK after receiving new packets.
   952  			// SendAck is only returned when we're congestion limited, so we don't need to set the pacingt timer.
   953  			return s.maybeSendAckOnlyPacket()
   954  		case ackhandler.SendTLP, ackhandler.SendRTO:
   955  			if err := s.sendProbePacket(); err != nil {
   956  				return err
   957  			}
   958  			numPacketsSent++
   959  		case ackhandler.SendRetransmission:
   960  			sentPacket, err := s.maybeSendRetransmission()
   961  			if err != nil {
   962  				return err
   963  			}
   964  			if sentPacket {
   965  				numPacketsSent++
   966  				// This can happen if a retransmission queued, but it wasn't necessary to send it.
   967  				// e.g. when an Initial is queued, but we already received a packet from the server.
   968  			}
   969  		case ackhandler.SendAny:
   970  			sentPacket, err := s.sendPacket()
   971  			if err != nil {
   972  				return err
   973  			}
   974  			if !sentPacket {
   975  				break sendLoop
   976  			}
   977  			numPacketsSent++
   978  		default:
   979  			return fmt.Errorf("BUG: invalid send mode %d", sendMode)
   980  		}
   981  		if numPacketsSent >= numPackets {
   982  			break
   983  		}
   984  		sendMode = s.sentPacketHandler.SendMode()
   985  	}
   986  	// Only start the pacing timer if we sent as many packets as we were allowed.
   987  	// There will probably be more to send when calling sendPacket again.
   988  	if numPacketsSent == numPackets {
   989  		s.pacingDeadline = s.sentPacketHandler.TimeUntilSend()
   990  	}
   991  	return nil
   992  }
   993  
   994  func (s *session) maybeSendAckOnlyPacket() error {
   995  	packet, err := s.packer.MaybePackAckPacket()
   996  	if err != nil {
   997  		return err
   998  	}
   999  	if packet == nil {
  1000  		return nil
  1001  	}
  1002  	s.sentPacketHandler.SentPacket(packet.ToAckHandlerPacket())
  1003  	return s.sendPackedPacket(packet)
  1004  }
  1005  
  1006  // maybeSendRetransmission sends retransmissions for at most one packet.
  1007  // It takes care that Initials aren't retransmitted, if a packet from the server was already received.
  1008  func (s *session) maybeSendRetransmission() (bool, error) {
  1009  	var retransmitPacket *ackhandler.Packet
  1010  	for {
  1011  		retransmitPacket = s.sentPacketHandler.DequeuePacketForRetransmission()
  1012  		if retransmitPacket == nil {
  1013  			return false, nil
  1014  		}
  1015  
  1016  		// Don't retransmit Initial packets if we already received a response.
  1017  		// An Initial might have been retransmitted multiple times before we receive a response.
  1018  		// As soon as we receive one response, we don't need to send any more Initials.
  1019  		if s.receivedFirstPacket && retransmitPacket.PacketType == protocol.PacketTypeInitial {
  1020  			s.logger.Debugf("Skipping retransmission of packet %d. Already received a response to an Initial.", retransmitPacket.PacketNumber)
  1021  			continue
  1022  		}
  1023  		break
  1024  	}
  1025  
  1026  	if retransmitPacket.EncryptionLevel != protocol.EncryptionForwardSecure {
  1027  		s.logger.Debugf("Dequeueing handshake retransmission for packet 0x%x", retransmitPacket.PacketNumber)
  1028  	} else {
  1029  		s.logger.Debugf("Dequeueing retransmission for packet 0x%x", retransmitPacket.PacketNumber)
  1030  	}
  1031  
  1032  	packets, err := s.packer.PackRetransmission(retransmitPacket)
  1033  	if err != nil {
  1034  		return false, err
  1035  	}
  1036  	ackhandlerPackets := make([]*ackhandler.Packet, len(packets))
  1037  	for i, packet := range packets {
  1038  		ackhandlerPackets[i] = packet.ToAckHandlerPacket()
  1039  	}
  1040  	s.sentPacketHandler.SentPacketsAsRetransmission(ackhandlerPackets, retransmitPacket.PacketNumber)
  1041  	for _, packet := range packets {
  1042  		if err := s.sendPackedPacket(packet); err != nil {
  1043  			return false, err
  1044  		}
  1045  	}
  1046  	return true, nil
  1047  }
  1048  
  1049  func (s *session) sendProbePacket() error {
  1050  	p, err := s.sentPacketHandler.DequeueProbePacket()
  1051  	if err != nil {
  1052  		return err
  1053  	}
  1054  	s.logger.Debugf("Sending a retransmission for %#x as a probe packet.", p.PacketNumber)
  1055  
  1056  	packets, err := s.packer.PackRetransmission(p)
  1057  	if err != nil {
  1058  		return err
  1059  	}
  1060  	ackhandlerPackets := make([]*ackhandler.Packet, len(packets))
  1061  	for i, packet := range packets {
  1062  		ackhandlerPackets[i] = packet.ToAckHandlerPacket()
  1063  	}
  1064  	s.sentPacketHandler.SentPacketsAsRetransmission(ackhandlerPackets, p.PacketNumber)
  1065  	for _, packet := range packets {
  1066  		if err := s.sendPackedPacket(packet); err != nil {
  1067  			return err
  1068  		}
  1069  	}
  1070  	return nil
  1071  }
  1072  
  1073  func (s *session) sendPacket() (bool, error) {
  1074  	if isBlocked, offset := s.connFlowController.IsNewlyBlocked(); isBlocked {
  1075  		s.framer.QueueControlFrame(&wire.BlockedFrame{Offset: offset})
  1076  	}
  1077  	s.windowUpdateQueue.QueueAll()
  1078  
  1079  	packet, err := s.packer.PackPacket()
  1080  	if err != nil || packet == nil {
  1081  		return false, err
  1082  	}
  1083  	s.sentPacketHandler.SentPacket(packet.ToAckHandlerPacket())
  1084  	if err := s.sendPackedPacket(packet); err != nil {
  1085  		return false, err
  1086  	}
  1087  	return true, nil
  1088  }
  1089  
  1090  func (s *session) sendPackedPacket(packet *packedPacket) error {
  1091  	defer putPacketBuffer(&packet.raw)
  1092  	s.logPacket(packet)
  1093  	return s.conn.Write(packet.raw)
  1094  }
  1095  
  1096  func (s *session) sendConnectionClose(quicErr *qerr.QuicError) error {
  1097  	packet, err := s.packer.PackConnectionClose(&wire.ConnectionCloseFrame{
  1098  		ErrorCode:    quicErr.ErrorCode,
  1099  		ReasonPhrase: quicErr.ErrorMessage,
  1100  	})
  1101  	if err != nil {
  1102  		return err
  1103  	}
  1104  	s.logPacket(packet)
  1105  	return s.conn.Write(packet.raw)
  1106  }
  1107  
  1108  func (s *session) logPacket(packet *packedPacket) {
  1109  	if !s.logger.Debug() {
  1110  		// We don't need to allocate the slices for calling the format functions
  1111  		return
  1112  	}
  1113  	s.logger.Debugf("-> Sending packet 0x%x (%d bytes) for connection %s, %s", packet.header.PacketNumber, len(packet.raw), s.srcConnID, packet.encryptionLevel)
  1114  	packet.header.Log(s.logger)
  1115  	for _, frame := range packet.frames {
  1116  		wire.LogFrame(s.logger, frame, true)
  1117  	}
  1118  }
  1119  
  1120  // GetOrOpenStream either returns an existing stream, a newly opened stream, or nil if a stream with the provided ID is already closed.
  1121  // It is *only* needed for gQUIC's H2.
  1122  // It will be removed as soon as gQUIC moves towards the IETF H2/QUIC stream mapping.
  1123  func (s *session) GetOrOpenStream(id protocol.StreamID) (Stream, error) {
  1124  	str, err := s.streamsMap.GetOrOpenSendStream(id)
  1125  	if str != nil {
  1126  		if bstr, ok := str.(Stream); ok {
  1127  			return bstr, err
  1128  		}
  1129  		return nil, fmt.Errorf("Stream %d is not a bidirectional stream", id)
  1130  	}
  1131  	// make sure to return an actual nil value here, not an Stream with value nil
  1132  	return nil, err
  1133  }
  1134  
  1135  // AcceptStream returns the next stream openend by the peer
  1136  func (s *session) AcceptStream() (Stream, error) {
  1137  	return s.streamsMap.AcceptStream()
  1138  }
  1139  
  1140  func (s *session) AcceptUniStream() (ReceiveStream, error) {
  1141  	return s.streamsMap.AcceptUniStream()
  1142  }
  1143  
  1144  // OpenStream opens a stream
  1145  func (s *session) OpenStream() (Stream, error) {
  1146  	return s.streamsMap.OpenStream()
  1147  }
  1148  
  1149  func (s *session) OpenStreamSync() (Stream, error) {
  1150  	return s.streamsMap.OpenStreamSync()
  1151  }
  1152  
  1153  func (s *session) OpenUniStream() (SendStream, error) {
  1154  	return s.streamsMap.OpenUniStream()
  1155  }
  1156  
  1157  func (s *session) OpenUniStreamSync() (SendStream, error) {
  1158  	return s.streamsMap.OpenUniStreamSync()
  1159  }
  1160  
  1161  func (s *session) newStream(id protocol.StreamID) streamI {
  1162  	flowController := s.newFlowController(id)
  1163  	return newStream(id, s, flowController, s.version)
  1164  }
  1165  
  1166  func (s *session) newFlowController(id protocol.StreamID) flowcontrol.StreamFlowController {
  1167  	var initialSendWindow protocol.ByteCount
  1168  	if s.peerParams != nil {
  1169  		initialSendWindow = s.peerParams.StreamFlowControlWindow
  1170  	}
  1171  	return flowcontrol.NewStreamFlowController(
  1172  		id,
  1173  		s.version.StreamContributesToConnectionFlowControl(id),
  1174  		s.connFlowController,
  1175  		protocol.ReceiveStreamFlowControlWindow,
  1176  		protocol.ByteCount(s.config.MaxReceiveStreamFlowControlWindow),
  1177  		initialSendWindow,
  1178  		s.onHasStreamWindowUpdate,
  1179  		s.rttStats,
  1180  		s.logger,
  1181  	)
  1182  }
  1183  
  1184  func (s *session) newCryptoStream() cryptoStream {
  1185  	id := s.version.CryptoStreamID()
  1186  	flowController := flowcontrol.NewStreamFlowController(
  1187  		id,
  1188  		s.version.StreamContributesToConnectionFlowControl(id),
  1189  		s.connFlowController,
  1190  		protocol.ReceiveStreamFlowControlWindow,
  1191  		protocol.ByteCount(s.config.MaxReceiveStreamFlowControlWindow),
  1192  		0,
  1193  		s.onHasStreamWindowUpdate,
  1194  		s.rttStats,
  1195  		s.logger,
  1196  	)
  1197  	return newCryptoStream(s, flowController, s.version)
  1198  }
  1199  
  1200  func (s *session) sendPublicReset(rejectedPacketNumber protocol.PacketNumber) error {
  1201  	s.logger.Infof("Sending PUBLIC_RESET for connection %s, packet number %d", s.destConnID, rejectedPacketNumber)
  1202  	return s.conn.Write(wire.WritePublicReset(s.destConnID, rejectedPacketNumber, 0))
  1203  }
  1204  
  1205  // scheduleSending signals that we have data for sending
  1206  func (s *session) scheduleSending() {
  1207  	select {
  1208  	case s.sendingScheduled <- struct{}{}:
  1209  	default:
  1210  	}
  1211  }
  1212  
  1213  func (s *session) tryQueueingUndecryptablePacket(p *receivedPacket) {
  1214  	if s.handshakeComplete {
  1215  		s.logger.Debugf("Received undecryptable packet from %s after the handshake: %#v, %d bytes data", p.remoteAddr.String(), p.header, len(p.data))
  1216  		return
  1217  	}
  1218  	if len(s.undecryptablePackets)+1 > protocol.MaxUndecryptablePackets {
  1219  		// if this is the first time the undecryptablePackets runs full, start the timer to send a Public Reset
  1220  		if s.receivedTooManyUndecrytablePacketsTime.IsZero() {
  1221  			s.receivedTooManyUndecrytablePacketsTime = time.Now()
  1222  			s.maybeResetTimer()
  1223  		}
  1224  		s.logger.Infof("Dropping undecrytable packet 0x%x (undecryptable packet queue full)", p.header.PacketNumber)
  1225  		return
  1226  	}
  1227  	s.logger.Infof("Queueing packet 0x%x for later decryption", p.header.PacketNumber)
  1228  	s.undecryptablePackets = append(s.undecryptablePackets, p)
  1229  }
  1230  
  1231  func (s *session) tryDecryptingQueuedPackets() {
  1232  	for _, p := range s.undecryptablePackets {
  1233  		s.handlePacket(p)
  1234  	}
  1235  	s.undecryptablePackets = s.undecryptablePackets[:0]
  1236  }
  1237  
  1238  func (s *session) queueControlFrame(f wire.Frame) {
  1239  	s.framer.QueueControlFrame(f)
  1240  	s.scheduleSending()
  1241  }
  1242  
  1243  func (s *session) onHasStreamWindowUpdate(id protocol.StreamID) {
  1244  	s.windowUpdateQueue.AddStream(id)
  1245  	s.scheduleSending()
  1246  }
  1247  
  1248  func (s *session) onHasConnectionWindowUpdate() {
  1249  	s.windowUpdateQueue.AddConnection()
  1250  	s.scheduleSending()
  1251  }
  1252  
  1253  func (s *session) onHasStreamData(id protocol.StreamID) {
  1254  	if id != s.version.CryptoStreamID() {
  1255  		s.framer.AddActiveStream(id)
  1256  	}
  1257  	s.scheduleSending()
  1258  }
  1259  
  1260  func (s *session) onStreamCompleted(id protocol.StreamID) {
  1261  	if err := s.streamsMap.DeleteStream(id); err != nil {
  1262  		s.closeLocal(err)
  1263  	}
  1264  }
  1265  
  1266  func (s *session) LocalAddr() net.Addr {
  1267  	return s.conn.LocalAddr()
  1268  }
  1269  
  1270  func (s *session) RemoteAddr() net.Addr {
  1271  	return s.conn.RemoteAddr()
  1272  }
  1273  
  1274  func (s *session) GetVersion() protocol.VersionNumber {
  1275  	return s.version
  1276  }