github.com/MerlinKodo/quic-go@v0.39.2/packet_packer_test.go (about)

     1  package quic
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"fmt"
     7  	"net"
     8  	"time"
     9  
    10  	"golang.org/x/exp/rand"
    11  
    12  	"github.com/MerlinKodo/quic-go/internal/ackhandler"
    13  	"github.com/MerlinKodo/quic-go/internal/handshake"
    14  	"github.com/MerlinKodo/quic-go/internal/mocks"
    15  	mockackhandler "github.com/MerlinKodo/quic-go/internal/mocks/ackhandler"
    16  	"github.com/MerlinKodo/quic-go/internal/protocol"
    17  	"github.com/MerlinKodo/quic-go/internal/qerr"
    18  	"github.com/MerlinKodo/quic-go/internal/utils"
    19  	"github.com/MerlinKodo/quic-go/internal/wire"
    20  
    21  	. "github.com/onsi/ginkgo/v2"
    22  	. "github.com/onsi/gomega"
    23  	"go.uber.org/mock/gomock"
    24  )
    25  
    26  var _ = Describe("Packet packer", func() {
    27  	const maxPacketSize protocol.ByteCount = 1357
    28  	const version = protocol.Version1
    29  
    30  	var (
    31  		packer              *packetPacker
    32  		retransmissionQueue *retransmissionQueue
    33  		datagramQueue       *datagramQueue
    34  		framer              *MockFrameSource
    35  		ackFramer           *MockAckFrameSource
    36  		initialStream       *MockCryptoStream
    37  		handshakeStream     *MockCryptoStream
    38  		sealingManager      *MockSealingManager
    39  		pnManager           *mockackhandler.MockSentPacketHandler
    40  	)
    41  	connID := protocol.ParseConnectionID([]byte{1, 2, 3, 4, 5, 6, 7, 8})
    42  
    43  	parsePacket := func(data []byte) (hdrs []*wire.ExtendedHeader, more []byte) {
    44  		for len(data) > 0 {
    45  			if !wire.IsLongHeaderPacket(data[0]) {
    46  				break
    47  			}
    48  			hdr, _, more, err := wire.ParsePacket(data)
    49  			Expect(err).ToNot(HaveOccurred())
    50  			r := bytes.NewReader(data)
    51  			extHdr, err := hdr.ParseExtended(r, version)
    52  			Expect(err).ToNot(HaveOccurred())
    53  			ExpectWithOffset(1, extHdr.Length).To(BeEquivalentTo(r.Len() - len(more) + int(extHdr.PacketNumberLen)))
    54  			ExpectWithOffset(1, extHdr.Length+protocol.ByteCount(extHdr.PacketNumberLen)).To(BeNumerically(">=", 4))
    55  			data = more
    56  			hdrs = append(hdrs, extHdr)
    57  		}
    58  		return hdrs, data
    59  	}
    60  
    61  	parseShortHeaderPacket := func(data []byte) {
    62  		l, _, pnLen, _, err := wire.ParseShortHeader(data, connID.Len())
    63  		ExpectWithOffset(1, err).ToNot(HaveOccurred())
    64  		ExpectWithOffset(1, len(data)-l+int(pnLen)).To(BeNumerically(">=", 4))
    65  	}
    66  
    67  	expectAppendStreamFrames := func(frames ...ackhandler.StreamFrame) {
    68  		framer.EXPECT().AppendStreamFrames(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(fs []ackhandler.StreamFrame, _ protocol.ByteCount, v protocol.VersionNumber) ([]ackhandler.StreamFrame, protocol.ByteCount) {
    69  			var length protocol.ByteCount
    70  			for _, f := range frames {
    71  				length += f.Frame.Length(v)
    72  			}
    73  			return append(fs, frames...), length
    74  		})
    75  	}
    76  
    77  	expectAppendControlFrames := func(frames ...ackhandler.Frame) {
    78  		framer.EXPECT().AppendControlFrames(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(fs []ackhandler.Frame, _ protocol.ByteCount, v protocol.VersionNumber) ([]ackhandler.Frame, protocol.ByteCount) {
    79  			var length protocol.ByteCount
    80  			for _, f := range frames {
    81  				length += f.Frame.Length(v)
    82  			}
    83  			return append(fs, frames...), length
    84  		})
    85  	}
    86  
    87  	BeforeEach(func() {
    88  		rand.Seed(uint64(GinkgoRandomSeed()))
    89  		retransmissionQueue = newRetransmissionQueue()
    90  		mockSender := NewMockStreamSender(mockCtrl)
    91  		mockSender.EXPECT().onHasStreamData(gomock.Any()).AnyTimes()
    92  		initialStream = NewMockCryptoStream(mockCtrl)
    93  		handshakeStream = NewMockCryptoStream(mockCtrl)
    94  		framer = NewMockFrameSource(mockCtrl)
    95  		ackFramer = NewMockAckFrameSource(mockCtrl)
    96  		sealingManager = NewMockSealingManager(mockCtrl)
    97  		pnManager = mockackhandler.NewMockSentPacketHandler(mockCtrl)
    98  		datagramQueue = newDatagramQueue(func() {}, utils.DefaultLogger)
    99  
   100  		packer = newPacketPacker(protocol.ParseConnectionID([]byte{1, 2, 3, 4, 5, 6, 7, 8}), func() protocol.ConnectionID { return connID }, initialStream, handshakeStream, pnManager, retransmissionQueue, sealingManager, framer, ackFramer, datagramQueue, protocol.PerspectiveServer)
   101  	})
   102  
   103  	Context("determining the maximum packet size", func() {
   104  		It("uses the minimum initial size, if it can't determine if the remote address is IPv4 or IPv6", func() {
   105  			Expect(getMaxPacketSize(&net.TCPAddr{})).To(BeEquivalentTo(protocol.MinInitialPacketSize))
   106  		})
   107  
   108  		It("uses the maximum IPv4 packet size, if the remote address is IPv4", func() {
   109  			addr := &net.UDPAddr{IP: net.IPv4(11, 12, 13, 14), Port: 1337}
   110  			Expect(getMaxPacketSize(addr)).To(BeEquivalentTo(protocol.InitialPacketSizeIPv4))
   111  		})
   112  
   113  		It("uses the maximum IPv6 packet size, if the remote address is IPv6", func() {
   114  			ip := net.ParseIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334")
   115  			addr := &net.UDPAddr{IP: ip, Port: 1337}
   116  			Expect(getMaxPacketSize(addr)).To(BeEquivalentTo(protocol.InitialPacketSizeIPv6))
   117  		})
   118  	})
   119  
   120  	Context("generating a packet header", func() {
   121  		It("uses the Long Header format", func() {
   122  			pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen3)
   123  			h := packer.getLongHeader(protocol.EncryptionHandshake, protocol.Version1)
   124  			Expect(h.PacketNumber).To(Equal(protocol.PacketNumber(0x42)))
   125  			Expect(h.PacketNumberLen).To(Equal(protocol.PacketNumberLen3))
   126  			Expect(h.Version).To(Equal(protocol.Version1))
   127  		})
   128  
   129  		It("sets source and destination connection ID", func() {
   130  			pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   131  			srcConnID := protocol.ParseConnectionID([]byte{1, 2, 3, 4, 5, 6, 7, 8})
   132  			destConnID := protocol.ParseConnectionID([]byte{8, 7, 6, 5, 4, 3, 2, 1})
   133  			packer.srcConnID = srcConnID
   134  			packer.getDestConnID = func() protocol.ConnectionID { return destConnID }
   135  			h := packer.getLongHeader(protocol.EncryptionHandshake, protocol.Version1)
   136  			Expect(h.SrcConnectionID).To(Equal(srcConnID))
   137  			Expect(h.DestConnectionID).To(Equal(destConnID))
   138  		})
   139  	})
   140  
   141  	Context("encrypting packets", func() {
   142  		It("encrypts a packet", func() {
   143  			pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x1337), protocol.PacketNumberLen2)
   144  			pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x1337))
   145  			sealer := mocks.NewMockShortHeaderSealer(mockCtrl)
   146  			sealer.EXPECT().Overhead().Return(4).AnyTimes()
   147  			var hdrRaw []byte
   148  			gomock.InOrder(
   149  				sealer.EXPECT().KeyPhase().Return(protocol.KeyPhaseOne),
   150  				sealer.EXPECT().Seal(gomock.Any(), gomock.Any(), protocol.PacketNumber(0x1337), gomock.Any()).DoAndReturn(func(_, src []byte, _ protocol.PacketNumber, aad []byte) []byte {
   151  					hdrRaw = append([]byte{}, aad...)
   152  					return append(src, []byte{0xde, 0xca, 0xfb, 0xad}...)
   153  				}),
   154  				sealer.EXPECT().EncryptHeader(gomock.Any(), gomock.Any(), gomock.Any()).Do(func(sample []byte, firstByte *byte, pnBytes []byte) {
   155  					Expect(firstByte).To(Equal(&hdrRaw[0]))
   156  					Expect(pnBytes).To(Equal(hdrRaw[len(hdrRaw)-2:]))
   157  					*firstByte ^= 0xff // invert the first byte
   158  					// invert the packet number bytes
   159  					for i := range pnBytes {
   160  						pnBytes[i] ^= 0xff
   161  					}
   162  				}),
   163  			)
   164  			framer.EXPECT().HasData().Return(true)
   165  			sealingManager.EXPECT().GetInitialSealer().Return(nil, nil)
   166  			sealingManager.EXPECT().GetHandshakeSealer().Return(nil, nil)
   167  			sealingManager.EXPECT().Get1RTTSealer().Return(sealer, nil)
   168  			ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   169  			expectAppendControlFrames()
   170  			f := &wire.StreamFrame{Data: []byte{0xde, 0xca, 0xfb, 0xad}}
   171  			expectAppendStreamFrames(ackhandler.StreamFrame{Frame: f})
   172  			p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   173  			Expect(err).ToNot(HaveOccurred())
   174  			Expect(p).ToNot(BeNil())
   175  			Expect(p.longHdrPackets).To(BeEmpty())
   176  			Expect(p.shortHdrPacket).ToNot(BeNil())
   177  			Expect(p.shortHdrPacket.Frames).To(BeEmpty())
   178  			Expect(p.shortHdrPacket.StreamFrames).To(HaveLen(1))
   179  			Expect(p.shortHdrPacket.StreamFrames[0].Frame).To(Equal(f))
   180  			hdrRawEncrypted := append([]byte{}, hdrRaw...)
   181  			hdrRawEncrypted[0] ^= 0xff
   182  			hdrRawEncrypted[len(hdrRaw)-2] ^= 0xff
   183  			hdrRawEncrypted[len(hdrRaw)-1] ^= 0xff
   184  			Expect(p.buffer.Data[0:len(hdrRaw)]).To(Equal(hdrRawEncrypted))
   185  			Expect(p.buffer.Data[p.buffer.Len()-4:]).To(Equal([]byte{0xde, 0xca, 0xfb, 0xad}))
   186  		})
   187  	})
   188  
   189  	Context("packing packets", func() {
   190  		// getSealer gets a sealer that's expected to seal exactly one packet
   191  		getSealer := func() *mocks.MockShortHeaderSealer {
   192  			sealer := mocks.NewMockShortHeaderSealer(mockCtrl)
   193  			sealer.EXPECT().KeyPhase().Return(protocol.KeyPhaseOne).AnyTimes()
   194  			sealer.EXPECT().Overhead().Return(7).AnyTimes()
   195  			sealer.EXPECT().EncryptHeader(gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes()
   196  			sealer.EXPECT().Seal(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn(func(dst, src []byte, pn protocol.PacketNumber, associatedData []byte) []byte {
   197  				return append(src, bytes.Repeat([]byte{'s'}, sealer.Overhead())...)
   198  			}).AnyTimes()
   199  			return sealer
   200  		}
   201  
   202  		Context("packing ACK packets", func() {
   203  			It("doesn't pack a packet if there's no ACK to send", func() {
   204  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   205  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   206  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   207  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   208  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true)
   209  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, true)
   210  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true)
   211  				p, err := packer.PackCoalescedPacket(true, maxPacketSize, protocol.Version1)
   212  				Expect(err).ToNot(HaveOccurred())
   213  				Expect(p).To(BeNil())
   214  			})
   215  
   216  			It("packs Initial ACK-only packets, and pads them (for the client)", func() {
   217  				packer.perspective = protocol.PerspectiveClient
   218  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   219  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
   220  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   221  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}
   222  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true).Return(ack)
   223  				p, err := packer.PackCoalescedPacket(true, maxPacketSize, protocol.Version1)
   224  				Expect(err).NotTo(HaveOccurred())
   225  				Expect(p).ToNot(BeNil())
   226  				Expect(p.longHdrPackets).To(HaveLen(1))
   227  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
   228  				Expect(p.longHdrPackets[0].ack).To(Equal(ack))
   229  				Expect(p.longHdrPackets[0].frames).To(BeEmpty())
   230  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
   231  				parsePacket(p.buffer.Data)
   232  			})
   233  
   234  			It("packs Initial ACK-only packets, and doesn't pads them (for the server)", func() {
   235  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   236  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
   237  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   238  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}
   239  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true).Return(ack)
   240  				p, err := packer.PackCoalescedPacket(true, maxPacketSize, protocol.Version1)
   241  				Expect(err).NotTo(HaveOccurred())
   242  				Expect(p).ToNot(BeNil())
   243  				Expect(p.longHdrPackets).To(HaveLen(1))
   244  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
   245  				Expect(p.longHdrPackets[0].ack).To(Equal(ack))
   246  				Expect(p.longHdrPackets[0].frames).To(BeEmpty())
   247  				Expect(p.buffer.Len()).To(BeNumerically("<", 100))
   248  				parsePacket(p.buffer.Data)
   249  			})
   250  
   251  			It("packs 1-RTT ACK-only packets, before handshake confirmation", func() {
   252  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
   253  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   254  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   255  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   256  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   257  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}
   258  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, true)
   259  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true).Return(ack)
   260  				p, err := packer.PackCoalescedPacket(true, maxPacketSize, protocol.Version1)
   261  				Expect(err).NotTo(HaveOccurred())
   262  				Expect(p).ToNot(BeNil())
   263  				Expect(p.longHdrPackets).To(BeEmpty())
   264  				Expect(p.shortHdrPacket).ToNot(BeNil())
   265  				Expect(p.shortHdrPacket.Ack).To(Equal(ack))
   266  				Expect(p.shortHdrPacket.Frames).To(BeEmpty())
   267  				parsePacket(p.buffer.Data)
   268  			})
   269  
   270  			It("packs 1-RTT ACK-only packets, after handshake confirmation", func() {
   271  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   272  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   273  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   274  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}
   275  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true).Return(ack)
   276  				p, buffer, err := packer.PackAckOnlyPacket(maxPacketSize, protocol.Version1)
   277  				Expect(err).NotTo(HaveOccurred())
   278  				Expect(p).ToNot(BeNil())
   279  				Expect(p.Ack).To(Equal(ack))
   280  				Expect(p.Frames).To(BeEmpty())
   281  				parsePacket(buffer.Data)
   282  			})
   283  		})
   284  
   285  		Context("packing 0-RTT packets", func() {
   286  			BeforeEach(func() {
   287  				packer.perspective = protocol.PerspectiveClient
   288  				sealingManager.EXPECT().GetInitialSealer().Return(nil, nil).AnyTimes()
   289  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, nil).AnyTimes()
   290  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable).AnyTimes()
   291  				initialStream.EXPECT().HasData().AnyTimes()
   292  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true).AnyTimes()
   293  				handshakeStream.EXPECT().HasData().AnyTimes()
   294  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, true).AnyTimes()
   295  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true).AnyTimes()
   296  			})
   297  
   298  			It("packs a 0-RTT packet", func() {
   299  				sealingManager.EXPECT().Get0RTTSealer().Return(getSealer(), nil).AnyTimes()
   300  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption0RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   301  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption0RTT).Return(protocol.PacketNumber(0x42))
   302  				cf := ackhandler.Frame{Frame: &wire.MaxDataFrame{MaximumData: 0x1337}}
   303  				framer.EXPECT().HasData().Return(true)
   304  				framer.EXPECT().AppendControlFrames(gomock.Any(), gomock.Any(), protocol.Version1).DoAndReturn(func(frames []ackhandler.Frame, _ protocol.ByteCount, v protocol.VersionNumber) ([]ackhandler.Frame, protocol.ByteCount) {
   305  					Expect(frames).To(BeEmpty())
   306  					return append(frames, cf), cf.Frame.Length(v)
   307  				})
   308  				// TODO: check sizes
   309  				framer.EXPECT().AppendStreamFrames(gomock.Any(), gomock.Any(), protocol.Version1).DoAndReturn(func(frames []ackhandler.StreamFrame, _ protocol.ByteCount, _ protocol.VersionNumber) ([]ackhandler.StreamFrame, protocol.ByteCount) {
   310  					return frames, 0
   311  				})
   312  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   313  				Expect(p).ToNot(BeNil())
   314  				Expect(err).ToNot(HaveOccurred())
   315  				Expect(p.longHdrPackets).To(HaveLen(1))
   316  				Expect(p.longHdrPackets[0].header.Type).To(Equal(protocol.PacketType0RTT))
   317  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.Encryption0RTT))
   318  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   319  				Expect(p.longHdrPackets[0].frames[0].Frame).To(Equal(cf.Frame))
   320  				Expect(p.longHdrPackets[0].frames[0].Handler).ToNot(BeNil())
   321  			})
   322  
   323  			It("doesn't add an ACK-only 0-RTT packet", func() { // ACK frames cannot be sent in 0-RTT packets
   324  				p, err := packer.PackCoalescedPacket(true, protocol.MaxByteCount, protocol.Version1)
   325  				Expect(err).ToNot(HaveOccurred())
   326  				Expect(p).To(BeNil())
   327  			})
   328  		})
   329  
   330  		Context("packing CONNECTION_CLOSE", func() {
   331  			It("clears the reason phrase for crypto errors", func() {
   332  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   333  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
   334  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
   335  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   336  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   337  				quicErr := qerr.NewLocalCryptoError(0x42, errors.New("crypto error"))
   338  				quicErr.FrameType = 0x1234
   339  				p, err := packer.PackConnectionClose(quicErr, maxPacketSize, protocol.Version1)
   340  				Expect(err).ToNot(HaveOccurred())
   341  				Expect(p.longHdrPackets).To(HaveLen(1))
   342  				Expect(p.longHdrPackets[0].header.Type).To(Equal(protocol.PacketTypeHandshake))
   343  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   344  				Expect(p.longHdrPackets[0].frames[0].Frame).To(BeAssignableToTypeOf(&wire.ConnectionCloseFrame{}))
   345  				ccf := p.longHdrPackets[0].frames[0].Frame.(*wire.ConnectionCloseFrame)
   346  				Expect(ccf.IsApplicationError).To(BeFalse())
   347  				Expect(ccf.ErrorCode).To(BeEquivalentTo(0x100 + 0x42))
   348  				Expect(ccf.FrameType).To(BeEquivalentTo(0x1234))
   349  				Expect(ccf.ReasonPhrase).To(BeEmpty())
   350  			})
   351  
   352  			It("packs a CONNECTION_CLOSE in 1-RTT", func() {
   353  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   354  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   355  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
   356  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysDropped)
   357  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   358  				// expect no framer.PopStreamFrames
   359  				p, err := packer.PackConnectionClose(&qerr.TransportError{
   360  					ErrorCode:    qerr.CryptoBufferExceeded,
   361  					ErrorMessage: "test error",
   362  				}, maxPacketSize, protocol.Version1)
   363  				Expect(err).ToNot(HaveOccurred())
   364  				Expect(p.longHdrPackets).To(BeEmpty())
   365  				Expect(p.shortHdrPacket.Frames).To(HaveLen(1))
   366  				Expect(p.shortHdrPacket.Frames[0].Frame).To(BeAssignableToTypeOf(&wire.ConnectionCloseFrame{}))
   367  				ccf := p.shortHdrPacket.Frames[0].Frame.(*wire.ConnectionCloseFrame)
   368  				Expect(ccf.IsApplicationError).To(BeFalse())
   369  				Expect(ccf.ErrorCode).To(BeEquivalentTo(qerr.CryptoBufferExceeded))
   370  				Expect(ccf.ReasonPhrase).To(Equal("test error"))
   371  			})
   372  
   373  			It("packs a CONNECTION_CLOSE in all available encryption levels, and replaces application errors in Initial and Handshake", func() {
   374  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(1), protocol.PacketNumberLen2)
   375  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(1))
   376  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(2), protocol.PacketNumberLen2)
   377  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(2))
   378  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(3), protocol.PacketNumberLen2)
   379  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(3))
   380  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   381  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   382  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   383  				p, err := packer.PackApplicationClose(&qerr.ApplicationError{
   384  					ErrorCode:    0x1337,
   385  					ErrorMessage: "test error",
   386  				}, maxPacketSize, protocol.Version1)
   387  				Expect(err).ToNot(HaveOccurred())
   388  				Expect(p.longHdrPackets).To(HaveLen(2))
   389  				Expect(p.longHdrPackets[0].header.Type).To(Equal(protocol.PacketTypeInitial))
   390  				Expect(p.longHdrPackets[0].header.PacketNumber).To(Equal(protocol.PacketNumber(1)))
   391  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   392  				Expect(p.longHdrPackets[0].frames[0].Frame).To(BeAssignableToTypeOf(&wire.ConnectionCloseFrame{}))
   393  				ccf := p.longHdrPackets[0].frames[0].Frame.(*wire.ConnectionCloseFrame)
   394  				Expect(ccf.IsApplicationError).To(BeFalse())
   395  				Expect(ccf.ErrorCode).To(BeEquivalentTo(qerr.ApplicationErrorErrorCode))
   396  				Expect(ccf.ReasonPhrase).To(BeEmpty())
   397  				Expect(p.longHdrPackets[1].header.Type).To(Equal(protocol.PacketTypeHandshake))
   398  				Expect(p.longHdrPackets[1].header.PacketNumber).To(Equal(protocol.PacketNumber(2)))
   399  				Expect(p.longHdrPackets[1].frames).To(HaveLen(1))
   400  				Expect(p.longHdrPackets[1].frames[0].Frame).To(BeAssignableToTypeOf(&wire.ConnectionCloseFrame{}))
   401  				ccf = p.longHdrPackets[1].frames[0].Frame.(*wire.ConnectionCloseFrame)
   402  				Expect(ccf.IsApplicationError).To(BeFalse())
   403  				Expect(ccf.ErrorCode).To(BeEquivalentTo(qerr.ApplicationErrorErrorCode))
   404  				Expect(ccf.ReasonPhrase).To(BeEmpty())
   405  				Expect(p.shortHdrPacket).ToNot(BeNil())
   406  				Expect(p.shortHdrPacket.PacketNumber).To(Equal(protocol.PacketNumber(3)))
   407  				Expect(p.shortHdrPacket.Frames).To(HaveLen(1))
   408  				Expect(p.shortHdrPacket.Frames[0].Frame).To(BeAssignableToTypeOf(&wire.ConnectionCloseFrame{}))
   409  				ccf = p.shortHdrPacket.Frames[0].Frame.(*wire.ConnectionCloseFrame)
   410  				Expect(ccf.IsApplicationError).To(BeTrue())
   411  				Expect(ccf.ErrorCode).To(BeEquivalentTo(0x1337))
   412  				Expect(ccf.ReasonPhrase).To(Equal("test error"))
   413  			})
   414  
   415  			It("packs a CONNECTION_CLOSE in all available encryption levels, as a client", func() {
   416  				packer.perspective = protocol.PerspectiveClient
   417  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(1), protocol.PacketNumberLen2)
   418  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(1))
   419  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(2), protocol.PacketNumberLen2)
   420  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(2))
   421  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
   422  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   423  				sealingManager.EXPECT().Get0RTTSealer().Return(nil, handshake.ErrKeysDropped)
   424  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   425  				p, err := packer.PackApplicationClose(&qerr.ApplicationError{
   426  					ErrorCode:    0x1337,
   427  					ErrorMessage: "test error",
   428  				}, maxPacketSize, protocol.Version1)
   429  				Expect(err).ToNot(HaveOccurred())
   430  				Expect(p.longHdrPackets).To(HaveLen(1))
   431  				Expect(p.buffer.Len()).To(BeNumerically("<", protocol.MinInitialPacketSize))
   432  				Expect(p.longHdrPackets[0].header.Type).To(Equal(protocol.PacketTypeHandshake))
   433  				Expect(p.longHdrPackets[0].header.PacketNumber).To(Equal(protocol.PacketNumber(1)))
   434  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   435  				Expect(p.longHdrPackets[0].frames[0].Frame).To(BeAssignableToTypeOf(&wire.ConnectionCloseFrame{}))
   436  				ccf := p.longHdrPackets[0].frames[0].Frame.(*wire.ConnectionCloseFrame)
   437  				Expect(ccf.IsApplicationError).To(BeFalse())
   438  				Expect(ccf.ErrorCode).To(BeEquivalentTo(qerr.ApplicationErrorErrorCode))
   439  				Expect(ccf.ReasonPhrase).To(BeEmpty())
   440  				Expect(p.shortHdrPacket).ToNot(BeNil())
   441  				Expect(p.shortHdrPacket.PacketNumber).To(Equal(protocol.PacketNumber(2)))
   442  				Expect(p.shortHdrPacket.Frames).To(HaveLen(1))
   443  				Expect(p.shortHdrPacket.Frames[0].Frame).To(BeAssignableToTypeOf(&wire.ConnectionCloseFrame{}))
   444  				ccf = p.shortHdrPacket.Frames[0].Frame.(*wire.ConnectionCloseFrame)
   445  				Expect(ccf.IsApplicationError).To(BeTrue())
   446  				Expect(ccf.ErrorCode).To(BeEquivalentTo(0x1337))
   447  				Expect(ccf.ReasonPhrase).To(Equal("test error"))
   448  			})
   449  
   450  			It("packs a CONNECTION_CLOSE in all available encryption levels and pads, as a client", func() {
   451  				packer.perspective = protocol.PerspectiveClient
   452  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(1), protocol.PacketNumberLen2)
   453  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(1))
   454  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption0RTT).Return(protocol.PacketNumber(2), protocol.PacketNumberLen2)
   455  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption0RTT).Return(protocol.PacketNumber(2))
   456  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   457  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   458  				sealingManager.EXPECT().Get0RTTSealer().Return(getSealer(), nil)
   459  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   460  				p, err := packer.PackApplicationClose(&qerr.ApplicationError{
   461  					ErrorCode:    0x1337,
   462  					ErrorMessage: "test error",
   463  				}, maxPacketSize, protocol.Version1)
   464  				Expect(err).ToNot(HaveOccurred())
   465  				Expect(p.longHdrPackets).To(HaveLen(2))
   466  				Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
   467  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
   468  				Expect(p.longHdrPackets[0].header.Type).To(Equal(protocol.PacketTypeInitial))
   469  				Expect(p.longHdrPackets[0].header.PacketNumber).To(Equal(protocol.PacketNumber(1)))
   470  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   471  				Expect(p.longHdrPackets[0].frames[0].Frame).To(BeAssignableToTypeOf(&wire.ConnectionCloseFrame{}))
   472  				ccf := p.longHdrPackets[0].frames[0].Frame.(*wire.ConnectionCloseFrame)
   473  				Expect(ccf.IsApplicationError).To(BeFalse())
   474  				Expect(ccf.ErrorCode).To(BeEquivalentTo(qerr.ApplicationErrorErrorCode))
   475  				Expect(ccf.ReasonPhrase).To(BeEmpty())
   476  				Expect(p.longHdrPackets[1].header.Type).To(Equal(protocol.PacketType0RTT))
   477  				Expect(p.longHdrPackets[1].header.PacketNumber).To(Equal(protocol.PacketNumber(2)))
   478  				Expect(p.longHdrPackets[1].frames).To(HaveLen(1))
   479  				Expect(p.longHdrPackets[1].frames[0].Frame).To(BeAssignableToTypeOf(&wire.ConnectionCloseFrame{}))
   480  				ccf = p.longHdrPackets[1].frames[0].Frame.(*wire.ConnectionCloseFrame)
   481  				Expect(ccf.IsApplicationError).To(BeTrue())
   482  				Expect(ccf.ErrorCode).To(BeEquivalentTo(0x1337))
   483  				Expect(ccf.ReasonPhrase).To(Equal("test error"))
   484  				hdrs, more := parsePacket(p.buffer.Data)
   485  				Expect(hdrs).To(HaveLen(2))
   486  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
   487  				Expect(hdrs[1].Type).To(Equal(protocol.PacketType0RTT))
   488  				Expect(more).To(BeEmpty())
   489  			})
   490  		})
   491  
   492  		Context("packing normal packets", func() {
   493  			It("returns nil when no packet is queued", func() {
   494  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   495  				// don't expect any calls to PopPacketNumber
   496  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   497  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true)
   498  				framer.EXPECT().HasData()
   499  				_, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   500  				Expect(err).To(MatchError(errNothingToPack))
   501  			})
   502  
   503  			It("appends single packets", func() {
   504  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   505  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   506  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   507  				framer.EXPECT().HasData().Return(true)
   508  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   509  				expectAppendControlFrames()
   510  				f := &wire.StreamFrame{
   511  					StreamID: 5,
   512  					Data:     []byte{0xde, 0xca, 0xfb, 0xad},
   513  				}
   514  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: f})
   515  				buffer := getPacketBuffer()
   516  				buffer.Data = append(buffer.Data, []byte("foobar")...)
   517  				p, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   518  				Expect(err).ToNot(HaveOccurred())
   519  				Expect(p).ToNot(BeNil())
   520  				b, err := f.Append(nil, protocol.Version1)
   521  				Expect(err).ToNot(HaveOccurred())
   522  				Expect(p.Frames).To(BeEmpty())
   523  				Expect(p.StreamFrames).To(HaveLen(1))
   524  				Expect(p.StreamFrames[0].Frame.StreamID).To(Equal(f.StreamID))
   525  				Expect(buffer.Data[:6]).To(Equal([]byte("foobar"))) // make sure the packet was actually appended
   526  				Expect(buffer.Data).To(ContainSubstring(string(b)))
   527  			})
   528  
   529  			It("packs a single ACK", func() {
   530  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   531  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   532  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Largest: 42, Smallest: 1}}}
   533  				framer.EXPECT().HasData()
   534  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true).Return(ack)
   535  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   536  				p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   537  				Expect(err).NotTo(HaveOccurred())
   538  				Expect(p).ToNot(BeNil())
   539  				Expect(p.Ack).To(Equal(ack))
   540  			})
   541  
   542  			It("packs control frames", func() {
   543  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   544  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   545  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   546  				framer.EXPECT().HasData().Return(true)
   547  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   548  				frames := []ackhandler.Frame{
   549  					{Frame: &wire.ResetStreamFrame{}},
   550  					{Frame: &wire.MaxDataFrame{}},
   551  				}
   552  				expectAppendControlFrames(frames...)
   553  				expectAppendStreamFrames()
   554  				buffer := getPacketBuffer()
   555  				p, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   556  				Expect(p).ToNot(BeNil())
   557  				Expect(err).ToNot(HaveOccurred())
   558  				Expect(p.Frames).To(HaveLen(2))
   559  				for i, f := range p.Frames {
   560  					Expect(f).To(BeAssignableToTypeOf(frames[i]))
   561  				}
   562  				Expect(buffer.Len()).ToNot(BeZero())
   563  			})
   564  
   565  			It("packs DATAGRAM frames", func() {
   566  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true)
   567  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   568  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   569  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   570  				f := &wire.DatagramFrame{
   571  					DataLenPresent: true,
   572  					Data:           []byte("foobar"),
   573  				}
   574  				done := make(chan struct{})
   575  				go func() {
   576  					defer GinkgoRecover()
   577  					defer close(done)
   578  					datagramQueue.AddAndWait(f)
   579  				}()
   580  				// make sure the DATAGRAM has actually been queued
   581  				time.Sleep(scaleDuration(20 * time.Millisecond))
   582  
   583  				framer.EXPECT().HasData()
   584  				buffer := getPacketBuffer()
   585  				p, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   586  				Expect(p).ToNot(BeNil())
   587  				Expect(err).ToNot(HaveOccurred())
   588  				Expect(p.Frames).To(HaveLen(1))
   589  				Expect(p.Frames[0].Frame).To(Equal(f))
   590  				Expect(buffer.Data).ToNot(BeEmpty())
   591  				Eventually(done).Should(BeClosed())
   592  			})
   593  
   594  			It("doesn't pack a DATAGRAM frame if the ACK frame is too large", func() {
   595  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true).Return(&wire.AckFrame{AckRanges: []wire.AckRange{{Largest: 100}}})
   596  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   597  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   598  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   599  				f := &wire.DatagramFrame{
   600  					DataLenPresent: true,
   601  					Data:           make([]byte, maxPacketSize-10),
   602  				}
   603  				done := make(chan struct{})
   604  				go func() {
   605  					defer GinkgoRecover()
   606  					defer close(done)
   607  					datagramQueue.AddAndWait(f)
   608  				}()
   609  				// make sure the DATAGRAM has actually been queued
   610  				time.Sleep(scaleDuration(20 * time.Millisecond))
   611  
   612  				framer.EXPECT().HasData()
   613  				buffer := getPacketBuffer()
   614  				p, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   615  				Expect(p).ToNot(BeNil())
   616  				Expect(err).ToNot(HaveOccurred())
   617  				Expect(p.Ack).ToNot(BeNil())
   618  				Expect(p.Frames).To(BeEmpty())
   619  				Expect(buffer.Data).ToNot(BeEmpty())
   620  				datagramQueue.CloseWithError(nil)
   621  				Eventually(done).Should(BeClosed())
   622  			})
   623  
   624  			It("accounts for the space consumed by control frames", func() {
   625  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   626  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   627  				framer.EXPECT().HasData().Return(true)
   628  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   629  				var maxSize protocol.ByteCount
   630  				gomock.InOrder(
   631  					framer.EXPECT().AppendControlFrames(gomock.Any(), gomock.Any(), protocol.Version1).DoAndReturn(func(fs []ackhandler.Frame, maxLen protocol.ByteCount, _ protocol.VersionNumber) ([]ackhandler.Frame, protocol.ByteCount) {
   632  						maxSize = maxLen
   633  						return fs, 444
   634  					}),
   635  					framer.EXPECT().AppendStreamFrames(gomock.Any(), gomock.Any(), protocol.Version1).Do(func(fs []ackhandler.StreamFrame, maxLen protocol.ByteCount, _ protocol.VersionNumber) ([]ackhandler.StreamFrame, protocol.ByteCount) {
   636  						Expect(maxLen).To(Equal(maxSize - 444))
   637  						return fs, 0
   638  					}),
   639  				)
   640  				_, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   641  				Expect(err).To(MatchError(errNothingToPack))
   642  			})
   643  
   644  			It("pads if payload length + packet number length is smaller than 4, for Long Header packets", func() {
   645  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
   646  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
   647  				sealer := getSealer()
   648  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
   649  				sealingManager.EXPECT().GetHandshakeSealer().Return(sealer, nil)
   650  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   651  				packer.retransmissionQueue.addHandshake(&wire.PingFrame{})
   652  				handshakeStream.EXPECT().HasData()
   653  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
   654  				packet, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   655  				Expect(err).ToNot(HaveOccurred())
   656  				Expect(packet).ToNot(BeNil())
   657  				Expect(packet.longHdrPackets).To(HaveLen(1))
   658  				Expect(packet.IsOnlyShortHeaderPacket()).To(BeFalse())
   659  				// cut off the tag that the mock sealer added
   660  				// packet.buffer.Data = packet.buffer.Data[:packet.buffer.Len()-protocol.ByteCount(sealer.Overhead())]
   661  				hdr, _, _, err := wire.ParsePacket(packet.buffer.Data)
   662  				Expect(err).ToNot(HaveOccurred())
   663  				data := packet.buffer.Data
   664  				r := bytes.NewReader(data)
   665  				extHdr, err := hdr.ParseExtended(r, protocol.Version1)
   666  				Expect(err).ToNot(HaveOccurred())
   667  				Expect(extHdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen1))
   668  				Expect(r.Len()).To(Equal(4 - 1 /* packet number length */ + sealer.Overhead()))
   669  				// the first bytes of the payload should be a 2 PADDING frames...
   670  				firstPayloadByte, err := r.ReadByte()
   671  				Expect(err).ToNot(HaveOccurred())
   672  				Expect(firstPayloadByte).To(Equal(byte(0)))
   673  				secondPayloadByte, err := r.ReadByte()
   674  				Expect(err).ToNot(HaveOccurred())
   675  				Expect(secondPayloadByte).To(Equal(byte(0)))
   676  				// ... followed by the PING
   677  				frameParser := wire.NewFrameParser(false)
   678  				l, frame, err := frameParser.ParseNext(data[len(data)-r.Len():], protocol.Encryption1RTT, protocol.Version1)
   679  				Expect(err).ToNot(HaveOccurred())
   680  				Expect(frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
   681  				Expect(r.Len() - l).To(Equal(sealer.Overhead()))
   682  			})
   683  
   684  			It("pads if payload length + packet number length is smaller than 4", func() {
   685  				f := &wire.StreamFrame{
   686  					StreamID: 0x10, // small stream ID, such that only a single byte is consumed
   687  					Fin:      true,
   688  				}
   689  				Expect(f.Length(protocol.Version1)).To(BeEquivalentTo(2))
   690  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
   691  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   692  				sealer := getSealer()
   693  				sealingManager.EXPECT().Get1RTTSealer().Return(sealer, nil)
   694  				framer.EXPECT().HasData().Return(true)
   695  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   696  				expectAppendControlFrames()
   697  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: f})
   698  				buffer := getPacketBuffer()
   699  				_, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   700  				Expect(err).ToNot(HaveOccurred())
   701  				// cut off the tag that the mock sealer added
   702  				buffer.Data = buffer.Data[:buffer.Len()-protocol.ByteCount(sealer.Overhead())]
   703  				data := buffer.Data
   704  				l, _, pnLen, _, err := wire.ParseShortHeader(data, connID.Len())
   705  				Expect(err).ToNot(HaveOccurred())
   706  				r := bytes.NewReader(data[l:])
   707  				Expect(pnLen).To(Equal(protocol.PacketNumberLen1))
   708  				Expect(r.Len()).To(Equal(4 - 1 /* packet number length */))
   709  				// the first byte of the payload should be a PADDING frame...
   710  				firstPayloadByte, err := r.ReadByte()
   711  				Expect(err).ToNot(HaveOccurred())
   712  				Expect(firstPayloadByte).To(Equal(byte(0)))
   713  				// ... followed by the STREAM frame
   714  				frameParser := wire.NewFrameParser(true)
   715  				l, frame, err := frameParser.ParseNext(buffer.Data[len(data)-r.Len():], protocol.Encryption1RTT, protocol.Version1)
   716  				Expect(err).ToNot(HaveOccurred())
   717  				Expect(frame).To(BeAssignableToTypeOf(&wire.StreamFrame{}))
   718  				sf := frame.(*wire.StreamFrame)
   719  				Expect(sf.StreamID).To(Equal(f.StreamID))
   720  				Expect(sf.Fin).To(Equal(f.Fin))
   721  				Expect(sf.Data).To(BeEmpty())
   722  				Expect(r.Len() - l).To(BeZero())
   723  			})
   724  
   725  			It("packs multiple small STREAM frames into single packet", func() {
   726  				f1 := &wire.StreamFrame{
   727  					StreamID:       5,
   728  					Data:           []byte("frame 1"),
   729  					DataLenPresent: true,
   730  				}
   731  				f2 := &wire.StreamFrame{
   732  					StreamID:       5,
   733  					Data:           []byte("frame 2"),
   734  					DataLenPresent: true,
   735  				}
   736  				f3 := &wire.StreamFrame{
   737  					StreamID:       3,
   738  					Data:           []byte("frame 3"),
   739  					DataLenPresent: true,
   740  				}
   741  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   742  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   743  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   744  				framer.EXPECT().HasData().Return(true)
   745  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   746  				expectAppendControlFrames()
   747  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: f1}, ackhandler.StreamFrame{Frame: f2}, ackhandler.StreamFrame{Frame: f3})
   748  				p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   749  				Expect(p).ToNot(BeNil())
   750  				Expect(err).ToNot(HaveOccurred())
   751  				Expect(p.Frames).To(BeEmpty())
   752  				Expect(p.StreamFrames).To(HaveLen(3))
   753  				Expect(p.StreamFrames[0].Frame.Data).To(Equal([]byte("frame 1")))
   754  				Expect(p.StreamFrames[1].Frame.Data).To(Equal([]byte("frame 2")))
   755  				Expect(p.StreamFrames[2].Frame.Data).To(Equal([]byte("frame 3")))
   756  			})
   757  
   758  			Context("making ACK packets ack-eliciting", func() {
   759  				sendMaxNumNonAckElicitingAcks := func() {
   760  					for i := 0; i < protocol.MaxNonAckElicitingAcks; i++ {
   761  						pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   762  						pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   763  						sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   764  						framer.EXPECT().HasData().Return(true)
   765  						ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false).Return(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}})
   766  						expectAppendControlFrames()
   767  						expectAppendStreamFrames()
   768  						p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   769  						Expect(p).ToNot(BeNil())
   770  						Expect(err).ToNot(HaveOccurred())
   771  						Expect(p.Ack).ToNot(BeNil())
   772  						Expect(p.Frames).To(BeEmpty())
   773  					}
   774  				}
   775  
   776  				It("adds a PING frame when it's supposed to send a ack-eliciting packet", func() {
   777  					sendMaxNumNonAckElicitingAcks()
   778  					pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   779  					pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   780  					sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   781  					framer.EXPECT().HasData().Return(true)
   782  					ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false).Return(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}})
   783  					expectAppendControlFrames()
   784  					expectAppendStreamFrames()
   785  					p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   786  					Expect(p).ToNot(BeNil())
   787  					Expect(err).ToNot(HaveOccurred())
   788  					var hasPing bool
   789  					for _, f := range p.Frames {
   790  						if _, ok := f.Frame.(*wire.PingFrame); ok {
   791  							hasPing = true
   792  							Expect(f.Handler).To(BeNil()) // make sure the PING is not retransmitted if lost
   793  						}
   794  					}
   795  					Expect(hasPing).To(BeTrue())
   796  					// make sure the next packet doesn't contain another PING
   797  					pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   798  					pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   799  					sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   800  					framer.EXPECT().HasData().Return(true)
   801  					ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false).Return(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}})
   802  					expectAppendControlFrames()
   803  					expectAppendStreamFrames()
   804  					p, err = packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   805  					Expect(p).ToNot(BeNil())
   806  					Expect(err).ToNot(HaveOccurred())
   807  					Expect(p.Ack).ToNot(BeNil())
   808  					Expect(p.Frames).To(BeEmpty())
   809  				})
   810  
   811  				It("waits until there's something to send before adding a PING frame", func() {
   812  					sendMaxNumNonAckElicitingAcks()
   813  					// nothing to send
   814  					pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   815  					sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   816  					framer.EXPECT().HasData().Return(true)
   817  					expectAppendControlFrames()
   818  					expectAppendStreamFrames()
   819  					ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   820  					_, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   821  					Expect(err).To(MatchError(errNothingToPack))
   822  					// now add some frame to send
   823  					expectAppendControlFrames()
   824  					expectAppendStreamFrames()
   825  					pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   826  					pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   827  					sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   828  					framer.EXPECT().HasData().Return(true)
   829  					ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}}
   830  					ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false).Return(ack)
   831  					p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   832  					Expect(err).ToNot(HaveOccurred())
   833  					Expect(p.Ack).To(Equal(ack))
   834  					var hasPing bool
   835  					for _, f := range p.Frames {
   836  						if _, ok := f.Frame.(*wire.PingFrame); ok {
   837  							hasPing = true
   838  							Expect(f.Handler).To(BeNil()) // make sure the PING is not retransmitted if lost
   839  						}
   840  					}
   841  					Expect(hasPing).To(BeTrue())
   842  				})
   843  
   844  				It("doesn't send a PING if it already sent another ack-eliciting frame", func() {
   845  					sendMaxNumNonAckElicitingAcks()
   846  					pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   847  					pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   848  					sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   849  					framer.EXPECT().HasData().Return(true)
   850  					ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   851  					expectAppendStreamFrames()
   852  					expectAppendControlFrames(ackhandler.Frame{Frame: &wire.MaxDataFrame{}})
   853  					p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   854  					Expect(err).ToNot(HaveOccurred())
   855  					Expect(p).ToNot(BeNil())
   856  					Expect(p.Frames).ToNot(ContainElement(&wire.PingFrame{}))
   857  				})
   858  			})
   859  		})
   860  
   861  		Context("packing crypto packets", func() {
   862  			It("sets the length", func() {
   863  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   864  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
   865  				f := &wire.CryptoFrame{
   866  					Offset: 0x1337,
   867  					Data:   []byte("foobar"),
   868  				}
   869  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
   870  				handshakeStream.EXPECT().HasData().Return(true).AnyTimes()
   871  				handshakeStream.EXPECT().PopCryptoFrame(gomock.Any()).Return(f)
   872  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
   873  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   874  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   875  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   876  				Expect(err).ToNot(HaveOccurred())
   877  				Expect(p).ToNot(BeNil())
   878  				Expect(p.IsOnlyShortHeaderPacket()).To(BeFalse())
   879  				parsePacket(p.buffer.Data)
   880  			})
   881  
   882  			It("packs an Initial packet and pads it", func() {
   883  				packer.perspective = protocol.PerspectiveClient
   884  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen1)
   885  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
   886  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   887  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   888  				sealingManager.EXPECT().Get0RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   889  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   890  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
   891  				initialStream.EXPECT().HasData().Return(true).Times(2)
   892  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
   893  					return &wire.CryptoFrame{Offset: 0x42, Data: []byte("initial")}
   894  				})
   895  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   896  				Expect(err).ToNot(HaveOccurred())
   897  				Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
   898  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
   899  				Expect(p.longHdrPackets).To(HaveLen(1))
   900  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
   901  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   902  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("initial")))
   903  				hdrs, more := parsePacket(p.buffer.Data)
   904  				Expect(hdrs).To(HaveLen(1))
   905  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
   906  				Expect(more).To(BeEmpty())
   907  			})
   908  
   909  			It("packs a maximum size Handshake packet", func() {
   910  				var f *wire.CryptoFrame
   911  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   912  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
   913  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   914  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   915  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true)
   916  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
   917  				initialStream.EXPECT().HasData()
   918  				handshakeStream.EXPECT().HasData().Return(true).Times(2)
   919  				handshakeStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
   920  					f = &wire.CryptoFrame{Offset: 0x1337}
   921  					f.Data = bytes.Repeat([]byte{'f'}, int(size-f.Length(protocol.Version1)-1))
   922  					Expect(f.Length(protocol.Version1)).To(Equal(size))
   923  					return f
   924  				})
   925  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   926  				Expect(err).ToNot(HaveOccurred())
   927  				Expect(p.longHdrPackets).To(HaveLen(1))
   928  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   929  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
   930  				parsePacket(p.buffer.Data)
   931  			})
   932  
   933  			It("packs a coalesced packet with Initial / Handshake, and pads it", func() {
   934  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
   935  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
   936  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   937  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
   938  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   939  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   940  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   941  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
   942  				// don't EXPECT any calls for a Handshake ACK frame
   943  				initialStream.EXPECT().HasData().Return(true).Times(2)
   944  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
   945  					return &wire.CryptoFrame{Offset: 0x42, Data: []byte("initial")}
   946  				})
   947  				handshakeStream.EXPECT().HasData().Return(true).Times(2)
   948  				handshakeStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
   949  					return &wire.CryptoFrame{Offset: 0x1337, Data: []byte("handshake")}
   950  				})
   951  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   952  				Expect(err).ToNot(HaveOccurred())
   953  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
   954  				Expect(p.longHdrPackets).To(HaveLen(2))
   955  				Expect(p.shortHdrPacket).To(BeNil())
   956  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
   957  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   958  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("initial")))
   959  				Expect(p.longHdrPackets[1].EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
   960  				Expect(p.longHdrPackets[1].frames).To(HaveLen(1))
   961  				Expect(p.longHdrPackets[1].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("handshake")))
   962  				hdrs, more := parsePacket(p.buffer.Data)
   963  				Expect(hdrs).To(HaveLen(2))
   964  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
   965  				Expect(hdrs[1].Type).To(Equal(protocol.PacketTypeHandshake))
   966  				Expect(more).To(BeEmpty())
   967  			})
   968  
   969  			It("packs a coalesced packet with Initial / super short Handshake, and pads it", func() {
   970  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
   971  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
   972  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
   973  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
   974  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   975  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   976  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   977  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
   978  				// don't EXPECT any calls for a Handshake ACK frame
   979  				initialStream.EXPECT().HasData().Return(true).Times(2)
   980  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
   981  					return &wire.CryptoFrame{Offset: 0x42, Data: []byte("initial")}
   982  				})
   983  				handshakeStream.EXPECT().HasData()
   984  				packer.retransmissionQueue.addHandshake(&wire.PingFrame{})
   985  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   986  				Expect(err).ToNot(HaveOccurred())
   987  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
   988  				Expect(p.longHdrPackets).To(HaveLen(2))
   989  				Expect(p.shortHdrPacket).To(BeNil())
   990  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
   991  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   992  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("initial")))
   993  				Expect(p.longHdrPackets[1].EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
   994  				Expect(p.longHdrPackets[1].frames).To(HaveLen(1))
   995  				Expect(p.longHdrPackets[1].frames[0].Frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
   996  				hdrs, more := parsePacket(p.buffer.Data)
   997  				Expect(hdrs).To(HaveLen(2))
   998  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
   999  				Expect(hdrs[1].Type).To(Equal(protocol.PacketTypeHandshake))
  1000  				Expect(more).To(BeEmpty())
  1001  			})
  1002  
  1003  			It("packs a coalesced packet with super short Initial / super short Handshake, and pads it", func() {
  1004  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen1)
  1005  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
  1006  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
  1007  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  1008  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1009  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1010  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1011  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, gomock.Any())
  1012  				initialStream.EXPECT().HasData()
  1013  				handshakeStream.EXPECT().HasData()
  1014  				packer.retransmissionQueue.addInitial(&wire.PingFrame{})
  1015  				packer.retransmissionQueue.addHandshake(&wire.PingFrame{})
  1016  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1017  				Expect(err).ToNot(HaveOccurred())
  1018  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1019  				Expect(p.longHdrPackets).To(HaveLen(2))
  1020  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1021  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1022  				Expect(p.longHdrPackets[0].frames[0].Frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1023  				Expect(p.longHdrPackets[1].EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1024  				Expect(p.longHdrPackets[1].frames).To(HaveLen(1))
  1025  				Expect(p.longHdrPackets[1].frames[0].Frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1026  				hdrs, more := parsePacket(p.buffer.Data)
  1027  				Expect(hdrs).To(HaveLen(2))
  1028  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
  1029  				Expect(hdrs[1].Type).To(Equal(protocol.PacketTypeHandshake))
  1030  				Expect(more).To(BeEmpty())
  1031  			})
  1032  
  1033  			It("packs a coalesced packet with Initial / super short 1-RTT, and pads it", func() {
  1034  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
  1035  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
  1036  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
  1037  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
  1038  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1039  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1040  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1041  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1042  				initialStream.EXPECT().HasData().Return(true).Times(2)
  1043  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
  1044  					return &wire.CryptoFrame{Offset: 0x42, Data: []byte("initial")}
  1045  				})
  1046  				expectAppendControlFrames()
  1047  				expectAppendStreamFrames()
  1048  				framer.EXPECT().HasData().Return(true)
  1049  				packer.retransmissionQueue.addAppData(&wire.PingFrame{})
  1050  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1051  				Expect(err).ToNot(HaveOccurred())
  1052  				Expect(p.IsOnlyShortHeaderPacket()).To(BeFalse())
  1053  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1054  				Expect(p.longHdrPackets).To(HaveLen(1))
  1055  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1056  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1057  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("initial")))
  1058  				Expect(p.shortHdrPacket).ToNot(BeNil())
  1059  				Expect(p.shortHdrPacket.Frames).To(HaveLen(1))
  1060  				Expect(p.shortHdrPacket.Frames[0].Frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1061  				hdrs, more := parsePacket(p.buffer.Data)
  1062  				Expect(hdrs).To(HaveLen(1))
  1063  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
  1064  				Expect(more).ToNot(BeEmpty())
  1065  				parseShortHeaderPacket(more)
  1066  			})
  1067  
  1068  			It("packs a coalesced packet with Initial / 0-RTT, and pads it", func() {
  1069  				packer.perspective = protocol.PerspectiveClient
  1070  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
  1071  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
  1072  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption0RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1073  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption0RTT).Return(protocol.PacketNumber(0x42))
  1074  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1075  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1076  				sealingManager.EXPECT().Get0RTTSealer().Return(getSealer(), nil)
  1077  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1078  				framer.EXPECT().HasData().Return(true)
  1079  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1080  				// don't EXPECT any calls for a Handshake ACK frame
  1081  				initialStream.EXPECT().HasData().Return(true).Times(2)
  1082  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
  1083  					return &wire.CryptoFrame{Offset: 0x42, Data: []byte("initial")}
  1084  				})
  1085  				expectAppendControlFrames()
  1086  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: &wire.StreamFrame{Data: []byte("foobar")}})
  1087  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1088  				Expect(err).ToNot(HaveOccurred())
  1089  				Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
  1090  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1091  				Expect(p.longHdrPackets).To(HaveLen(2))
  1092  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1093  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1094  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("initial")))
  1095  				Expect(p.longHdrPackets[0].streamFrames).To(BeEmpty())
  1096  				Expect(p.longHdrPackets[1].EncryptionLevel()).To(Equal(protocol.Encryption0RTT))
  1097  				Expect(p.longHdrPackets[1].frames).To(BeEmpty())
  1098  				Expect(p.longHdrPackets[1].streamFrames).To(HaveLen(1))
  1099  				Expect(p.longHdrPackets[1].streamFrames[0].Frame.Data).To(Equal([]byte("foobar")))
  1100  				hdrs, more := parsePacket(p.buffer.Data)
  1101  				Expect(hdrs).To(HaveLen(2))
  1102  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
  1103  				Expect(hdrs[1].Type).To(Equal(protocol.PacketType0RTT))
  1104  				Expect(more).To(BeEmpty())
  1105  			})
  1106  
  1107  			It("packs a coalesced packet with Handshake / 1-RTT", func() {
  1108  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
  1109  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x24))
  1110  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1111  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
  1112  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
  1113  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1114  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1115  				framer.EXPECT().HasData().Return(true)
  1116  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
  1117  				// don't EXPECT any calls for a 1-RTT ACK frame
  1118  				handshakeStream.EXPECT().HasData().Return(true).Times(2)
  1119  				handshakeStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
  1120  					return &wire.CryptoFrame{Offset: 0x1337, Data: []byte("handshake")}
  1121  				})
  1122  				expectAppendControlFrames()
  1123  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: &wire.StreamFrame{Data: []byte("foobar")}})
  1124  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1125  				Expect(err).ToNot(HaveOccurred())
  1126  				Expect(p.buffer.Len()).To(BeNumerically("<", 100))
  1127  				Expect(p.longHdrPackets).To(HaveLen(1))
  1128  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1129  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1130  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("handshake")))
  1131  				Expect(p.shortHdrPacket).ToNot(BeNil())
  1132  				Expect(p.shortHdrPacket.Frames).To(BeEmpty())
  1133  				Expect(p.shortHdrPacket.StreamFrames).To(HaveLen(1))
  1134  				Expect(p.shortHdrPacket.StreamFrames[0].Frame.Data).To(Equal([]byte("foobar")))
  1135  				hdrs, more := parsePacket(p.buffer.Data)
  1136  				Expect(hdrs).To(HaveLen(1))
  1137  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeHandshake))
  1138  				Expect(more).ToNot(BeEmpty())
  1139  				parseShortHeaderPacket(more)
  1140  			})
  1141  
  1142  			It("doesn't add a coalesced packet if the remaining size is smaller than MaxCoalescedPacketSize", func() {
  1143  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
  1144  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x24))
  1145  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
  1146  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1147  				// don't EXPECT any calls to GetHandshakeSealer and Get1RTTSealer
  1148  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
  1149  				handshakeStream.EXPECT().HasData().Return(true).Times(2)
  1150  				handshakeStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
  1151  					s := size - protocol.MinCoalescedPacketSize
  1152  					f := &wire.CryptoFrame{Offset: 0x1337}
  1153  					f.Data = bytes.Repeat([]byte{'f'}, int(s-f.Length(protocol.Version1)-1))
  1154  					Expect(f.Length(protocol.Version1)).To(Equal(s))
  1155  					return f
  1156  				})
  1157  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1158  				Expect(err).ToNot(HaveOccurred())
  1159  				Expect(p.longHdrPackets).To(HaveLen(1))
  1160  				Expect(p.shortHdrPacket).To(BeNil())
  1161  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1162  				Expect(len(p.buffer.Data)).To(BeEquivalentTo(maxPacketSize - protocol.MinCoalescedPacketSize))
  1163  				parsePacket(p.buffer.Data)
  1164  			})
  1165  
  1166  			It("pads if payload length + packet number length is smaller than 4, for Long Header packets", func() {
  1167  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
  1168  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  1169  				sealer := getSealer()
  1170  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
  1171  				sealingManager.EXPECT().GetHandshakeSealer().Return(sealer, nil)
  1172  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1173  				packer.retransmissionQueue.addHandshake(&wire.PingFrame{})
  1174  				handshakeStream.EXPECT().HasData()
  1175  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
  1176  				packet, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1177  				Expect(err).ToNot(HaveOccurred())
  1178  				Expect(packet).ToNot(BeNil())
  1179  				Expect(packet.longHdrPackets).To(HaveLen(1))
  1180  				Expect(packet.shortHdrPacket).To(BeNil())
  1181  				// cut off the tag that the mock sealer added
  1182  				// packet.buffer.Data = packet.buffer.Data[:packet.buffer.Len()-protocol.ByteCount(sealer.Overhead())]
  1183  				hdr, _, _, err := wire.ParsePacket(packet.buffer.Data)
  1184  				Expect(err).ToNot(HaveOccurred())
  1185  				data := packet.buffer.Data
  1186  				r := bytes.NewReader(data)
  1187  				extHdr, err := hdr.ParseExtended(r, protocol.Version1)
  1188  				Expect(err).ToNot(HaveOccurred())
  1189  				Expect(extHdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen1))
  1190  				Expect(r.Len()).To(Equal(4 - 1 /* packet number length */ + sealer.Overhead()))
  1191  				// the first bytes of the payload should be a 2 PADDING frames...
  1192  				firstPayloadByte, err := r.ReadByte()
  1193  				Expect(err).ToNot(HaveOccurred())
  1194  				Expect(firstPayloadByte).To(Equal(byte(0)))
  1195  				secondPayloadByte, err := r.ReadByte()
  1196  				Expect(err).ToNot(HaveOccurred())
  1197  				Expect(secondPayloadByte).To(Equal(byte(0)))
  1198  				// ... followed by the PING
  1199  				frameParser := wire.NewFrameParser(false)
  1200  				l, frame, err := frameParser.ParseNext(data[len(data)-r.Len():], protocol.Encryption1RTT, protocol.Version1)
  1201  				Expect(err).ToNot(HaveOccurred())
  1202  				Expect(frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1203  				Expect(r.Len() - l).To(Equal(sealer.Overhead()))
  1204  			})
  1205  
  1206  			It("adds retransmissions", func() {
  1207  				f := &wire.CryptoFrame{Data: []byte("Initial")}
  1208  				retransmissionQueue.addInitial(f)
  1209  				retransmissionQueue.addHandshake(&wire.CryptoFrame{Data: []byte("Handshake")})
  1210  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1211  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1212  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1213  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1214  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1215  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1216  				initialStream.EXPECT().HasData()
  1217  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1218  				Expect(err).ToNot(HaveOccurred())
  1219  				Expect(p.longHdrPackets).To(HaveLen(1))
  1220  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1221  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1222  				Expect(p.longHdrPackets[0].frames[0].Frame).To(Equal(f))
  1223  				Expect(p.longHdrPackets[0].frames[0].Handler).ToNot(BeNil())
  1224  			})
  1225  
  1226  			It("sends an Initial packet containing only an ACK", func() {
  1227  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 10, Largest: 20}}}
  1228  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true).Return(ack)
  1229  				initialStream.EXPECT().HasData().Times(2)
  1230  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1231  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1232  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1233  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1234  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1235  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1236  				Expect(err).ToNot(HaveOccurred())
  1237  				Expect(p.longHdrPackets).To(HaveLen(1))
  1238  				Expect(p.longHdrPackets[0].ack).To(Equal(ack))
  1239  			})
  1240  
  1241  			It("doesn't pack anything if there's nothing to send at Initial and Handshake keys are not yet available", func() {
  1242  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1243  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1244  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1245  				initialStream.EXPECT().HasData()
  1246  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true)
  1247  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1248  				Expect(err).ToNot(HaveOccurred())
  1249  				Expect(p).To(BeNil())
  1250  			})
  1251  
  1252  			It("sends a Handshake packet containing only an ACK", func() {
  1253  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 10, Largest: 20}}}
  1254  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true)
  1255  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, true).Return(ack)
  1256  				initialStream.EXPECT().HasData()
  1257  				handshakeStream.EXPECT().HasData().Times(2)
  1258  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1259  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1260  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1261  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1262  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  1263  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1264  				Expect(err).ToNot(HaveOccurred())
  1265  				Expect(p.longHdrPackets).To(HaveLen(1))
  1266  				Expect(p.longHdrPackets[0].ack).To(Equal(ack))
  1267  			})
  1268  
  1269  			for _, pers := range []protocol.Perspective{protocol.PerspectiveServer, protocol.PerspectiveClient} {
  1270  				perspective := pers
  1271  
  1272  				It(fmt.Sprintf("pads Initial packets to the required minimum packet size, for the %s", perspective), func() {
  1273  					token := []byte("initial token")
  1274  					packer.SetToken(token)
  1275  					f := &wire.CryptoFrame{Data: []byte("foobar")}
  1276  					pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1277  					pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1278  					sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1279  					sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1280  					sealingManager.EXPECT().Get0RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1281  					sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1282  					ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1283  					initialStream.EXPECT().HasData().Return(true).Times(2)
  1284  					initialStream.EXPECT().PopCryptoFrame(gomock.Any()).Return(f)
  1285  					packer.perspective = protocol.PerspectiveClient
  1286  					p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1287  					Expect(err).ToNot(HaveOccurred())
  1288  					Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
  1289  					Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1290  					Expect(p.longHdrPackets).To(HaveLen(1))
  1291  					Expect(p.longHdrPackets[0].header.Token).To(Equal(token))
  1292  					Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1293  					cf := p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame)
  1294  					Expect(cf.Data).To(Equal([]byte("foobar")))
  1295  				})
  1296  			}
  1297  
  1298  			It("adds an ACK frame", func() {
  1299  				f := &wire.CryptoFrame{Data: []byte("foobar")}
  1300  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 42, Largest: 1337}}}
  1301  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1302  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1303  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1304  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1305  				sealingManager.EXPECT().Get0RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1306  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1307  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false).Return(ack)
  1308  				initialStream.EXPECT().HasData().Return(true).Times(2)
  1309  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).Return(f)
  1310  				packer.perspective = protocol.PerspectiveClient
  1311  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1312  				Expect(err).ToNot(HaveOccurred())
  1313  				Expect(p.longHdrPackets).To(HaveLen(1))
  1314  				Expect(p.longHdrPackets[0].ack).To(Equal(ack))
  1315  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1316  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1317  			})
  1318  		})
  1319  
  1320  		Context("packing probe packets", func() {
  1321  			for _, pers := range []protocol.Perspective{protocol.PerspectiveServer, protocol.PerspectiveClient} {
  1322  				perspective := pers
  1323  
  1324  				It(fmt.Sprintf("packs an Initial probe packet and pads it, for the %s", perspective), func() {
  1325  					packer.perspective = perspective
  1326  					f := &wire.CryptoFrame{Data: []byte("Initial")}
  1327  					retransmissionQueue.addInitial(f)
  1328  					sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1329  					ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1330  					initialStream.EXPECT().HasData()
  1331  					pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1332  					pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1333  
  1334  					p, err := packer.MaybePackProbePacket(protocol.EncryptionInitial, maxPacketSize, protocol.Version1)
  1335  					Expect(err).ToNot(HaveOccurred())
  1336  					Expect(p).ToNot(BeNil())
  1337  					Expect(p.longHdrPackets).To(HaveLen(1))
  1338  					packet := p.longHdrPackets[0]
  1339  					Expect(packet.EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1340  					Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
  1341  					Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1342  					Expect(packet.frames).To(HaveLen(1))
  1343  					Expect(packet.frames[0].Frame).To(Equal(f))
  1344  					parsePacket(p.buffer.Data)
  1345  				})
  1346  
  1347  				It(fmt.Sprintf("packs an Initial probe packet with 1 byte payload, for the %s", perspective), func() {
  1348  					packer.perspective = perspective
  1349  					retransmissionQueue.addInitial(&wire.PingFrame{})
  1350  					sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1351  					ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1352  					initialStream.EXPECT().HasData()
  1353  					pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
  1354  					pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1355  
  1356  					p, err := packer.MaybePackProbePacket(protocol.EncryptionInitial, maxPacketSize, protocol.Version1)
  1357  					Expect(err).ToNot(HaveOccurred())
  1358  					Expect(err).ToNot(HaveOccurred())
  1359  					Expect(p).ToNot(BeNil())
  1360  					Expect(p.longHdrPackets).To(HaveLen(1))
  1361  					packet := p.longHdrPackets[0]
  1362  					Expect(packet.EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1363  					Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
  1364  					Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1365  					Expect(packet.frames).To(HaveLen(1))
  1366  					Expect(packet.frames[0].Frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1367  					parsePacket(p.buffer.Data)
  1368  				})
  1369  			}
  1370  
  1371  			It("packs a Handshake probe packet", func() {
  1372  				f := &wire.CryptoFrame{Data: []byte("Handshake")}
  1373  				retransmissionQueue.addHandshake(f)
  1374  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1375  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
  1376  				handshakeStream.EXPECT().HasData()
  1377  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1378  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  1379  
  1380  				p, err := packer.MaybePackProbePacket(protocol.EncryptionHandshake, maxPacketSize, protocol.Version1)
  1381  				Expect(err).ToNot(HaveOccurred())
  1382  				Expect(err).ToNot(HaveOccurred())
  1383  				Expect(p).ToNot(BeNil())
  1384  				Expect(p.longHdrPackets).To(HaveLen(1))
  1385  				packet := p.longHdrPackets[0]
  1386  				Expect(packet.EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1387  				Expect(packet.frames).To(HaveLen(1))
  1388  				Expect(packet.frames[0].Frame).To(Equal(f))
  1389  				parsePacket(p.buffer.Data)
  1390  			})
  1391  
  1392  			It("packs a full size  Handshake probe packet", func() {
  1393  				f := &wire.CryptoFrame{Data: make([]byte, 2000)}
  1394  				retransmissionQueue.addHandshake(f)
  1395  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1396  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
  1397  				handshakeStream.EXPECT().HasData()
  1398  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1399  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  1400  
  1401  				p, err := packer.MaybePackProbePacket(protocol.EncryptionHandshake, maxPacketSize, protocol.Version1)
  1402  				Expect(err).ToNot(HaveOccurred())
  1403  				Expect(err).ToNot(HaveOccurred())
  1404  				Expect(p).ToNot(BeNil())
  1405  				Expect(p.longHdrPackets).To(HaveLen(1))
  1406  				packet := p.longHdrPackets[0]
  1407  				Expect(packet.EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1408  				Expect(packet.frames).To(HaveLen(1))
  1409  				Expect(packet.frames[0].Frame).To(BeAssignableToTypeOf(&wire.CryptoFrame{}))
  1410  				Expect(packet.length).To(Equal(maxPacketSize))
  1411  				parsePacket(p.buffer.Data)
  1412  			})
  1413  
  1414  			It("packs a 1-RTT probe packet", func() {
  1415  				f := &wire.StreamFrame{Data: []byte("1-RTT")}
  1416  				retransmissionQueue.addInitial(f)
  1417  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1418  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
  1419  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1420  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
  1421  				framer.EXPECT().HasData().Return(true)
  1422  				expectAppendControlFrames()
  1423  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: f})
  1424  
  1425  				p, err := packer.MaybePackProbePacket(protocol.Encryption1RTT, maxPacketSize, protocol.Version1)
  1426  				Expect(err).ToNot(HaveOccurred())
  1427  				Expect(p).ToNot(BeNil())
  1428  				Expect(p.IsOnlyShortHeaderPacket()).To(BeTrue())
  1429  				Expect(p.longHdrPackets).To(BeEmpty())
  1430  				Expect(p.shortHdrPacket).ToNot(BeNil())
  1431  				packet := p.shortHdrPacket
  1432  				Expect(packet.Frames).To(BeEmpty())
  1433  				Expect(packet.StreamFrames).To(HaveLen(1))
  1434  				Expect(packet.StreamFrames[0].Frame).To(Equal(f))
  1435  			})
  1436  
  1437  			It("packs a full size 1-RTT probe packet", func() {
  1438  				f := &wire.StreamFrame{Data: make([]byte, 2000)}
  1439  				retransmissionQueue.addInitial(f)
  1440  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1441  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
  1442  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1443  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
  1444  				framer.EXPECT().HasData().Return(true)
  1445  				expectAppendControlFrames()
  1446  				framer.EXPECT().AppendStreamFrames(gomock.Any(), gomock.Any(), protocol.Version1).DoAndReturn(func(fs []ackhandler.StreamFrame, maxSize protocol.ByteCount, v protocol.VersionNumber) ([]ackhandler.StreamFrame, protocol.ByteCount) {
  1447  					sf, split := f.MaybeSplitOffFrame(maxSize, v)
  1448  					Expect(split).To(BeTrue())
  1449  					return append(fs, ackhandler.StreamFrame{Frame: sf}), sf.Length(v)
  1450  				})
  1451  
  1452  				p, err := packer.MaybePackProbePacket(protocol.Encryption1RTT, maxPacketSize, protocol.Version1)
  1453  				Expect(err).ToNot(HaveOccurred())
  1454  				Expect(p).ToNot(BeNil())
  1455  				Expect(p.IsOnlyShortHeaderPacket()).To(BeTrue())
  1456  				Expect(p.longHdrPackets).To(BeEmpty())
  1457  				Expect(p.shortHdrPacket).ToNot(BeNil())
  1458  				packet := p.shortHdrPacket
  1459  				Expect(packet.Frames).To(BeEmpty())
  1460  				Expect(packet.StreamFrames).To(HaveLen(1))
  1461  				Expect(packet.Length).To(Equal(maxPacketSize))
  1462  			})
  1463  
  1464  			It("returns nil if there's no probe data to send", func() {
  1465  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1466  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1467  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true)
  1468  				framer.EXPECT().HasData()
  1469  
  1470  				packet, err := packer.MaybePackProbePacket(protocol.Encryption1RTT, maxPacketSize, protocol.Version1)
  1471  				Expect(err).ToNot(HaveOccurred())
  1472  				Expect(packet).To(BeNil())
  1473  			})
  1474  
  1475  			It("packs an MTU probe packet", func() {
  1476  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1477  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x43), protocol.PacketNumberLen2)
  1478  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x43))
  1479  				ping := ackhandler.Frame{Frame: &wire.PingFrame{}}
  1480  				const probePacketSize = maxPacketSize + 42
  1481  				p, buffer, err := packer.PackMTUProbePacket(ping, probePacketSize, protocol.Version1)
  1482  				Expect(err).ToNot(HaveOccurred())
  1483  				Expect(p.Length).To(BeEquivalentTo(probePacketSize))
  1484  				Expect(p.PacketNumber).To(Equal(protocol.PacketNumber(0x43)))
  1485  				Expect(buffer.Data).To(HaveLen(int(probePacketSize)))
  1486  				Expect(p.IsPathMTUProbePacket).To(BeTrue())
  1487  			})
  1488  		})
  1489  	})
  1490  })