github.com/daeuniverse/quic-go@v0.0.0-20240413031024-943f218e0810/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/daeuniverse/quic-go/internal/ackhandler"
    13  	"github.com/daeuniverse/quic-go/internal/handshake"
    14  	"github.com/daeuniverse/quic-go/internal/mocks"
    15  	mockackhandler "github.com/daeuniverse/quic-go/internal/mocks/ackhandler"
    16  	"github.com/daeuniverse/quic-go/internal/protocol"
    17  	"github.com/daeuniverse/quic-go/internal/qerr"
    18  	"github.com/daeuniverse/quic-go/internal/utils"
    19  	"github.com/daeuniverse/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.Version) ([]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.Version) ([]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.Version) ([]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.Version) ([]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  				b, err := f.Append(nil, protocol.Version1)
   520  				Expect(err).ToNot(HaveOccurred())
   521  				Expect(p.Frames).To(BeEmpty())
   522  				Expect(p.StreamFrames).To(HaveLen(1))
   523  				Expect(p.StreamFrames[0].Frame.StreamID).To(Equal(f.StreamID))
   524  				Expect(buffer.Data[:6]).To(Equal([]byte("foobar"))) // make sure the packet was actually appended
   525  				Expect(buffer.Data).To(ContainSubstring(string(b)))
   526  			})
   527  
   528  			It("packs a single ACK", func() {
   529  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   530  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   531  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Largest: 42, Smallest: 1}}}
   532  				framer.EXPECT().HasData()
   533  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true).Return(ack)
   534  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   535  				p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   536  				Expect(err).NotTo(HaveOccurred())
   537  				Expect(p.Ack).To(Equal(ack))
   538  			})
   539  
   540  			It("packs control frames", func() {
   541  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   542  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   543  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   544  				framer.EXPECT().HasData().Return(true)
   545  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   546  				frames := []ackhandler.Frame{
   547  					{Frame: &wire.ResetStreamFrame{}},
   548  					{Frame: &wire.MaxDataFrame{}},
   549  				}
   550  				expectAppendControlFrames(frames...)
   551  				expectAppendStreamFrames()
   552  				buffer := getPacketBuffer()
   553  				p, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   554  				Expect(err).ToNot(HaveOccurred())
   555  				Expect(p.Frames).To(HaveLen(2))
   556  				for i, f := range p.Frames {
   557  					Expect(f).To(BeAssignableToTypeOf(frames[i]))
   558  				}
   559  				Expect(buffer.Len()).ToNot(BeZero())
   560  			})
   561  
   562  			It("packs PATH_CHALLENGE and PATH_RESPONSE frames", func() {
   563  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   564  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   565  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   566  				framer.EXPECT().HasData().Return(true)
   567  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   568  				frames := []ackhandler.Frame{
   569  					{Frame: &wire.PathChallengeFrame{}},
   570  					{Frame: &wire.PathResponseFrame{}},
   571  					{Frame: &wire.DataBlockedFrame{}},
   572  				}
   573  				expectAppendControlFrames(frames...)
   574  				expectAppendStreamFrames()
   575  				buffer := getPacketBuffer()
   576  				p, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   577  				Expect(err).ToNot(HaveOccurred())
   578  				Expect(p.Frames).To(HaveLen(3))
   579  				for i, f := range p.Frames {
   580  					Expect(f).To(BeAssignableToTypeOf(frames[i]))
   581  					switch f.Frame.(type) {
   582  					case *wire.PathChallengeFrame, *wire.PathResponseFrame:
   583  						// This means that the frame won't be retransmitted.
   584  						Expect(f.Handler).To(BeNil())
   585  					default:
   586  						Expect(f.Handler).ToNot(BeNil())
   587  					}
   588  				}
   589  				Expect(buffer.Len()).ToNot(BeZero())
   590  			})
   591  
   592  			It("packs DATAGRAM frames", func() {
   593  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true)
   594  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   595  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   596  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   597  				f := &wire.DatagramFrame{
   598  					DataLenPresent: true,
   599  					Data:           []byte("foobar"),
   600  				}
   601  				done := make(chan struct{})
   602  				go func() {
   603  					defer GinkgoRecover()
   604  					defer close(done)
   605  					datagramQueue.Add(f)
   606  				}()
   607  				// make sure the DATAGRAM has actually been queued
   608  				time.Sleep(scaleDuration(20 * time.Millisecond))
   609  
   610  				framer.EXPECT().HasData()
   611  				buffer := getPacketBuffer()
   612  				p, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   613  				Expect(err).ToNot(HaveOccurred())
   614  				Expect(p.Frames).To(HaveLen(1))
   615  				Expect(p.Frames[0].Frame).To(Equal(f))
   616  				Expect(buffer.Data).ToNot(BeEmpty())
   617  				Eventually(done).Should(BeClosed())
   618  			})
   619  
   620  			It("doesn't pack a DATAGRAM frame if the ACK frame is too large", func() {
   621  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true).Return(&wire.AckFrame{AckRanges: []wire.AckRange{{Largest: 100}}})
   622  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   623  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   624  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   625  				f := &wire.DatagramFrame{
   626  					DataLenPresent: true,
   627  					Data:           make([]byte, maxPacketSize-10),
   628  				}
   629  				done := make(chan struct{})
   630  				go func() {
   631  					defer GinkgoRecover()
   632  					defer close(done)
   633  					datagramQueue.Add(f)
   634  				}()
   635  				// make sure the DATAGRAM has actually been queued
   636  				time.Sleep(scaleDuration(20 * time.Millisecond))
   637  
   638  				framer.EXPECT().HasData()
   639  				buffer := getPacketBuffer()
   640  				p, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   641  				Expect(err).ToNot(HaveOccurred())
   642  				Expect(p.Ack).ToNot(BeNil())
   643  				Expect(p.Frames).To(BeEmpty())
   644  				Expect(buffer.Data).ToNot(BeEmpty())
   645  				Expect(datagramQueue.Peek()).To(Equal(f)) // make sure the frame is still there
   646  				datagramQueue.CloseWithError(nil)
   647  				Eventually(done).Should(BeClosed())
   648  			})
   649  
   650  			It("discards a DATAGRAM frame if it doesn't fit into a packet that doesn't contain an ACK", func() {
   651  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true)
   652  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   653  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   654  				f := &wire.DatagramFrame{
   655  					DataLenPresent: true,
   656  					Data:           make([]byte, maxPacketSize+10), // won't fit
   657  				}
   658  				done := make(chan struct{})
   659  				go func() {
   660  					defer GinkgoRecover()
   661  					defer close(done)
   662  					datagramQueue.Add(f)
   663  				}()
   664  				// make sure the DATAGRAM has actually been queued
   665  				time.Sleep(scaleDuration(20 * time.Millisecond))
   666  
   667  				framer.EXPECT().HasData()
   668  				buffer := getPacketBuffer()
   669  				p, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   670  				Expect(err).To(MatchError(errNothingToPack))
   671  				Expect(p.Frames).To(BeEmpty())
   672  				Expect(p.Ack).To(BeNil())
   673  				Expect(datagramQueue.Peek()).To(BeNil())
   674  				Eventually(done).Should(BeClosed())
   675  			})
   676  
   677  			It("accounts for the space consumed by control frames", func() {
   678  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   679  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   680  				framer.EXPECT().HasData().Return(true)
   681  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   682  				var maxSize protocol.ByteCount
   683  				gomock.InOrder(
   684  					framer.EXPECT().AppendControlFrames(gomock.Any(), gomock.Any(), protocol.Version1).DoAndReturn(func(fs []ackhandler.Frame, maxLen protocol.ByteCount, _ protocol.Version) ([]ackhandler.Frame, protocol.ByteCount) {
   685  						maxSize = maxLen
   686  						return fs, 444
   687  					}),
   688  					framer.EXPECT().AppendStreamFrames(gomock.Any(), gomock.Any(), protocol.Version1).Do(func(fs []ackhandler.StreamFrame, maxLen protocol.ByteCount, _ protocol.Version) ([]ackhandler.StreamFrame, protocol.ByteCount) {
   689  						Expect(maxLen).To(Equal(maxSize - 444))
   690  						return fs, 0
   691  					}),
   692  				)
   693  				_, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   694  				Expect(err).To(MatchError(errNothingToPack))
   695  			})
   696  
   697  			It("pads if payload length + packet number length is smaller than 4, for Long Header packets", func() {
   698  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
   699  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
   700  				sealer := getSealer()
   701  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
   702  				sealingManager.EXPECT().GetHandshakeSealer().Return(sealer, nil)
   703  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   704  				packer.retransmissionQueue.addHandshake(&wire.PingFrame{})
   705  				handshakeStream.EXPECT().HasData()
   706  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
   707  				packet, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   708  				Expect(err).ToNot(HaveOccurred())
   709  				Expect(packet).ToNot(BeNil())
   710  				Expect(packet.longHdrPackets).To(HaveLen(1))
   711  				Expect(packet.IsOnlyShortHeaderPacket()).To(BeFalse())
   712  				// cut off the tag that the mock sealer added
   713  				// packet.buffer.Data = packet.buffer.Data[:packet.buffer.Len()-protocol.ByteCount(sealer.Overhead())]
   714  				hdr, _, _, err := wire.ParsePacket(packet.buffer.Data)
   715  				Expect(err).ToNot(HaveOccurred())
   716  				data := packet.buffer.Data
   717  				r := bytes.NewReader(data)
   718  				extHdr, err := hdr.ParseExtended(r, protocol.Version1)
   719  				Expect(err).ToNot(HaveOccurred())
   720  				Expect(extHdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen1))
   721  				Expect(r.Len()).To(Equal(4 - 1 /* packet number length */ + sealer.Overhead()))
   722  				// the first bytes of the payload should be a 2 PADDING frames...
   723  				firstPayloadByte, err := r.ReadByte()
   724  				Expect(err).ToNot(HaveOccurred())
   725  				Expect(firstPayloadByte).To(Equal(byte(0)))
   726  				secondPayloadByte, err := r.ReadByte()
   727  				Expect(err).ToNot(HaveOccurred())
   728  				Expect(secondPayloadByte).To(Equal(byte(0)))
   729  				// ... followed by the PING
   730  				frameParser := wire.NewFrameParser(false)
   731  				l, frame, err := frameParser.ParseNext(data[len(data)-r.Len():], protocol.Encryption1RTT, protocol.Version1)
   732  				Expect(err).ToNot(HaveOccurred())
   733  				Expect(frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
   734  				Expect(r.Len() - l).To(Equal(sealer.Overhead()))
   735  			})
   736  
   737  			It("pads if payload length + packet number length is smaller than 4", func() {
   738  				f := &wire.StreamFrame{
   739  					StreamID: 0x10, // small stream ID, such that only a single byte is consumed
   740  					Fin:      true,
   741  				}
   742  				Expect(f.Length(protocol.Version1)).To(BeEquivalentTo(2))
   743  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
   744  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   745  				sealer := getSealer()
   746  				sealingManager.EXPECT().Get1RTTSealer().Return(sealer, nil)
   747  				framer.EXPECT().HasData().Return(true)
   748  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   749  				expectAppendControlFrames()
   750  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: f})
   751  				buffer := getPacketBuffer()
   752  				_, err := packer.AppendPacket(buffer, maxPacketSize, protocol.Version1)
   753  				Expect(err).ToNot(HaveOccurred())
   754  				// cut off the tag that the mock sealer added
   755  				buffer.Data = buffer.Data[:buffer.Len()-protocol.ByteCount(sealer.Overhead())]
   756  				data := buffer.Data
   757  				l, _, pnLen, _, err := wire.ParseShortHeader(data, connID.Len())
   758  				Expect(err).ToNot(HaveOccurred())
   759  				r := bytes.NewReader(data[l:])
   760  				Expect(pnLen).To(Equal(protocol.PacketNumberLen1))
   761  				Expect(r.Len()).To(Equal(4 - 1 /* packet number length */))
   762  				// the first byte of the payload should be a PADDING frame...
   763  				firstPayloadByte, err := r.ReadByte()
   764  				Expect(err).ToNot(HaveOccurred())
   765  				Expect(firstPayloadByte).To(Equal(byte(0)))
   766  				// ... followed by the STREAM frame
   767  				frameParser := wire.NewFrameParser(true)
   768  				l, frame, err := frameParser.ParseNext(buffer.Data[len(data)-r.Len():], protocol.Encryption1RTT, protocol.Version1)
   769  				Expect(err).ToNot(HaveOccurred())
   770  				Expect(frame).To(BeAssignableToTypeOf(&wire.StreamFrame{}))
   771  				sf := frame.(*wire.StreamFrame)
   772  				Expect(sf.StreamID).To(Equal(f.StreamID))
   773  				Expect(sf.Fin).To(Equal(f.Fin))
   774  				Expect(sf.Data).To(BeEmpty())
   775  				Expect(r.Len() - l).To(BeZero())
   776  			})
   777  
   778  			It("packs multiple small STREAM frames into single packet", func() {
   779  				f1 := &wire.StreamFrame{
   780  					StreamID:       5,
   781  					Data:           []byte("frame 1"),
   782  					DataLenPresent: true,
   783  				}
   784  				f2 := &wire.StreamFrame{
   785  					StreamID:       5,
   786  					Data:           []byte("frame 2"),
   787  					DataLenPresent: true,
   788  				}
   789  				f3 := &wire.StreamFrame{
   790  					StreamID:       3,
   791  					Data:           []byte("frame 3"),
   792  					DataLenPresent: true,
   793  				}
   794  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   795  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   796  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   797  				framer.EXPECT().HasData().Return(true)
   798  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   799  				expectAppendControlFrames()
   800  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: f1}, ackhandler.StreamFrame{Frame: f2}, ackhandler.StreamFrame{Frame: f3})
   801  				p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   802  				Expect(err).ToNot(HaveOccurred())
   803  				Expect(p.Frames).To(BeEmpty())
   804  				Expect(p.StreamFrames).To(HaveLen(3))
   805  				Expect(p.StreamFrames[0].Frame.Data).To(Equal([]byte("frame 1")))
   806  				Expect(p.StreamFrames[1].Frame.Data).To(Equal([]byte("frame 2")))
   807  				Expect(p.StreamFrames[2].Frame.Data).To(Equal([]byte("frame 3")))
   808  			})
   809  
   810  			Context("making ACK packets ack-eliciting", func() {
   811  				sendMaxNumNonAckElicitingAcks := func() {
   812  					for i := 0; i < protocol.MaxNonAckElicitingAcks; i++ {
   813  						pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   814  						pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   815  						sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   816  						framer.EXPECT().HasData().Return(true)
   817  						ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false).Return(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}})
   818  						expectAppendControlFrames()
   819  						expectAppendStreamFrames()
   820  						p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   821  						Expect(err).ToNot(HaveOccurred())
   822  						Expect(p.Ack).ToNot(BeNil())
   823  						Expect(p.Frames).To(BeEmpty())
   824  					}
   825  				}
   826  
   827  				It("adds a PING frame when it's supposed to send a ack-eliciting packet", func() {
   828  					sendMaxNumNonAckElicitingAcks()
   829  					pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   830  					pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   831  					sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   832  					framer.EXPECT().HasData().Return(true)
   833  					ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false).Return(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}})
   834  					expectAppendControlFrames()
   835  					expectAppendStreamFrames()
   836  					p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   837  					Expect(err).ToNot(HaveOccurred())
   838  					var hasPing bool
   839  					for _, f := range p.Frames {
   840  						if _, ok := f.Frame.(*wire.PingFrame); ok {
   841  							hasPing = true
   842  							Expect(f.Handler).To(BeNil()) // make sure the PING is not retransmitted if lost
   843  						}
   844  					}
   845  					Expect(hasPing).To(BeTrue())
   846  					// make sure the next packet doesn't contain another PING
   847  					pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   848  					pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   849  					sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   850  					framer.EXPECT().HasData().Return(true)
   851  					ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false).Return(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}})
   852  					expectAppendControlFrames()
   853  					expectAppendStreamFrames()
   854  					p, err = packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   855  					Expect(err).ToNot(HaveOccurred())
   856  					Expect(p.Ack).ToNot(BeNil())
   857  					Expect(p.Frames).To(BeEmpty())
   858  				})
   859  
   860  				It("waits until there's something to send before adding a PING frame", func() {
   861  					sendMaxNumNonAckElicitingAcks()
   862  					// nothing to send
   863  					pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   864  					sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   865  					framer.EXPECT().HasData().Return(true)
   866  					expectAppendControlFrames()
   867  					expectAppendStreamFrames()
   868  					ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   869  					_, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   870  					Expect(err).To(MatchError(errNothingToPack))
   871  					// now add some frame to send
   872  					expectAppendControlFrames()
   873  					expectAppendStreamFrames()
   874  					pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   875  					pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   876  					sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   877  					framer.EXPECT().HasData().Return(true)
   878  					ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}}
   879  					ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false).Return(ack)
   880  					p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   881  					Expect(err).ToNot(HaveOccurred())
   882  					Expect(p.Ack).To(Equal(ack))
   883  					var hasPing bool
   884  					for _, f := range p.Frames {
   885  						if _, ok := f.Frame.(*wire.PingFrame); ok {
   886  							hasPing = true
   887  							Expect(f.Handler).To(BeNil()) // make sure the PING is not retransmitted if lost
   888  						}
   889  					}
   890  					Expect(hasPing).To(BeTrue())
   891  				})
   892  
   893  				It("doesn't send a PING if it already sent another ack-eliciting frame", func() {
   894  					sendMaxNumNonAckElicitingAcks()
   895  					pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   896  					pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
   897  					sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
   898  					framer.EXPECT().HasData().Return(true)
   899  					ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
   900  					expectAppendStreamFrames()
   901  					expectAppendControlFrames(ackhandler.Frame{Frame: &wire.MaxDataFrame{}})
   902  					p, err := packer.AppendPacket(getPacketBuffer(), maxPacketSize, protocol.Version1)
   903  					Expect(err).ToNot(HaveOccurred())
   904  					Expect(p.Frames).ToNot(ContainElement(&wire.PingFrame{}))
   905  				})
   906  			})
   907  		})
   908  
   909  		Context("packing crypto packets", func() {
   910  			It("sets the length", func() {
   911  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   912  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
   913  				f := &wire.CryptoFrame{
   914  					Offset: 0x1337,
   915  					Data:   []byte("foobar"),
   916  				}
   917  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
   918  				handshakeStream.EXPECT().HasData().Return(true).AnyTimes()
   919  				handshakeStream.EXPECT().PopCryptoFrame(gomock.Any()).Return(f)
   920  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
   921  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   922  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   923  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   924  				Expect(err).ToNot(HaveOccurred())
   925  				Expect(p).ToNot(BeNil())
   926  				Expect(p.IsOnlyShortHeaderPacket()).To(BeFalse())
   927  				parsePacket(p.buffer.Data)
   928  			})
   929  
   930  			It("packs an Initial packet and pads it", func() {
   931  				packer.perspective = protocol.PerspectiveClient
   932  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen1)
   933  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
   934  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   935  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   936  				sealingManager.EXPECT().Get0RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   937  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   938  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
   939  				initialStream.EXPECT().HasData().Return(true).Times(2)
   940  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
   941  					return &wire.CryptoFrame{Offset: 0x42, Data: []byte("initial")}
   942  				})
   943  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   944  				Expect(err).ToNot(HaveOccurred())
   945  				Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
   946  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
   947  				Expect(p.longHdrPackets).To(HaveLen(1))
   948  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
   949  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   950  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("initial")))
   951  				hdrs, more := parsePacket(p.buffer.Data)
   952  				Expect(hdrs).To(HaveLen(1))
   953  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
   954  				Expect(more).To(BeEmpty())
   955  			})
   956  
   957  			It("packs a maximum size Handshake packet", func() {
   958  				var f *wire.CryptoFrame
   959  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   960  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
   961  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   962  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   963  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true)
   964  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
   965  				initialStream.EXPECT().HasData()
   966  				handshakeStream.EXPECT().HasData().Return(true).Times(2)
   967  				handshakeStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
   968  					f = &wire.CryptoFrame{Offset: 0x1337}
   969  					f.Data = bytes.Repeat([]byte{'f'}, int(size-f.Length(protocol.Version1)-1))
   970  					Expect(f.Length(protocol.Version1)).To(Equal(size))
   971  					return f
   972  				})
   973  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
   974  				Expect(err).ToNot(HaveOccurred())
   975  				Expect(p.longHdrPackets).To(HaveLen(1))
   976  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
   977  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
   978  				parsePacket(p.buffer.Data)
   979  			})
   980  
   981  			It("packs a coalesced packet with Initial / Handshake, and pads it", func() {
   982  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
   983  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
   984  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
   985  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
   986  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
   987  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
   988  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
   989  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
   990  				// don't EXPECT any calls for a Handshake ACK frame
   991  				initialStream.EXPECT().HasData().Return(true).Times(2)
   992  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
   993  					return &wire.CryptoFrame{Offset: 0x42, Data: []byte("initial")}
   994  				})
   995  				handshakeStream.EXPECT().HasData().Return(true).Times(2)
   996  				handshakeStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
   997  					return &wire.CryptoFrame{Offset: 0x1337, Data: []byte("handshake")}
   998  				})
   999  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1000  				Expect(err).ToNot(HaveOccurred())
  1001  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1002  				Expect(p.longHdrPackets).To(HaveLen(2))
  1003  				Expect(p.shortHdrPacket).To(BeNil())
  1004  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1005  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1006  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("initial")))
  1007  				Expect(p.longHdrPackets[1].EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1008  				Expect(p.longHdrPackets[1].frames).To(HaveLen(1))
  1009  				Expect(p.longHdrPackets[1].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("handshake")))
  1010  				hdrs, more := parsePacket(p.buffer.Data)
  1011  				Expect(hdrs).To(HaveLen(2))
  1012  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
  1013  				Expect(hdrs[1].Type).To(Equal(protocol.PacketTypeHandshake))
  1014  				Expect(more).To(BeEmpty())
  1015  			})
  1016  
  1017  			It("packs a coalesced packet with Initial / super short Handshake, and pads it", func() {
  1018  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
  1019  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
  1020  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
  1021  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  1022  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1023  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1024  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1025  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1026  				// don't EXPECT any calls for a Handshake ACK frame
  1027  				initialStream.EXPECT().HasData().Return(true).Times(2)
  1028  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
  1029  					return &wire.CryptoFrame{Offset: 0x42, Data: []byte("initial")}
  1030  				})
  1031  				handshakeStream.EXPECT().HasData()
  1032  				packer.retransmissionQueue.addHandshake(&wire.PingFrame{})
  1033  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1034  				Expect(err).ToNot(HaveOccurred())
  1035  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1036  				Expect(p.longHdrPackets).To(HaveLen(2))
  1037  				Expect(p.shortHdrPacket).To(BeNil())
  1038  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1039  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1040  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("initial")))
  1041  				Expect(p.longHdrPackets[1].EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1042  				Expect(p.longHdrPackets[1].frames).To(HaveLen(1))
  1043  				Expect(p.longHdrPackets[1].frames[0].Frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1044  				hdrs, more := parsePacket(p.buffer.Data)
  1045  				Expect(hdrs).To(HaveLen(2))
  1046  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
  1047  				Expect(hdrs[1].Type).To(Equal(protocol.PacketTypeHandshake))
  1048  				Expect(more).To(BeEmpty())
  1049  			})
  1050  
  1051  			It("packs a coalesced packet with super short Initial / super short Handshake, and pads it", func() {
  1052  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen1)
  1053  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
  1054  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
  1055  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  1056  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1057  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1058  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1059  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, gomock.Any())
  1060  				initialStream.EXPECT().HasData()
  1061  				handshakeStream.EXPECT().HasData()
  1062  				packer.retransmissionQueue.addInitial(&wire.PingFrame{})
  1063  				packer.retransmissionQueue.addHandshake(&wire.PingFrame{})
  1064  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1065  				Expect(err).ToNot(HaveOccurred())
  1066  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1067  				Expect(p.longHdrPackets).To(HaveLen(2))
  1068  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1069  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1070  				Expect(p.longHdrPackets[0].frames[0].Frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1071  				Expect(p.longHdrPackets[1].EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1072  				Expect(p.longHdrPackets[1].frames).To(HaveLen(1))
  1073  				Expect(p.longHdrPackets[1].frames[0].Frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1074  				hdrs, more := parsePacket(p.buffer.Data)
  1075  				Expect(hdrs).To(HaveLen(2))
  1076  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
  1077  				Expect(hdrs[1].Type).To(Equal(protocol.PacketTypeHandshake))
  1078  				Expect(more).To(BeEmpty())
  1079  			})
  1080  
  1081  			It("packs a coalesced packet with Initial / super short 1-RTT, and pads it", func() {
  1082  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
  1083  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
  1084  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
  1085  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
  1086  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1087  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1088  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1089  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1090  				initialStream.EXPECT().HasData().Return(true).Times(2)
  1091  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
  1092  					return &wire.CryptoFrame{Offset: 0x42, Data: []byte("initial")}
  1093  				})
  1094  				expectAppendControlFrames()
  1095  				expectAppendStreamFrames()
  1096  				framer.EXPECT().HasData().Return(true)
  1097  				packer.retransmissionQueue.addAppData(&wire.PingFrame{})
  1098  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1099  				Expect(err).ToNot(HaveOccurred())
  1100  				Expect(p.IsOnlyShortHeaderPacket()).To(BeFalse())
  1101  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1102  				Expect(p.longHdrPackets).To(HaveLen(1))
  1103  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1104  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1105  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("initial")))
  1106  				Expect(p.shortHdrPacket).ToNot(BeNil())
  1107  				Expect(p.shortHdrPacket.Frames).To(HaveLen(1))
  1108  				Expect(p.shortHdrPacket.Frames[0].Frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1109  				hdrs, more := parsePacket(p.buffer.Data)
  1110  				Expect(hdrs).To(HaveLen(1))
  1111  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
  1112  				Expect(more).ToNot(BeEmpty())
  1113  				parseShortHeaderPacket(more)
  1114  			})
  1115  
  1116  			It("packs a coalesced packet with Initial / 0-RTT, and pads it", func() {
  1117  				packer.perspective = protocol.PerspectiveClient
  1118  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
  1119  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x24))
  1120  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption0RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1121  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption0RTT).Return(protocol.PacketNumber(0x42))
  1122  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1123  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1124  				sealingManager.EXPECT().Get0RTTSealer().Return(getSealer(), nil)
  1125  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1126  				framer.EXPECT().HasData().Return(true)
  1127  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1128  				// don't EXPECT any calls for a Handshake ACK frame
  1129  				initialStream.EXPECT().HasData().Return(true).Times(2)
  1130  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
  1131  					return &wire.CryptoFrame{Offset: 0x42, Data: []byte("initial")}
  1132  				})
  1133  				expectAppendControlFrames()
  1134  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: &wire.StreamFrame{Data: []byte("foobar")}})
  1135  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1136  				Expect(err).ToNot(HaveOccurred())
  1137  				Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
  1138  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1139  				Expect(p.longHdrPackets).To(HaveLen(2))
  1140  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1141  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1142  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("initial")))
  1143  				Expect(p.longHdrPackets[0].streamFrames).To(BeEmpty())
  1144  				Expect(p.longHdrPackets[1].EncryptionLevel()).To(Equal(protocol.Encryption0RTT))
  1145  				Expect(p.longHdrPackets[1].frames).To(BeEmpty())
  1146  				Expect(p.longHdrPackets[1].streamFrames).To(HaveLen(1))
  1147  				Expect(p.longHdrPackets[1].streamFrames[0].Frame.Data).To(Equal([]byte("foobar")))
  1148  				hdrs, more := parsePacket(p.buffer.Data)
  1149  				Expect(hdrs).To(HaveLen(2))
  1150  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeInitial))
  1151  				Expect(hdrs[1].Type).To(Equal(protocol.PacketType0RTT))
  1152  				Expect(more).To(BeEmpty())
  1153  			})
  1154  
  1155  			It("packs a coalesced packet with Handshake / 1-RTT", func() {
  1156  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
  1157  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x24))
  1158  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1159  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
  1160  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
  1161  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1162  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1163  				framer.EXPECT().HasData().Return(true)
  1164  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
  1165  				// don't EXPECT any calls for a 1-RTT ACK frame
  1166  				handshakeStream.EXPECT().HasData().Return(true).Times(2)
  1167  				handshakeStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
  1168  					return &wire.CryptoFrame{Offset: 0x1337, Data: []byte("handshake")}
  1169  				})
  1170  				expectAppendControlFrames()
  1171  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: &wire.StreamFrame{Data: []byte("foobar")}})
  1172  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1173  				Expect(err).ToNot(HaveOccurred())
  1174  				Expect(p.buffer.Len()).To(BeNumerically("<", 100))
  1175  				Expect(p.longHdrPackets).To(HaveLen(1))
  1176  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1177  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1178  				Expect(p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame).Data).To(Equal([]byte("handshake")))
  1179  				Expect(p.shortHdrPacket).ToNot(BeNil())
  1180  				Expect(p.shortHdrPacket.Frames).To(BeEmpty())
  1181  				Expect(p.shortHdrPacket.StreamFrames).To(HaveLen(1))
  1182  				Expect(p.shortHdrPacket.StreamFrames[0].Frame.Data).To(Equal([]byte("foobar")))
  1183  				hdrs, more := parsePacket(p.buffer.Data)
  1184  				Expect(hdrs).To(HaveLen(1))
  1185  				Expect(hdrs[0].Type).To(Equal(protocol.PacketTypeHandshake))
  1186  				Expect(more).ToNot(BeEmpty())
  1187  				parseShortHeaderPacket(more)
  1188  			})
  1189  
  1190  			It("doesn't add a coalesced packet if the remaining size is smaller than MaxCoalescedPacketSize", func() {
  1191  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x24), protocol.PacketNumberLen2)
  1192  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x24))
  1193  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
  1194  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1195  				// don't EXPECT any calls to GetHandshakeSealer and Get1RTTSealer
  1196  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
  1197  				handshakeStream.EXPECT().HasData().Return(true).Times(2)
  1198  				handshakeStream.EXPECT().PopCryptoFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.CryptoFrame {
  1199  					s := size - protocol.MinCoalescedPacketSize
  1200  					f := &wire.CryptoFrame{Offset: 0x1337}
  1201  					f.Data = bytes.Repeat([]byte{'f'}, int(s-f.Length(protocol.Version1)-1))
  1202  					Expect(f.Length(protocol.Version1)).To(Equal(s))
  1203  					return f
  1204  				})
  1205  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1206  				Expect(err).ToNot(HaveOccurred())
  1207  				Expect(p.longHdrPackets).To(HaveLen(1))
  1208  				Expect(p.shortHdrPacket).To(BeNil())
  1209  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1210  				Expect(len(p.buffer.Data)).To(BeEquivalentTo(maxPacketSize - protocol.MinCoalescedPacketSize))
  1211  				parsePacket(p.buffer.Data)
  1212  			})
  1213  
  1214  			It("pads if payload length + packet number length is smaller than 4, for Long Header packets", func() {
  1215  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
  1216  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  1217  				sealer := getSealer()
  1218  				sealingManager.EXPECT().GetInitialSealer().Return(nil, handshake.ErrKeysDropped)
  1219  				sealingManager.EXPECT().GetHandshakeSealer().Return(sealer, nil)
  1220  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1221  				packer.retransmissionQueue.addHandshake(&wire.PingFrame{})
  1222  				handshakeStream.EXPECT().HasData()
  1223  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
  1224  				packet, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1225  				Expect(err).ToNot(HaveOccurred())
  1226  				Expect(packet).ToNot(BeNil())
  1227  				Expect(packet.longHdrPackets).To(HaveLen(1))
  1228  				Expect(packet.shortHdrPacket).To(BeNil())
  1229  				// cut off the tag that the mock sealer added
  1230  				// packet.buffer.Data = packet.buffer.Data[:packet.buffer.Len()-protocol.ByteCount(sealer.Overhead())]
  1231  				hdr, _, _, err := wire.ParsePacket(packet.buffer.Data)
  1232  				Expect(err).ToNot(HaveOccurred())
  1233  				data := packet.buffer.Data
  1234  				r := bytes.NewReader(data)
  1235  				extHdr, err := hdr.ParseExtended(r, protocol.Version1)
  1236  				Expect(err).ToNot(HaveOccurred())
  1237  				Expect(extHdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen1))
  1238  				Expect(r.Len()).To(Equal(4 - 1 /* packet number length */ + sealer.Overhead()))
  1239  				// the first bytes of the payload should be a 2 PADDING frames...
  1240  				firstPayloadByte, err := r.ReadByte()
  1241  				Expect(err).ToNot(HaveOccurred())
  1242  				Expect(firstPayloadByte).To(Equal(byte(0)))
  1243  				secondPayloadByte, err := r.ReadByte()
  1244  				Expect(err).ToNot(HaveOccurred())
  1245  				Expect(secondPayloadByte).To(Equal(byte(0)))
  1246  				// ... followed by the PING
  1247  				frameParser := wire.NewFrameParser(false)
  1248  				l, frame, err := frameParser.ParseNext(data[len(data)-r.Len():], protocol.Encryption1RTT, protocol.Version1)
  1249  				Expect(err).ToNot(HaveOccurred())
  1250  				Expect(frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1251  				Expect(r.Len() - l).To(Equal(sealer.Overhead()))
  1252  			})
  1253  
  1254  			It("adds retransmissions", func() {
  1255  				f := &wire.CryptoFrame{Data: []byte("Initial")}
  1256  				retransmissionQueue.addInitial(f)
  1257  				retransmissionQueue.addHandshake(&wire.CryptoFrame{Data: []byte("Handshake")})
  1258  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1259  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1260  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1261  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1262  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1263  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1264  				initialStream.EXPECT().HasData()
  1265  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1266  				Expect(err).ToNot(HaveOccurred())
  1267  				Expect(p.longHdrPackets).To(HaveLen(1))
  1268  				Expect(p.longHdrPackets[0].EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1269  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1270  				Expect(p.longHdrPackets[0].frames[0].Frame).To(Equal(f))
  1271  				Expect(p.longHdrPackets[0].frames[0].Handler).ToNot(BeNil())
  1272  			})
  1273  
  1274  			It("sends an Initial packet containing only an ACK", func() {
  1275  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 10, Largest: 20}}}
  1276  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true).Return(ack)
  1277  				initialStream.EXPECT().HasData().Times(2)
  1278  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1279  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1280  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1281  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1282  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1283  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1284  				Expect(err).ToNot(HaveOccurred())
  1285  				Expect(p.longHdrPackets).To(HaveLen(1))
  1286  				Expect(p.longHdrPackets[0].ack).To(Equal(ack))
  1287  			})
  1288  
  1289  			It("doesn't pack anything if there's nothing to send at Initial and Handshake keys are not yet available", func() {
  1290  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1291  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1292  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1293  				initialStream.EXPECT().HasData()
  1294  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true)
  1295  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1296  				Expect(err).ToNot(HaveOccurred())
  1297  				Expect(p).To(BeNil())
  1298  			})
  1299  
  1300  			It("sends a Handshake packet containing only an ACK", func() {
  1301  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 10, Largest: 20}}}
  1302  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, true)
  1303  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, true).Return(ack)
  1304  				initialStream.EXPECT().HasData()
  1305  				handshakeStream.EXPECT().HasData().Times(2)
  1306  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1307  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1308  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1309  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1310  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  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  			})
  1316  
  1317  			for _, pers := range []protocol.Perspective{protocol.PerspectiveServer, protocol.PerspectiveClient} {
  1318  				perspective := pers
  1319  
  1320  				It(fmt.Sprintf("pads Initial packets to the required minimum packet size, for the %s", perspective), func() {
  1321  					token := []byte("initial token")
  1322  					packer.SetToken(token)
  1323  					f := &wire.CryptoFrame{Data: []byte("foobar")}
  1324  					pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1325  					pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1326  					sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1327  					sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1328  					sealingManager.EXPECT().Get0RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1329  					sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1330  					ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1331  					initialStream.EXPECT().HasData().Return(true).Times(2)
  1332  					initialStream.EXPECT().PopCryptoFrame(gomock.Any()).Return(f)
  1333  					packer.perspective = protocol.PerspectiveClient
  1334  					p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1335  					Expect(err).ToNot(HaveOccurred())
  1336  					Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
  1337  					Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1338  					Expect(p.longHdrPackets).To(HaveLen(1))
  1339  					Expect(p.longHdrPackets[0].header.Token).To(Equal(token))
  1340  					Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1341  					cf := p.longHdrPackets[0].frames[0].Frame.(*wire.CryptoFrame)
  1342  					Expect(cf.Data).To(Equal([]byte("foobar")))
  1343  				})
  1344  			}
  1345  
  1346  			It("adds an ACK frame", func() {
  1347  				f := &wire.CryptoFrame{Data: []byte("foobar")}
  1348  				ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 42, Largest: 1337}}}
  1349  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1350  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1351  				sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1352  				sealingManager.EXPECT().GetHandshakeSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1353  				sealingManager.EXPECT().Get0RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1354  				sealingManager.EXPECT().Get1RTTSealer().Return(nil, handshake.ErrKeysNotYetAvailable)
  1355  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false).Return(ack)
  1356  				initialStream.EXPECT().HasData().Return(true).Times(2)
  1357  				initialStream.EXPECT().PopCryptoFrame(gomock.Any()).Return(f)
  1358  				packer.perspective = protocol.PerspectiveClient
  1359  				p, err := packer.PackCoalescedPacket(false, maxPacketSize, protocol.Version1)
  1360  				Expect(err).ToNot(HaveOccurred())
  1361  				Expect(p.longHdrPackets).To(HaveLen(1))
  1362  				Expect(p.longHdrPackets[0].ack).To(Equal(ack))
  1363  				Expect(p.longHdrPackets[0].frames).To(HaveLen(1))
  1364  				Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1365  			})
  1366  		})
  1367  
  1368  		Context("packing probe packets", func() {
  1369  			for _, pers := range []protocol.Perspective{protocol.PerspectiveServer, protocol.PerspectiveClient} {
  1370  				perspective := pers
  1371  
  1372  				It(fmt.Sprintf("packs an Initial probe packet and pads it, for the %s", perspective), func() {
  1373  					packer.perspective = perspective
  1374  					f := &wire.CryptoFrame{Data: []byte("Initial")}
  1375  					retransmissionQueue.addInitial(f)
  1376  					sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1377  					ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1378  					initialStream.EXPECT().HasData()
  1379  					pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1380  					pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1381  
  1382  					p, err := packer.MaybePackProbePacket(protocol.EncryptionInitial, maxPacketSize, protocol.Version1)
  1383  					Expect(err).ToNot(HaveOccurred())
  1384  					Expect(p).ToNot(BeNil())
  1385  					Expect(p.longHdrPackets).To(HaveLen(1))
  1386  					packet := p.longHdrPackets[0]
  1387  					Expect(packet.EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1388  					Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
  1389  					Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1390  					Expect(packet.frames).To(HaveLen(1))
  1391  					Expect(packet.frames[0].Frame).To(Equal(f))
  1392  					parsePacket(p.buffer.Data)
  1393  				})
  1394  
  1395  				It(fmt.Sprintf("packs an Initial probe packet with 1 byte payload, for the %s", perspective), func() {
  1396  					packer.perspective = perspective
  1397  					retransmissionQueue.addInitial(&wire.PingFrame{})
  1398  					sealingManager.EXPECT().GetInitialSealer().Return(getSealer(), nil)
  1399  					ackFramer.EXPECT().GetAckFrame(protocol.EncryptionInitial, false)
  1400  					initialStream.EXPECT().HasData()
  1401  					pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen1)
  1402  					pnManager.EXPECT().PopPacketNumber(protocol.EncryptionInitial).Return(protocol.PacketNumber(0x42))
  1403  
  1404  					p, err := packer.MaybePackProbePacket(protocol.EncryptionInitial, maxPacketSize, protocol.Version1)
  1405  					Expect(err).ToNot(HaveOccurred())
  1406  					Expect(err).ToNot(HaveOccurred())
  1407  					Expect(p).ToNot(BeNil())
  1408  					Expect(p.longHdrPackets).To(HaveLen(1))
  1409  					packet := p.longHdrPackets[0]
  1410  					Expect(packet.EncryptionLevel()).To(Equal(protocol.EncryptionInitial))
  1411  					Expect(p.buffer.Len()).To(BeNumerically(">=", protocol.MinInitialPacketSize))
  1412  					Expect(p.buffer.Len()).To(BeEquivalentTo(maxPacketSize))
  1413  					Expect(packet.frames).To(HaveLen(1))
  1414  					Expect(packet.frames[0].Frame).To(BeAssignableToTypeOf(&wire.PingFrame{}))
  1415  					parsePacket(p.buffer.Data)
  1416  				})
  1417  			}
  1418  
  1419  			It("packs a Handshake probe packet", func() {
  1420  				f := &wire.CryptoFrame{Data: []byte("Handshake")}
  1421  				retransmissionQueue.addHandshake(f)
  1422  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1423  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
  1424  				handshakeStream.EXPECT().HasData()
  1425  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1426  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  1427  
  1428  				p, err := packer.MaybePackProbePacket(protocol.EncryptionHandshake, maxPacketSize, protocol.Version1)
  1429  				Expect(err).ToNot(HaveOccurred())
  1430  				Expect(err).ToNot(HaveOccurred())
  1431  				Expect(p).ToNot(BeNil())
  1432  				Expect(p.longHdrPackets).To(HaveLen(1))
  1433  				packet := p.longHdrPackets[0]
  1434  				Expect(packet.EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1435  				Expect(packet.frames).To(HaveLen(1))
  1436  				Expect(packet.frames[0].Frame).To(Equal(f))
  1437  				parsePacket(p.buffer.Data)
  1438  			})
  1439  
  1440  			It("packs a full size  Handshake probe packet", func() {
  1441  				f := &wire.CryptoFrame{Data: make([]byte, 2000)}
  1442  				retransmissionQueue.addHandshake(f)
  1443  				sealingManager.EXPECT().GetHandshakeSealer().Return(getSealer(), nil)
  1444  				ackFramer.EXPECT().GetAckFrame(protocol.EncryptionHandshake, false)
  1445  				handshakeStream.EXPECT().HasData()
  1446  				pnManager.EXPECT().PeekPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1447  				pnManager.EXPECT().PopPacketNumber(protocol.EncryptionHandshake).Return(protocol.PacketNumber(0x42))
  1448  
  1449  				p, err := packer.MaybePackProbePacket(protocol.EncryptionHandshake, maxPacketSize, protocol.Version1)
  1450  				Expect(err).ToNot(HaveOccurred())
  1451  				Expect(err).ToNot(HaveOccurred())
  1452  				Expect(p).ToNot(BeNil())
  1453  				Expect(p.longHdrPackets).To(HaveLen(1))
  1454  				packet := p.longHdrPackets[0]
  1455  				Expect(packet.EncryptionLevel()).To(Equal(protocol.EncryptionHandshake))
  1456  				Expect(packet.frames).To(HaveLen(1))
  1457  				Expect(packet.frames[0].Frame).To(BeAssignableToTypeOf(&wire.CryptoFrame{}))
  1458  				Expect(packet.length).To(Equal(maxPacketSize))
  1459  				parsePacket(p.buffer.Data)
  1460  			})
  1461  
  1462  			It("packs a 1-RTT probe packet", func() {
  1463  				f := &wire.StreamFrame{Data: []byte("1-RTT")}
  1464  				retransmissionQueue.addInitial(f)
  1465  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1466  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
  1467  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1468  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
  1469  				framer.EXPECT().HasData().Return(true)
  1470  				expectAppendControlFrames()
  1471  				expectAppendStreamFrames(ackhandler.StreamFrame{Frame: f})
  1472  
  1473  				p, err := packer.MaybePackProbePacket(protocol.Encryption1RTT, maxPacketSize, protocol.Version1)
  1474  				Expect(err).ToNot(HaveOccurred())
  1475  				Expect(p).ToNot(BeNil())
  1476  				Expect(p.IsOnlyShortHeaderPacket()).To(BeTrue())
  1477  				Expect(p.longHdrPackets).To(BeEmpty())
  1478  				Expect(p.shortHdrPacket).ToNot(BeNil())
  1479  				packet := p.shortHdrPacket
  1480  				Expect(packet.Frames).To(BeEmpty())
  1481  				Expect(packet.StreamFrames).To(HaveLen(1))
  1482  				Expect(packet.StreamFrames[0].Frame).To(Equal(f))
  1483  			})
  1484  
  1485  			It("packs a full size 1-RTT probe packet", func() {
  1486  				f := &wire.StreamFrame{Data: make([]byte, 2000)}
  1487  				retransmissionQueue.addInitial(f)
  1488  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1489  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, false)
  1490  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1491  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42))
  1492  				framer.EXPECT().HasData().Return(true)
  1493  				expectAppendControlFrames()
  1494  				framer.EXPECT().AppendStreamFrames(gomock.Any(), gomock.Any(), protocol.Version1).DoAndReturn(func(fs []ackhandler.StreamFrame, maxSize protocol.ByteCount, v protocol.Version) ([]ackhandler.StreamFrame, protocol.ByteCount) {
  1495  					sf, split := f.MaybeSplitOffFrame(maxSize, v)
  1496  					Expect(split).To(BeTrue())
  1497  					return append(fs, ackhandler.StreamFrame{Frame: sf}), sf.Length(v)
  1498  				})
  1499  
  1500  				p, err := packer.MaybePackProbePacket(protocol.Encryption1RTT, maxPacketSize, protocol.Version1)
  1501  				Expect(err).ToNot(HaveOccurred())
  1502  				Expect(p).ToNot(BeNil())
  1503  				Expect(p.IsOnlyShortHeaderPacket()).To(BeTrue())
  1504  				Expect(p.longHdrPackets).To(BeEmpty())
  1505  				Expect(p.shortHdrPacket).ToNot(BeNil())
  1506  				packet := p.shortHdrPacket
  1507  				Expect(packet.Frames).To(BeEmpty())
  1508  				Expect(packet.StreamFrames).To(HaveLen(1))
  1509  				Expect(packet.Length).To(Equal(maxPacketSize))
  1510  			})
  1511  
  1512  			It("returns nil if there's no probe data to send", func() {
  1513  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1514  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x42), protocol.PacketNumberLen2)
  1515  				ackFramer.EXPECT().GetAckFrame(protocol.Encryption1RTT, true)
  1516  				framer.EXPECT().HasData()
  1517  
  1518  				packet, err := packer.MaybePackProbePacket(protocol.Encryption1RTT, maxPacketSize, protocol.Version1)
  1519  				Expect(err).ToNot(HaveOccurred())
  1520  				Expect(packet).To(BeNil())
  1521  			})
  1522  
  1523  			It("packs an MTU probe packet", func() {
  1524  				sealingManager.EXPECT().Get1RTTSealer().Return(getSealer(), nil)
  1525  				pnManager.EXPECT().PeekPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x43), protocol.PacketNumberLen2)
  1526  				pnManager.EXPECT().PopPacketNumber(protocol.Encryption1RTT).Return(protocol.PacketNumber(0x43))
  1527  				ping := ackhandler.Frame{Frame: &wire.PingFrame{}}
  1528  				const probePacketSize = maxPacketSize + 42
  1529  				p, buffer, err := packer.PackMTUProbePacket(ping, probePacketSize, protocol.Version1)
  1530  				Expect(err).ToNot(HaveOccurred())
  1531  				Expect(p.Length).To(BeEquivalentTo(probePacketSize))
  1532  				Expect(p.PacketNumber).To(Equal(protocol.PacketNumber(0x43)))
  1533  				Expect(buffer.Data).To(HaveLen(int(probePacketSize)))
  1534  				Expect(p.IsPathMTUProbePacket).To(BeTrue())
  1535  			})
  1536  		})
  1537  	})
  1538  })