route/vendor/github.com/lucas-clemente/quic-go/session.go

1011 lines
30 KiB
Go
Raw Normal View History

2017-12-12 02:51:45 +00:00
package quic
import (
2018-01-03 19:19:49 +00:00
"context"
2017-12-12 02:51:45 +00:00
"crypto/tls"
"errors"
"net"
2018-01-03 19:19:49 +00:00
"sync"
2017-12-12 02:51:45 +00:00
"time"
"github.com/lucas-clemente/quic-go/ackhandler"
"github.com/lucas-clemente/quic-go/congestion"
2018-01-03 19:19:49 +00:00
"github.com/lucas-clemente/quic-go/internal/crypto"
"github.com/lucas-clemente/quic-go/internal/flowcontrol"
"github.com/lucas-clemente/quic-go/internal/handshake"
"github.com/lucas-clemente/quic-go/internal/protocol"
"github.com/lucas-clemente/quic-go/internal/utils"
"github.com/lucas-clemente/quic-go/internal/wire"
2017-12-12 02:51:45 +00:00
"github.com/lucas-clemente/quic-go/qerr"
)
type unpacker interface {
2018-01-03 19:19:49 +00:00
Unpack(headerBinary []byte, hdr *wire.Header, data []byte) (*unpackedPacket, error)
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
type streamGetter interface {
GetOrOpenReceiveStream(protocol.StreamID) (receiveStreamI, error)
GetOrOpenSendStream(protocol.StreamID) (sendStreamI, error)
}
type streamManager interface {
GetOrOpenStream(protocol.StreamID) (streamI, error)
GetOrOpenSendStream(protocol.StreamID) (sendStreamI, error)
GetOrOpenReceiveStream(protocol.StreamID) (receiveStreamI, error)
OpenStream() (Stream, error)
OpenStreamSync() (Stream, error)
AcceptStream() (Stream, error)
DeleteStream(protocol.StreamID) error
UpdateLimits(*handshake.TransportParameters)
CloseWithError(error)
}
2017-12-12 02:51:45 +00:00
type receivedPacket struct {
2018-01-03 19:19:49 +00:00
remoteAddr net.Addr
header *wire.Header
data []byte
rcvTime time.Time
2017-12-12 02:51:45 +00:00
}
var (
2018-01-03 19:19:49 +00:00
newCryptoSetup = handshake.NewCryptoSetup
newCryptoSetupClient = handshake.NewCryptoSetupClient
2017-12-12 02:51:45 +00:00
)
2018-01-03 19:19:49 +00:00
type closeError struct {
err error
remote bool
}
2017-12-12 02:51:45 +00:00
// A Session is a QUIC session
type session struct {
connectionID protocol.ConnectionID
perspective protocol.Perspective
version protocol.VersionNumber
2018-01-03 19:19:49 +00:00
config *Config
2017-12-12 02:51:45 +00:00
conn connection
2018-01-20 18:07:01 +00:00
streamsMap streamManager
cryptoStream cryptoStreamI
2017-12-12 02:51:45 +00:00
rttStats *congestion.RTTStats
sentPacketHandler ackhandler.SentPacketHandler
receivedPacketHandler ackhandler.ReceivedPacketHandler
streamFramer *streamFramer
2018-01-20 18:07:01 +00:00
windowUpdateQueue *windowUpdateQueue
connFlowController flowcontrol.ConnectionFlowController
2017-12-12 02:51:45 +00:00
unpacker unpacker
packer *packetPacker
cryptoSetup handshake.CryptoSetup
receivedPackets chan *receivedPacket
sendingScheduled chan struct{}
// closeChan is used to notify the run loop that it should terminate.
2018-01-03 19:19:49 +00:00
closeChan chan closeError
closeOnce sync.Once
ctx context.Context
ctxCancel context.CancelFunc
2017-12-12 02:51:45 +00:00
// when we receive too many undecryptable packets during the handshake, we send a Public reset
// but only after a time of protocol.PublicResetTimeout has passed
undecryptablePackets []*receivedPacket
receivedTooManyUndecrytablePacketsTime time.Time
2018-01-03 19:19:49 +00:00
// this channel is passed to the CryptoSetup and receives the transport parameters, as soon as the peer sends them
paramsChan <-chan handshake.TransportParameters
2018-01-20 18:07:01 +00:00
// the handshakeEvent channel is passed to the CryptoSetup.
// It receives when it makes sense to try decrypting undecryptable packets.
handshakeEvent <-chan struct{}
// handshakeChan is returned by handshakeStatus.
// It receives any error that might occur during the handshake.
// It is closed when the handshake is complete.
handshakeChan chan error
2018-01-03 19:19:49 +00:00
handshakeComplete bool
2017-12-12 02:51:45 +00:00
lastRcvdPacketNumber protocol.PacketNumber
// Used to calculate the next packet number from the truncated wire
// representation, and sent back in public reset packets
largestRcvdPacketNumber protocol.PacketNumber
sessionCreationTime time.Time
lastNetworkActivityTime time.Time
2018-01-03 19:19:49 +00:00
peerParams *handshake.TransportParameters
timer *utils.Timer
// keepAlivePingSent stores whether a Ping frame was sent to the peer or not
// it is reset as soon as we receive a packet from the peer
keepAlivePingSent bool
2017-12-12 02:51:45 +00:00
}
var _ Session = &session{}
2018-01-20 18:07:01 +00:00
var _ streamSender = &session{}
2017-12-12 02:51:45 +00:00
// newSession makes a new session
2018-01-03 19:19:49 +00:00
func newSession(
conn connection,
v protocol.VersionNumber,
connectionID protocol.ConnectionID,
scfg *handshake.ServerConfig,
tlsConf *tls.Config,
config *Config,
) (packetHandler, error) {
paramsChan := make(chan handshake.TransportParameters)
2018-01-20 18:07:01 +00:00
handshakeEvent := make(chan struct{}, 1)
2017-12-12 02:51:45 +00:00
s := &session{
2018-01-20 18:07:01 +00:00
conn: conn,
connectionID: connectionID,
perspective: protocol.PerspectiveServer,
version: v,
config: config,
handshakeEvent: handshakeEvent,
paramsChan: paramsChan,
2018-01-03 19:19:49 +00:00
}
s.preSetup()
transportParams := &handshake.TransportParameters{
StreamFlowControlWindow: protocol.ReceiveStreamFlowControlWindow,
ConnectionFlowControlWindow: protocol.ReceiveConnectionFlowControlWindow,
MaxStreams: protocol.MaxIncomingStreams,
IdleTimeout: s.config.IdleTimeout,
}
cs, err := newCryptoSetup(
s.cryptoStream,
s.connectionID,
s.conn.RemoteAddr(),
s.version,
scfg,
transportParams,
s.config.Versions,
s.config.AcceptCookie,
paramsChan,
2018-01-20 18:07:01 +00:00
handshakeEvent,
2018-01-03 19:19:49 +00:00
)
if err != nil {
return nil, err
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
s.cryptoSetup = cs
return s, s.postSetup(1)
}
// declare this as a variable, so that we can it mock it in the tests
var newClientSession = func(
conn connection,
hostname string,
v protocol.VersionNumber,
connectionID protocol.ConnectionID,
tlsConf *tls.Config,
config *Config,
initialVersion protocol.VersionNumber,
negotiatedVersions []protocol.VersionNumber, // needed for validation of the GQUIC version negotiaton
) (packetHandler, error) {
paramsChan := make(chan handshake.TransportParameters)
2018-01-20 18:07:01 +00:00
handshakeEvent := make(chan struct{}, 1)
2018-01-03 19:19:49 +00:00
s := &session{
2018-01-20 18:07:01 +00:00
conn: conn,
connectionID: connectionID,
perspective: protocol.PerspectiveClient,
version: v,
config: config,
handshakeEvent: handshakeEvent,
paramsChan: paramsChan,
2018-01-03 19:19:49 +00:00
}
s.preSetup()
transportParams := &handshake.TransportParameters{
StreamFlowControlWindow: protocol.ReceiveStreamFlowControlWindow,
ConnectionFlowControlWindow: protocol.ReceiveConnectionFlowControlWindow,
MaxStreams: protocol.MaxIncomingStreams,
IdleTimeout: s.config.IdleTimeout,
OmitConnectionID: s.config.RequestConnectionIDOmission,
}
cs, err := newCryptoSetupClient(
s.cryptoStream,
hostname,
s.connectionID,
s.version,
tlsConf,
transportParams,
paramsChan,
2018-01-20 18:07:01 +00:00
handshakeEvent,
2018-01-03 19:19:49 +00:00
initialVersion,
negotiatedVersions,
)
2017-12-12 02:51:45 +00:00
if err != nil {
return nil, err
}
2018-01-03 19:19:49 +00:00
s.cryptoSetup = cs
return s, s.postSetup(1)
}
func newTLSServerSession(
conn connection,
connectionID protocol.ConnectionID,
initialPacketNumber protocol.PacketNumber,
config *Config,
tls handshake.MintTLS,
cryptoStreamConn *handshake.CryptoStreamConn,
nullAEAD crypto.AEAD,
peerParams *handshake.TransportParameters,
v protocol.VersionNumber,
) (packetHandler, error) {
2018-01-20 18:07:01 +00:00
handshakeEvent := make(chan struct{}, 1)
2018-01-03 19:19:49 +00:00
s := &session{
2018-01-20 18:07:01 +00:00
conn: conn,
config: config,
connectionID: connectionID,
perspective: protocol.PerspectiveServer,
version: v,
handshakeEvent: handshakeEvent,
2018-01-03 19:19:49 +00:00
}
s.preSetup()
s.cryptoSetup = handshake.NewCryptoSetupTLSServer(
tls,
cryptoStreamConn,
nullAEAD,
2018-01-20 18:07:01 +00:00
handshakeEvent,
2018-01-03 19:19:49 +00:00
v,
)
if err := s.postSetup(initialPacketNumber); err != nil {
return nil, err
}
s.peerParams = peerParams
s.processTransportParameters(peerParams)
2017-12-12 02:51:45 +00:00
s.unpacker = &packetUnpacker{aead: s.cryptoSetup, version: s.version}
2018-01-03 19:19:49 +00:00
return s, nil
}
// declare this as a variable, such that we can it mock it in the tests
var newTLSClientSession = func(
conn connection,
hostname string,
v protocol.VersionNumber,
connectionID protocol.ConnectionID,
config *Config,
tls handshake.MintTLS,
paramsChan <-chan handshake.TransportParameters,
initialPacketNumber protocol.PacketNumber,
) (packetHandler, error) {
2018-01-20 18:07:01 +00:00
handshakeEvent := make(chan struct{}, 1)
2017-12-12 02:51:45 +00:00
s := &session{
2018-01-20 18:07:01 +00:00
conn: conn,
config: config,
connectionID: connectionID,
perspective: protocol.PerspectiveClient,
version: v,
handshakeEvent: handshakeEvent,
paramsChan: paramsChan,
2018-01-03 19:19:49 +00:00
}
s.preSetup()
tls.SetCryptoStream(s.cryptoStream)
cs, err := handshake.NewCryptoSetupTLSClient(
s.cryptoStream,
s.connectionID,
hostname,
2018-01-20 18:07:01 +00:00
handshakeEvent,
2018-01-03 19:19:49 +00:00
tls,
v,
)
2017-12-12 02:51:45 +00:00
if err != nil {
return nil, err
}
2018-01-03 19:19:49 +00:00
s.cryptoSetup = cs
return s, s.postSetup(initialPacketNumber)
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
func (s *session) preSetup() {
2017-12-12 02:51:45 +00:00
s.rttStats = &congestion.RTTStats{}
2018-01-03 19:19:49 +00:00
s.connFlowController = flowcontrol.NewConnectionFlowController(
protocol.ReceiveConnectionFlowControlWindow,
protocol.ByteCount(s.config.MaxReceiveConnectionFlowControlWindow),
s.rttStats,
)
2018-01-20 18:07:01 +00:00
s.cryptoStream = s.newCryptoStream()
2018-01-03 19:19:49 +00:00
}
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
func (s *session) postSetup(initialPacketNumber protocol.PacketNumber) error {
2018-01-20 18:07:01 +00:00
s.handshakeChan = make(chan error, 1)
2017-12-12 02:51:45 +00:00
s.receivedPackets = make(chan *receivedPacket, protocol.MaxSessionUnprocessedPackets)
2018-01-03 19:19:49 +00:00
s.closeChan = make(chan closeError, 1)
2017-12-12 02:51:45 +00:00
s.sendingScheduled = make(chan struct{}, 1)
s.undecryptablePackets = make([]*receivedPacket, 0, protocol.MaxUndecryptablePackets)
2018-01-03 19:19:49 +00:00
s.ctx, s.ctxCancel = context.WithCancel(context.Background())
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
s.timer = utils.NewTimer()
now := time.Now()
2017-12-12 02:51:45 +00:00
s.lastNetworkActivityTime = now
s.sessionCreationTime = now
2018-01-03 19:19:49 +00:00
s.sentPacketHandler = ackhandler.NewSentPacketHandler(s.rttStats)
s.receivedPacketHandler = ackhandler.NewReceivedPacketHandler(s.version)
2018-01-20 18:07:01 +00:00
if s.version.UsesTLS() {
s.streamsMap = newStreamsMap(s.newStream, s.perspective)
} else {
s.streamsMap = newStreamsMapLegacy(s.newStream, s.perspective)
}
s.streamFramer = newStreamFramer(s.cryptoStream, s.streamsMap, s.version)
2018-01-03 19:19:49 +00:00
s.packer = newPacketPacker(s.connectionID,
initialPacketNumber,
s.cryptoSetup,
s.streamFramer,
s.perspective,
s.version,
)
2018-01-20 18:07:01 +00:00
s.windowUpdateQueue = newWindowUpdateQueue(s.streamsMap, s.cryptoStream, s.packer.QueueControlFrame)
2018-01-03 19:19:49 +00:00
s.unpacker = &packetUnpacker{aead: s.cryptoSetup, version: s.version}
return nil
2017-12-12 02:51:45 +00:00
}
// run the session main loop
2018-01-03 19:19:49 +00:00
func (s *session) run() error {
defer s.ctxCancel()
2017-12-12 02:51:45 +00:00
go func() {
if err := s.cryptoSetup.HandleCryptoStream(); err != nil {
s.Close(err)
}
}()
2018-01-03 19:19:49 +00:00
var closeErr closeError
2018-01-20 18:07:01 +00:00
handshakeEvent := s.handshakeEvent
2018-01-03 19:19:49 +00:00
2017-12-12 02:51:45 +00:00
runLoop:
for {
// Close immediately if requested
select {
2018-01-03 19:19:49 +00:00
case closeErr = <-s.closeChan:
2017-12-12 02:51:45 +00:00
break runLoop
default:
}
s.maybeResetTimer()
select {
2018-01-03 19:19:49 +00:00
case closeErr = <-s.closeChan:
2017-12-12 02:51:45 +00:00
break runLoop
2018-01-03 19:19:49 +00:00
case <-s.timer.Chan():
s.timer.SetRead()
2017-12-12 02:51:45 +00:00
// We do all the interesting stuff after the switch statement, so
// nothing to see here.
case <-s.sendingScheduled:
// We do all the interesting stuff after the switch statement, so
// nothing to see here.
case p := <-s.receivedPackets:
2018-01-03 19:19:49 +00:00
err := s.handlePacketImpl(p)
if err != nil {
if qErr, ok := err.(*qerr.QuicError); ok && qErr.ErrorCode == qerr.DecryptionFailure {
s.tryQueueingUndecryptablePacket(p)
continue
}
s.closeLocal(err)
2017-12-12 02:51:45 +00:00
continue
}
// This is a bit unclean, but works properly, since the packet always
// begins with the public header and we never copy it.
2018-01-03 19:19:49 +00:00
putPacketBuffer(p.header.Raw)
case p := <-s.paramsChan:
s.processTransportParameters(&p)
2018-01-20 18:07:01 +00:00
case _, ok := <-handshakeEvent:
2018-01-03 19:19:49 +00:00
if !ok { // the aeadChanged chan was closed. This means that the handshake is completed.
s.handshakeComplete = true
2018-01-20 18:07:01 +00:00
handshakeEvent = nil // prevent this case from ever being selected again
2018-01-03 19:19:49 +00:00
s.sentPacketHandler.SetHandshakeComplete()
2018-01-20 18:07:01 +00:00
if !s.version.UsesTLS() && s.perspective == protocol.PerspectiveClient {
// In gQUIC, there's no equivalent to the Finished message in TLS
// The server knows that the handshake is complete when it receives the first forward-secure packet sent by the client.
// We need to make sure that the client actually sends such a packet.
s.packer.QueueControlFrame(&wire.PingFrame{})
}
2018-01-03 19:19:49 +00:00
close(s.handshakeChan)
} else {
s.tryDecryptingQueuedPackets()
2017-12-12 02:51:45 +00:00
}
}
now := time.Now()
2018-01-03 19:19:49 +00:00
if timeout := s.sentPacketHandler.GetAlarmTimeout(); !timeout.IsZero() && timeout.Before(now) {
2017-12-12 02:51:45 +00:00
// This could cause packets to be retransmitted, so check it before trying
// to send packets.
s.sentPacketHandler.OnAlarm()
}
2018-01-03 19:19:49 +00:00
if s.config.KeepAlive && s.handshakeComplete && time.Since(s.lastNetworkActivityTime) >= s.peerParams.IdleTimeout/2 {
// send the PING frame since there is no activity in the session
s.packer.QueueControlFrame(&wire.PingFrame{})
s.keepAlivePingSent = true
}
2018-01-20 18:07:01 +00:00
sendingAllowed := s.sentPacketHandler.SendingAllowed()
if !sendingAllowed { // if congestion limited, at least try sending an ACK frame
if err := s.maybeSendAckOnlyPacket(); err != nil {
s.closeLocal(err)
}
} else {
// repeatedly try sending until we don't have any more data, or run out of the congestion window
for sendingAllowed {
sentPacket, err := s.sendPacket()
if err != nil {
s.closeLocal(err)
break
}
if !sentPacket {
break
}
sendingAllowed = s.sentPacketHandler.SendingAllowed()
}
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
2017-12-12 02:51:45 +00:00
if !s.receivedTooManyUndecrytablePacketsTime.IsZero() && s.receivedTooManyUndecrytablePacketsTime.Add(protocol.PublicResetTimeout).Before(now) && len(s.undecryptablePackets) != 0 {
2018-01-03 19:19:49 +00:00
s.closeLocal(qerr.Error(qerr.DecryptionFailure, "too many undecryptable packets received"))
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
if !s.handshakeComplete && now.Sub(s.sessionCreationTime) >= s.config.HandshakeTimeout {
s.closeLocal(qerr.Error(qerr.HandshakeTimeout, "Crypto handshake did not complete in time."))
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
if s.handshakeComplete && now.Sub(s.lastNetworkActivityTime) >= s.config.IdleTimeout {
s.closeLocal(qerr.Error(qerr.NetworkIdleTimeout, "No recent network activity."))
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
}
// only send the error the handshakeChan when the handshake is not completed yet
// otherwise this chan will already be closed
if !s.handshakeComplete {
2018-01-20 18:07:01 +00:00
s.handshakeChan <- closeErr.err
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
s.handleCloseError(closeErr)
return closeErr.err
}
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
func (s *session) Context() context.Context {
return s.ctx
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
func (s *session) ConnectionState() ConnectionState {
return s.cryptoSetup.ConnectionState()
}
2017-12-12 02:51:45 +00:00
func (s *session) maybeResetTimer() {
2018-01-03 19:19:49 +00:00
var deadline time.Time
if s.config.KeepAlive && s.handshakeComplete && !s.keepAlivePingSent {
deadline = s.lastNetworkActivityTime.Add(s.peerParams.IdleTimeout / 2)
} else {
deadline = s.lastNetworkActivityTime.Add(s.config.IdleTimeout)
}
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
if ackAlarm := s.receivedPacketHandler.GetAlarmTimeout(); !ackAlarm.IsZero() {
deadline = utils.MinTime(deadline, ackAlarm)
2017-12-12 02:51:45 +00:00
}
if lossTime := s.sentPacketHandler.GetAlarmTimeout(); !lossTime.IsZero() {
2018-01-03 19:19:49 +00:00
deadline = utils.MinTime(deadline, lossTime)
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
if !s.handshakeComplete {
handshakeDeadline := s.sessionCreationTime.Add(s.config.HandshakeTimeout)
deadline = utils.MinTime(deadline, handshakeDeadline)
2017-12-12 02:51:45 +00:00
}
if !s.receivedTooManyUndecrytablePacketsTime.IsZero() {
2018-01-03 19:19:49 +00:00
deadline = utils.MinTime(deadline, s.receivedTooManyUndecrytablePacketsTime.Add(protocol.PublicResetTimeout))
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
s.timer.Reset(deadline)
2017-12-12 02:51:45 +00:00
}
func (s *session) handlePacketImpl(p *receivedPacket) error {
if s.perspective == protocol.PerspectiveClient {
2018-01-03 19:19:49 +00:00
diversificationNonce := p.header.DiversificationNonce
2017-12-12 02:51:45 +00:00
if len(diversificationNonce) > 0 {
s.cryptoSetup.SetDiversificationNonce(diversificationNonce)
}
}
if p.rcvTime.IsZero() {
// To simplify testing
p.rcvTime = time.Now()
}
s.lastNetworkActivityTime = p.rcvTime
2018-01-03 19:19:49 +00:00
s.keepAlivePingSent = false
hdr := p.header
2017-12-12 02:51:45 +00:00
data := p.data
// Calculate packet number
hdr.PacketNumber = protocol.InferPacketNumber(
hdr.PacketNumberLen,
s.largestRcvdPacketNumber,
hdr.PacketNumber,
)
packet, err := s.unpacker.Unpack(hdr.Raw, hdr, data)
if utils.Debug() {
if err != nil {
2018-01-03 19:19:49 +00:00
utils.Debugf("<- Reading packet 0x%x (%d bytes) for connection %x", hdr.PacketNumber, len(data)+len(hdr.Raw), hdr.ConnectionID)
2017-12-12 02:51:45 +00:00
} else {
2018-01-03 19:19:49 +00:00
utils.Debugf("<- Reading packet 0x%x (%d bytes) for connection %x, %s", hdr.PacketNumber, len(data)+len(hdr.Raw), hdr.ConnectionID, packet.encryptionLevel)
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
hdr.Log()
2017-12-12 02:51:45 +00:00
}
// if the decryption failed, this might be a packet sent by an attacker
if err != nil {
return err
}
s.lastRcvdPacketNumber = hdr.PacketNumber
// Only do this after decrypting, so we are sure the packet is not attacker-controlled
s.largestRcvdPacketNumber = utils.MaxPacketNumber(s.largestRcvdPacketNumber, hdr.PacketNumber)
2018-01-03 19:19:49 +00:00
isRetransmittable := ackhandler.HasRetransmittableFrames(packet.frames)
2018-01-20 18:07:01 +00:00
if err = s.receivedPacketHandler.ReceivedPacket(hdr.PacketNumber, p.rcvTime, isRetransmittable); err != nil {
2017-12-12 02:51:45 +00:00
return err
}
2018-01-03 19:19:49 +00:00
return s.handleFrames(packet.frames, packet.encryptionLevel)
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
func (s *session) handleFrames(fs []wire.Frame, encLevel protocol.EncryptionLevel) error {
2017-12-12 02:51:45 +00:00
for _, ff := range fs {
var err error
2018-01-03 19:19:49 +00:00
wire.LogFrame(ff, false)
2017-12-12 02:51:45 +00:00
switch frame := ff.(type) {
2018-01-03 19:19:49 +00:00
case *wire.StreamFrame:
2017-12-12 02:51:45 +00:00
err = s.handleStreamFrame(frame)
2018-01-03 19:19:49 +00:00
case *wire.AckFrame:
err = s.handleAckFrame(frame, encLevel)
case *wire.ConnectionCloseFrame:
s.closeRemote(qerr.Error(frame.ErrorCode, frame.ReasonPhrase))
case *wire.GoawayFrame:
2017-12-12 02:51:45 +00:00
err = errors.New("unimplemented: handling GOAWAY frames")
2018-01-20 18:07:01 +00:00
case *wire.StopWaitingFrame: // ignore STOP_WAITINGs
2018-01-03 19:19:49 +00:00
case *wire.RstStreamFrame:
2017-12-12 02:51:45 +00:00
err = s.handleRstStreamFrame(frame)
2018-01-03 19:19:49 +00:00
case *wire.MaxDataFrame:
s.handleMaxDataFrame(frame)
case *wire.MaxStreamDataFrame:
err = s.handleMaxStreamDataFrame(frame)
case *wire.BlockedFrame:
case *wire.StreamBlockedFrame:
2018-01-20 18:07:01 +00:00
case *wire.StopSendingFrame:
err = s.handleStopSendingFrame(frame)
2018-01-03 19:19:49 +00:00
case *wire.PingFrame:
2017-12-12 02:51:45 +00:00
default:
return errors.New("Session BUG: unexpected frame type")
}
if err != nil {
switch err {
case ackhandler.ErrDuplicateOrOutOfOrderAck:
// Can happen e.g. when packets thought missing arrive late
default:
return err
}
}
}
return nil
}
// handlePacket is called by the server with a new packet
func (s *session) handlePacket(p *receivedPacket) {
// Discard packets once the amount of queued packets is larger than
// the channel size, protocol.MaxSessionUnprocessedPackets
select {
case s.receivedPackets <- p:
default:
}
}
2018-01-03 19:19:49 +00:00
func (s *session) handleStreamFrame(frame *wire.StreamFrame) error {
if frame.StreamID == s.version.CryptoStreamID() {
2018-01-20 18:07:01 +00:00
if frame.FinBit {
return errors.New("Received STREAM frame with FIN bit for the crypto stream")
}
return s.cryptoStream.handleStreamFrame(frame)
2018-01-03 19:19:49 +00:00
}
2018-01-20 18:07:01 +00:00
str, err := s.streamsMap.GetOrOpenReceiveStream(frame.StreamID)
2017-12-12 02:51:45 +00:00
if err != nil {
return err
}
if str == nil {
// Stream is closed and already garbage collected
// ignore this StreamFrame
return nil
}
2018-01-20 18:07:01 +00:00
return str.handleStreamFrame(frame)
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
func (s *session) handleMaxDataFrame(frame *wire.MaxDataFrame) {
s.connFlowController.UpdateSendWindow(frame.ByteOffset)
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
func (s *session) handleMaxStreamDataFrame(frame *wire.MaxStreamDataFrame) error {
2018-01-20 18:07:01 +00:00
if frame.StreamID == s.version.CryptoStreamID() {
s.cryptoStream.handleMaxStreamDataFrame(frame)
return nil
}
str, err := s.streamsMap.GetOrOpenSendStream(frame.StreamID)
2017-12-12 02:51:45 +00:00
if err != nil {
return err
}
if str == nil {
2018-01-03 19:19:49 +00:00
// stream is closed and already garbage collected
return nil
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
str.handleMaxStreamDataFrame(frame)
2018-01-03 19:19:49 +00:00
return nil
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
func (s *session) handleRstStreamFrame(frame *wire.RstStreamFrame) error {
2018-01-20 18:07:01 +00:00
if frame.StreamID == s.version.CryptoStreamID() {
return errors.New("Received RST_STREAM frame for the crypto stream")
}
str, err := s.streamsMap.GetOrOpenReceiveStream(frame.StreamID)
if err != nil {
return err
}
if str == nil {
// stream is closed and already garbage collected
return nil
}
return str.handleRstStreamFrame(frame)
}
func (s *session) handleStopSendingFrame(frame *wire.StopSendingFrame) error {
if frame.StreamID == s.version.CryptoStreamID() {
return errors.New("Received a STOP_SENDING frame for the crypto stream")
}
str, err := s.streamsMap.GetOrOpenSendStream(frame.StreamID)
2018-01-03 19:19:49 +00:00
if err != nil {
2017-12-12 02:51:45 +00:00
return err
}
2018-01-03 19:19:49 +00:00
if str == nil {
// stream is closed and already garbage collected
2017-12-12 02:51:45 +00:00
return nil
}
2018-01-20 18:07:01 +00:00
str.handleStopSendingFrame(frame)
return nil
2018-01-03 19:19:49 +00:00
}
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
func (s *session) handleAckFrame(frame *wire.AckFrame, encLevel protocol.EncryptionLevel) error {
2018-01-20 18:07:01 +00:00
if err := s.sentPacketHandler.ReceivedAck(frame, s.lastRcvdPacketNumber, encLevel, s.lastNetworkActivityTime); err != nil {
return err
}
s.receivedPacketHandler.IgnoreBelow(s.sentPacketHandler.GetLowestPacketNotConfirmedAcked())
return nil
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
func (s *session) closeLocal(e error) {
s.closeOnce.Do(func() {
s.closeChan <- closeError{err: e, remote: false}
})
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
func (s *session) closeRemote(e error) {
s.closeOnce.Do(func() {
s.closeChan <- closeError{err: e, remote: true}
})
}
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
// Close the connection. If err is nil it will be set to qerr.PeerGoingAway.
// It waits until the run loop has stopped before returning
func (s *session) Close(e error) error {
s.closeLocal(e)
<-s.ctx.Done()
return nil
}
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
func (s *session) handleCloseError(closeErr closeError) error {
if closeErr.err == nil {
closeErr.err = qerr.PeerGoingAway
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
var quicErr *qerr.QuicError
var ok bool
if quicErr, ok = closeErr.err.(*qerr.QuicError); !ok {
quicErr = qerr.ToQuicError(closeErr.err)
}
2017-12-12 02:51:45 +00:00
// Don't log 'normal' reasons
if quicErr.ErrorCode == qerr.PeerGoingAway || quicErr.ErrorCode == qerr.NetworkIdleTimeout {
utils.Infof("Closing connection %x", s.connectionID)
} else {
2018-01-03 19:19:49 +00:00
utils.Errorf("Closing session with error: %s", closeErr.err.Error())
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
s.cryptoStream.closeForShutdown(quicErr)
2017-12-12 02:51:45 +00:00
s.streamsMap.CloseWithError(quicErr)
2018-01-03 19:19:49 +00:00
if closeErr.err == errCloseSessionForNewVersion || closeErr.err == handshake.ErrCloseSessionForRetry {
return nil
}
// If this is a remote close we're done here
if closeErr.remote {
2017-12-12 02:51:45 +00:00
return nil
}
2018-01-03 19:19:49 +00:00
if quicErr.ErrorCode == qerr.DecryptionFailure ||
quicErr == handshake.ErrHOLExperiment ||
quicErr == handshake.ErrNSTPExperiment {
2017-12-12 02:51:45 +00:00
return s.sendPublicReset(s.lastRcvdPacketNumber)
}
2018-01-03 19:19:49 +00:00
return s.sendConnectionClose(quicErr)
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
func (s *session) processTransportParameters(params *handshake.TransportParameters) {
s.peerParams = params
2018-01-20 18:07:01 +00:00
s.streamsMap.UpdateLimits(params)
2018-01-03 19:19:49 +00:00
if params.OmitConnectionID {
s.packer.SetOmitConnectionID()
}
s.connFlowController.UpdateSendWindow(params.ConnectionFlowControlWindow)
2018-01-20 18:07:01 +00:00
// the crypto stream is the only open stream at this moment
// so we don't need to update stream flow control windows
}
func (s *session) maybeSendAckOnlyPacket() error {
ack := s.receivedPacketHandler.GetAckFrame()
if ack == nil {
return nil
}
s.packer.QueueControlFrame(ack)
if !s.version.UsesIETFFrameFormat() { // for gQUIC, maybe add a STOP_WAITING
if swf := s.sentPacketHandler.GetStopWaitingFrame(false); swf != nil {
s.packer.QueueControlFrame(swf)
}
}
packet, err := s.packer.PackAckPacket()
if err != nil {
return err
}
return s.sendPackedPacket(packet)
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
func (s *session) sendPacket() (bool, error) {
2018-01-03 19:19:49 +00:00
s.packer.SetLeastUnacked(s.sentPacketHandler.GetLeastUnacked())
2018-01-20 18:07:01 +00:00
if offset := s.connFlowController.GetWindowUpdate(); offset != 0 {
s.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: offset})
}
if isBlocked, offset := s.connFlowController.IsNewlyBlocked(); isBlocked {
s.packer.QueueControlFrame(&wire.BlockedFrame{Offset: offset})
2018-01-03 19:19:49 +00:00
}
2018-01-20 18:07:01 +00:00
s.windowUpdateQueue.QueueAll()
2018-01-03 19:19:49 +00:00
ack := s.receivedPacketHandler.GetAckFrame()
if ack != nil {
s.packer.QueueControlFrame(ack)
}
2018-01-20 18:07:01 +00:00
// check for retransmissions first
2017-12-12 02:51:45 +00:00
for {
2018-01-20 18:07:01 +00:00
retransmitPacket := s.sentPacketHandler.DequeuePacketForRetransmission()
if retransmitPacket == nil {
break
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
// retransmit handshake packets
if retransmitPacket.EncryptionLevel != protocol.EncryptionForwardSecure {
utils.Debugf("\tDequeueing handshake retransmission for packet 0x%x", retransmitPacket.PacketNumber)
if !s.version.UsesIETFFrameFormat() {
2018-01-03 19:19:49 +00:00
s.packer.QueueControlFrame(s.sentPacketHandler.GetStopWaitingFrame(true))
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
packet, err := s.packer.PackHandshakeRetransmission(retransmitPacket)
if err != nil {
return false, err
}
if err := s.sendPackedPacket(packet); err != nil {
return false, err
}
return true, nil
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
// queue all retransmittable frames sent in forward-secure packets
utils.Debugf("\tDequeueing retransmission for packet 0x%x", retransmitPacket.PacketNumber)
// resend the frames that were in the packet
for _, frame := range retransmitPacket.GetFramesForRetransmission() {
// TODO: only retransmit WINDOW_UPDATEs if they actually enlarge the window
switch f := frame.(type) {
case *wire.StreamFrame:
s.streamFramer.AddFrameForRetransmission(f)
default:
s.packer.QueueControlFrame(frame)
2018-01-03 19:19:49 +00:00
}
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
}
2017-12-12 02:51:45 +00:00
2018-01-20 18:07:01 +00:00
hasRetransmission := s.streamFramer.HasFramesForRetransmission()
if !s.version.UsesIETFFrameFormat() && (ack != nil || hasRetransmission) {
if swf := s.sentPacketHandler.GetStopWaitingFrame(hasRetransmission); swf != nil {
s.packer.QueueControlFrame(swf)
2017-12-12 02:51:45 +00:00
}
}
2018-01-20 18:07:01 +00:00
// add a retransmittable frame
if s.sentPacketHandler.ShouldSendRetransmittablePacket() {
s.packer.MakeNextPacketRetransmittable()
}
packet, err := s.packer.PackPacket()
if err != nil || packet == nil {
return false, err
}
if err := s.sendPackedPacket(packet); err != nil {
return false, err
}
return true, nil
2017-12-12 02:51:45 +00:00
}
func (s *session) sendPackedPacket(packet *packedPacket) error {
2018-01-03 19:19:49 +00:00
defer putPacketBuffer(packet.raw)
2017-12-12 02:51:45 +00:00
err := s.sentPacketHandler.SentPacket(&ackhandler.Packet{
2018-01-03 19:19:49 +00:00
PacketNumber: packet.header.PacketNumber,
2017-12-12 02:51:45 +00:00
Frames: packet.frames,
Length: protocol.ByteCount(len(packet.raw)),
EncryptionLevel: packet.encryptionLevel,
})
if err != nil {
return err
}
s.logPacket(packet)
2018-01-03 19:19:49 +00:00
return s.conn.Write(packet.raw)
2017-12-12 02:51:45 +00:00
}
func (s *session) sendConnectionClose(quicErr *qerr.QuicError) error {
2018-01-03 19:19:49 +00:00
s.packer.SetLeastUnacked(s.sentPacketHandler.GetLeastUnacked())
packet, err := s.packer.PackConnectionClose(&wire.ConnectionCloseFrame{
ErrorCode: quicErr.ErrorCode,
ReasonPhrase: quicErr.ErrorMessage,
})
2017-12-12 02:51:45 +00:00
if err != nil {
return err
}
s.logPacket(packet)
return s.conn.Write(packet.raw)
}
func (s *session) logPacket(packet *packedPacket) {
if !utils.Debug() {
// We don't need to allocate the slices for calling the format functions
return
}
2018-01-03 19:19:49 +00:00
utils.Debugf("-> Sending packet 0x%x (%d bytes) for connection %x, %s", packet.header.PacketNumber, len(packet.raw), s.connectionID, packet.encryptionLevel)
packet.header.Log()
for _, frame := range packet.frames {
wire.LogFrame(frame, true)
2017-12-12 02:51:45 +00:00
}
}
// GetOrOpenStream either returns an existing stream, a newly opened stream, or nil if a stream with the provided ID is already closed.
// Newly opened streams should only originate from the client. To open a stream from the server, OpenStream should be used.
func (s *session) GetOrOpenStream(id protocol.StreamID) (Stream, error) {
str, err := s.streamsMap.GetOrOpenStream(id)
if str != nil {
return str, err
}
// make sure to return an actual nil value here, not an Stream with value nil
2018-01-20 18:07:01 +00:00
return str, err
2017-12-12 02:51:45 +00:00
}
// AcceptStream returns the next stream openend by the peer
func (s *session) AcceptStream() (Stream, error) {
return s.streamsMap.AcceptStream()
}
// OpenStream opens a stream
func (s *session) OpenStream() (Stream, error) {
return s.streamsMap.OpenStream()
}
func (s *session) OpenStreamSync() (Stream, error) {
return s.streamsMap.OpenStreamSync()
}
2018-01-03 19:19:49 +00:00
func (s *session) newStream(id protocol.StreamID) streamI {
var initialSendWindow protocol.ByteCount
if s.peerParams != nil {
initialSendWindow = s.peerParams.StreamFlowControlWindow
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
flowController := flowcontrol.NewStreamFlowController(
id,
s.version.StreamContributesToConnectionFlowControl(id),
s.connFlowController,
protocol.ReceiveStreamFlowControlWindow,
protocol.ByteCount(s.config.MaxReceiveStreamFlowControlWindow),
initialSendWindow,
s.rttStats,
)
2018-01-20 18:07:01 +00:00
return newStream(id, s, flowController, s.version)
}
func (s *session) newCryptoStream() cryptoStreamI {
id := s.version.CryptoStreamID()
flowController := flowcontrol.NewStreamFlowController(
id,
s.version.StreamContributesToConnectionFlowControl(id),
s.connFlowController,
protocol.ReceiveStreamFlowControlWindow,
protocol.ByteCount(s.config.MaxReceiveStreamFlowControlWindow),
0,
s.rttStats,
)
return newCryptoStream(s, flowController, s.version)
2017-12-12 02:51:45 +00:00
}
func (s *session) sendPublicReset(rejectedPacketNumber protocol.PacketNumber) error {
utils.Infof("Sending public reset for connection %x, packet number %d", s.connectionID, rejectedPacketNumber)
2018-01-03 19:19:49 +00:00
return s.conn.Write(wire.WritePublicReset(s.connectionID, rejectedPacketNumber, 0))
2017-12-12 02:51:45 +00:00
}
// scheduleSending signals that we have data for sending
func (s *session) scheduleSending() {
select {
case s.sendingScheduled <- struct{}{}:
default:
}
}
func (s *session) tryQueueingUndecryptablePacket(p *receivedPacket) {
2018-01-03 19:19:49 +00:00
if s.handshakeComplete {
utils.Debugf("Received undecryptable packet from %s after the handshake: %#v, %d bytes data", p.remoteAddr.String(), p.header, len(p.data))
2017-12-12 02:51:45 +00:00
return
}
if len(s.undecryptablePackets)+1 > protocol.MaxUndecryptablePackets {
// if this is the first time the undecryptablePackets runs full, start the timer to send a Public Reset
if s.receivedTooManyUndecrytablePacketsTime.IsZero() {
s.receivedTooManyUndecrytablePacketsTime = time.Now()
s.maybeResetTimer()
}
2018-01-03 19:19:49 +00:00
utils.Infof("Dropping undecrytable packet 0x%x (undecryptable packet queue full)", p.header.PacketNumber)
2017-12-12 02:51:45 +00:00
return
}
2018-01-03 19:19:49 +00:00
utils.Infof("Queueing packet 0x%x for later decryption", p.header.PacketNumber)
2017-12-12 02:51:45 +00:00
s.undecryptablePackets = append(s.undecryptablePackets, p)
}
func (s *session) tryDecryptingQueuedPackets() {
for _, p := range s.undecryptablePackets {
s.handlePacket(p)
}
s.undecryptablePackets = s.undecryptablePackets[:0]
}
2018-01-20 18:07:01 +00:00
func (s *session) queueControlFrame(f wire.Frame) {
s.packer.QueueControlFrame(f)
s.scheduleSending()
}
func (s *session) onHasWindowUpdate(id protocol.StreamID) {
s.windowUpdateQueue.Add(id)
s.scheduleSending()
}
func (s *session) onHasStreamData(id protocol.StreamID) {
s.streamFramer.AddActiveStream(id)
s.scheduleSending()
}
func (s *session) onStreamCompleted(id protocol.StreamID) {
if err := s.streamsMap.DeleteStream(id); err != nil {
s.Close(err)
2017-12-12 02:51:45 +00:00
}
}
func (s *session) LocalAddr() net.Addr {
return s.conn.LocalAddr()
}
// RemoteAddr returns the net.Addr of the client
func (s *session) RemoteAddr() net.Addr {
return s.conn.RemoteAddr()
}
2018-01-03 19:19:49 +00:00
2018-01-20 18:07:01 +00:00
func (s *session) handshakeStatus() <-chan error {
2018-01-03 19:19:49 +00:00
return s.handshakeChan
}
2018-01-20 18:07:01 +00:00
func (s *session) getCryptoStream() cryptoStreamI {
2018-01-03 19:19:49 +00:00
return s.cryptoStream
}
func (s *session) GetVersion() protocol.VersionNumber {
return s.version
}