diff --git a/vendor/lucas-clemente/quic-go/benchmark/benchmark_suite_test.go b/vendor/lucas-clemente/quic-go/benchmark/benchmark_suite_test.go deleted file mode 100644 index d24ef6bed..000000000 --- a/vendor/lucas-clemente/quic-go/benchmark/benchmark_suite_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package benchmark - -import ( - "flag" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestBenchmark(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Benchmark Suite") -} - -var ( - size int // file size in MB, will be read from flags - samples int // number of samples for Measure, will be read from flags -) - -func init() { - flag.IntVar(&size, "size", 50, "data length (in MB)") - flag.IntVar(&samples, "samples", 6, "number of samples") - flag.Parse() -} diff --git a/vendor/lucas-clemente/quic-go/benchmark/benchmark_test.go b/vendor/lucas-clemente/quic-go/benchmark/benchmark_test.go deleted file mode 100644 index 70b0264cb..000000000 --- a/vendor/lucas-clemente/quic-go/benchmark/benchmark_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package benchmark - -import ( - "bytes" - "crypto/tls" - "fmt" - "io" - "math/rand" - "net" - - quic "github.com/lucas-clemente/quic-go" - _ "github.com/lucas-clemente/quic-go/integrationtests/tools/testlog" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -func init() { - var _ = Describe("Benchmarks", func() { - dataLen := size * /* MB */ 1e6 - data := make([]byte, dataLen) - rand.Seed(GinkgoRandomSeed()) - rand.Read(data) // no need to check for an error. math.Rand.Read never errors - - for i := range protocol.SupportedVersions { - version := protocol.SupportedVersions[i] - - Context(fmt.Sprintf("with version %s", version), func() { - Measure(fmt.Sprintf("transferring a %d MB file", size), func(b Benchmarker) { - var ln quic.Listener - serverAddr := make(chan net.Addr) - handshakeChan := make(chan struct{}) - // start the server - go func() { - defer GinkgoRecover() - var err error - ln, err = quic.ListenAddr( - "localhost:0", - testdata.GetTLSConfig(), - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - serverAddr <- ln.Addr() - sess, err := ln.Accept() - Expect(err).ToNot(HaveOccurred()) - // wait for the client to complete the handshake before sending the data - // this should not be necessary, but due to timing issues on the CIs, this is necessary to avoid sending too many undecryptable packets - <-handshakeChan - str, err := sess.OpenStream() - Expect(err).ToNot(HaveOccurred()) - _, err = str.Write(data) - Expect(err).ToNot(HaveOccurred()) - err = str.Close() - Expect(err).ToNot(HaveOccurred()) - }() - - // start the client - addr := <-serverAddr - sess, err := quic.DialAddr( - addr.String(), - &tls.Config{InsecureSkipVerify: true}, - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - close(handshakeChan) - str, err := sess.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - - buf := &bytes.Buffer{} - // measure the time it takes to download the dataLen bytes - // note we're measuring the time for the transfer, i.e. excluding the handshake - runtime := b.Time("transfer time", func() { - _, err := io.Copy(buf, str) - Expect(err).NotTo(HaveOccurred()) - }) - Expect(buf.Bytes()).To(Equal(data)) - - b.RecordValue("transfer rate [MB/s]", float64(dataLen)/1e6/runtime.Seconds()) - - ln.Close() - sess.Close() - }, samples) - }) - } - }) -} diff --git a/vendor/lucas-clemente/quic-go/buffer_pool_test.go b/vendor/lucas-clemente/quic-go/buffer_pool_test.go deleted file mode 100644 index 7413ceaf6..000000000 --- a/vendor/lucas-clemente/quic-go/buffer_pool_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package quic - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Buffer Pool", func() { - It("returns buffers of cap", func() { - buf := *getPacketBuffer() - Expect(buf).To(HaveCap(int(protocol.MaxReceivePacketSize))) - }) - - It("panics if wrong-sized buffers are passed", func() { - Expect(func() { - putPacketBuffer(&[]byte{0}) - }).To(Panic()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/client_test.go b/vendor/lucas-clemente/quic-go/client_test.go deleted file mode 100644 index ef39eec21..000000000 --- a/vendor/lucas-clemente/quic-go/client_test.go +++ /dev/null @@ -1,1030 +0,0 @@ -package quic - -import ( - "bytes" - "context" - "crypto/tls" - "errors" - "fmt" - "net" - "os" - "time" - - "github.com/bifurcation/mint" - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/handshake" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" - "github.com/lucas-clemente/quic-go/qerr" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Client", func() { - var ( - cl *client - packetConn *mockPacketConn - addr net.Addr - connID protocol.ConnectionID - mockMultiplexer *MockMultiplexer - origMultiplexer multiplexer - - supportedVersionsWithoutGQUIC44 []protocol.VersionNumber - - originalClientSessConstructor func(connection, sessionRunner, string, protocol.VersionNumber, protocol.ConnectionID, protocol.ConnectionID, *tls.Config, *Config, protocol.VersionNumber, []protocol.VersionNumber, utils.Logger) (quicSession, error) - ) - - // generate a packet sent by the server that accepts the QUIC version suggested by the client - acceptClientVersionPacket := func(connID protocol.ConnectionID) []byte { - b := &bytes.Buffer{} - err := (&wire.Header{ - DestConnectionID: connID, - PacketNumber: 1, - PacketNumberLen: 1, - }).Write(b, protocol.PerspectiveServer, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - return b.Bytes() - } - - composeVersionNegotiationPacket := func(connID protocol.ConnectionID, versions []protocol.VersionNumber) *receivedPacket { - return &receivedPacket{ - rcvTime: time.Now(), - header: &wire.Header{ - IsVersionNegotiation: true, - DestConnectionID: connID, - SupportedVersions: versions, - }, - } - } - - BeforeEach(func() { - connID = protocol.ConnectionID{0, 0, 0, 0, 0, 0, 0x13, 0x37} - originalClientSessConstructor = newClientSession - Eventually(areSessionsRunning).Should(BeFalse()) - // sess = NewMockQuicSession(mockCtrl) - addr = &net.UDPAddr{IP: net.IPv4(192, 168, 100, 200), Port: 1337} - packetConn = newMockPacketConn() - packetConn.addr = &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1234} - packetConn.dataReadFrom = addr - cl = &client{ - srcConnID: connID, - destConnID: connID, - version: protocol.SupportedVersions[0], - conn: &conn{pconn: packetConn, currentAddr: addr}, - logger: utils.DefaultLogger, - } - getMultiplexer() // make the sync.Once execute - // replace the clientMuxer. getClientMultiplexer will now return the MockMultiplexer - mockMultiplexer = NewMockMultiplexer(mockCtrl) - origMultiplexer = connMuxer - connMuxer = mockMultiplexer - for _, v := range protocol.SupportedVersions { - if v != protocol.Version44 { - supportedVersionsWithoutGQUIC44 = append(supportedVersionsWithoutGQUIC44, v) - } - } - Expect(supportedVersionsWithoutGQUIC44).ToNot(BeEmpty()) - }) - - AfterEach(func() { - connMuxer = origMultiplexer - newClientSession = originalClientSessConstructor - }) - - AfterEach(func() { - if s, ok := cl.session.(*session); ok { - s.Close() - } - Eventually(areSessionsRunning).Should(BeFalse()) - }) - - Context("Dialing", func() { - var origGenerateConnectionID func(int) (protocol.ConnectionID, error) - var origGenerateConnectionIDForInitial func() (protocol.ConnectionID, error) - - BeforeEach(func() { - origGenerateConnectionID = generateConnectionID - origGenerateConnectionIDForInitial = generateConnectionIDForInitial - generateConnectionID = func(int) (protocol.ConnectionID, error) { - return connID, nil - } - generateConnectionIDForInitial = func() (protocol.ConnectionID, error) { - return connID, nil - } - }) - - AfterEach(func() { - generateConnectionID = origGenerateConnectionID - generateConnectionIDForInitial = origGenerateConnectionIDForInitial - }) - - It("resolves the address", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(gomock.Any(), gomock.Any()) - mockMultiplexer.EXPECT().AddConn(gomock.Any(), gomock.Any()).Return(manager, nil) - - if os.Getenv("APPVEYOR") == "True" { - Skip("This test is flaky on AppVeyor.") - } - remoteAddrChan := make(chan string, 1) - newClientSession = func( - conn connection, - _ sessionRunner, - _ string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - remoteAddrChan <- conn.RemoteAddr().String() - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().run() - return sess, nil - } - _, err := DialAddr("localhost:17890", nil, &Config{HandshakeTimeout: time.Millisecond}) - Expect(err).ToNot(HaveOccurred()) - Eventually(remoteAddrChan).Should(Receive(Equal("127.0.0.1:17890"))) - }) - - It("uses the tls.Config.ServerName as the hostname, if present", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(gomock.Any(), gomock.Any()) - mockMultiplexer.EXPECT().AddConn(gomock.Any(), gomock.Any()).Return(manager, nil) - - hostnameChan := make(chan string, 1) - newClientSession = func( - _ connection, - _ sessionRunner, - h string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - hostnameChan <- h - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().run() - return sess, nil - } - _, err := DialAddr("localhost:17890", &tls.Config{ServerName: "foobar"}, nil) - Expect(err).ToNot(HaveOccurred()) - Eventually(hostnameChan).Should(Receive(Equal("foobar"))) - }) - - It("returns after the handshake is complete", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(gomock.Any(), gomock.Any()) - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - run := make(chan struct{}) - newClientSession = func( - _ connection, - runner sessionRunner, - _ string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().run().Do(func() { close(run) }) - runner.onHandshakeComplete(sess) - return sess, nil - } - s, err := Dial( - packetConn, - addr, - "quic.clemente.io:1337", - nil, - &Config{Versions: supportedVersionsWithoutGQUIC44}, - ) - Expect(err).ToNot(HaveOccurred()) - Expect(s).ToNot(BeNil()) - Eventually(run).Should(BeClosed()) - }) - - It("refuses to multiplex gQUIC 44", func() { - _, err := Dial( - packetConn, - addr, - "quic.clemente.io:1337", - nil, - &Config{Versions: []protocol.VersionNumber{protocol.Version44}}, - ) - Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("Cannot multiplex connections using gQUIC 44")) - }) - - It("returns an error that occurs while waiting for the connection to become secure", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(gomock.Any(), gomock.Any()) - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - testErr := errors.New("early handshake error") - newClientSession = func( - conn connection, - _ sessionRunner, - _ string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().run().Return(testErr) - return sess, nil - } - packetConn.dataToRead <- acceptClientVersionPacket(cl.srcConnID) - _, err := Dial( - packetConn, - addr, - "quic.clemente.io:1337", - nil, - &Config{Versions: supportedVersionsWithoutGQUIC44}, - ) - Expect(err).To(MatchError(testErr)) - }) - - It("closes the session when the context is canceled", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(gomock.Any(), gomock.Any()) - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - sessionRunning := make(chan struct{}) - defer close(sessionRunning) - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().run().Do(func() { - <-sessionRunning - }) - newClientSession = func( - conn connection, - _ sessionRunner, - _ string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - return sess, nil - } - ctx, cancel := context.WithCancel(context.Background()) - dialed := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := DialContext( - ctx, - packetConn, - addr, - "quic.clemnte.io:1337", - nil, - &Config{Versions: supportedVersionsWithoutGQUIC44}, - ) - Expect(err).To(MatchError(context.Canceled)) - close(dialed) - }() - Consistently(dialed).ShouldNot(BeClosed()) - sess.EXPECT().Close() - cancel() - Eventually(dialed).Should(BeClosed()) - }) - - It("removes closed sessions from the multiplexer", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(connID, gomock.Any()) - manager.EXPECT().Remove(connID) - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - var runner sessionRunner - sess := NewMockQuicSession(mockCtrl) - newClientSession = func( - conn connection, - runnerP sessionRunner, - _ string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - runner = runnerP - return sess, nil - } - sess.EXPECT().run().Do(func() { - runner.removeConnectionID(connID) - }) - - _, err := DialContext( - context.Background(), - packetConn, - addr, - "quic.clemnte.io:1337", - nil, - &Config{Versions: supportedVersionsWithoutGQUIC44}, - ) - Expect(err).ToNot(HaveOccurred()) - }) - - It("closes the connection when it was created by DialAddr", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - mockMultiplexer.EXPECT().AddConn(gomock.Any(), gomock.Any()).Return(manager, nil) - manager.EXPECT().Add(gomock.Any(), gomock.Any()) - - var conn connection - run := make(chan struct{}) - sessionCreated := make(chan struct{}) - sess := NewMockQuicSession(mockCtrl) - newClientSession = func( - connP connection, - _ sessionRunner, - _ string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - conn = connP - close(sessionCreated) - return sess, nil - } - sess.EXPECT().run().Do(func() { - <-run - }) - - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := DialAddr("quic.clemente.io:1337", nil, nil) - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - - Eventually(sessionCreated).Should(BeClosed()) - - // check that the connection is not closed - Expect(conn.Write([]byte("foobar"))).To(Succeed()) - - close(run) - time.Sleep(50 * time.Millisecond) - // check that the connection is closed - err := conn.Write([]byte("foobar")) - Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("use of closed network connection")) - - Eventually(done).Should(BeClosed()) - }) - - Context("quic.Config", func() { - It("setups with the right values", func() { - config := &Config{ - HandshakeTimeout: 1337 * time.Minute, - IdleTimeout: 42 * time.Hour, - RequestConnectionIDOmission: true, - MaxIncomingStreams: 1234, - MaxIncomingUniStreams: 4321, - ConnectionIDLength: 13, - Versions: supportedVersionsWithoutGQUIC44, - } - c := populateClientConfig(config, false) - Expect(c.HandshakeTimeout).To(Equal(1337 * time.Minute)) - Expect(c.IdleTimeout).To(Equal(42 * time.Hour)) - Expect(c.RequestConnectionIDOmission).To(BeTrue()) - Expect(c.MaxIncomingStreams).To(Equal(1234)) - Expect(c.MaxIncomingUniStreams).To(Equal(4321)) - Expect(c.ConnectionIDLength).To(Equal(13)) - }) - - It("uses a 0 byte connection IDs if gQUIC 44 is supported", func() { - config := &Config{ - Versions: []protocol.VersionNumber{protocol.Version43, protocol.Version44}, - ConnectionIDLength: 13, - } - c := populateClientConfig(config, false) - Expect(c.Versions).To(Equal([]protocol.VersionNumber{protocol.Version43, protocol.Version44})) - Expect(c.ConnectionIDLength).To(BeZero()) - }) - - It("doesn't use 0-byte connection IDs when dialing an address", func() { - config := &Config{Versions: supportedVersionsWithoutGQUIC44} - c := populateClientConfig(config, false) - Expect(c.ConnectionIDLength).To(Equal(protocol.DefaultConnectionIDLength)) - }) - - It("errors when the Config contains an invalid version", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - version := protocol.VersionNumber(0x1234) - _, err := Dial(packetConn, nil, "localhost:1234", &tls.Config{}, &Config{Versions: []protocol.VersionNumber{version}}) - Expect(err).To(MatchError("0x1234 is not a valid QUIC version")) - }) - - It("disables bidirectional streams", func() { - config := &Config{ - MaxIncomingStreams: -1, - MaxIncomingUniStreams: 4321, - } - c := populateClientConfig(config, false) - Expect(c.MaxIncomingStreams).To(BeZero()) - Expect(c.MaxIncomingUniStreams).To(Equal(4321)) - }) - - It("disables unidirectional streams", func() { - config := &Config{ - MaxIncomingStreams: 1234, - MaxIncomingUniStreams: -1, - } - c := populateClientConfig(config, false) - Expect(c.MaxIncomingStreams).To(Equal(1234)) - Expect(c.MaxIncomingUniStreams).To(BeZero()) - }) - - It("uses 0-byte connection IDs when dialing an address", func() { - config := &Config{} - c := populateClientConfig(config, true) - Expect(c.ConnectionIDLength).To(BeZero()) - }) - - It("fills in default values if options are not set in the Config", func() { - c := populateClientConfig(&Config{}, false) - Expect(c.Versions).To(Equal(protocol.SupportedVersions)) - Expect(c.HandshakeTimeout).To(Equal(protocol.DefaultHandshakeTimeout)) - Expect(c.IdleTimeout).To(Equal(protocol.DefaultIdleTimeout)) - Expect(c.RequestConnectionIDOmission).To(BeFalse()) - }) - }) - - Context("gQUIC", func() { - It("errors if it can't create a session", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - testErr := errors.New("error creating session") - newClientSession = func( - _ connection, - _ sessionRunner, - _ string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - return nil, testErr - } - _, err := Dial( - packetConn, - addr, - "quic.clemente.io:1337", - nil, - &Config{Versions: supportedVersionsWithoutGQUIC44}, - ) - Expect(err).To(MatchError(testErr)) - }) - }) - - Context("IETF QUIC", func() { - It("creates new TLS sessions with the right parameters", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(connID, gomock.Any()) - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - config := &Config{Versions: []protocol.VersionNumber{protocol.VersionTLS}} - c := make(chan struct{}) - var cconn connection - var version protocol.VersionNumber - var conf *Config - newTLSClientSession = func( - connP connection, - _ sessionRunner, - tokenP []byte, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - configP *Config, - _ *mint.Config, - paramsChan <-chan handshake.TransportParameters, - _ protocol.PacketNumber, - _ utils.Logger, - versionP protocol.VersionNumber, - ) (quicSession, error) { - cconn = connP - version = versionP - conf = configP - close(c) - // TODO: check connection IDs? - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().run() - return sess, nil - } - _, err := Dial(packetConn, addr, "quic.clemente.io:1337", nil, config) - Expect(err).ToNot(HaveOccurred()) - Eventually(c).Should(BeClosed()) - Expect(cconn.(*conn).pconn).To(Equal(packetConn)) - Expect(version).To(Equal(config.Versions[0])) - Expect(conf.Versions).To(Equal(config.Versions)) - }) - - It("creates a new session when the server performs a retry", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(gomock.Any(), gomock.Any()).Do(func(id protocol.ConnectionID, handler packetHandler) { - go handler.handlePacket(&receivedPacket{ - header: &wire.Header{ - IsLongHeader: true, - Type: protocol.PacketTypeRetry, - Token: []byte("foobar"), - DestConnectionID: id, - OrigDestConnectionID: connID, - }, - }) - }) - manager.EXPECT().Add(gomock.Any(), gomock.Any()) - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - config := &Config{Versions: []protocol.VersionNumber{protocol.VersionTLS}} - cl.config = config - run1 := make(chan error) - sess1 := NewMockQuicSession(mockCtrl) - sess1.EXPECT().run().DoAndReturn(func() error { - return <-run1 - }) - sess1.EXPECT().destroy(errCloseSessionForRetry).Do(func(e error) { - run1 <- e - }) - sess2 := NewMockQuicSession(mockCtrl) - sess2.EXPECT().run() - sessions := make(chan quicSession, 2) - sessions <- sess1 - sessions <- sess2 - newTLSClientSession = func( - _ connection, - _ sessionRunner, - _ []byte, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *Config, - _ *mint.Config, - _ <-chan handshake.TransportParameters, - _ protocol.PacketNumber, - _ utils.Logger, - _ protocol.VersionNumber, - ) (quicSession, error) { - return <-sessions, nil - } - _, err := Dial(packetConn, addr, "quic.clemente.io:1337", nil, config) - Expect(err).ToNot(HaveOccurred()) - Expect(sessions).To(BeEmpty()) - }) - - It("only accepts 3 retries", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(gomock.Any(), gomock.Any()).Do(func(id protocol.ConnectionID, handler packetHandler) { - go handler.handlePacket(&receivedPacket{ - header: &wire.Header{ - IsLongHeader: true, - Type: protocol.PacketTypeRetry, - Token: []byte("foobar"), - SrcConnectionID: connID, - DestConnectionID: id, - OrigDestConnectionID: connID, - Version: protocol.VersionTLS, - }, - }) - }).AnyTimes() - manager.EXPECT().Add(gomock.Any(), gomock.Any()).AnyTimes() - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - config := &Config{Versions: []protocol.VersionNumber{protocol.VersionTLS}} - cl.config = config - - sessions := make(chan quicSession, protocol.MaxRetries+1) - for i := 0; i < protocol.MaxRetries+1; i++ { - run := make(chan error) - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().run().DoAndReturn(func() error { - return <-run - }) - sess.EXPECT().destroy(gomock.Any()).Do(func(e error) { - run <- e - }) - sessions <- sess - } - - newTLSClientSession = func( - _ connection, - _ sessionRunner, - _ []byte, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *Config, - _ *mint.Config, - _ <-chan handshake.TransportParameters, - _ protocol.PacketNumber, - _ utils.Logger, - _ protocol.VersionNumber, - ) (quicSession, error) { - return <-sessions, nil - } - _, err := Dial(packetConn, addr, "quic.clemente.io:1337", nil, config) - Expect(err).To(HaveOccurred()) - Expect(err.(qerr.ErrorCode)).To(Equal(qerr.CryptoTooManyRejects)) - Expect(sessions).To(BeEmpty()) - }) - }) - - Context("version negotiation", func() { - var origSupportedVersions []protocol.VersionNumber - - BeforeEach(func() { - origSupportedVersions = protocol.SupportedVersions - protocol.SupportedVersions = append(protocol.SupportedVersions, []protocol.VersionNumber{77, 78}...) - }) - - AfterEach(func() { - protocol.SupportedVersions = origSupportedVersions - }) - - It("returns an error that occurs during version negotiation", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(connID, gomock.Any()) - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - testErr := errors.New("early handshake error") - newClientSession = func( - conn connection, - _ sessionRunner, - _ string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - Expect(conn.Write([]byte("0 fake CHLO"))).To(Succeed()) - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().run().Return(testErr) - return sess, nil - } - _, err := Dial( - packetConn, - addr, - "quic.clemente.io:1337", - nil, - &Config{Versions: supportedVersionsWithoutGQUIC44}, - ) - Expect(err).To(MatchError(testErr)) - }) - - It("recognizes that a packet without VersionFlag means that the server accepted the suggested version", func() { - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().handlePacket(gomock.Any()) - cl.session = sess - cl.config = &Config{} - ph := &wire.Header{ - PacketNumber: 1, - PacketNumberLen: protocol.PacketNumberLen2, - DestConnectionID: connID, - SrcConnectionID: connID, - } - err := cl.handlePacketImpl(&receivedPacket{header: ph}) - Expect(err).ToNot(HaveOccurred()) - Expect(cl.versionNegotiated).To(BeTrue()) - }) - - It("changes the version after receiving a Version Negotiation Packet", func() { - phm := NewMockPacketHandlerManager(mockCtrl) - phm.EXPECT().Add(connID, gomock.Any()).Times(2) - cl.packetHandlers = phm - - version1 := protocol.Version39 - version2 := protocol.Version39 + 1 - Expect(version2.UsesTLS()).To(BeFalse()) - sess1 := NewMockQuicSession(mockCtrl) - run1 := make(chan struct{}) - sess1.EXPECT().run().Do(func() { <-run1 }).Return(errCloseSessionForNewVersion) - sess1.EXPECT().destroy(errCloseSessionForNewVersion).Do(func(error) { close(run1) }) - sess2 := NewMockQuicSession(mockCtrl) - sess2.EXPECT().run() - sessionChan := make(chan *MockQuicSession, 2) - sessionChan <- sess1 - sessionChan <- sess2 - newClientSession = func( - _ connection, - _ sessionRunner, - _ string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - return <-sessionChan, nil - } - - cl.config = &Config{Versions: []protocol.VersionNumber{version1, version2}} - dialed := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := cl.dial(context.Background()) - Expect(err).ToNot(HaveOccurred()) - close(dialed) - }() - Eventually(sessionChan).Should(HaveLen(1)) - cl.handlePacket(composeVersionNegotiationPacket(connID, []protocol.VersionNumber{version2})) - Eventually(sessionChan).Should(BeEmpty()) - }) - - It("only accepts one version negotiation packet", func() { - phm := NewMockPacketHandlerManager(mockCtrl) - phm.EXPECT().Add(connID, gomock.Any()).Times(2) - cl.packetHandlers = phm - version1 := protocol.Version39 - version2 := protocol.Version39 + 1 - version3 := protocol.Version39 + 2 - Expect(version2.UsesTLS()).To(BeFalse()) - Expect(version3.UsesTLS()).To(BeFalse()) - sess1 := NewMockQuicSession(mockCtrl) - run1 := make(chan struct{}) - sess1.EXPECT().run().Do(func() { <-run1 }).Return(errCloseSessionForNewVersion) - sess1.EXPECT().destroy(errCloseSessionForNewVersion).Do(func(error) { close(run1) }) - sess2 := NewMockQuicSession(mockCtrl) - sess2.EXPECT().run() - sessionChan := make(chan *MockQuicSession, 2) - sessionChan <- sess1 - sessionChan <- sess2 - newClientSession = func( - _ connection, - _ sessionRunner, - _ string, - _ protocol.VersionNumber, - _ protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - _ *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - return <-sessionChan, nil - } - - cl.config = &Config{Versions: []protocol.VersionNumber{version1, version2, version3}} - dialed := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := cl.dial(context.Background()) - Expect(err).ToNot(HaveOccurred()) - close(dialed) - }() - Eventually(sessionChan).Should(HaveLen(1)) - cl.handlePacket(composeVersionNegotiationPacket(connID, []protocol.VersionNumber{version2})) - Eventually(sessionChan).Should(BeEmpty()) - Expect(cl.version).To(Equal(version2)) - cl.handlePacket(composeVersionNegotiationPacket(connID, []protocol.VersionNumber{version3})) - Eventually(dialed).Should(BeClosed()) - Expect(cl.version).To(Equal(version2)) - }) - - It("errors if no matching version is found", func() { - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().destroy(qerr.InvalidVersion) - cl.session = sess - cl.config = &Config{Versions: protocol.SupportedVersions} - cl.handlePacket(composeVersionNegotiationPacket(connID, []protocol.VersionNumber{1})) - }) - - It("errors if the version is supported by quic-go, but disabled by the quic.Config", func() { - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().destroy(qerr.InvalidVersion) - cl.session = sess - v := protocol.VersionNumber(1234) - Expect(v).ToNot(Equal(cl.version)) - cl.config = &Config{Versions: protocol.SupportedVersions} - cl.handlePacket(composeVersionNegotiationPacket(connID, []protocol.VersionNumber{v})) - }) - - It("changes to the version preferred by the quic.Config", func() { - phm := NewMockPacketHandlerManager(mockCtrl) - cl.packetHandlers = phm - - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().destroy(errCloseSessionForNewVersion) - cl.session = sess - versions := []protocol.VersionNumber{1234, 4321} - cl.config = &Config{Versions: versions} - cl.handlePacket(composeVersionNegotiationPacket(connID, versions)) - Expect(cl.version).To(Equal(protocol.VersionNumber(1234))) - }) - - It("drops version negotiation packets that contain the offered version", func() { - cl.config = &Config{} - ver := cl.version - cl.handlePacket(composeVersionNegotiationPacket(connID, []protocol.VersionNumber{ver})) - Expect(cl.version).To(Equal(ver)) - }) - }) - }) - - It("tells its version", func() { - Expect(cl.version).ToNot(BeZero()) - Expect(cl.GetVersion()).To(Equal(cl.version)) - }) - - It("ignores packets with the wrong Long Header Type", func() { - cl.config = &Config{} - hdr := &wire.Header{ - IsLongHeader: true, - Type: protocol.PacketTypeInitial, - PayloadLen: 123, - SrcConnectionID: connID, - DestConnectionID: connID, - PacketNumberLen: protocol.PacketNumberLen1, - Version: versionIETFFrames, - } - err := cl.handlePacketImpl(&receivedPacket{ - remoteAddr: addr, - header: hdr, - data: make([]byte, 456), - }) - Expect(err).To(MatchError("Received unsupported packet type: Initial")) - }) - - It("ignores packets without connection id, if it didn't request connection id trunctation", func() { - cl.version = versionGQUICFrames - cl.session = NewMockQuicSession(mockCtrl) // don't EXPECT any handlePacket calls - cl.config = &Config{RequestConnectionIDOmission: false} - hdr := &wire.Header{ - IsPublicHeader: true, - PacketNumber: 1, - PacketNumberLen: 1, - } - err := cl.handlePacketImpl(&receivedPacket{ - remoteAddr: addr, - header: hdr, - }) - Expect(err).To(MatchError("received packet with truncated connection ID, but didn't request truncation")) - }) - - It("ignores packets with the wrong destination connection ID", func() { - cl.session = NewMockQuicSession(mockCtrl) // don't EXPECT any handlePacket calls - cl.version = versionIETFFrames - cl.config = &Config{RequestConnectionIDOmission: false} - connID2 := protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1} - Expect(connID).ToNot(Equal(connID2)) - hdr := &wire.Header{ - DestConnectionID: connID2, - SrcConnectionID: connID, - PacketNumber: 1, - PacketNumberLen: protocol.PacketNumberLen1, - Version: versionIETFFrames, - } - err := cl.handlePacketImpl(&receivedPacket{ - remoteAddr: addr, - header: hdr, - }) - Expect(err).To(MatchError(fmt.Sprintf("received a packet with an unexpected connection ID (0x0807060504030201, expected %s)", connID))) - }) - - It("creates new gQUIC sessions with the right parameters", func() { - manager := NewMockPacketHandlerManager(mockCtrl) - manager.EXPECT().Add(gomock.Any(), gomock.Any()) - mockMultiplexer.EXPECT().AddConn(packetConn, gomock.Any()).Return(manager, nil) - - c := make(chan struct{}) - var cconn connection - var hostname string - var version protocol.VersionNumber - var conf *Config - newClientSession = func( - connP connection, - _ sessionRunner, - hostnameP string, - versionP protocol.VersionNumber, - connIDP protocol.ConnectionID, - _ protocol.ConnectionID, - _ *tls.Config, - configP *Config, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (quicSession, error) { - cconn = connP - hostname = hostnameP - version = versionP - conf = configP - connID = connIDP - close(c) - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().run() - return sess, nil - } - - config := &Config{Versions: supportedVersionsWithoutGQUIC44} - _, err := Dial( - packetConn, - addr, - "quic.clemente.io:1337", - nil, - config, - ) - Expect(err).ToNot(HaveOccurred()) - Eventually(c).Should(BeClosed()) - Expect(cconn.(*conn).pconn).To(Equal(packetConn)) - Expect(hostname).To(Equal("quic.clemente.io")) - Expect(version).To(Equal(config.Versions[0])) - Expect(conf.Versions).To(Equal(config.Versions)) - }) - - Context("Public Reset handling", func() { - var ( - pr []byte - hdr *wire.Header - hdrLen int - ) - - BeforeEach(func() { - cl.config = &Config{} - - pr = wire.WritePublicReset(cl.destConnID, 1, 0) - r := bytes.NewReader(pr) - iHdr, err := wire.ParseInvariantHeader(r, 0) - Expect(err).ToNot(HaveOccurred()) - hdr, err = iHdr.Parse(r, protocol.PerspectiveServer, versionGQUICFrames) - Expect(err).ToNot(HaveOccurred()) - hdrLen = r.Len() - }) - - It("closes the session when receiving a Public Reset", func() { - cl.version = versionGQUICFrames - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().closeRemote(gomock.Any()).Do(func(err error) { - Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.PublicReset)) - }) - cl.session = sess - cl.handlePacketImpl(&receivedPacket{ - remoteAddr: addr, - header: hdr, - data: pr[len(pr)-hdrLen:], - }) - }) - - It("ignores Public Resets from the wrong remote address", func() { - cl.version = versionGQUICFrames - cl.session = NewMockQuicSession(mockCtrl) // don't EXPECT any calls - spoofedAddr := &net.UDPAddr{IP: net.IPv4(1, 2, 3, 4), Port: 5678} - err := cl.handlePacketImpl(&receivedPacket{ - remoteAddr: spoofedAddr, - header: hdr, - data: pr[len(pr)-hdrLen:], - }) - Expect(err).To(MatchError("Received a spoofed Public Reset")) - }) - - It("ignores unparseable Public Resets", func() { - cl.version = versionGQUICFrames - cl.session = NewMockQuicSession(mockCtrl) // don't EXPECT any calls - err := cl.handlePacketImpl(&receivedPacket{ - remoteAddr: addr, - header: hdr, - data: pr[len(pr)-hdrLen : len(pr)-5], // cut off the last 5 bytes - }) - Expect(err.Error()).To(ContainSubstring("Received a Public Reset. An error occurred parsing the packet")) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/conn_test.go b/vendor/lucas-clemente/quic-go/conn_test.go deleted file mode 100644 index f7e00cac9..000000000 --- a/vendor/lucas-clemente/quic-go/conn_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package quic - -import ( - "bytes" - "errors" - "net" - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type mockPacketConn struct { - addr net.Addr - dataToRead chan []byte - dataReadFrom net.Addr - readErr error - dataWritten bytes.Buffer - dataWrittenTo net.Addr - closed bool -} - -func newMockPacketConn() *mockPacketConn { - return &mockPacketConn{ - dataToRead: make(chan []byte, 1000), - } -} - -func (c *mockPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { - if c.readErr != nil { - return 0, nil, c.readErr - } - data, ok := <-c.dataToRead - if !ok { - return 0, nil, errors.New("connection closed") - } - n := copy(b, data) - return n, c.dataReadFrom, nil -} -func (c *mockPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { - c.dataWrittenTo = addr - return c.dataWritten.Write(b) -} -func (c *mockPacketConn) Close() error { - if !c.closed { - close(c.dataToRead) - } - c.closed = true - return nil -} -func (c *mockPacketConn) LocalAddr() net.Addr { return c.addr } -func (c *mockPacketConn) SetDeadline(t time.Time) error { panic("not implemented") } -func (c *mockPacketConn) SetReadDeadline(t time.Time) error { panic("not implemented") } -func (c *mockPacketConn) SetWriteDeadline(t time.Time) error { panic("not implemented") } - -var _ net.PacketConn = &mockPacketConn{} - -var _ = Describe("Connection", func() { - var c *conn - var packetConn *mockPacketConn - - BeforeEach(func() { - addr := &net.UDPAddr{ - IP: net.IPv4(192, 168, 100, 200), - Port: 1337, - } - packetConn = newMockPacketConn() - c = &conn{ - currentAddr: addr, - pconn: packetConn, - } - }) - - It("writes", func() { - err := c.Write([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - Expect(packetConn.dataWritten.Bytes()).To(Equal([]byte("foobar"))) - Expect(packetConn.dataWrittenTo.String()).To(Equal("192.168.100.200:1337")) - }) - - It("reads", func() { - packetConn.dataToRead <- []byte("foo") - packetConn.dataReadFrom = &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1336} - p := make([]byte, 10) - n, raddr, err := c.Read(p) - Expect(err).ToNot(HaveOccurred()) - Expect(raddr.String()).To(Equal("127.0.0.1:1336")) - Expect(n).To(Equal(3)) - Expect(p[0:3]).To(Equal([]byte("foo"))) - }) - - It("gets the remote address", func() { - Expect(c.RemoteAddr().String()).To(Equal("192.168.100.200:1337")) - }) - - It("gets the local address", func() { - addr := &net.UDPAddr{ - IP: net.IPv4(192, 168, 0, 1), - Port: 1234, - } - packetConn.addr = addr - Expect(c.LocalAddr()).To(Equal(addr)) - }) - - It("changes the remote address", func() { - addr := &net.UDPAddr{ - IP: net.IPv4(127, 0, 0, 1), - Port: 7331, - } - c.SetCurrentRemoteAddr(addr) - Expect(c.RemoteAddr().String()).To(Equal(addr.String())) - }) - - It("closes", func() { - err := c.Close() - Expect(err).ToNot(HaveOccurred()) - Expect(packetConn.closed).To(BeTrue()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/crypto_stream_test.go b/vendor/lucas-clemente/quic-go/crypto_stream_test.go deleted file mode 100644 index ce97e94ae..000000000 --- a/vendor/lucas-clemente/quic-go/crypto_stream_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package quic - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Crypto Stream", func() { - var ( - str *cryptoStreamImpl - mockSender *MockStreamSender - ) - - BeforeEach(func() { - mockSender = NewMockStreamSender(mockCtrl) - str = newCryptoStream(mockSender, nil, protocol.VersionWhatever).(*cryptoStreamImpl) - }) - - It("sets the read offset", func() { - str.setReadOffset(0x42) - Expect(str.receiveStream.readOffset).To(Equal(protocol.ByteCount(0x42))) - Expect(str.receiveStream.frameQueue.readPos).To(Equal(protocol.ByteCount(0x42))) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/example/Dockerfile b/vendor/lucas-clemente/quic-go/example/Dockerfile deleted file mode 100644 index d0723ee48..000000000 --- a/vendor/lucas-clemente/quic-go/example/Dockerfile +++ /dev/null @@ -1,9 +0,0 @@ -FROM scratch - -VOLUME /certs -VOLUME /www -EXPOSE 6121 - -ADD main /main - -CMD ["/main", "-bind=0.0.0.0", "-certpath=/certs/", "-www=/www"] diff --git a/vendor/lucas-clemente/quic-go/example/Readme.md b/vendor/lucas-clemente/quic-go/example/Readme.md deleted file mode 100644 index f87852332..000000000 --- a/vendor/lucas-clemente/quic-go/example/Readme.md +++ /dev/null @@ -1,7 +0,0 @@ -# About the certificate - -Yes, this folder contains a private key and a certificate for quic.clemente.io. - -Unfortunately we need a valid certificate for the integration tests with Chrome and `quic_client`. No important data is served on the "real" `quic.clemente.io` (only a test page), and the MITM problem is imho negligible. - -If you figure out a way to test with Chrome without having a cert and key here, let us now in an issue. diff --git a/vendor/lucas-clemente/quic-go/example/client/main.go b/vendor/lucas-clemente/quic-go/example/client/main.go deleted file mode 100644 index 23f045c84..000000000 --- a/vendor/lucas-clemente/quic-go/example/client/main.go +++ /dev/null @@ -1,66 +0,0 @@ -package main - -import ( - "bytes" - "flag" - "io" - "net/http" - "sync" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/h2quic" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -func main() { - verbose := flag.Bool("v", false, "verbose") - tls := flag.Bool("tls", false, "activate support for IETF QUIC (work in progress)") - flag.Parse() - urls := flag.Args() - - logger := utils.DefaultLogger - - if *verbose { - logger.SetLogLevel(utils.LogLevelDebug) - } else { - logger.SetLogLevel(utils.LogLevelInfo) - } - logger.SetLogTimeFormat("") - - versions := protocol.SupportedVersions - if *tls { - versions = append([]protocol.VersionNumber{protocol.VersionTLS}, versions...) - } - - roundTripper := &h2quic.RoundTripper{ - QuicConfig: &quic.Config{Versions: versions}, - } - defer roundTripper.Close() - hclient := &http.Client{ - Transport: roundTripper, - } - - var wg sync.WaitGroup - wg.Add(len(urls)) - for _, addr := range urls { - logger.Infof("GET %s", addr) - go func(addr string) { - rsp, err := hclient.Get(addr) - if err != nil { - panic(err) - } - logger.Infof("Got response for %s: %#v", addr, rsp) - - body := &bytes.Buffer{} - _, err = io.Copy(body, rsp.Body) - if err != nil { - panic(err) - } - logger.Infof("Request Body:") - logger.Infof("%s", body.Bytes()) - wg.Done() - }(addr) - } - wg.Wait() -} diff --git a/vendor/lucas-clemente/quic-go/example/echo/echo.go b/vendor/lucas-clemente/quic-go/example/echo/echo.go deleted file mode 100644 index 0f39c1270..000000000 --- a/vendor/lucas-clemente/quic-go/example/echo/echo.go +++ /dev/null @@ -1,105 +0,0 @@ -package main - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "encoding/pem" - "fmt" - "io" - "log" - "math/big" - - quic "github.com/lucas-clemente/quic-go" -) - -const addr = "localhost:4242" - -const message = "foobar" - -// We start a server echoing data on the first stream the client opens, -// then connect with a client, send the message, and wait for its receipt. -func main() { - go func() { log.Fatal(echoServer()) }() - - err := clientMain() - if err != nil { - panic(err) - } -} - -// Start a server that echos all data on the first stream opened by the client -func echoServer() error { - listener, err := quic.ListenAddr(addr, generateTLSConfig(), nil) - if err != nil { - return err - } - sess, err := listener.Accept() - if err != nil { - return err - } - stream, err := sess.AcceptStream() - if err != nil { - panic(err) - } - // Echo through the loggingWriter - _, err = io.Copy(loggingWriter{stream}, stream) - return err -} - -func clientMain() error { - session, err := quic.DialAddr(addr, &tls.Config{InsecureSkipVerify: true}, nil) - if err != nil { - return err - } - - stream, err := session.OpenStreamSync() - if err != nil { - return err - } - - fmt.Printf("Client: Sending '%s'\n", message) - _, err = stream.Write([]byte(message)) - if err != nil { - return err - } - - buf := make([]byte, len(message)) - _, err = io.ReadFull(stream, buf) - if err != nil { - return err - } - fmt.Printf("Client: Got '%s'\n", buf) - - return nil -} - -// A wrapper for io.Writer that also logs the message. -type loggingWriter struct{ io.Writer } - -func (w loggingWriter) Write(b []byte) (int, error) { - fmt.Printf("Server: Got '%s'\n", string(b)) - return w.Writer.Write(b) -} - -// Setup a bare-bones TLS config for the server -func generateTLSConfig() *tls.Config { - key, err := rsa.GenerateKey(rand.Reader, 1024) - if err != nil { - panic(err) - } - template := x509.Certificate{SerialNumber: big.NewInt(1)} - certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key) - if err != nil { - panic(err) - } - keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}) - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER}) - - tlsCert, err := tls.X509KeyPair(certPEM, keyPEM) - if err != nil { - panic(err) - } - return &tls.Config{Certificates: []tls.Certificate{tlsCert}} -} diff --git a/vendor/lucas-clemente/quic-go/example/fullchain.pem b/vendor/lucas-clemente/quic-go/example/fullchain.pem deleted file mode 100644 index 76c34db91..000000000 --- a/vendor/lucas-clemente/quic-go/example/fullchain.pem +++ /dev/null @@ -1,62 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIGCzCCBPOgAwIBAgISA6pwet1vq9IjS9ThcggZYGfyMA0GCSqGSIb3DQEBCwUA -MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD -ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0xODA2MDkwODI2MjVaFw0x -ODA5MDcwODI2MjVaMBsxGTAXBgNVBAMTEHF1aWMuY2xlbWVudGUuaW8wggEiMA0G -CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDqON9RKCMK4dHxLTLiv3n+b/v4KCbY -Fo38rxCcv4/qoWI1Zoz4XMyPnTZPrzVMz6rhDKWTve1v7g+itgQDp1OoRo5ihtqC -m9Dr1Ed+qb3hHtFRBBOTiWQy1Y0fvUDYGlSHQ4R7xXYVzCYkQ9zopqr2otJp/9ZA -1Yy3ATITSgcds9wJaAOpkSxCx+D7cqpGbaNtxogRZ4ZT1vVs3l7Kr26fvnALMM4K -nf2Rpq1ZjgPRoLNcfUWCZO7gr+VNCFaI2AQRaAzZkSXAk0B91waTtaFD87kYXl9Z -8Jgx1PhJnO8WBUz/7+OAO6M+kuT78e6FltMN004Q8WmuNww6PzmVwnmpAgMBAAGj -ggMYMIIDFDAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsG -AQUFBwMCMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFIs3yJaLnEw7MRtNf9EbzESy -TrHwMB8GA1UdIwQYMBaAFKhKamMEfd265tE5t6ZFZe/zqOyhMG8GCCsGAQUFBwEB -BGMwYTAuBggrBgEFBQcwAYYiaHR0cDovL29jc3AuaW50LXgzLmxldHNlbmNyeXB0 -Lm9yZzAvBggrBgEFBQcwAoYjaHR0cDovL2NlcnQuaW50LXgzLmxldHNlbmNyeXB0 -Lm9yZy8wGwYDVR0RBBQwEoIQcXVpYy5jbGVtZW50ZS5pbzCB/gYDVR0gBIH2MIHz -MAgGBmeBDAECATCB5gYLKwYBBAGC3xMBAQEwgdYwJgYIKwYBBQUHAgEWGmh0dHA6 -Ly9jcHMubGV0c2VuY3J5cHQub3JnMIGrBggrBgEFBQcCAjCBngyBm1RoaXMgQ2Vy -dGlmaWNhdGUgbWF5IG9ubHkgYmUgcmVsaWVkIHVwb24gYnkgUmVseWluZyBQYXJ0 -aWVzIGFuZCBvbmx5IGluIGFjY29yZGFuY2Ugd2l0aCB0aGUgQ2VydGlmaWNhdGUg -UG9saWN5IGZvdW5kIGF0IGh0dHBzOi8vbGV0c2VuY3J5cHQub3JnL3JlcG9zaXRv -cnkvMIIBBAYKKwYBBAHWeQIEAgSB9QSB8gDwAHYA23Sv7ssp7LH+yj5xbSzluaq7 -NveEcYPHXZ1PN7Yfv2QAAAFj495INQAABAMARzBFAiEApF0BFCWyGIUrJrsYuugt -tshGVdg2+7f6d4B1D/xF2s0CIGGsVL2nRlXJXrkk3aa83lH4HzP9vcQSnMFHdXOf -9XeZAHYAKTxRllTIOWW6qlD8WAfUt2+/WHopctykwwz05UVH9HgAAAFj495IQwAA -BAMARzBFAiEAkV4gbM6hucL7ZwqTzb5fKxYhk6WHr5y8pzClZD3qqv4CIBYH7MSA -P05CXv7tHiHEizIvhWJJvVa2E6XLjbDRQMnUMA0GCSqGSIb3DQEBCwUAA4IBAQA2 -CALjtlxGXkkfKsRgKDoPpzg/IAl7crq5OrGGwW/bxbeDeiRHVt0Hlhr+0XPYlh/A -m8qBlg7TMHJa2zIt7wkG/MX3d9bO2bxXxsdjfMXLtxQu7eZ5nzGuXL8WGnZwtSqz -M5pOF/AU1JQojIhehKCeqqUi5UobxXUm+9D6OVmr8s732X3n/TL6pgsWRhay9tjB -kdZ9TSe0tLYyXnbwHp0rgwNWOMMN1Tc+Fpqc8UlrCq5REb0bLIQ6A2IJH08MEPWG -ukXHPAaHLz9oB1emR3flCoMKB0KrXUpDFXemOIPN6QVBO16LNNuRffKwXnzp60+b -MoB4Krxrab7TzlfT+HnP ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/ -MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT -DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow -SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT -GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC -AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF -q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8 -SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0 -Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA -a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj -/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T -AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG -CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv -bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k -c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw -VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC -ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz -MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu -Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF -AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo -uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/ -wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu -X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG -PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6 -KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg== ------END CERTIFICATE----- diff --git a/vendor/lucas-clemente/quic-go/example/main.go b/vendor/lucas-clemente/quic-go/example/main.go deleted file mode 100644 index e83fb8703..000000000 --- a/vendor/lucas-clemente/quic-go/example/main.go +++ /dev/null @@ -1,174 +0,0 @@ -package main - -import ( - "crypto/md5" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "log" - "mime/multipart" - "net/http" - "path" - "runtime" - "strings" - "sync" - - _ "net/http/pprof" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/h2quic" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -type binds []string - -func (b binds) String() string { - return strings.Join(b, ",") -} - -func (b *binds) Set(v string) error { - *b = strings.Split(v, ",") - return nil -} - -// Size is needed by the /demo/upload handler to determine the size of the uploaded file -type Size interface { - Size() int64 -} - -func init() { - http.HandleFunc("/demo/tile", func(w http.ResponseWriter, r *http.Request) { - // Small 40x40 png - w.Write([]byte{ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, - 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x28, - 0x01, 0x03, 0x00, 0x00, 0x00, 0xb6, 0x30, 0x2a, 0x2e, 0x00, 0x00, 0x00, - 0x03, 0x50, 0x4c, 0x54, 0x45, 0x5a, 0xc3, 0x5a, 0xad, 0x38, 0xaa, 0xdb, - 0x00, 0x00, 0x00, 0x0b, 0x49, 0x44, 0x41, 0x54, 0x78, 0x01, 0x63, 0x18, - 0x61, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x01, 0xe2, 0xb8, 0x75, 0x22, 0x00, - 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, - }) - }) - - http.HandleFunc("/demo/tiles", func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "") - for i := 0; i < 200; i++ { - fmt.Fprintf(w, ``, i) - } - io.WriteString(w, "") - }) - - http.HandleFunc("/demo/echo", func(w http.ResponseWriter, r *http.Request) { - body, err := ioutil.ReadAll(r.Body) - if err != nil { - fmt.Printf("error reading body while handling /echo: %s\n", err.Error()) - } - w.Write(body) - }) - - // accept file uploads and return the MD5 of the uploaded file - // maximum accepted file size is 1 GB - http.HandleFunc("/demo/upload", func(w http.ResponseWriter, r *http.Request) { - if r.Method == http.MethodPost { - err := r.ParseMultipartForm(1 << 30) // 1 GB - if err == nil { - var file multipart.File - file, _, err = r.FormFile("uploadfile") - if err == nil { - var size int64 - if sizeInterface, ok := file.(Size); ok { - size = sizeInterface.Size() - b := make([]byte, size) - file.Read(b) - md5 := md5.Sum(b) - fmt.Fprintf(w, "%x", md5) - return - } - err = errors.New("couldn't get uploaded file size") - } - } - if err != nil { - utils.DefaultLogger.Infof("Error receiving upload: %#v", err) - } - } - io.WriteString(w, `
-
- -
`) - }) -} - -func getBuildDir() string { - _, filename, _, ok := runtime.Caller(0) - if !ok { - panic("Failed to get current frame") - } - - return path.Dir(filename) -} - -func main() { - // defer profile.Start().Stop() - go func() { - log.Println(http.ListenAndServe("localhost:6060", nil)) - }() - // runtime.SetBlockProfileRate(1) - - verbose := flag.Bool("v", false, "verbose") - bs := binds{} - flag.Var(&bs, "bind", "bind to") - certPath := flag.String("certpath", getBuildDir(), "certificate directory") - www := flag.String("www", "/var/www", "www data") - tcp := flag.Bool("tcp", false, "also listen on TCP") - tls := flag.Bool("tls", false, "activate support for IETF QUIC (work in progress)") - flag.Parse() - - logger := utils.DefaultLogger - - if *verbose { - logger.SetLogLevel(utils.LogLevelDebug) - } else { - logger.SetLogLevel(utils.LogLevelInfo) - } - logger.SetLogTimeFormat("") - - versions := protocol.SupportedVersions - if *tls { - versions = append([]protocol.VersionNumber{protocol.VersionTLS}, versions...) - } - - certFile := *certPath + "/fullchain.pem" - keyFile := *certPath + "/privkey.pem" - - http.Handle("/", http.FileServer(http.Dir(*www))) - - if len(bs) == 0 { - bs = binds{"localhost:6121"} - } - - var wg sync.WaitGroup - wg.Add(len(bs)) - for _, b := range bs { - bCap := b - go func() { - var err error - if *tcp { - err = h2quic.ListenAndServe(bCap, certFile, keyFile, nil) - } else { - server := h2quic.Server{ - Server: &http.Server{Addr: bCap}, - QuicConfig: &quic.Config{Versions: versions}, - } - err = server.ListenAndServeTLS(certFile, keyFile) - } - if err != nil { - fmt.Println(err) - } - wg.Done() - }() - } - wg.Wait() -} diff --git a/vendor/lucas-clemente/quic-go/example/privkey.pem b/vendor/lucas-clemente/quic-go/example/privkey.pem deleted file mode 100644 index 50681cfc3..000000000 --- a/vendor/lucas-clemente/quic-go/example/privkey.pem +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDqON9RKCMK4dHx -LTLiv3n+b/v4KCbYFo38rxCcv4/qoWI1Zoz4XMyPnTZPrzVMz6rhDKWTve1v7g+i -tgQDp1OoRo5ihtqCm9Dr1Ed+qb3hHtFRBBOTiWQy1Y0fvUDYGlSHQ4R7xXYVzCYk -Q9zopqr2otJp/9ZA1Yy3ATITSgcds9wJaAOpkSxCx+D7cqpGbaNtxogRZ4ZT1vVs -3l7Kr26fvnALMM4Knf2Rpq1ZjgPRoLNcfUWCZO7gr+VNCFaI2AQRaAzZkSXAk0B9 -1waTtaFD87kYXl9Z8Jgx1PhJnO8WBUz/7+OAO6M+kuT78e6FltMN004Q8WmuNww6 -PzmVwnmpAgMBAAECggEAAW7hpux48msZTsF5CzwisfTbdNRCEJZqvf4QOvVNGyFr -qWn8ONTQh5xtpaUrzVGD+SaLqNDDsCijvdohQih28ZOk8WNj2OK9L4Q3/8VoHQWE -QFunBwMTMuBtoaEV0XyvwbgfCmbV5yI9pYEoy9+hMisi4HUpSXJFDyWZudZ9Hqhl -FBf5UPxF1AjZViODVfnKkrWh85jaENyWjWrMEDSohzxP8IStFMK8E0feXaQb+G0f -uTelpG2JmVcO3xaYgtRVeS4p5liMQg5gE5oa2Jh7Vp3TwMhQVg0aLmslSLAYlPoh -hyBeOS3ucyFHoC/6Stnnx3jdOEf2lEUObJj3QVEeBQKBgQD3qptNY9R62UQFO8gT -pseEO5CAZRGuKG0VLPNqKKerYQreiT3xYOTPmwEy+xXzYV6DKHtlKDetHuOB862M -E1bKmjDedafQ3KMc4tywLW+U9I8GyooT8uoetzARzgoftRcMzdeu4fexWTsi+kOh -5/PeXUBnFph8E68nXHQR5+MWAwKBgQDyGnT9KUVuLvzrFAghe9Eu1iZJSDs/IrJj -we3XQ7loqMc/Qv34eVKATsgtb2cTSeTivQcSvQO+Uu9dgo17BoWAABDTaV8NAOZ6 -cV2kedrWnxaTRXzB6Z5EKLg+DOMTpCV4Nf3OwzGq/mnKAe8cNM/hS+8HcZywKwr2 -UwLKSq6n4wKBgQDXGUaOnVCSbZZlETnAz43i67ShvqXvY07yIDs8jRiqgLrm8b1p -oaS4JkCRXX8ABSYHtaYOAjLw2a3wVIn66WTsy6P74aWhga7szJ+tJ5kMfqal2Ey5 -7LSnfqRyIkeqqCXfyfsz+S+dyQjSZRdOS90C2Gyx2+8NfC8YeXSZhJM2rwKBgQDB -pL28G/2nsrejQ2N5fLKE9s6qwLZ6ukLbHasiCc5L0uuDQw8mZcvCSsE77iYQvILx -hGYa68oJugYw0hJdu4qeJe9PWbGoEfdHKlPPEZQjJB4Hb4XpB/YJ6FPtdZtPA3Tg -4LaAYYnhjhqJc+CPvAIl3vlyB8Je+h6LhTvvF6r5JwKBgHBkpQ2Y+N3dMgfE8T38 -+Vy+75i9ew3F0TB8o2MWJzYLYCzNLqrB4GkZieudoYP1Cmh50wYIifsk2zNpxOG0 -27tUfMxza4ITUfmtVHS22DGWCqb1TgfQt7jajdioK4TUOZFEmiQiOYMZoFMenbzZ -miz6s3fWx1/b3wNd1J5uV2QS ------END PRIVATE KEY----- diff --git a/vendor/lucas-clemente/quic-go/frame_sorter_test.go b/vendor/lucas-clemente/quic-go/frame_sorter_test.go deleted file mode 100644 index 9def2100a..000000000 --- a/vendor/lucas-clemente/quic-go/frame_sorter_test.go +++ /dev/null @@ -1,435 +0,0 @@ -package quic - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("STREAM frame sorter", func() { - var s *frameSorter - - checkGaps := func(expectedGaps []utils.ByteInterval) { - Expect(s.gaps.Len()).To(Equal(len(expectedGaps))) - var i int - for gap := s.gaps.Front(); gap != nil; gap = gap.Next() { - Expect(gap.Value).To(Equal(expectedGaps[i])) - i++ - } - } - - BeforeEach(func() { - s = newFrameSorter() - }) - - It("head returns nil when empty", func() { - Expect(s.Pop()).To(BeNil()) - }) - - Context("Push", func() { - It("inserts and pops a single frame", func() { - Expect(s.Push([]byte("foobar"), 0, false)).To(Succeed()) - data, fin := s.Pop() - Expect(data).To(Equal([]byte("foobar"))) - Expect(fin).To(BeFalse()) - Expect(s.Pop()).To(BeNil()) - }) - - It("inserts and pops two consecutive frame", func() { - Expect(s.Push([]byte("foo"), 0, false)).To(Succeed()) - Expect(s.Push([]byte("bar"), 3, false)).To(Succeed()) - data, fin := s.Pop() - Expect(data).To(Equal([]byte("foo"))) - Expect(fin).To(BeFalse()) - data, fin = s.Pop() - Expect(data).To(Equal([]byte("bar"))) - Expect(fin).To(BeFalse()) - Expect(s.Pop()).To(BeNil()) - }) - - It("ignores empty frames", func() { - Expect(s.Push(nil, 0, false)).To(Succeed()) - Expect(s.Pop()).To(BeNil()) - }) - - Context("FIN handling", func() { - It("saves a FIN at offset 0", func() { - Expect(s.Push(nil, 0, true)).To(Succeed()) - data, fin := s.Pop() - Expect(data).To(BeEmpty()) - Expect(fin).To(BeTrue()) - data, fin = s.Pop() - Expect(data).To(BeNil()) - Expect(fin).To(BeTrue()) - }) - - It("saves a FIN frame at non-zero offset", func() { - Expect(s.Push([]byte("foobar"), 0, true)).To(Succeed()) - data, fin := s.Pop() - Expect(data).To(Equal([]byte("foobar"))) - Expect(fin).To(BeTrue()) - data, fin = s.Pop() - Expect(data).To(BeNil()) - Expect(fin).To(BeTrue()) - }) - - It("sets the FIN if a stream is closed after receiving some data", func() { - Expect(s.Push([]byte("foobar"), 0, false)).To(Succeed()) - Expect(s.Push(nil, 6, true)).To(Succeed()) - data, fin := s.Pop() - Expect(data).To(Equal([]byte("foobar"))) - Expect(fin).To(BeTrue()) - data, fin = s.Pop() - Expect(data).To(BeNil()) - Expect(fin).To(BeTrue()) - }) - }) - - Context("Gap handling", func() { - It("finds the first gap", func() { - Expect(s.Push([]byte("foobar"), 10, false)).To(Succeed()) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 10}, - {Start: 16, End: protocol.MaxByteCount}, - }) - }) - - It("correctly sets the first gap for a frame with offset 0", func() { - Expect(s.Push([]byte("foobar"), 0, false)).To(Succeed()) - checkGaps([]utils.ByteInterval{ - {Start: 6, End: protocol.MaxByteCount}, - }) - }) - - It("finds the two gaps", func() { - Expect(s.Push([]byte("foobar"), 10, false)).To(Succeed()) - Expect(s.Push([]byte("foobar"), 20, false)).To(Succeed()) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 10}, - {Start: 16, End: 20}, - {Start: 26, End: protocol.MaxByteCount}, - }) - }) - - It("finds the two gaps in reverse order", func() { - Expect(s.Push([]byte("foobar"), 20, false)).To(Succeed()) - Expect(s.Push([]byte("foobar"), 10, false)).To(Succeed()) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 10}, - {Start: 16, End: 20}, - {Start: 26, End: protocol.MaxByteCount}, - }) - }) - - It("shrinks a gap when it is partially filled", func() { - Expect(s.Push([]byte("test"), 10, false)).To(Succeed()) - Expect(s.Push([]byte("foobar"), 4, false)).To(Succeed()) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 4}, - {Start: 14, End: protocol.MaxByteCount}, - }) - }) - - It("deletes a gap at the beginning, when it is filled", func() { - Expect(s.Push([]byte("test"), 6, false)).To(Succeed()) - Expect(s.Push([]byte("foobar"), 0, false)).To(Succeed()) - checkGaps([]utils.ByteInterval{ - {Start: 10, End: protocol.MaxByteCount}, - }) - }) - - It("deletes a gap in the middle, when it is filled", func() { - Expect(s.Push([]byte("test"), 0, false)).To(Succeed()) - Expect(s.Push([]byte("test2"), 10, false)).To(Succeed()) - Expect(s.Push([]byte("foobar"), 4, false)).To(Succeed()) - Expect(s.queue).To(HaveLen(3)) - checkGaps([]utils.ByteInterval{ - {Start: 15, End: protocol.MaxByteCount}, - }) - }) - - It("splits a gap into two", func() { - Expect(s.Push([]byte("test"), 100, false)).To(Succeed()) - Expect(s.Push([]byte("foobar"), 50, false)).To(Succeed()) - Expect(s.queue).To(HaveLen(2)) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 50}, - {Start: 56, End: 100}, - {Start: 104, End: protocol.MaxByteCount}, - }) - }) - - Context("Overlapping Stream Data detection", func() { - // create gaps: 0-5, 10-15, 20-25, 30-inf - BeforeEach(func() { - Expect(s.Push([]byte("12345"), 5, false)).To(Succeed()) - Expect(s.Push([]byte("12345"), 15, false)).To(Succeed()) - Expect(s.Push([]byte("12345"), 25, false)).To(Succeed()) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 5}, - {Start: 10, End: 15}, - {Start: 20, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("cuts a frame with offset 0 that overlaps at the end", func() { - Expect(s.Push([]byte("foobar"), 0, false)).To(Succeed()) - Expect(s.queue).To(HaveKey(protocol.ByteCount(0))) - Expect(s.queue[0]).To(Equal([]byte("fooba"))) - Expect(s.queue[0]).To(HaveCap(5)) - checkGaps([]utils.ByteInterval{ - {Start: 10, End: 15}, - {Start: 20, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("cuts a frame that overlaps at the end", func() { - // 4 to 7 - Expect(s.Push([]byte("foo"), 4, false)).To(Succeed()) - Expect(s.queue).To(HaveKey(protocol.ByteCount(4))) - Expect(s.queue[4]).To(Equal([]byte("f"))) - Expect(s.queue[4]).To(HaveCap(1)) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 4}, - {Start: 10, End: 15}, - {Start: 20, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("cuts a frame that completely fills a gap, but overlaps at the end", func() { - // 10 to 16 - Expect(s.Push([]byte("foobar"), 10, false)).To(Succeed()) - Expect(s.queue).To(HaveKey(protocol.ByteCount(10))) - Expect(s.queue[10]).To(Equal([]byte("fooba"))) - Expect(s.queue[10]).To(HaveCap(5)) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 5}, - {Start: 20, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("cuts a frame that overlaps at the beginning", func() { - // 8 to 14 - Expect(s.Push([]byte("foobar"), 8, false)).To(Succeed()) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(8))) - Expect(s.queue).To(HaveKey(protocol.ByteCount(10))) - Expect(s.queue[10]).To(Equal([]byte("obar"))) - Expect(s.queue[10]).To(HaveCap(4)) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 5}, - {Start: 14, End: 15}, - {Start: 20, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("processes a frame that overlaps at the beginning and at the end, starting in a gap", func() { - // 2 to 12 - Expect(s.Push([]byte("1234567890"), 2, false)).To(Succeed()) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(5))) - Expect(s.queue).To(HaveKey(protocol.ByteCount(2))) - Expect(s.queue[2]).To(Equal([]byte("1234567890"))) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 2}, - {Start: 12, End: 15}, - {Start: 20, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("processes a frame that overlaps at the beginning and at the end, starting in a gap, ending in data", func() { - // 2 to 17 - Expect(s.Push([]byte("123456789012345"), 2, false)).To(Succeed()) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(5))) - Expect(s.queue).To(HaveKey(protocol.ByteCount(2))) - Expect(s.queue[2]).To(Equal([]byte("1234567890123"))) - Expect(s.queue[2]).To(HaveCap(13)) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 2}, - {Start: 20, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("processes a frame that overlaps at the beginning and at the end, starting in a gap, ending in data", func() { - // 5 to 22 - Expect(s.Push([]byte("12345678901234567"), 5, false)).To(Succeed()) - Expect(s.queue).To(HaveKey(protocol.ByteCount(5))) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(15))) - Expect(s.queue[10]).To(Equal([]byte("678901234567"))) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 5}, - {Start: 22, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("processes a frame that closes multiple gaps", func() { - // 2 to 27 - Expect(s.Push(bytes.Repeat([]byte{'e'}, 25), 2, false)).To(Succeed()) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(5))) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(15))) - Expect(s.queue).To(HaveKey(protocol.ByteCount(25))) - Expect(s.queue).To(HaveKey(protocol.ByteCount(2))) - Expect(s.queue[2]).To(Equal(bytes.Repeat([]byte{'e'}, 23))) - Expect(s.queue[2]).To(HaveCap(23)) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 2}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("processes a frame that closes multiple gaps", func() { - // 5 to 27 - Expect(s.Push(bytes.Repeat([]byte{'d'}, 22), 5, false)).To(Succeed()) - Expect(s.queue).To(HaveKey(protocol.ByteCount(5))) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(15))) - Expect(s.queue).To(HaveKey(protocol.ByteCount(25))) - Expect(s.queue).To(HaveKey(protocol.ByteCount(10))) - Expect(s.queue[10]).To(Equal(bytes.Repeat([]byte{'d'}, 15))) - Expect(s.queue[10]).To(HaveCap(15)) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 5}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("processes a frame that covers multiple gaps and ends at the end of a gap", func() { - data := bytes.Repeat([]byte{'e'}, 14) - // 1 to 15 - Expect(s.Push(data, 1, false)).To(Succeed()) - Expect(s.queue).To(HaveKey(protocol.ByteCount(1))) - Expect(s.queue).To(HaveKey(protocol.ByteCount(15))) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(5))) - Expect(s.queue[1]).To(Equal(data)) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 1}, - {Start: 20, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("processes a frame that closes all gaps (except for the last one)", func() { - data := bytes.Repeat([]byte{'f'}, 32) - // 0 to 32 - Expect(s.Push(data, 0, false)).To(Succeed()) - Expect(s.queue).To(HaveLen(1)) - Expect(s.queue).To(HaveKey(protocol.ByteCount(0))) - Expect(s.queue[0]).To(Equal(data)) - checkGaps([]utils.ByteInterval{ - {Start: 32, End: protocol.MaxByteCount}, - }) - }) - - It("cuts a frame that overlaps at the beginning and at the end, starting in data already received", func() { - // 8 to 17 - Expect(s.Push([]byte("123456789"), 8, false)).To(Succeed()) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(8))) - Expect(s.queue).To(HaveKey(protocol.ByteCount(10))) - Expect(s.queue[10]).To(Equal([]byte("34567"))) - Expect(s.queue[10]).To(HaveCap(5)) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 5}, - {Start: 20, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - - It("cuts a frame that completely covers two gaps", func() { - // 10 to 20 - Expect(s.Push([]byte("1234567890"), 10, false)).To(Succeed()) - Expect(s.queue).To(HaveKey(protocol.ByteCount(10))) - Expect(s.queue[10]).To(Equal([]byte("12345"))) - Expect(s.queue[10]).To(HaveCap(5)) - checkGaps([]utils.ByteInterval{ - {Start: 0, End: 5}, - {Start: 20, End: 25}, - {Start: 30, End: protocol.MaxByteCount}, - }) - }) - }) - - Context("duplicate data", func() { - expectedGaps := []utils.ByteInterval{ - {Start: 5, End: 10}, - {Start: 15, End: protocol.MaxByteCount}, - } - - BeforeEach(func() { - // create gaps: 5-10, 15-inf - Expect(s.Push([]byte("12345"), 0, false)).To(Succeed()) - Expect(s.Push([]byte("12345"), 10, false)).To(Succeed()) - checkGaps(expectedGaps) - }) - - AfterEach(func() { - // check that the gaps were not modified - checkGaps(expectedGaps) - }) - - It("does not modify data when receiving a duplicate", func() { - err := s.push([]byte("fffff"), 0, false) - Expect(err).To(MatchError(errDuplicateStreamData)) - Expect(s.queue[0]).ToNot(Equal([]byte("fffff"))) - }) - - It("detects a duplicate frame that is smaller than the original, starting at the beginning", func() { - // 10 to 12 - err := s.push([]byte("12"), 10, false) - Expect(err).To(MatchError(errDuplicateStreamData)) - Expect(s.queue[10]).To(HaveLen(5)) - }) - - It("detects a duplicate frame that is smaller than the original, somewhere in the middle", func() { - // 1 to 4 - err := s.push([]byte("123"), 1, false) - Expect(err).To(MatchError(errDuplicateStreamData)) - Expect(s.queue[0]).To(HaveLen(5)) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(1))) - }) - - It("detects a duplicate frame that is smaller than the original, somewhere in the middle in the last block", func() { - // 11 to 14 - err := s.push([]byte("123"), 11, false) - Expect(err).To(MatchError(errDuplicateStreamData)) - Expect(s.queue[10]).To(HaveLen(5)) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(11))) - }) - - It("detects a duplicate frame that is smaller than the original, with aligned end in the last block", func() { - // 11 to 15 - err := s.push([]byte("1234"), 1, false) - Expect(err).To(MatchError(errDuplicateStreamData)) - Expect(s.queue[10]).To(HaveLen(5)) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(11))) - }) - - It("detects a duplicate frame that is smaller than the original, with aligned end", func() { - // 3 to 5 - err := s.push([]byte("12"), 3, false) - Expect(err).To(MatchError(errDuplicateStreamData)) - Expect(s.queue[0]).To(HaveLen(5)) - Expect(s.queue).ToNot(HaveKey(protocol.ByteCount(3))) - }) - }) - - Context("DoS protection", func() { - It("errors when too many gaps are created", func() { - for i := 0; i < protocol.MaxStreamFrameSorterGaps; i++ { - Expect(s.Push([]byte("foobar"), protocol.ByteCount(i*7), false)).To(Succeed()) - } - Expect(s.gaps.Len()).To(Equal(protocol.MaxStreamFrameSorterGaps)) - err := s.Push([]byte("foobar"), protocol.ByteCount(protocol.MaxStreamFrameSorterGaps*7)+100, false) - Expect(err).To(MatchError("Too many gaps in received data")) - }) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/h2quic/client_test.go b/vendor/lucas-clemente/quic-go/h2quic/client_test.go deleted file mode 100644 index d4732c633..000000000 --- a/vendor/lucas-clemente/quic-go/h2quic/client_test.go +++ /dev/null @@ -1,639 +0,0 @@ -package h2quic - -import ( - "bytes" - "compress/gzip" - "context" - "crypto/tls" - "errors" - "io" - "net/http" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/qerr" - - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Client", func() { - var ( - client *client - session *mockSession - headerStream *mockStream - req *http.Request - origDialAddr = dialAddr - ) - - injectResponse := func(id protocol.StreamID, rsp *http.Response) { - EventuallyWithOffset(0, func() bool { - client.mutex.Lock() - defer client.mutex.Unlock() - _, ok := client.responses[id] - return ok - }).Should(BeTrue()) - rspChan := client.responses[5] - ExpectWithOffset(0, rspChan).ToNot(BeClosed()) - rspChan <- rsp - } - - BeforeEach(func() { - origDialAddr = dialAddr - hostname := "quic.clemente.io:1337" - client = newClient(hostname, nil, &roundTripperOpts{}, nil, nil) - Expect(client.hostname).To(Equal(hostname)) - session = newMockSession() - session.ctx, session.ctxCancel = context.WithCancel(context.Background()) - client.session = session - - headerStream = newMockStream(3) - client.headerStream = headerStream - client.requestWriter = newRequestWriter(headerStream, utils.DefaultLogger) - var err error - req, err = http.NewRequest("GET", "https://localhost:1337", nil) - Expect(err).ToNot(HaveOccurred()) - }) - - AfterEach(func() { - dialAddr = origDialAddr - }) - - It("saves the TLS config", func() { - tlsConf := &tls.Config{InsecureSkipVerify: true} - client = newClient("", tlsConf, &roundTripperOpts{}, nil, nil) - Expect(client.tlsConf).To(Equal(tlsConf)) - }) - - It("saves the QUIC config", func() { - quicConf := &quic.Config{HandshakeTimeout: time.Nanosecond} - client = newClient("", &tls.Config{}, &roundTripperOpts{}, quicConf, nil) - Expect(client.config).To(Equal(quicConf)) - }) - - It("uses the default QUIC config if none is give", func() { - client = newClient("", &tls.Config{}, &roundTripperOpts{}, nil, nil) - Expect(client.config).ToNot(BeNil()) - Expect(client.config).To(Equal(defaultQuicConfig)) - }) - - It("adds the port to the hostname, if none is given", func() { - client = newClient("quic.clemente.io", nil, &roundTripperOpts{}, nil, nil) - Expect(client.hostname).To(Equal("quic.clemente.io:443")) - }) - - It("dials", func() { - client = newClient("localhost:1337", nil, &roundTripperOpts{}, nil, nil) - session.streamsToOpen = []quic.Stream{newMockStream(3), newMockStream(5)} - dialAddr = func(hostname string, _ *tls.Config, _ *quic.Config) (quic.Session, error) { - return session, nil - } - close(headerStream.unblockRead) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := client.RoundTrip(req) - Expect(err).ToNot(HaveOccurred()) - close(done) - // fmt.Println("done") - }() - Eventually(func() quic.Session { return client.session }).Should(Equal(session)) - // make the go routine return - injectResponse(5, &http.Response{}) - Eventually(done).Should(BeClosed()) - }) - - It("errors when dialing fails", func() { - testErr := errors.New("handshake error") - client = newClient("localhost:1337", nil, &roundTripperOpts{}, nil, nil) - dialAddr = func(hostname string, _ *tls.Config, _ *quic.Config) (quic.Session, error) { - return nil, testErr - } - _, err := client.RoundTrip(req) - Expect(err).To(MatchError(testErr)) - }) - - It("uses the custom dialer, if provided", func() { - var tlsCfg *tls.Config - var qCfg *quic.Config - session.streamsToOpen = []quic.Stream{newMockStream(3), newMockStream(5)} - dialer := func(_, _ string, tlsCfgP *tls.Config, cfg *quic.Config) (quic.Session, error) { - tlsCfg = tlsCfgP - qCfg = cfg - return session, nil - } - client = newClient("localhost:1337", nil, &roundTripperOpts{}, nil, dialer) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := client.RoundTrip(req) - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - Eventually(func() quic.Session { return client.session }).Should(Equal(session)) - Expect(qCfg).To(Equal(client.config)) - Expect(tlsCfg).To(Equal(client.tlsConf)) - // make the go routine return - injectResponse(5, &http.Response{}) - Eventually(done).Should(BeClosed()) - }) - - It("errors if it can't open a stream", func() { - testErr := errors.New("you shall not pass") - client = newClient("localhost:1337", nil, &roundTripperOpts{}, nil, nil) - session.streamOpenErr = testErr - dialAddr = func(hostname string, _ *tls.Config, _ *quic.Config) (quic.Session, error) { - return session, nil - } - _, err := client.RoundTrip(req) - Expect(err).To(MatchError(testErr)) - }) - - It("returns a request when dial fails", func() { - testErr := errors.New("dial error") - dialAddr = func(hostname string, _ *tls.Config, _ *quic.Config) (quic.Session, error) { - return nil, testErr - } - request, err := http.NewRequest("https", "https://quic.clemente.io:1337/file1.dat", nil) - Expect(err).ToNot(HaveOccurred()) - - done := make(chan struct{}) - go func() { - _, err := client.RoundTrip(request) - Expect(err).To(MatchError(testErr)) - close(done) - }() - _, err = client.RoundTrip(request) - Expect(err).To(MatchError(testErr)) - Eventually(done).Should(BeClosed()) - }) - - Context("Doing requests", func() { - var request *http.Request - var dataStream *mockStream - - getRequest := func(data []byte) *http2.MetaHeadersFrame { - r := bytes.NewReader(data) - decoder := hpack.NewDecoder(4096, func(hf hpack.HeaderField) {}) - h2framer := http2.NewFramer(nil, r) - frame, err := h2framer.ReadFrame() - Expect(err).ToNot(HaveOccurred()) - mhframe := &http2.MetaHeadersFrame{HeadersFrame: frame.(*http2.HeadersFrame)} - mhframe.Fields, err = decoder.DecodeFull(mhframe.HeadersFrame.HeaderBlockFragment()) - Expect(err).ToNot(HaveOccurred()) - return mhframe - } - - getHeaderFields := func(f *http2.MetaHeadersFrame) map[string]string { - fields := make(map[string]string) - for _, hf := range f.Fields { - fields[hf.Name] = hf.Value - } - return fields - } - - BeforeEach(func() { - var err error - dialAddr = func(hostname string, _ *tls.Config, _ *quic.Config) (quic.Session, error) { - return session, nil - } - dataStream = newMockStream(5) - session.streamsToOpen = []quic.Stream{headerStream, dataStream} - request, err = http.NewRequest("https", "https://quic.clemente.io:1337/file1.dat", nil) - Expect(err).ToNot(HaveOccurred()) - }) - - It("does a request", func() { - teapot := &http.Response{ - Status: "418 I'm a teapot", - StatusCode: 418, - } - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - rsp, err := client.RoundTrip(request) - Expect(err).ToNot(HaveOccurred()) - Expect(rsp).To(Equal(teapot)) - Expect(rsp.Body).To(Equal(dataStream)) - Expect(rsp.ContentLength).To(BeEquivalentTo(-1)) - Expect(rsp.Request).To(Equal(request)) - close(done) - }() - - Eventually(func() []byte { return headerStream.dataWritten.Bytes() }).ShouldNot(BeEmpty()) - injectResponse(5, teapot) - Expect(client.headerErrored).ToNot(BeClosed()) - Eventually(done).Should(BeClosed()) - }) - - It("errors if a request without a body is canceled", func() { - done := make(chan struct{}) - ctx, cancel := context.WithCancel(context.Background()) - go func() { - defer GinkgoRecover() - request = request.WithContext(ctx) - rsp, err := client.RoundTrip(request) - Expect(err).To(MatchError(context.Canceled)) - Expect(rsp).To(BeNil()) - close(done) - }() - - cancel() - Eventually(done).Should(BeClosed()) - Expect(dataStream.reset).To(BeTrue()) - Expect(dataStream.canceledWrite).To(BeTrue()) - Expect(client.headerErrored).ToNot(BeClosed()) - }) - - It("errors if a request with a body is canceled after the body is sent", func() { - done := make(chan struct{}) - ctx, cancel := context.WithCancel(context.Background()) - go func() { - defer GinkgoRecover() - request = request.WithContext(ctx) - request.Body = &mockBody{} - rsp, err := client.RoundTrip(request) - Expect(err).To(MatchError(context.Canceled)) - Expect(rsp).To(BeNil()) - close(done) - }() - - time.Sleep(10 * time.Millisecond) - cancel() - Eventually(done).Should(BeClosed()) - Expect(dataStream.reset).To(BeTrue()) - Expect(dataStream.canceledWrite).To(BeTrue()) - Expect(client.headerErrored).ToNot(BeClosed()) - }) - - It("errors if a request with a body is canceled before the body is sent", func() { - done := make(chan struct{}) - ctx, cancel := context.WithCancel(context.Background()) - go func() { - defer GinkgoRecover() - request = request.WithContext(ctx) - request.Body = &mockBody{} - cancel() - time.Sleep(10 * time.Millisecond) - rsp, err := client.RoundTrip(request) - Expect(err).To(MatchError(context.Canceled)) - Expect(rsp).To(BeNil()) - close(done) - }() - - Eventually(done).Should(BeClosed()) - Expect(dataStream.reset).To(BeTrue()) - Expect(dataStream.canceledWrite).To(BeTrue()) - Expect(client.headerErrored).ToNot(BeClosed()) - }) - - It("closes the quic client when encountering an error on the header stream", func() { - headerStream.dataToRead.Write(bytes.Repeat([]byte{0}, 100)) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - rsp, err := client.RoundTrip(request) - Expect(err).To(MatchError(client.headerErr)) - Expect(rsp).To(BeNil()) - close(done) - }() - - Eventually(done).Should(BeClosed()) - Expect(client.headerErr.ErrorCode).To(Equal(qerr.InvalidHeadersStreamData)) - Expect(client.session.(*mockSession).closedWithError).To(MatchError(client.headerErr)) - }) - - It("returns subsequent request if there was an error on the header stream before", func() { - session.streamsToOpen = []quic.Stream{headerStream, dataStream, newMockStream(7)} - headerStream.dataToRead.Write(bytes.Repeat([]byte{0}, 100)) - _, err := client.RoundTrip(request) - Expect(err).To(BeAssignableToTypeOf(&qerr.QuicError{})) - Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.InvalidHeadersStreamData)) - // now that the first request failed due to an error on the header stream, try another request - _, nextErr := client.RoundTrip(request) - Expect(nextErr).To(MatchError(err)) - }) - - It("blocks if no stream is available", func() { - session.streamsToOpen = []quic.Stream{headerStream, dataStream} - session.blockOpenStreamSync = true - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := client.RoundTrip(request) - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - - Consistently(done).ShouldNot(BeClosed()) - // make the go routine return - client.Close() - injectResponse(5, &http.Response{}) - Eventually(done).Should(BeClosed()) - }) - - Context("validating the address", func() { - It("refuses to do requests for the wrong host", func() { - req, err := http.NewRequest("https", "https://quic.clemente.io:1336/foobar.html", nil) - Expect(err).ToNot(HaveOccurred()) - _, err = client.RoundTrip(req) - Expect(err).To(MatchError("h2quic Client BUG: RoundTrip called for the wrong client (expected quic.clemente.io:1337, got quic.clemente.io:1336)")) - }) - - It("refuses to do plain HTTP requests", func() { - req, err := http.NewRequest("https", "http://quic.clemente.io:1337/foobar.html", nil) - Expect(err).ToNot(HaveOccurred()) - _, err = client.RoundTrip(req) - Expect(err).To(MatchError("quic http2: unsupported scheme")) - }) - - It("adds the port for request URLs without one", func() { - client = newClient("quic.clemente.io", nil, &roundTripperOpts{}, nil, nil) - req, err := http.NewRequest("https", "https://quic.clemente.io/foobar.html", nil) - Expect(err).ToNot(HaveOccurred()) - - done := make(chan struct{}) - // the client.RoundTrip will block, because the encryption level is still set to Unencrypted - go func() { - defer GinkgoRecover() - _, err := client.RoundTrip(req) - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - - Consistently(done).ShouldNot(BeClosed()) - // make the go routine return - injectResponse(5, &http.Response{}) - Eventually(done).Should(BeClosed()) - }) - }) - - It("sets the EndStream header for requests without a body", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - client.RoundTrip(request) - close(done) - }() - Eventually(func() []byte { return headerStream.dataWritten.Bytes() }).ShouldNot(BeNil()) - mhf := getRequest(headerStream.dataWritten.Bytes()) - Expect(mhf.HeadersFrame.StreamEnded()).To(BeTrue()) - // make the go routine return - injectResponse(5, &http.Response{}) - Eventually(done).Should(BeClosed()) - }) - - It("sets the EndStream header to false for requests with a body", func() { - request.Body = &mockBody{} - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - client.RoundTrip(request) - close(done) - }() - Eventually(func() []byte { return headerStream.dataWritten.Bytes() }).ShouldNot(BeNil()) - mhf := getRequest(headerStream.dataWritten.Bytes()) - Expect(mhf.HeadersFrame.StreamEnded()).To(BeFalse()) - // make the go routine return - injectResponse(5, &http.Response{}) - Eventually(done).Should(BeClosed()) - }) - - Context("requests containing a Body", func() { - var requestBody []byte - var response *http.Response - - BeforeEach(func() { - requestBody = []byte("request body") - body := &mockBody{} - body.SetData(requestBody) - request.Body = body - response = &http.Response{ - StatusCode: 200, - Header: http.Header{"Content-Length": []string{"1000"}}, - } - // fake a handshake - client.dialOnce.Do(func() {}) - session.streamsToOpen = []quic.Stream{dataStream} - }) - - It("sends a request", func() { - rspChan := make(chan *http.Response) - go func() { - defer GinkgoRecover() - rsp, err := client.RoundTrip(request) - Expect(err).ToNot(HaveOccurred()) - rspChan <- rsp - }() - injectResponse(5, response) - Eventually(rspChan).Should(Receive(Equal(response))) - Expect(dataStream.dataWritten.Bytes()).To(Equal(requestBody)) - Expect(dataStream.closed).To(BeTrue()) - Expect(request.Body.(*mockBody).closed).To(BeTrue()) - }) - - It("returns the error that occurred when reading the body", func() { - testErr := errors.New("testErr") - request.Body.(*mockBody).readErr = testErr - - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - rsp, err := client.RoundTrip(request) - Expect(err).To(MatchError(testErr)) - Expect(rsp).To(BeNil()) - close(done) - }() - Eventually(done).Should(BeClosed()) - Expect(request.Body.(*mockBody).closed).To(BeTrue()) - }) - - It("returns the error that occurred when closing the body", func() { - testErr := errors.New("testErr") - request.Body.(*mockBody).closeErr = testErr - - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - rsp, err := client.RoundTrip(request) - Expect(err).To(MatchError(testErr)) - Expect(rsp).To(BeNil()) - close(done) - }() - Eventually(done).Should(BeClosed()) - Expect(request.Body.(*mockBody).closed).To(BeTrue()) - }) - }) - - Context("gzip compression", func() { - var gzippedData []byte // a gzipped foobar - var response *http.Response - - BeforeEach(func() { - var b bytes.Buffer - w := gzip.NewWriter(&b) - w.Write([]byte("foobar")) - w.Close() - gzippedData = b.Bytes() - response = &http.Response{ - StatusCode: 200, - Header: http.Header{"Content-Length": []string{"1000"}}, - } - }) - - It("adds the gzip header to requests", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - rsp, err := client.RoundTrip(request) - Expect(err).ToNot(HaveOccurred()) - Expect(rsp).ToNot(BeNil()) - Expect(rsp.ContentLength).To(BeEquivalentTo(-1)) - Expect(rsp.Header.Get("Content-Encoding")).To(BeEmpty()) - Expect(rsp.Header.Get("Content-Length")).To(BeEmpty()) - data := make([]byte, 6) - _, err = io.ReadFull(rsp.Body, data) - Expect(err).ToNot(HaveOccurred()) - Expect(data).To(Equal([]byte("foobar"))) - close(done) - }() - - dataStream.dataToRead.Write(gzippedData) - response.Header.Add("Content-Encoding", "gzip") - injectResponse(5, response) - headers := getHeaderFields(getRequest(headerStream.dataWritten.Bytes())) - Expect(headers).To(HaveKeyWithValue("accept-encoding", "gzip")) - close(dataStream.unblockRead) - Eventually(done).Should(BeClosed()) - }) - - It("doesn't add gzip if the header disable it", func() { - client.opts.DisableCompression = true - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := client.RoundTrip(request) - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - - Eventually(func() []byte { return headerStream.dataWritten.Bytes() }).ShouldNot(BeEmpty()) - headers := getHeaderFields(getRequest(headerStream.dataWritten.Bytes())) - Expect(headers).ToNot(HaveKey("accept-encoding")) - // make the go routine return - injectResponse(5, &http.Response{}) - Eventually(done).Should(BeClosed()) - }) - - It("only decompresses the response if the response contains the right content-encoding header", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - rsp, err := client.RoundTrip(request) - Expect(err).ToNot(HaveOccurred()) - Expect(rsp).ToNot(BeNil()) - data := make([]byte, 11) - rsp.Body.Read(data) - Expect(rsp.ContentLength).ToNot(BeEquivalentTo(-1)) - Expect(data).To(Equal([]byte("not gzipped"))) - close(done) - }() - - dataStream.dataToRead.Write([]byte("not gzipped")) - injectResponse(5, response) - headers := getHeaderFields(getRequest(headerStream.dataWritten.Bytes())) - Expect(headers).To(HaveKeyWithValue("accept-encoding", "gzip")) - Eventually(done).Should(BeClosed()) - }) - - It("doesn't add the gzip header for requests that have the accept-enconding set", func() { - request.Header.Add("accept-encoding", "gzip") - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - rsp, err := client.RoundTrip(request) - Expect(err).ToNot(HaveOccurred()) - data := make([]byte, 12) - _, err = rsp.Body.Read(data) - Expect(err).ToNot(HaveOccurred()) - Expect(rsp.ContentLength).ToNot(BeEquivalentTo(-1)) - Expect(data).To(Equal([]byte("gzipped data"))) - close(done) - }() - - dataStream.dataToRead.Write([]byte("gzipped data")) - injectResponse(5, response) - headers := getHeaderFields(getRequest(headerStream.dataWritten.Bytes())) - Expect(headers).To(HaveKeyWithValue("accept-encoding", "gzip")) - Eventually(done).Should(BeClosed()) - }) - }) - - Context("handling the header stream", func() { - var h2framer *http2.Framer - - BeforeEach(func() { - h2framer = http2.NewFramer(&headerStream.dataToRead, nil) - client.responses[23] = make(chan *http.Response) - }) - - It("reads header values from a response", func() { - // Taken from https://http2.github.io/http2-spec/compression.html#request.examples.with.huffman.coding - data := []byte{0x48, 0x03, 0x33, 0x30, 0x32, 0x58, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x61, 0x1d, 0x4d, 0x6f, 0x6e, 0x2c, 0x20, 0x32, 0x31, 0x20, 0x4f, 0x63, 0x74, 0x20, 0x32, 0x30, 0x31, 0x33, 0x20, 0x32, 0x30, 0x3a, 0x31, 0x33, 0x3a, 0x32, 0x31, 0x20, 0x47, 0x4d, 0x54, 0x6e, 0x17, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d} - headerStream.dataToRead.Write([]byte{0x0, 0x0, byte(len(data)), 0x1, 0x5, 0x0, 0x0, 0x0, 23}) - headerStream.dataToRead.Write(data) - go client.handleHeaderStream() - var rsp *http.Response - Eventually(client.responses[23]).Should(Receive(&rsp)) - Expect(rsp).ToNot(BeNil()) - Expect(rsp.Proto).To(Equal("HTTP/2.0")) - Expect(rsp.ProtoMajor).To(BeEquivalentTo(2)) - Expect(rsp.StatusCode).To(BeEquivalentTo(302)) - Expect(rsp.Status).To(Equal("302 Found")) - Expect(rsp.Header).To(HaveKeyWithValue("Location", []string{"https://www.example.com"})) - Expect(rsp.Header).To(HaveKeyWithValue("Cache-Control", []string{"private"})) - }) - - It("errors if the H2 frame is not a HeadersFrame", func() { - h2framer.WritePing(true, [8]byte{0, 0, 0, 0, 0, 0, 0, 0}) - client.handleHeaderStream() - Eventually(client.headerErrored).Should(BeClosed()) - Expect(client.headerErr).To(MatchError(qerr.Error(qerr.InvalidHeadersStreamData, "not a headers frame"))) - }) - - It("errors if it can't read the HPACK encoded header fields", func() { - h2framer.WriteHeaders(http2.HeadersFrameParam{ - StreamID: 23, - EndHeaders: true, - BlockFragment: []byte("invalid HPACK data"), - }) - client.handleHeaderStream() - Eventually(client.headerErrored).Should(BeClosed()) - Expect(client.headerErr.ErrorCode).To(Equal(qerr.InvalidHeadersStreamData)) - Expect(client.headerErr.ErrorMessage).To(ContainSubstring("cannot read header fields")) - }) - - It("errors if the stream cannot be found", func() { - var headers bytes.Buffer - enc := hpack.NewEncoder(&headers) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - err := h2framer.WriteHeaders(http2.HeadersFrameParam{ - StreamID: 1337, - EndHeaders: true, - BlockFragment: headers.Bytes(), - }) - Expect(err).ToNot(HaveOccurred()) - client.handleHeaderStream() - Eventually(client.headerErrored).Should(BeClosed()) - Expect(client.headerErr.ErrorCode).To(Equal(qerr.InvalidHeadersStreamData)) - Expect(client.headerErr.ErrorMessage).To(ContainSubstring("response channel for stream 1337 not found")) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/h2quic/h2quic_suite_test.go b/vendor/lucas-clemente/quic-go/h2quic/h2quic_suite_test.go deleted file mode 100644 index f0b265524..000000000 --- a/vendor/lucas-clemente/quic-go/h2quic/h2quic_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package h2quic - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestH2quic(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "H2quic Suite") -} diff --git a/vendor/lucas-clemente/quic-go/h2quic/request_body_test.go b/vendor/lucas-clemente/quic-go/h2quic/request_body_test.go deleted file mode 100644 index a12053bf5..000000000 --- a/vendor/lucas-clemente/quic-go/h2quic/request_body_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package h2quic - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Request body", func() { - var ( - stream *mockStream - rb *requestBody - ) - - BeforeEach(func() { - stream = &mockStream{} - stream.dataToRead.Write([]byte("foobar")) // provides data to be read - rb = newRequestBody(stream) - }) - - It("reads from the stream", func() { - b := make([]byte, 10) - n, _ := stream.Read(b) - Expect(n).To(Equal(6)) - Expect(b[0:6]).To(Equal([]byte("foobar"))) - }) - - It("saves if the stream was read from", func() { - Expect(rb.requestRead).To(BeFalse()) - rb.Read(make([]byte, 1)) - Expect(rb.requestRead).To(BeTrue()) - }) - - It("doesn't close the stream when closing the request body", func() { - Expect(stream.closed).To(BeFalse()) - err := rb.Close() - Expect(err).ToNot(HaveOccurred()) - Expect(stream.closed).To(BeFalse()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/h2quic/request_test.go b/vendor/lucas-clemente/quic-go/h2quic/request_test.go deleted file mode 100644 index 55085add3..000000000 --- a/vendor/lucas-clemente/quic-go/h2quic/request_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package h2quic - -import ( - "net/http" - "net/url" - - "golang.org/x/net/http2/hpack" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Request", func() { - It("populates request", func() { - headers := []hpack.HeaderField{ - {Name: ":path", Value: "/foo"}, - {Name: ":authority", Value: "quic.clemente.io"}, - {Name: ":method", Value: "GET"}, - {Name: "content-length", Value: "42"}, - } - req, err := requestFromHeaders(headers) - Expect(err).NotTo(HaveOccurred()) - Expect(req.Method).To(Equal("GET")) - Expect(req.URL.Path).To(Equal("/foo")) - Expect(req.Proto).To(Equal("HTTP/2.0")) - Expect(req.ProtoMajor).To(Equal(2)) - Expect(req.ProtoMinor).To(Equal(0)) - Expect(req.ContentLength).To(Equal(int64(42))) - Expect(req.Header).To(BeEmpty()) - Expect(req.Body).To(BeNil()) - Expect(req.Host).To(Equal("quic.clemente.io")) - Expect(req.RequestURI).To(Equal("/foo")) - Expect(req.TLS).ToNot(BeNil()) - }) - - It("concatenates the cookie headers", func() { - headers := []hpack.HeaderField{ - {Name: ":path", Value: "/foo"}, - {Name: ":authority", Value: "quic.clemente.io"}, - {Name: ":method", Value: "GET"}, - {Name: "cookie", Value: "cookie1=foobar1"}, - {Name: "cookie", Value: "cookie2=foobar2"}, - } - req, err := requestFromHeaders(headers) - Expect(err).NotTo(HaveOccurred()) - Expect(req.Header).To(Equal(http.Header{ - "Cookie": []string{"cookie1=foobar1; cookie2=foobar2"}, - })) - }) - - It("handles other headers", func() { - headers := []hpack.HeaderField{ - {Name: ":path", Value: "/foo"}, - {Name: ":authority", Value: "quic.clemente.io"}, - {Name: ":method", Value: "GET"}, - {Name: "cache-control", Value: "max-age=0"}, - {Name: "duplicate-header", Value: "1"}, - {Name: "duplicate-header", Value: "2"}, - } - req, err := requestFromHeaders(headers) - Expect(err).NotTo(HaveOccurred()) - Expect(req.Header).To(Equal(http.Header{ - "Cache-Control": []string{"max-age=0"}, - "Duplicate-Header": []string{"1", "2"}, - })) - }) - - It("errors with missing path", func() { - headers := []hpack.HeaderField{ - {Name: ":authority", Value: "quic.clemente.io"}, - {Name: ":method", Value: "GET"}, - } - _, err := requestFromHeaders(headers) - Expect(err).To(MatchError(":path, :authority and :method must not be empty")) - }) - - It("errors with missing method", func() { - headers := []hpack.HeaderField{ - {Name: ":path", Value: "/foo"}, - {Name: ":authority", Value: "quic.clemente.io"}, - } - _, err := requestFromHeaders(headers) - Expect(err).To(MatchError(":path, :authority and :method must not be empty")) - }) - - It("errors with missing authority", func() { - headers := []hpack.HeaderField{ - {Name: ":path", Value: "/foo"}, - {Name: ":method", Value: "GET"}, - } - _, err := requestFromHeaders(headers) - Expect(err).To(MatchError(":path, :authority and :method must not be empty")) - }) - - Context("extracting the hostname from a request", func() { - var url *url.URL - - BeforeEach(func() { - var err error - url, err = url.Parse("https://quic.clemente.io:1337") - Expect(err).ToNot(HaveOccurred()) - }) - - It("uses req.URL.Host", func() { - req := &http.Request{URL: url} - Expect(hostnameFromRequest(req)).To(Equal("quic.clemente.io:1337")) - }) - - It("uses req.URL.Host even if req.Host is available", func() { - req := &http.Request{ - Host: "www.example.org", - URL: url, - } - Expect(hostnameFromRequest(req)).To(Equal("quic.clemente.io:1337")) - }) - - It("returns an empty hostname if nothing is set", func() { - Expect(hostnameFromRequest(&http.Request{})).To(BeEmpty()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/h2quic/request_writer_test.go b/vendor/lucas-clemente/quic-go/h2quic/request_writer_test.go deleted file mode 100644 index 2b33fe7d5..000000000 --- a/vendor/lucas-clemente/quic-go/h2quic/request_writer_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package h2quic - -import ( - "bytes" - "net/http" - "net/url" - "strconv" - "strings" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Request", func() { - var ( - rw *requestWriter - headerStream *mockStream - decoder *hpack.Decoder - ) - - BeforeEach(func() { - headerStream = &mockStream{} - rw = newRequestWriter(headerStream, utils.DefaultLogger) - decoder = hpack.NewDecoder(4096, func(hf hpack.HeaderField) {}) - }) - - decode := func(p []byte) (*http2.HeadersFrame, map[string] /* HeaderField.Name */ string /* HeaderField.Value */) { - framer := http2.NewFramer(nil, bytes.NewReader(p)) - frame, err := framer.ReadFrame() - Expect(err).ToNot(HaveOccurred()) - headerFrame := frame.(*http2.HeadersFrame) - fields, err := decoder.DecodeFull(headerFrame.HeaderBlockFragment()) - Expect(err).ToNot(HaveOccurred()) - values := make(map[string]string) - for _, headerField := range fields { - values[headerField.Name] = headerField.Value - } - return headerFrame, values - } - - It("writes a GET request", func() { - req, err := http.NewRequest("GET", "https://quic.clemente.io/index.html?foo=bar", nil) - Expect(err).ToNot(HaveOccurred()) - rw.WriteRequest(req, 1337, true, false) - headerFrame, headerFields := decode(headerStream.dataWritten.Bytes()) - Expect(headerFrame.StreamID).To(Equal(uint32(1337))) - Expect(headerFrame.HasPriority()).To(BeTrue()) - Expect(headerFields).To(HaveKeyWithValue(":authority", "quic.clemente.io")) - Expect(headerFields).To(HaveKeyWithValue(":method", "GET")) - Expect(headerFields).To(HaveKeyWithValue(":path", "/index.html?foo=bar")) - Expect(headerFields).To(HaveKeyWithValue(":scheme", "https")) - Expect(headerFields).ToNot(HaveKey("accept-encoding")) - }) - - It("sets the EndStream header", func() { - req, err := http.NewRequest("GET", "https://quic.clemente.io/", nil) - Expect(err).ToNot(HaveOccurred()) - rw.WriteRequest(req, 1337, true, false) - headerFrame, _ := decode(headerStream.dataWritten.Bytes()) - Expect(headerFrame.StreamEnded()).To(BeTrue()) - }) - - It("doesn't set the EndStream header, if requested", func() { - req, err := http.NewRequest("GET", "https://quic.clemente.io/", nil) - Expect(err).ToNot(HaveOccurred()) - rw.WriteRequest(req, 1337, false, false) - headerFrame, _ := decode(headerStream.dataWritten.Bytes()) - Expect(headerFrame.StreamEnded()).To(BeFalse()) - }) - - It("requests gzip compression, if requested", func() { - req, err := http.NewRequest("GET", "https://quic.clemente.io/index.html?foo=bar", nil) - Expect(err).ToNot(HaveOccurred()) - rw.WriteRequest(req, 1337, true, true) - _, headerFields := decode(headerStream.dataWritten.Bytes()) - Expect(headerFields).To(HaveKeyWithValue("accept-encoding", "gzip")) - }) - - It("writes a POST request", func() { - form := url.Values{} - form.Add("foo", "bar") - req, err := http.NewRequest("POST", "https://quic.clemente.io/upload.html", strings.NewReader(form.Encode())) - Expect(err).ToNot(HaveOccurred()) - rw.WriteRequest(req, 5, true, false) - _, headerFields := decode(headerStream.dataWritten.Bytes()) - Expect(headerFields).To(HaveKeyWithValue(":method", "POST")) - Expect(headerFields).To(HaveKey("content-length")) - contentLength, err := strconv.Atoi(headerFields["content-length"]) - Expect(err).ToNot(HaveOccurred()) - Expect(contentLength).To(BeNumerically(">", 0)) - }) - - It("sends cookies", func() { - req, err := http.NewRequest("GET", "https://quic.clemente.io/", nil) - Expect(err).ToNot(HaveOccurred()) - cookie1 := &http.Cookie{ - Name: "Cookie #1", - Value: "Value #1", - } - cookie2 := &http.Cookie{ - Name: "Cookie #2", - Value: "Value #2", - } - req.AddCookie(cookie1) - req.AddCookie(cookie2) - rw.WriteRequest(req, 11, true, false) - _, headerFields := decode(headerStream.dataWritten.Bytes()) - // TODO(lclemente): Remove Or() once we drop support for Go 1.8. - Expect(headerFields).To(Or( - HaveKeyWithValue("cookie", "Cookie #1=Value #1; Cookie #2=Value #2"), - HaveKeyWithValue("cookie", `Cookie #1="Value #1"; Cookie #2="Value #2"`), - )) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/h2quic/response_writer_test.go b/vendor/lucas-clemente/quic-go/h2quic/response_writer_test.go deleted file mode 100644 index 77c67a93e..000000000 --- a/vendor/lucas-clemente/quic-go/h2quic/response_writer_test.go +++ /dev/null @@ -1,163 +0,0 @@ -package h2quic - -import ( - "bytes" - "context" - "io" - "net/http" - "sync" - "time" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type mockStream struct { - id protocol.StreamID - dataToRead bytes.Buffer - dataWritten bytes.Buffer - reset bool - canceledWrite bool - closed bool - remoteClosed bool - - unblockRead chan struct{} - ctx context.Context - ctxCancel context.CancelFunc -} - -var _ quic.Stream = &mockStream{} - -func newMockStream(id protocol.StreamID) *mockStream { - s := &mockStream{ - id: id, - unblockRead: make(chan struct{}), - } - s.ctx, s.ctxCancel = context.WithCancel(context.Background()) - return s -} - -func (s *mockStream) Close() error { s.closed = true; s.ctxCancel(); return nil } -func (s *mockStream) CancelRead(quic.ErrorCode) error { s.reset = true; return nil } -func (s *mockStream) CancelWrite(quic.ErrorCode) error { s.canceledWrite = true; return nil } -func (s *mockStream) CloseRemote(offset protocol.ByteCount) { s.remoteClosed = true; s.ctxCancel() } -func (s mockStream) StreamID() protocol.StreamID { return s.id } -func (s *mockStream) Context() context.Context { return s.ctx } -func (s *mockStream) SetDeadline(time.Time) error { panic("not implemented") } -func (s *mockStream) SetReadDeadline(time.Time) error { panic("not implemented") } -func (s *mockStream) SetWriteDeadline(time.Time) error { panic("not implemented") } - -func (s *mockStream) Read(p []byte) (int, error) { - n, _ := s.dataToRead.Read(p) - if n == 0 { // block if there's no data - <-s.unblockRead - return 0, io.EOF - } - return n, nil // never return an EOF -} -func (s *mockStream) Write(p []byte) (int, error) { return s.dataWritten.Write(p) } - -var _ = Describe("Response Writer", func() { - var ( - w *responseWriter - headerStream *mockStream - dataStream *mockStream - ) - - BeforeEach(func() { - headerStream = &mockStream{} - dataStream = &mockStream{} - w = newResponseWriter(headerStream, &sync.Mutex{}, dataStream, 5, utils.DefaultLogger) - }) - - decodeHeaderFields := func() map[string][]string { - fields := make(map[string][]string) - decoder := hpack.NewDecoder(4096, func(hf hpack.HeaderField) {}) - h2framer := http2.NewFramer(nil, bytes.NewReader(headerStream.dataWritten.Bytes())) - - frame, err := h2framer.ReadFrame() - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(BeAssignableToTypeOf(&http2.HeadersFrame{})) - hframe := frame.(*http2.HeadersFrame) - mhframe := &http2.MetaHeadersFrame{HeadersFrame: hframe} - Expect(mhframe.StreamID).To(BeEquivalentTo(5)) - mhframe.Fields, err = decoder.DecodeFull(hframe.HeaderBlockFragment()) - Expect(err).ToNot(HaveOccurred()) - for _, p := range mhframe.Fields { - fields[p.Name] = append(fields[p.Name], p.Value) - } - return fields - } - - It("writes status", func() { - w.WriteHeader(http.StatusTeapot) - fields := decodeHeaderFields() - Expect(fields).To(HaveLen(1)) - Expect(fields).To(HaveKeyWithValue(":status", []string{"418"})) - }) - - It("writes headers", func() { - w.Header().Add("content-length", "42") - w.WriteHeader(http.StatusTeapot) - fields := decodeHeaderFields() - Expect(fields).To(HaveKeyWithValue("content-length", []string{"42"})) - }) - - It("writes multiple headers with the same name", func() { - const cookie1 = "test1=1; Max-Age=7200; path=/" - const cookie2 = "test2=2; Max-Age=7200; path=/" - w.Header().Add("set-cookie", cookie1) - w.Header().Add("set-cookie", cookie2) - w.WriteHeader(http.StatusTeapot) - fields := decodeHeaderFields() - Expect(fields).To(HaveKey("set-cookie")) - cookies := fields["set-cookie"] - Expect(cookies).To(ContainElement(cookie1)) - Expect(cookies).To(ContainElement(cookie2)) - }) - - It("writes data", func() { - n, err := w.Write([]byte("foobar")) - Expect(n).To(Equal(6)) - Expect(err).ToNot(HaveOccurred()) - // Should have written 200 on the header stream - fields := decodeHeaderFields() - Expect(fields).To(HaveKeyWithValue(":status", []string{"200"})) - // And foobar on the data stream - Expect(dataStream.dataWritten.Bytes()).To(Equal([]byte("foobar"))) - }) - - It("writes data after WriteHeader is called", func() { - w.WriteHeader(http.StatusTeapot) - n, err := w.Write([]byte("foobar")) - Expect(n).To(Equal(6)) - Expect(err).ToNot(HaveOccurred()) - // Should have written 418 on the header stream - fields := decodeHeaderFields() - Expect(fields).To(HaveKeyWithValue(":status", []string{"418"})) - // And foobar on the data stream - Expect(dataStream.dataWritten.Bytes()).To(Equal([]byte("foobar"))) - }) - - It("does not WriteHeader() twice", func() { - w.WriteHeader(200) - w.WriteHeader(500) - fields := decodeHeaderFields() - Expect(fields).To(HaveLen(1)) - Expect(fields).To(HaveKeyWithValue(":status", []string{"200"})) - }) - - It("doesn't allow writes if the status code doesn't allow a body", func() { - w.WriteHeader(304) - n, err := w.Write([]byte("foobar")) - Expect(n).To(BeZero()) - Expect(err).To(MatchError(http.ErrBodyNotAllowed)) - Expect(dataStream.dataWritten.Bytes()).To(HaveLen(0)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/h2quic/roundtrip_test.go b/vendor/lucas-clemente/quic-go/h2quic/roundtrip_test.go deleted file mode 100644 index cec802f04..000000000 --- a/vendor/lucas-clemente/quic-go/h2quic/roundtrip_test.go +++ /dev/null @@ -1,218 +0,0 @@ -package h2quic - -import ( - "bytes" - "crypto/tls" - "errors" - "io" - "net/http" - "time" - - quic "github.com/lucas-clemente/quic-go" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type mockClient struct { - closed bool -} - -func (m *mockClient) RoundTrip(req *http.Request) (*http.Response, error) { - return &http.Response{Request: req}, nil -} -func (m *mockClient) Close() error { - m.closed = true - return nil -} - -var _ roundTripCloser = &mockClient{} - -type mockBody struct { - reader bytes.Reader - readErr error - closeErr error - closed bool -} - -func (m *mockBody) Read(p []byte) (int, error) { - if m.readErr != nil { - return 0, m.readErr - } - return m.reader.Read(p) -} - -func (m *mockBody) SetData(data []byte) { - m.reader = *bytes.NewReader(data) -} - -func (m *mockBody) Close() error { - m.closed = true - return m.closeErr -} - -// make sure the mockBody can be used as a http.Request.Body -var _ io.ReadCloser = &mockBody{} - -var _ = Describe("RoundTripper", func() { - var ( - rt *RoundTripper - req1 *http.Request - ) - - BeforeEach(func() { - rt = &RoundTripper{} - var err error - req1, err = http.NewRequest("GET", "https://www.example.org/file1.html", nil) - Expect(err).ToNot(HaveOccurred()) - }) - - Context("dialing hosts", func() { - origDialAddr := dialAddr - streamOpenErr := errors.New("error opening stream") - - BeforeEach(func() { - origDialAddr = dialAddr - dialAddr = func(addr string, tlsConf *tls.Config, config *quic.Config) (quic.Session, error) { - // return an error when trying to open a stream - // we don't want to test all the dial logic here, just that dialing happens at all - return &mockSession{streamOpenErr: streamOpenErr}, nil - } - }) - - AfterEach(func() { - dialAddr = origDialAddr - }) - - It("creates new clients", func() { - req, err := http.NewRequest("GET", "https://quic.clemente.io/foobar.html", nil) - Expect(err).ToNot(HaveOccurred()) - _, err = rt.RoundTrip(req) - Expect(err).To(MatchError(streamOpenErr)) - Expect(rt.clients).To(HaveLen(1)) - }) - - It("uses the quic.Config, if provided", func() { - config := &quic.Config{HandshakeTimeout: time.Millisecond} - var receivedConfig *quic.Config - dialAddr = func(addr string, tlsConf *tls.Config, config *quic.Config) (quic.Session, error) { - receivedConfig = config - return nil, errors.New("err") - } - rt.QuicConfig = config - rt.RoundTrip(req1) - Expect(receivedConfig).To(Equal(config)) - }) - - It("uses the custom dialer, if provided", func() { - var dialed bool - dialer := func(_, _ string, tlsCfgP *tls.Config, cfg *quic.Config) (quic.Session, error) { - dialed = true - return nil, errors.New("err") - } - rt.Dial = dialer - rt.RoundTrip(req1) - Expect(dialed).To(BeTrue()) - }) - - It("reuses existing clients", func() { - req, err := http.NewRequest("GET", "https://quic.clemente.io/file1.html", nil) - Expect(err).ToNot(HaveOccurred()) - _, err = rt.RoundTrip(req) - Expect(err).To(MatchError(streamOpenErr)) - Expect(rt.clients).To(HaveLen(1)) - req2, err := http.NewRequest("GET", "https://quic.clemente.io/file2.html", nil) - Expect(err).ToNot(HaveOccurred()) - _, err = rt.RoundTrip(req2) - Expect(err).To(MatchError(streamOpenErr)) - Expect(rt.clients).To(HaveLen(1)) - }) - - It("doesn't create new clients if RoundTripOpt.OnlyCachedConn is set", func() { - req, err := http.NewRequest("GET", "https://quic.clemente.io/foobar.html", nil) - Expect(err).ToNot(HaveOccurred()) - _, err = rt.RoundTripOpt(req, RoundTripOpt{OnlyCachedConn: true}) - Expect(err).To(MatchError(ErrNoCachedConn)) - }) - }) - - Context("validating request", func() { - It("rejects plain HTTP requests", func() { - req, err := http.NewRequest("GET", "http://www.example.org/", nil) - req.Body = &mockBody{} - Expect(err).ToNot(HaveOccurred()) - _, err = rt.RoundTrip(req) - Expect(err).To(MatchError("quic: unsupported protocol scheme: http")) - Expect(req.Body.(*mockBody).closed).To(BeTrue()) - }) - - It("rejects requests without a URL", func() { - req1.URL = nil - req1.Body = &mockBody{} - _, err := rt.RoundTrip(req1) - Expect(err).To(MatchError("quic: nil Request.URL")) - Expect(req1.Body.(*mockBody).closed).To(BeTrue()) - }) - - It("rejects request without a URL Host", func() { - req1.URL.Host = "" - req1.Body = &mockBody{} - _, err := rt.RoundTrip(req1) - Expect(err).To(MatchError("quic: no Host in request URL")) - Expect(req1.Body.(*mockBody).closed).To(BeTrue()) - }) - - It("doesn't try to close the body if the request doesn't have one", func() { - req1.URL = nil - Expect(req1.Body).To(BeNil()) - _, err := rt.RoundTrip(req1) - Expect(err).To(MatchError("quic: nil Request.URL")) - }) - - It("rejects requests without a header", func() { - req1.Header = nil - req1.Body = &mockBody{} - _, err := rt.RoundTrip(req1) - Expect(err).To(MatchError("quic: nil Request.Header")) - Expect(req1.Body.(*mockBody).closed).To(BeTrue()) - }) - - It("rejects requests with invalid header name fields", func() { - req1.Header.Add("foobär", "value") - _, err := rt.RoundTrip(req1) - Expect(err).To(MatchError("quic: invalid http header field name \"foobär\"")) - }) - - It("rejects requests with invalid header name values", func() { - req1.Header.Add("foo", string([]byte{0x7})) - _, err := rt.RoundTrip(req1) - Expect(err.Error()).To(ContainSubstring("quic: invalid http header field value")) - }) - - It("rejects requests with an invalid request method", func() { - req1.Method = "foobär" - req1.Body = &mockBody{} - _, err := rt.RoundTrip(req1) - Expect(err).To(MatchError("quic: invalid method \"foobär\"")) - Expect(req1.Body.(*mockBody).closed).To(BeTrue()) - }) - }) - - Context("closing", func() { - It("closes", func() { - rt.clients = make(map[string]roundTripCloser) - cl := &mockClient{} - rt.clients["foo.bar"] = cl - err := rt.Close() - Expect(err).ToNot(HaveOccurred()) - Expect(len(rt.clients)).To(BeZero()) - Expect(cl.closed).To(BeTrue()) - }) - - It("closes a RoundTripper that has never been used", func() { - Expect(len(rt.clients)).To(BeZero()) - err := rt.Close() - Expect(err).ToNot(HaveOccurred()) - Expect(len(rt.clients)).To(BeZero()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/h2quic/server_test.go b/vendor/lucas-clemente/quic-go/h2quic/server_test.go deleted file mode 100644 index 6125f2bce..000000000 --- a/vendor/lucas-clemente/quic-go/h2quic/server_test.go +++ /dev/null @@ -1,536 +0,0 @@ -package h2quic - -import ( - "bytes" - "context" - "crypto/tls" - "errors" - "fmt" - "io" - "net" - "net/http" - "strings" - "sync" - "time" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/qerr" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type mockSession struct { - closed bool - closedWithError error - dataStream quic.Stream - streamToAccept quic.Stream - streamsToOpen []quic.Stream - blockOpenStreamSync bool - blockOpenStreamChan chan struct{} // close this chan (or call Close) to make OpenStreamSync return - streamOpenErr error - ctx context.Context - ctxCancel context.CancelFunc -} - -func newMockSession() *mockSession { - return &mockSession{blockOpenStreamChan: make(chan struct{})} -} - -func (s *mockSession) GetOrOpenStream(id protocol.StreamID) (quic.Stream, error) { - return s.dataStream, nil -} -func (s *mockSession) AcceptStream() (quic.Stream, error) { return s.streamToAccept, nil } -func (s *mockSession) OpenStream() (quic.Stream, error) { - if s.streamOpenErr != nil { - return nil, s.streamOpenErr - } - str := s.streamsToOpen[0] - s.streamsToOpen = s.streamsToOpen[1:] - return str, nil -} -func (s *mockSession) OpenStreamSync() (quic.Stream, error) { - if s.blockOpenStreamSync { - <-s.blockOpenStreamChan - } - return s.OpenStream() -} -func (s *mockSession) Close() error { - s.ctxCancel() - if !s.closed { - close(s.blockOpenStreamChan) - } - s.closed = true - return nil -} -func (s *mockSession) CloseWithError(_ quic.ErrorCode, e error) error { - s.closedWithError = e - return s.Close() -} -func (s *mockSession) LocalAddr() net.Addr { - panic("not implemented") -} -func (s *mockSession) RemoteAddr() net.Addr { - return &net.UDPAddr{IP: []byte{127, 0, 0, 1}, Port: 42} -} -func (s *mockSession) Context() context.Context { - return s.ctx -} -func (s *mockSession) ConnectionState() quic.ConnectionState { panic("not implemented") } -func (s *mockSession) AcceptUniStream() (quic.ReceiveStream, error) { panic("not implemented") } -func (s *mockSession) OpenUniStream() (quic.SendStream, error) { panic("not implemented") } -func (s *mockSession) OpenUniStreamSync() (quic.SendStream, error) { panic("not implemented") } - -var _ = Describe("H2 server", func() { - var ( - s *Server - session *mockSession - dataStream *mockStream - origQuicListenAddr = quicListenAddr - ) - - BeforeEach(func() { - s = &Server{ - Server: &http.Server{ - TLSConfig: testdata.GetTLSConfig(), - }, - logger: utils.DefaultLogger, - } - dataStream = newMockStream(0) - close(dataStream.unblockRead) - session = newMockSession() - session.dataStream = dataStream - session.ctx, session.ctxCancel = context.WithCancel(context.Background()) - origQuicListenAddr = quicListenAddr - }) - - AfterEach(func() { - quicListenAddr = origQuicListenAddr - }) - - Context("handling requests", func() { - var ( - h2framer *http2.Framer - hpackDecoder *hpack.Decoder - headerStream *mockStream - ) - - BeforeEach(func() { - headerStream = &mockStream{} - hpackDecoder = hpack.NewDecoder(4096, nil) - h2framer = http2.NewFramer(nil, headerStream) - }) - - It("handles a sample GET request", func() { - var handlerCalled bool - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer GinkgoRecover() - Expect(r.Host).To(Equal("www.example.com")) - Expect(r.RemoteAddr).To(Equal("127.0.0.1:42")) - handlerCalled = true - }) - headerStream.dataToRead.Write([]byte{ - 0x0, 0x0, 0x11, 0x1, 0x5, 0x0, 0x0, 0x0, 0x5, - // Taken from https://http2.github.io/http2-spec/compression.html#request.examples.with.huffman.coding - 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, - }) - err := s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).NotTo(HaveOccurred()) - Eventually(func() bool { return handlerCalled }).Should(BeTrue()) - Expect(dataStream.remoteClosed).To(BeTrue()) - Expect(dataStream.reset).To(BeFalse()) - }) - - It("returns 200 with an empty handler", func() { - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - headerStream.dataToRead.Write([]byte{ - 0x0, 0x0, 0x11, 0x1, 0x5, 0x0, 0x0, 0x0, 0x5, - // Taken from https://http2.github.io/http2-spec/compression.html#request.examples.with.huffman.coding - 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, - }) - err := s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).NotTo(HaveOccurred()) - Eventually(func() []byte { - return headerStream.dataWritten.Bytes() - }).Should(Equal([]byte{0x0, 0x0, 0x1, 0x1, 0x4, 0x0, 0x0, 0x0, 0x5, 0x88})) // 0x88 is 200 - }) - - It("correctly handles a panicking handler", func() { - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - panic("foobar") - }) - headerStream.dataToRead.Write([]byte{ - 0x0, 0x0, 0x11, 0x1, 0x5, 0x0, 0x0, 0x0, 0x5, - // Taken from https://http2.github.io/http2-spec/compression.html#request.examples.with.huffman.coding - 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, - }) - err := s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).NotTo(HaveOccurred()) - Eventually(func() []byte { - return headerStream.dataWritten.Bytes() - }).Should(Equal([]byte{0x0, 0x0, 0x1, 0x1, 0x4, 0x0, 0x0, 0x0, 0x5, 0x8e})) // 0x82 is 500 - }) - - It("resets the dataStream when client sends a body in GET request", func() { - var handlerCalled bool - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - Expect(r.Host).To(Equal("www.example.com")) - handlerCalled = true - }) - headerStream.dataToRead.Write([]byte{ - 0x0, 0x0, 0x11, 0x1, 0x4, 0x0, 0x0, 0x0, 0x5, - // Taken from https://http2.github.io/http2-spec/compression.html#request.examples.with.huffman.coding - 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, - }) - err := s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).NotTo(HaveOccurred()) - Eventually(func() bool { return handlerCalled }).Should(BeTrue()) - Eventually(func() bool { return dataStream.reset }).Should(BeTrue()) - Expect(dataStream.remoteClosed).To(BeFalse()) - }) - - It("resets the dataStream when the body of POST request is not read", func() { - var handlerCalled bool - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - Expect(r.Host).To(Equal("www.example.com")) - Expect(r.Method).To(Equal("POST")) - handlerCalled = true - }) - headerStream.dataToRead.Write([]byte{0x0, 0x0, 0x20, 0x1, 0x24, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x0, 0xff, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, 0x83, 0x84, 0x87, 0x5c, 0x1, 0x37, 0x7a, 0x85, 0xed, 0x69, 0x88, 0xb4, 0xc7}) - err := s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).NotTo(HaveOccurred()) - Eventually(func() bool { return dataStream.reset }).Should(BeTrue()) - Consistently(func() bool { return dataStream.remoteClosed }).Should(BeFalse()) - Expect(handlerCalled).To(BeTrue()) - }) - - It("handles a request for which the client immediately resets the data stream", func() { - session.dataStream = nil - var handlerCalled bool - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - handlerCalled = true - }) - headerStream.dataToRead.Write([]byte{ - 0x0, 0x0, 0x11, 0x1, 0x5, 0x0, 0x0, 0x0, 0x5, - // Taken from https://http2.github.io/http2-spec/compression.html#request.examples.with.huffman.coding - 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, - }) - err := s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).NotTo(HaveOccurred()) - Consistently(func() bool { return handlerCalled }).Should(BeFalse()) - }) - - It("resets the dataStream when the body of POST request is not read, and the request handler replaces the request.Body", func() { - var handlerCalled bool - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - r.Body = struct { - io.Reader - io.Closer - }{} - handlerCalled = true - }) - headerStream.dataToRead.Write([]byte{0x0, 0x0, 0x20, 0x1, 0x24, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x0, 0xff, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, 0x83, 0x84, 0x87, 0x5c, 0x1, 0x37, 0x7a, 0x85, 0xed, 0x69, 0x88, 0xb4, 0xc7}) - err := s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).NotTo(HaveOccurred()) - Eventually(func() bool { return dataStream.reset }).Should(BeTrue()) - Consistently(func() bool { return dataStream.remoteClosed }).Should(BeFalse()) - Expect(handlerCalled).To(BeTrue()) - }) - - It("closes the dataStream if the body of POST request was read", func() { - var handlerCalled bool - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - Expect(r.Host).To(Equal("www.example.com")) - Expect(r.Method).To(Equal("POST")) - handlerCalled = true - // read the request body - b := make([]byte, 1000) - n, _ := r.Body.Read(b) - Expect(n).ToNot(BeZero()) - }) - headerStream.dataToRead.Write([]byte{0x0, 0x0, 0x20, 0x1, 0x24, 0x0, 0x0, 0x0, 0x5, 0x0, 0x0, 0x0, 0x0, 0xff, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, 0x83, 0x84, 0x87, 0x5c, 0x1, 0x37, 0x7a, 0x85, 0xed, 0x69, 0x88, 0xb4, 0xc7}) - dataStream.dataToRead.Write([]byte("foo=bar")) - err := s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).NotTo(HaveOccurred()) - Eventually(func() bool { return handlerCalled }).Should(BeTrue()) - Expect(dataStream.reset).To(BeFalse()) - }) - - It("ignores PRIORITY frames", func() { - handlerCalled := make(chan struct{}) - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - close(handlerCalled) - }) - buf := &bytes.Buffer{} - framer := http2.NewFramer(buf, nil) - err := framer.WritePriority(10, http2.PriorityParam{Weight: 42}) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).ToNot(BeEmpty()) - headerStream.dataToRead.Write(buf.Bytes()) - err = s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).ToNot(HaveOccurred()) - Consistently(handlerCalled).ShouldNot(BeClosed()) - Expect(dataStream.reset).To(BeFalse()) - Expect(dataStream.closed).To(BeFalse()) - }) - - It("errors when non-header frames are received", func() { - headerStream.dataToRead.Write([]byte{ - 0x0, 0x0, 0x06, 0x0, 0x0, 0x0, 0x0, 0x0, 0x5, - 'f', 'o', 'o', 'b', 'a', 'r', - }) - err := s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).To(MatchError("InvalidHeadersStreamData: expected a header frame")) - }) - - It("Cancels the request context when the datstream is closed", func() { - var handlerCalled bool - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer GinkgoRecover() - err := r.Context().Err() - Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(Equal("context canceled")) - handlerCalled = true - }) - headerStream.dataToRead.Write([]byte{ - 0x0, 0x0, 0x11, 0x1, 0x5, 0x0, 0x0, 0x0, 0x5, - // Taken from https://http2.github.io/http2-spec/compression.html#request.examples.with.huffman.coding - 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, - }) - dataStream.Close() - err := s.handleRequest(session, headerStream, &sync.Mutex{}, hpackDecoder, h2framer) - Expect(err).NotTo(HaveOccurred()) - Eventually(func() bool { return handlerCalled }).Should(BeTrue()) - Expect(dataStream.remoteClosed).To(BeTrue()) - Expect(dataStream.reset).To(BeFalse()) - }) - }) - - It("handles the header stream", func() { - var handlerCalled bool - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - Expect(r.Host).To(Equal("www.example.com")) - handlerCalled = true - }) - headerStream := &mockStream{id: 3} - headerStream.dataToRead.Write([]byte{ - 0x0, 0x0, 0x11, 0x1, 0x4, 0x0, 0x0, 0x0, 0x5, - // Taken from https://http2.github.io/http2-spec/compression.html#request.examples.with.huffman.coding - 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, - }) - session.streamToAccept = headerStream - go s.handleHeaderStream(session) - Eventually(func() bool { return handlerCalled }).Should(BeTrue()) - }) - - It("closes the connection if it encounters an error on the header stream", func() { - var handlerCalled bool - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - handlerCalled = true - }) - headerStream := &mockStream{id: 3} - headerStream.dataToRead.Write(bytes.Repeat([]byte{0}, 100)) - session.streamToAccept = headerStream - go s.handleHeaderStream(session) - Consistently(func() bool { return handlerCalled }).Should(BeFalse()) - Eventually(func() bool { return session.closed }).Should(BeTrue()) - Expect(session.closedWithError).To(MatchError(qerr.Error(qerr.HeadersStreamDataDecompressFailure, "cannot read frame"))) - }) - - It("supports closing after first request", func() { - s.CloseAfterFirstRequest = true - s.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - headerStream := &mockStream{id: 3} - headerStream.dataToRead.Write([]byte{ - 0x0, 0x0, 0x11, 0x1, 0x4, 0x0, 0x0, 0x0, 0x5, - // Taken from https://http2.github.io/http2-spec/compression.html#request.examples.with.huffman.coding - 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, - }) - session.streamToAccept = headerStream - Expect(session.closed).To(BeFalse()) - go s.handleHeaderStream(session) - Eventually(func() bool { return session.closed }).Should(BeTrue()) - }) - - It("uses the default handler as fallback", func() { - var handlerCalled bool - http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - Expect(r.Host).To(Equal("www.example.com")) - handlerCalled = true - })) - headerStream := &mockStream{id: 3} - headerStream.dataToRead.Write([]byte{ - 0x0, 0x0, 0x11, 0x1, 0x4, 0x0, 0x0, 0x0, 0x5, - // Taken from https://http2.github.io/http2-spec/compression.html#request.examples.with.huffman.coding - 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, - }) - session.streamToAccept = headerStream - go s.handleHeaderStream(session) - Eventually(func() bool { return handlerCalled }).Should(BeTrue()) - }) - - Context("setting http headers", func() { - var expected http.Header - - getExpectedHeader := func(versions []protocol.VersionNumber) http.Header { - var versionsAsString []string - for _, v := range versions { - versionsAsString = append(versionsAsString, v.ToAltSvc()) - } - return http.Header{ - "Alt-Svc": {fmt.Sprintf(`quic=":443"; ma=2592000; v="%s"`, strings.Join(versionsAsString, ","))}, - } - } - - BeforeEach(func() { - Expect(getExpectedHeader([]protocol.VersionNumber{99, 90, 9})).To(Equal(http.Header{"Alt-Svc": {`quic=":443"; ma=2592000; v="99,90,9"`}})) - expected = getExpectedHeader(protocol.SupportedVersions) - }) - - It("sets proper headers with numeric port", func() { - s.Server.Addr = ":443" - hdr := http.Header{} - err := s.SetQuicHeaders(hdr) - Expect(err).NotTo(HaveOccurred()) - Expect(hdr).To(Equal(expected)) - }) - - It("sets proper headers with full addr", func() { - s.Server.Addr = "127.0.0.1:443" - hdr := http.Header{} - err := s.SetQuicHeaders(hdr) - Expect(err).NotTo(HaveOccurred()) - Expect(hdr).To(Equal(expected)) - }) - - It("sets proper headers with string port", func() { - s.Server.Addr = ":https" - hdr := http.Header{} - err := s.SetQuicHeaders(hdr) - Expect(err).NotTo(HaveOccurred()) - Expect(hdr).To(Equal(expected)) - }) - - It("works multiple times", func() { - s.Server.Addr = ":https" - hdr := http.Header{} - err := s.SetQuicHeaders(hdr) - Expect(err).NotTo(HaveOccurred()) - Expect(hdr).To(Equal(expected)) - hdr = http.Header{} - err = s.SetQuicHeaders(hdr) - Expect(err).NotTo(HaveOccurred()) - Expect(hdr).To(Equal(expected)) - }) - }) - - It("should error when ListenAndServe is called with s.Server nil", func() { - err := (&Server{}).ListenAndServe() - Expect(err).To(MatchError("use of h2quic.Server without http.Server")) - }) - - It("should error when ListenAndServeTLS is called with s.Server nil", func() { - err := (&Server{}).ListenAndServeTLS(testdata.GetCertificatePaths()) - Expect(err).To(MatchError("use of h2quic.Server without http.Server")) - }) - - It("should nop-Close() when s.server is nil", func() { - err := (&Server{}).Close() - Expect(err).NotTo(HaveOccurred()) - }) - - It("errors when ListenAndServer is called after Close", func() { - serv := &Server{Server: &http.Server{}} - Expect(serv.Close()).To(Succeed()) - err := serv.ListenAndServe() - Expect(err).To(MatchError("Server is already closed")) - }) - - Context("ListenAndServe", func() { - BeforeEach(func() { - s.Server.Addr = "localhost:0" - }) - - AfterEach(func() { - Expect(s.Close()).To(Succeed()) - }) - - It("may only be called once", func() { - cErr := make(chan error) - for i := 0; i < 2; i++ { - go func() { - defer GinkgoRecover() - err := s.ListenAndServe() - if err != nil { - cErr <- err - } - }() - } - err := <-cErr - Expect(err).To(MatchError("ListenAndServe may only be called once")) - err = s.Close() - Expect(err).NotTo(HaveOccurred()) - }, 0.5) - - It("uses the quic.Config to start the quic server", func() { - conf := &quic.Config{HandshakeTimeout: time.Nanosecond} - var receivedConf *quic.Config - quicListenAddr = func(addr string, tlsConf *tls.Config, config *quic.Config) (quic.Listener, error) { - receivedConf = config - return nil, errors.New("listen err") - } - s.QuicConfig = conf - go s.ListenAndServe() - Eventually(func() *quic.Config { return receivedConf }).Should(Equal(conf)) - }) - }) - - Context("ListenAndServeTLS", func() { - BeforeEach(func() { - s.Server.Addr = "localhost:0" - }) - - AfterEach(func() { - err := s.Close() - Expect(err).NotTo(HaveOccurred()) - }) - - It("may only be called once", func() { - cErr := make(chan error) - for i := 0; i < 2; i++ { - go func() { - defer GinkgoRecover() - err := s.ListenAndServeTLS(testdata.GetCertificatePaths()) - if err != nil { - cErr <- err - } - }() - } - err := <-cErr - Expect(err).To(MatchError("ListenAndServe may only be called once")) - err = s.Close() - Expect(err).NotTo(HaveOccurred()) - }, 0.5) - }) - - It("closes gracefully", func() { - err := s.CloseGracefully(0) - Expect(err).NotTo(HaveOccurred()) - }) - - It("errors when listening fails", func() { - testErr := errors.New("listen error") - quicListenAddr = func(addr string, tlsConf *tls.Config, config *quic.Config) (quic.Listener, error) { - return nil, testErr - } - fullpem, privkey := testdata.GetCertificatePaths() - err := ListenAndServeQUIC("", fullpem, privkey, nil) - Expect(err).To(MatchError(testErr)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/chrome/chrome_suite_test.go b/vendor/lucas-clemente/quic-go/integrationtests/chrome/chrome_suite_test.go deleted file mode 100644 index d54edfd12..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/chrome/chrome_suite_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package chrome_test - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - "os/exec" - "runtime" - "strconv" - "strings" - "sync/atomic" - - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - - _ "github.com/lucas-clemente/quic-go/integrationtests/tools/testlog" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gexec" - - "testing" -) - -const ( - dataLen = 500 * 1024 // 500 KB - dataLongLen = 50 * 1024 * 1024 // 50 MB -) - -var ( - nFilesUploaded int32 // should be used atomically - doneCalled utils.AtomicBool -) - -func TestChrome(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Chrome Suite") -} - -func init() { - // Requires the len & num GET parameters, e.g. /uploadtest?len=100&num=1 - http.HandleFunc("/uploadtest", func(w http.ResponseWriter, r *http.Request) { - defer GinkgoRecover() - response := uploadHTML - response = strings.Replace(response, "LENGTH", r.URL.Query().Get("len"), -1) - response = strings.Replace(response, "NUM", r.URL.Query().Get("num"), -1) - _, err := io.WriteString(w, response) - Expect(err).NotTo(HaveOccurred()) - }) - - // Requires the len & num GET parameters, e.g. /downloadtest?len=100&num=1 - http.HandleFunc("/downloadtest", func(w http.ResponseWriter, r *http.Request) { - defer GinkgoRecover() - response := downloadHTML - response = strings.Replace(response, "LENGTH", r.URL.Query().Get("len"), -1) - response = strings.Replace(response, "NUM", r.URL.Query().Get("num"), -1) - _, err := io.WriteString(w, response) - Expect(err).NotTo(HaveOccurred()) - }) - - http.HandleFunc("/uploadhandler", func(w http.ResponseWriter, r *http.Request) { - defer GinkgoRecover() - - l, err := strconv.Atoi(r.URL.Query().Get("len")) - Expect(err).NotTo(HaveOccurred()) - - defer r.Body.Close() - actual, err := ioutil.ReadAll(r.Body) - Expect(err).NotTo(HaveOccurred()) - - Expect(bytes.Equal(actual, testserver.GeneratePRData(l))).To(BeTrue()) - - atomic.AddInt32(&nFilesUploaded, 1) - }) - - http.HandleFunc("/done", func(w http.ResponseWriter, r *http.Request) { - doneCalled.Set(true) - }) -} - -var _ = AfterEach(func() { - testserver.StopQuicServer() - - atomic.StoreInt32(&nFilesUploaded, 0) - doneCalled.Set(false) -}) - -func getChromePath() string { - if runtime.GOOS == "darwin" { - return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" - } - if path, err := exec.LookPath("google-chrome"); err == nil { - return path - } - if path, err := exec.LookPath("chromium-browser"); err == nil { - return path - } - Fail("No Chrome executable found.") - return "" -} - -func chromeTest(version protocol.VersionNumber, url string, blockUntilDone func()) { - userDataDir, err := ioutil.TempDir("", "quic-go-test-chrome-dir") - Expect(err).NotTo(HaveOccurred()) - defer os.RemoveAll(userDataDir) - path := getChromePath() - args := []string{ - "--disable-gpu", - "--no-first-run=true", - "--no-default-browser-check=true", - "--user-data-dir=" + userDataDir, - "--enable-quic=true", - "--no-proxy-server=true", - "--no-sandbox", - "--origin-to-force-quic-on=quic.clemente.io:443", - fmt.Sprintf(`--host-resolver-rules=MAP quic.clemente.io:443 127.0.0.1:%s`, testserver.Port()), - fmt.Sprintf("--quic-version=QUIC_VERSION_%s", version.ToAltSvc()), - url, - } - utils.DefaultLogger.Infof("Running chrome: %s '%s'", getChromePath(), strings.Join(args, "' '")) - command := exec.Command(path, args...) - session, err := gexec.Start(command, nil, nil) - Expect(err).NotTo(HaveOccurred()) - defer session.Kill() - blockUntilDone() -} - -func waitForDone() { - Eventually(func() bool { return doneCalled.Get() }, 60).Should(BeTrue()) -} - -func waitForNUploaded(expected int) func() { - return func() { - Eventually(func() int32 { - return atomic.LoadInt32(&nFilesUploaded) - }, 60).Should(BeEquivalentTo(expected)) - } -} - -const commonJS = ` -var buf = new ArrayBuffer(LENGTH); -var prng = new Uint8Array(buf); -var seed = 1; -for (var i = 0; i < LENGTH; i++) { - // https://en.wikipedia.org/wiki/Lehmer_random_number_generator - seed = seed * 48271 % 2147483647; - prng[i] = seed; -} -` - -const uploadHTML = ` - - - - - -` - -const downloadHTML = ` - - - - - -` diff --git a/vendor/lucas-clemente/quic-go/integrationtests/chrome/chrome_test.go b/vendor/lucas-clemente/quic-go/integrationtests/chrome/chrome_test.go deleted file mode 100644 index 60eb9e951..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/chrome/chrome_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package chrome_test - -import ( - "fmt" - - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - - . "github.com/onsi/ginkgo" -) - -var _ = Describe("Chrome tests", func() { - for i := range protocol.SupportedVersions { - version := protocol.SupportedVersions[i] - - // TODO: activate Chrome integration tests with gQUIC 44 - if version == protocol.Version44 { - continue - } - - Context(fmt.Sprintf("with version %s", version), func() { - JustBeforeEach(func() { - testserver.StartQuicServer([]protocol.VersionNumber{version}) - }) - - It("downloads a small file", func() { - chromeTest( - version, - fmt.Sprintf("https://quic.clemente.io/downloadtest?num=1&len=%d", dataLen), - waitForDone, - ) - }) - - It("downloads a large file", func() { - chromeTest( - version, - fmt.Sprintf("https://quic.clemente.io/downloadtest?num=1&len=%d", dataLongLen), - waitForDone, - ) - }) - - It("loads a large number of files", func() { - chromeTest( - version, - "https://quic.clemente.io/downloadtest?num=4&len=100", - waitForDone, - ) - }) - - It("uploads a small file", func() { - chromeTest( - version, - fmt.Sprintf("https://quic.clemente.io/uploadtest?num=1&len=%d", dataLen), - waitForNUploaded(1), - ) - }) - - It("uploads a large file", func() { - chromeTest( - version, - fmt.Sprintf("https://quic.clemente.io/uploadtest?num=1&len=%d", dataLongLen), - waitForNUploaded(1), - ) - }) - - It("uploads many small files", func() { - num := protocol.DefaultMaxIncomingStreams + 20 - chromeTest( - version, - fmt.Sprintf("https://quic.clemente.io/uploadtest?num=%d&len=%d", num, dataLen), - waitForNUploaded(num), - ) - }) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/gquic/drop_test.go b/vendor/lucas-clemente/quic-go/integrationtests/gquic/drop_test.go deleted file mode 100644 index 4bb7e51e3..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/gquic/drop_test.go +++ /dev/null @@ -1,137 +0,0 @@ -package gquic_test - -import ( - "bytes" - "fmt" - mrand "math/rand" - "os/exec" - "strconv" - - _ "github.com/lucas-clemente/quic-clients" // download clients - "github.com/lucas-clemente/quic-go/integrationtests/tools/proxy" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/gbytes" - . "github.com/onsi/gomega/gexec" -) - -var directions = []quicproxy.Direction{quicproxy.DirectionIncoming, quicproxy.DirectionOutgoing, quicproxy.DirectionBoth} - -var _ = Describe("Drop tests", func() { - var proxy *quicproxy.QuicProxy - - startProxy := func(dropCallback quicproxy.DropCallback, version protocol.VersionNumber) { - var err error - proxy, err = quicproxy.NewQuicProxy("localhost:0", version, &quicproxy.Opts{ - RemoteAddr: "localhost:" + testserver.Port(), - DropPacket: dropCallback, - }) - Expect(err).ToNot(HaveOccurred()) - } - - downloadFile := func(version protocol.VersionNumber) { - command := exec.Command( - clientPath, - "--quic-version="+version.ToAltSvc(), - "--host=127.0.0.1", - "--port="+strconv.Itoa(proxy.LocalPort()), - "https://quic.clemente.io/prdata", - ) - session, err := Start(command, nil, GinkgoWriter) - Expect(err).NotTo(HaveOccurred()) - defer session.Kill() - Eventually(session, 20).Should(Exit(0)) - Expect(bytes.Contains(session.Out.Contents(), testserver.PRData)).To(BeTrue()) - } - - downloadHello := func(version protocol.VersionNumber) { - command := exec.Command( - clientPath, - "--quic-version="+version.ToAltSvc(), - "--host=127.0.0.1", - "--port="+strconv.Itoa(proxy.LocalPort()), - "https://quic.clemente.io/hello", - ) - session, err := Start(command, nil, GinkgoWriter) - Expect(err).NotTo(HaveOccurred()) - defer session.Kill() - Eventually(session, 20).Should(Exit(0)) - Expect(session.Out).To(Say(":status 200")) - Expect(session.Out).To(Say("body: Hello, World!\n")) - } - - deterministicDropper := func(p, interval, dropInARow uint64) bool { - return (p % interval) < dropInARow - } - - stochasticDropper := func(freq int) bool { - return mrand.Int63n(int64(freq)) == 0 - } - - AfterEach(func() { - Expect(proxy.Close()).To(Succeed()) - }) - - for _, v := range protocol.SupportedVersions { - version := v - - Context(fmt.Sprintf("with QUIC version %s", version), func() { - Context("during the crypto handshake", func() { - for _, d := range directions { - direction := d - - It(fmt.Sprintf("establishes a connection when the first packet is lost in %s direction", d), func() { - startProxy(func(d quicproxy.Direction, p uint64) bool { - return p == 1 && d.Is(direction) - }, version) - downloadHello(version) - }) - - It(fmt.Sprintf("establishes a connection when the second packet is lost in %s direction", d), func() { - startProxy(func(d quicproxy.Direction, p uint64) bool { - return p == 2 && d.Is(direction) - }, version) - downloadHello(version) - }) - - It(fmt.Sprintf("establishes a connection when 1/5 of the packets are lost in %s direction", d), func() { - startProxy(func(d quicproxy.Direction, p uint64) bool { - return d.Is(direction) && stochasticDropper(5) - }, version) - downloadHello(version) - }) - } - }) - - Context("after the crypto handshake", func() { - for _, d := range directions { - direction := d - - It(fmt.Sprintf("downloads a file when every 5th packet is dropped in %s direction", d), func() { - startProxy(func(d quicproxy.Direction, p uint64) bool { - return p >= 10 && d.Is(direction) && deterministicDropper(p, 5, 1) - }, version) - downloadFile(version) - }) - - It(fmt.Sprintf("downloads a file when 1/5th of all packet are dropped randomly in %s direction", d), func() { - startProxy(func(d quicproxy.Direction, p uint64) bool { - return p >= 10 && d.Is(direction) && stochasticDropper(5) - }, version) - downloadFile(version) - }) - - It(fmt.Sprintf("downloads a file when 10 packets every 100 packet are dropped in %s direction", d), func() { - startProxy(func(d quicproxy.Direction, p uint64) bool { - return p >= 10 && d.Is(direction) && deterministicDropper(p, 100, 10) - }, version) - downloadFile(version) - }) - } - }) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/gquic/gquic_suite_test.go b/vendor/lucas-clemente/quic-go/integrationtests/gquic/gquic_suite_test.go deleted file mode 100644 index f8183fddf..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/gquic/gquic_suite_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package gquic_test - -import ( - "fmt" - "math/rand" - "path/filepath" - "runtime" - - _ "github.com/lucas-clemente/quic-go/integrationtests/tools/testlog" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -var ( - clientPath string - serverPath string -) - -func TestIntegration(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "GQuic Tests Suite") -} - -var _ = BeforeSuite(func() { - rand.Seed(GinkgoRandomSeed()) -}) - -var _ = JustBeforeEach(func() { - testserver.StartQuicServer(nil) -}) - -var _ = AfterEach(testserver.StopQuicServer) - -func init() { - _, thisfile, _, ok := runtime.Caller(0) - if !ok { - panic("Failed to get current path") - } - clientPath = filepath.Join(thisfile, fmt.Sprintf("../../../../quic-clients/client-%s-debug", runtime.GOOS)) - serverPath = filepath.Join(thisfile, fmt.Sprintf("../../../../quic-clients/server-%s-debug", runtime.GOOS)) -} diff --git a/vendor/lucas-clemente/quic-go/integrationtests/gquic/integration_test.go b/vendor/lucas-clemente/quic-go/integrationtests/gquic/integration_test.go deleted file mode 100644 index 595a55824..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/gquic/integration_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package gquic_test - -import ( - "bytes" - "fmt" - "os/exec" - "sync" - - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - - _ "github.com/lucas-clemente/quic-clients" // download clients - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/gbytes" - . "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Integration tests", func() { - for i := range protocol.SupportedVersions { - version := protocol.SupportedVersions[i] - - Context(fmt.Sprintf("with QUIC version %s", version), func() { - It("gets a simple file", func() { - command := exec.Command( - clientPath, - "--quic-version="+version.ToAltSvc(), - "--host=127.0.0.1", - "--port="+testserver.Port(), - "https://quic.clemente.io/hello", - ) - session, err := Start(command, nil, GinkgoWriter) - Expect(err).NotTo(HaveOccurred()) - defer session.Kill() - Eventually(session, 5).Should(Exit(0)) - Expect(session.Out).To(Say(":status 200")) - Expect(session.Out).To(Say("body: Hello, World!\n")) - }) - - It("posts and reads a body", func() { - command := exec.Command( - clientPath, - "--quic-version="+version.ToAltSvc(), - "--host=127.0.0.1", - "--port="+testserver.Port(), - "--body=foo", - "https://quic.clemente.io/echo", - ) - session, err := Start(command, nil, GinkgoWriter) - Expect(err).NotTo(HaveOccurred()) - defer session.Kill() - Eventually(session, 5).Should(Exit(0)) - Expect(session.Out).To(Say(":status 200")) - Expect(session.Out).To(Say("body: foo\n")) - }) - - It("gets a file", func() { - command := exec.Command( - clientPath, - "--quic-version="+version.ToAltSvc(), - "--host=127.0.0.1", - "--port="+testserver.Port(), - "https://quic.clemente.io/prdata", - ) - session, err := Start(command, nil, GinkgoWriter) - Expect(err).NotTo(HaveOccurred()) - defer session.Kill() - Eventually(session, 10).Should(Exit(0)) - Expect(bytes.Contains(session.Out.Contents(), testserver.PRData)).To(BeTrue()) - }) - - It("gets many copies of a file in parallel", func() { - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - defer wg.Done() - defer GinkgoRecover() - command := exec.Command( - clientPath, - "--quic-version="+version.ToAltSvc(), - "--host=127.0.0.1", - "--port="+testserver.Port(), - "https://quic.clemente.io/prdata", - ) - session, err := Start(command, nil, GinkgoWriter) - Expect(err).NotTo(HaveOccurred()) - defer session.Kill() - Eventually(session, 20).Should(Exit(0)) - Expect(bytes.Contains(session.Out.Contents(), testserver.PRData)).To(BeTrue()) - }() - } - wg.Wait() - }) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/gquic/random_rtt_test.go b/vendor/lucas-clemente/quic-go/integrationtests/gquic/random_rtt_test.go deleted file mode 100644 index f51aa8d1f..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/gquic/random_rtt_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package gquic_test - -import ( - "bytes" - "fmt" - "math/rand" - "os/exec" - "strconv" - "time" - - _ "github.com/lucas-clemente/quic-clients" // download clients - "github.com/lucas-clemente/quic-go/integrationtests/tools/proxy" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/gexec" -) - -// get a random duration between min and max -func getRandomDuration(min, max time.Duration) time.Duration { - return min + time.Duration(rand.Int63n(int64(max-min))) -} - -var _ = Describe("Random Duration Generator", func() { - It("gets a random RTT", func() { - var min time.Duration = time.Hour - var max time.Duration - - var sum time.Duration - rep := 10000 - for i := 0; i < rep; i++ { - val := getRandomDuration(100*time.Millisecond, 500*time.Millisecond) - sum += val - if val < min { - min = val - } - if val > max { - max = val - } - } - avg := sum / time.Duration(rep) - Expect(avg).To(BeNumerically("~", 300*time.Millisecond, 5*time.Millisecond)) - Expect(min).To(BeNumerically(">=", 100*time.Millisecond)) - Expect(min).To(BeNumerically("<", 105*time.Millisecond)) - Expect(max).To(BeNumerically(">", 495*time.Millisecond)) - Expect(max).To(BeNumerically("<=", 500*time.Millisecond)) - }) -}) - -var _ = Describe("Random RTT", func() { - var proxy *quicproxy.QuicProxy - - runRTTTest := func(minRtt, maxRtt time.Duration, version protocol.VersionNumber) { - var err error - proxy, err = quicproxy.NewQuicProxy("localhost:", version, &quicproxy.Opts{ - RemoteAddr: "localhost:" + testserver.Port(), - DelayPacket: func(_ quicproxy.Direction, _ uint64) time.Duration { - return getRandomDuration(minRtt, maxRtt) - }, - }) - Expect(err).ToNot(HaveOccurred()) - - command := exec.Command( - clientPath, - "--quic-version="+version.ToAltSvc(), - "--host=127.0.0.1", - "--port="+strconv.Itoa(proxy.LocalPort()), - "https://quic.clemente.io/prdata", - ) - - session, err := Start(command, nil, GinkgoWriter) - Expect(err).NotTo(HaveOccurred()) - defer session.Kill() - Eventually(session, 20).Should(Exit(0)) - Expect(bytes.Contains(session.Out.Contents(), testserver.PRData)).To(BeTrue()) - } - - AfterEach(func() { - err := proxy.Close() - Expect(err).ToNot(HaveOccurred()) - time.Sleep(time.Millisecond) - }) - - for i := range protocol.SupportedVersions { - version := protocol.SupportedVersions[i] - - Context(fmt.Sprintf("with QUIC version %s", version), func() { - It("gets a file a random RTT between 10ms and 30ms", func() { - runRTTTest(10*time.Millisecond, 30*time.Millisecond, version) - }) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/gquic/rtt_test.go b/vendor/lucas-clemente/quic-go/integrationtests/gquic/rtt_test.go deleted file mode 100644 index 669200ee8..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/gquic/rtt_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package gquic_test - -import ( - "bytes" - "fmt" - "os/exec" - "strconv" - "time" - - _ "github.com/lucas-clemente/quic-clients" // download clients - "github.com/lucas-clemente/quic-go/integrationtests/tools/proxy" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/gexec" -) - -var _ = Describe("non-zero RTT", func() { - var proxy *quicproxy.QuicProxy - - runRTTTest := func(rtt time.Duration, version protocol.VersionNumber) { - var err error - proxy, err = quicproxy.NewQuicProxy("localhost:", version, &quicproxy.Opts{ - RemoteAddr: "localhost:" + testserver.Port(), - DelayPacket: func(_ quicproxy.Direction, _ uint64) time.Duration { - return rtt / 2 - }, - }) - Expect(err).ToNot(HaveOccurred()) - - command := exec.Command( - clientPath, - "--quic-version="+version.ToAltSvc(), - "--host=127.0.0.1", - "--port="+strconv.Itoa(proxy.LocalPort()), - "https://quic.clemente.io/prdata", - ) - - session, err := Start(command, nil, GinkgoWriter) - Expect(err).NotTo(HaveOccurred()) - defer session.Kill() - Eventually(session, 20).Should(Exit(0)) - Expect(bytes.Contains(session.Out.Contents(), testserver.PRData)).To(BeTrue()) - } - - AfterEach(func() { - err := proxy.Close() - Expect(err).ToNot(HaveOccurred()) - time.Sleep(time.Millisecond) - }) - - for i := range protocol.SupportedVersions { - version := protocol.SupportedVersions[i] - - Context(fmt.Sprintf("with QUIC version %s", version), func() { - roundTrips := [...]int{10, 50, 100, 200} - for _, rtt := range roundTrips { - It(fmt.Sprintf("gets a 500kB file with %dms RTT", rtt), func() { - runRTTTest(time.Duration(rtt)*time.Millisecond, version) - }) - } - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/gquic/server_test.go b/vendor/lucas-clemente/quic-go/integrationtests/gquic/server_test.go deleted file mode 100644 index 993ebd037..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/gquic/server_test.go +++ /dev/null @@ -1,218 +0,0 @@ -package gquic_test - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/pem" - "fmt" - "io/ioutil" - "math/big" - mrand "math/rand" - "net/http" - "os" - "os/exec" - "path/filepath" - "strconv" - "time" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/h2quic" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - . "github.com/onsi/gomega/gexec" -) - -var _ = Describe("Server tests", func() { - for i := range protocol.SupportedVersions { - version := protocol.SupportedVersions[i] - - var ( - serverPort string - tmpDir string - session *Session - client *http.Client - ) - - generateCA := func() (*rsa.PrivateKey, *x509.Certificate) { - key, err := rsa.GenerateKey(rand.Reader, 1024) - Expect(err).ToNot(HaveOccurred()) - - templateRoot := &x509.Certificate{ - SerialNumber: big.NewInt(1), - NotBefore: time.Now().Add(-time.Hour), - NotAfter: time.Now().Add(time.Hour), - IsCA: true, - BasicConstraintsValid: true, - } - certDER, err := x509.CreateCertificate(rand.Reader, templateRoot, templateRoot, &key.PublicKey, key) - Expect(err).ToNot(HaveOccurred()) - cert, err := x509.ParseCertificate(certDER) - Expect(err).ToNot(HaveOccurred()) - return key, cert - } - - // prepare the file such that it can be by the quic_server - // some HTTP headers neeed to be prepended, see https://www.chromium.org/quic/playing-with-quic - createDownloadFile := func(filename string, data []byte) { - dataDir := filepath.Join(tmpDir, "quic.clemente.io") - err := os.Mkdir(dataDir, 0777) - Expect(err).ToNot(HaveOccurred()) - f, err := os.Create(filepath.Join(dataDir, filename)) - Expect(err).ToNot(HaveOccurred()) - defer f.Close() - _, err = f.Write([]byte("HTTP/1.1 200 OK\n")) - Expect(err).ToNot(HaveOccurred()) - _, err = f.Write([]byte("Content-Type: text/html\n")) - Expect(err).ToNot(HaveOccurred()) - _, err = f.Write([]byte("X-Original-Url: https://quic.clemente.io:" + serverPort + "/" + filename + "\n")) - Expect(err).ToNot(HaveOccurred()) - _, err = f.Write([]byte("Content-Length: " + strconv.Itoa(len(data)) + "\n\n")) - Expect(err).ToNot(HaveOccurred()) - _, err = f.Write(data) - Expect(err).ToNot(HaveOccurred()) - } - - // download files must be create *before* the quic_server is started - // the quic_server reads its data dir on startup, and only serves those files that were already present then - startServer := func(version protocol.VersionNumber) { - defer GinkgoRecover() - var err error - command := exec.Command( - serverPath, - "--quic_response_cache_dir="+filepath.Join(tmpDir, "quic.clemente.io"), - "--key_file="+filepath.Join(tmpDir, "key.pkcs8"), - "--certificate_file="+filepath.Join(tmpDir, "cert.pem"), - "--quic-version="+strconv.Itoa(int(version)), - "--port="+serverPort, - ) - session, err = Start(command, nil, GinkgoWriter) - Expect(err).NotTo(HaveOccurred()) - } - - stopServer := func() { - session.Kill() - } - - BeforeEach(func() { - serverPort = strconv.Itoa(20000 + int(mrand.Int31n(10000))) - - var err error - tmpDir, err = ioutil.TempDir("", "quic-server-certs") - Expect(err).ToNot(HaveOccurred()) - - // generate an RSA key pair for the server - key, err := rsa.GenerateKey(rand.Reader, 1024) - Expect(err).ToNot(HaveOccurred()) - - // save the private key in PKCS8 format to disk (required by quic_server) - pkcs8key, err := asn1.Marshal(struct { // copied from the x509 package - Version int - Algo pkix.AlgorithmIdentifier - PrivateKey []byte - }{ - PrivateKey: x509.MarshalPKCS1PrivateKey(key), - Algo: pkix.AlgorithmIdentifier{ - Algorithm: asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}, - Parameters: asn1.RawValue{Tag: 5}, - }, - }) - Expect(err).ToNot(HaveOccurred()) - f, err := os.Create(filepath.Join(tmpDir, "key.pkcs8")) - Expect(err).ToNot(HaveOccurred()) - _, err = f.Write(pkcs8key) - Expect(err).ToNot(HaveOccurred()) - f.Close() - - // generate a Certificate Authority - // this CA is used to sign the server's key - // it is set as a valid CA in the QUIC client - rootKey, CACert := generateCA() - // generate the server certificate - template := &x509.Certificate{ - SerialNumber: big.NewInt(1), - NotBefore: time.Now().Add(-30 * time.Minute), - NotAfter: time.Now().Add(30 * time.Minute), - Subject: pkix.Name{CommonName: "quic.clemente.io"}, - } - certDER, err := x509.CreateCertificate(rand.Reader, template, CACert, &key.PublicKey, rootKey) - Expect(err).ToNot(HaveOccurred()) - // save the certificate to disk - certOut, err := os.Create(filepath.Join(tmpDir, "cert.pem")) - Expect(err).ToNot(HaveOccurred()) - pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certDER}) - certOut.Close() - - // prepare the h2quic.client - certPool := x509.NewCertPool() - certPool.AddCert(CACert) - client = &http.Client{ - Transport: &h2quic.RoundTripper{ - TLSClientConfig: &tls.Config{RootCAs: certPool}, - QuicConfig: &quic.Config{ - Versions: []protocol.VersionNumber{version}, - }, - }, - } - }) - - AfterEach(func() { - Expect(tmpDir).ToNot(BeEmpty()) - err := os.RemoveAll(tmpDir) - Expect(err).ToNot(HaveOccurred()) - tmpDir = "" - }) - - Context(fmt.Sprintf("with QUIC version %s", version), func() { - It("downloads a hello", func() { - data := []byte("Hello world!\n") - createDownloadFile("hello", data) - - startServer(version) - defer stopServer() - - rsp, err := client.Get("https://quic.clemente.io:" + serverPort + "/hello") - Expect(err).ToNot(HaveOccurred()) - Expect(rsp.StatusCode).To(Equal(200)) - body, err := ioutil.ReadAll(gbytes.TimeoutReader(rsp.Body, 5*time.Second)) - Expect(err).ToNot(HaveOccurred()) - Expect(body).To(Equal(data)) - }) - - It("downloads a small file", func() { - createDownloadFile("file.dat", testserver.PRData) - - startServer(version) - defer stopServer() - - rsp, err := client.Get("https://quic.clemente.io:" + serverPort + "/file.dat") - Expect(err).ToNot(HaveOccurred()) - Expect(rsp.StatusCode).To(Equal(200)) - body, err := ioutil.ReadAll(gbytes.TimeoutReader(rsp.Body, 5*time.Second)) - Expect(err).ToNot(HaveOccurred()) - Expect(body).To(Equal(testserver.PRData)) - }) - - It("downloads a large file", func() { - createDownloadFile("file.dat", testserver.PRDataLong) - - startServer(version) - defer stopServer() - - rsp, err := client.Get("https://quic.clemente.io:" + serverPort + "/file.dat") - Expect(err).ToNot(HaveOccurred()) - Expect(rsp.StatusCode).To(Equal(200)) - body, err := ioutil.ReadAll(gbytes.TimeoutReader(rsp.Body, 20*time.Second)) - Expect(err).ToNot(HaveOccurred()) - Expect(body).To(Equal(testserver.PRDataLong)) - }) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/self/client_test.go b/vendor/lucas-clemente/quic-go/integrationtests/self/client_test.go deleted file mode 100644 index fcb9cb5a7..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/self/client_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package self_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "net" - "net/http" - "os" - "time" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/h2quic" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" -) - -var _ = Describe("Client tests", func() { - var client *http.Client - - // also run some tests with the TLS handshake - versions := append(protocol.SupportedVersions, protocol.VersionTLS) - - BeforeEach(func() { - err := os.Setenv("HOSTALIASES", "quic.clemente.io 127.0.0.1") - Expect(err).ToNot(HaveOccurred()) - addr, err := net.ResolveUDPAddr("udp4", "quic.clemente.io:0") - Expect(err).ToNot(HaveOccurred()) - if addr.String() != "127.0.0.1:0" { - Fail("quic.clemente.io does not resolve to 127.0.0.1. Consider adding it to /etc/hosts.") - } - testserver.StartQuicServer(versions) - }) - - AfterEach(func() { - testserver.StopQuicServer() - }) - - for _, v := range versions { - version := v - - Context(fmt.Sprintf("with QUIC version %s", version), func() { - BeforeEach(func() { - client = &http.Client{ - Transport: &h2quic.RoundTripper{ - QuicConfig: &quic.Config{ - Versions: []protocol.VersionNumber{version}, - }, - }, - } - }) - - It("downloads a hello", func() { - resp, err := client.Get("https://quic.clemente.io:" + testserver.Port() + "/hello") - Expect(err).ToNot(HaveOccurred()) - Expect(resp.StatusCode).To(Equal(200)) - body, err := ioutil.ReadAll(gbytes.TimeoutReader(resp.Body, 3*time.Second)) - Expect(err).ToNot(HaveOccurred()) - Expect(string(body)).To(Equal("Hello, World!\n")) - }) - - It("downloads a small file", func() { - resp, err := client.Get("https://quic.clemente.io:" + testserver.Port() + "/prdata") - Expect(err).ToNot(HaveOccurred()) - Expect(resp.StatusCode).To(Equal(200)) - body, err := ioutil.ReadAll(gbytes.TimeoutReader(resp.Body, 5*time.Second)) - Expect(err).ToNot(HaveOccurred()) - Expect(body).To(Equal(testserver.PRData)) - }) - - It("downloads a large file", func() { - resp, err := client.Get("https://quic.clemente.io:" + testserver.Port() + "/prdatalong") - Expect(err).ToNot(HaveOccurred()) - Expect(resp.StatusCode).To(Equal(200)) - body, err := ioutil.ReadAll(gbytes.TimeoutReader(resp.Body, 20*time.Second)) - Expect(err).ToNot(HaveOccurred()) - Expect(body).To(Equal(testserver.PRDataLong)) - }) - - It("uploads a file", func() { - resp, err := client.Post( - "https://quic.clemente.io:"+testserver.Port()+"/echo", - "text/plain", - bytes.NewReader(testserver.PRData), - ) - Expect(err).ToNot(HaveOccurred()) - Expect(resp.StatusCode).To(Equal(200)) - body, err := ioutil.ReadAll(gbytes.TimeoutReader(resp.Body, 5*time.Second)) - Expect(err).ToNot(HaveOccurred()) - Expect(bytes.Equal(body, testserver.PRData)).To(BeTrue()) - }) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/self/conn_id_test.go b/vendor/lucas-clemente/quic-go/integrationtests/self/conn_id_test.go deleted file mode 100644 index 991154f22..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/self/conn_id_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package self_test - -import ( - "crypto/tls" - "fmt" - "io/ioutil" - "math/rand" - "net" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Connection ID lengths tests", func() { - randomConnIDLen := func() int { - return 4 + int(rand.Int31n(15)) - } - - runServer := func(conf *quic.Config) quic.Listener { - GinkgoWriter.Write([]byte(fmt.Sprintf("Using %d byte connection ID for the server\n", conf.ConnectionIDLength))) - ln, err := quic.ListenAddr("localhost:0", testdata.GetTLSConfig(), conf) - Expect(err).ToNot(HaveOccurred()) - go func() { - defer GinkgoRecover() - for { - sess, err := ln.Accept() - if err != nil { - return - } - go func() { - defer GinkgoRecover() - str, err := sess.OpenStream() - Expect(err).ToNot(HaveOccurred()) - defer str.Close() - _, err = str.Write(testserver.PRData) - Expect(err).ToNot(HaveOccurred()) - }() - } - }() - return ln - } - - runClient := func(addr net.Addr, conf *quic.Config) { - GinkgoWriter.Write([]byte(fmt.Sprintf("Using %d byte connection ID for the client\n", conf.ConnectionIDLength))) - cl, err := quic.DialAddr( - fmt.Sprintf("quic.clemente.io:%d", addr.(*net.UDPAddr).Port), - &tls.Config{InsecureSkipVerify: true}, - conf, - ) - Expect(err).ToNot(HaveOccurred()) - defer cl.Close() - str, err := cl.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - data, err := ioutil.ReadAll(str) - Expect(err).ToNot(HaveOccurred()) - Expect(data).To(Equal(testserver.PRData)) - } - - Context("IETF QUIC", func() { - It("downloads a file using a 0-byte connection ID for the client", func() { - serverConf := &quic.Config{ - ConnectionIDLength: randomConnIDLen(), - Versions: []protocol.VersionNumber{protocol.VersionTLS}, - } - clientConf := &quic.Config{ - Versions: []protocol.VersionNumber{protocol.VersionTLS}, - } - - ln := runServer(serverConf) - defer ln.Close() - runClient(ln.Addr(), clientConf) - }) - - It("downloads a file when both client and server use a random connection ID length", func() { - serverConf := &quic.Config{ - ConnectionIDLength: randomConnIDLen(), - Versions: []protocol.VersionNumber{protocol.VersionTLS}, - } - clientConf := &quic.Config{ - ConnectionIDLength: randomConnIDLen(), - Versions: []protocol.VersionNumber{protocol.VersionTLS}, - } - - ln := runServer(serverConf) - defer ln.Close() - runClient(ln.Addr(), clientConf) - }) - }) - - Context("gQUIC", func() { - It("downloads a file using a 0-byte connection ID for the client", func() { - ln := runServer(&quic.Config{}) - defer ln.Close() - runClient(ln.Addr(), &quic.Config{RequestConnectionIDOmission: true}) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/self/handshake_drop_test.go b/vendor/lucas-clemente/quic-go/integrationtests/self/handshake_drop_test.go deleted file mode 100644 index dd83c9dd6..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/self/handshake_drop_test.go +++ /dev/null @@ -1,189 +0,0 @@ -package self_test - -import ( - "fmt" - mrand "math/rand" - "net" - "time" - - _ "github.com/lucas-clemente/quic-clients" // download clients - "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/integrationtests/tools/proxy" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" -) - -var directions = []quicproxy.Direction{quicproxy.DirectionIncoming, quicproxy.DirectionOutgoing, quicproxy.DirectionBoth} - -type applicationProtocol struct { - name string - run func(protocol.VersionNumber) -} - -var _ = Describe("Handshake drop tests", func() { - var ( - proxy *quicproxy.QuicProxy - ln quic.Listener - ) - - startListenerAndProxy := func(dropCallback quicproxy.DropCallback, version protocol.VersionNumber) { - var err error - ln, err = quic.ListenAddr( - "localhost:0", - testdata.GetTLSConfig(), - &quic.Config{ - Versions: []protocol.VersionNumber{version}, - }, - ) - Expect(err).ToNot(HaveOccurred()) - serverPort := ln.Addr().(*net.UDPAddr).Port - proxy, err = quicproxy.NewQuicProxy("localhost:0", version, &quicproxy.Opts{ - RemoteAddr: fmt.Sprintf("localhost:%d", serverPort), - DropPacket: dropCallback, - }, - ) - Expect(err).ToNot(HaveOccurred()) - } - - stochasticDropper := func(freq int) bool { - return mrand.Int63n(int64(freq)) == 0 - } - - clientSpeaksFirst := &applicationProtocol{ - name: "client speaks first", - run: func(version protocol.VersionNumber) { - serverSessionChan := make(chan quic.Session) - go func() { - defer GinkgoRecover() - sess, err := ln.Accept() - Expect(err).ToNot(HaveOccurred()) - defer sess.Close() - str, err := sess.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - b := make([]byte, 6) - _, err = gbytes.TimeoutReader(str, 10*time.Second).Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(string(b)).To(Equal("foobar")) - serverSessionChan <- sess - }() - sess, err := quic.DialAddr( - fmt.Sprintf("quic.clemente.io:%d", proxy.LocalPort()), - nil, - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - str, err := sess.OpenStream() - Expect(err).ToNot(HaveOccurred()) - _, err = str.Write([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - - var serverSession quic.Session - Eventually(serverSessionChan, 10*time.Second).Should(Receive(&serverSession)) - sess.Close() - serverSession.Close() - }, - } - - serverSpeaksFirst := &applicationProtocol{ - name: "server speaks first", - run: func(version protocol.VersionNumber) { - serverSessionChan := make(chan quic.Session) - go func() { - defer GinkgoRecover() - sess, err := ln.Accept() - Expect(err).ToNot(HaveOccurred()) - str, err := sess.OpenStream() - Expect(err).ToNot(HaveOccurred()) - _, err = str.Write([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - serverSessionChan <- sess - }() - sess, err := quic.DialAddr( - fmt.Sprintf("quic.clemente.io:%d", proxy.LocalPort()), - nil, - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - str, err := sess.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - b := make([]byte, 6) - _, err = gbytes.TimeoutReader(str, 10*time.Second).Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(string(b)).To(Equal("foobar")) - - var serverSession quic.Session - Eventually(serverSessionChan, 10*time.Second).Should(Receive(&serverSession)) - sess.Close() - serverSession.Close() - }, - } - - nobodySpeaks := &applicationProtocol{ - name: "nobody speaks", - run: func(version protocol.VersionNumber) { - serverSessionChan := make(chan quic.Session) - go func() { - defer GinkgoRecover() - sess, err := ln.Accept() - Expect(err).ToNot(HaveOccurred()) - serverSessionChan <- sess - }() - sess, err := quic.DialAddr( - fmt.Sprintf("quic.clemente.io:%d", proxy.LocalPort()), - nil, - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - var serverSession quic.Session - Eventually(serverSessionChan, 10*time.Second).Should(Receive(&serverSession)) - // both server and client accepted a session. Close now. - sess.Close() - serverSession.Close() - }, - } - - AfterEach(func() { - Expect(proxy.Close()).To(Succeed()) - }) - - for _, v := range append(protocol.SupportedVersions, protocol.VersionTLS) { - version := v - - Context(fmt.Sprintf("with QUIC version %s", version), func() { - for _, d := range directions { - direction := d - - for _, a := range []*applicationProtocol{clientSpeaksFirst, serverSpeaksFirst, nobodySpeaks} { - app := a - - Context(app.name, func() { - It(fmt.Sprintf("establishes a connection when the first packet is lost in %s direction", d), func() { - startListenerAndProxy(func(d quicproxy.Direction, p uint64) bool { - return p == 1 && d.Is(direction) - }, version) - app.run(version) - }) - - It(fmt.Sprintf("establishes a connection when the second packet is lost in %s direction", d), func() { - startListenerAndProxy(func(d quicproxy.Direction, p uint64) bool { - return p == 2 && d.Is(direction) - }, version) - app.run(version) - }) - - It(fmt.Sprintf("establishes a connection when 1/5 of the packets are lost in %s direction", d), func() { - startListenerAndProxy(func(d quicproxy.Direction, p uint64) bool { - return d.Is(direction) && stochasticDropper(5) - }, version) - app.run(version) - }) - }) - } - } - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/self/handshake_rtt_test.go b/vendor/lucas-clemente/quic-go/integrationtests/self/handshake_rtt_test.go deleted file mode 100644 index 67cc74ae1..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/self/handshake_rtt_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package self_test - -import ( - "crypto/tls" - "net" - "time" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/integrationtests/tools/proxy" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/qerr" - - "github.com/lucas-clemente/quic-go/internal/testdata" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Handshake RTT tests", func() { - var ( - proxy *quicproxy.QuicProxy - server quic.Listener - serverConfig *quic.Config - testStartedAt time.Time - acceptStopped chan struct{} - ) - - rtt := 400 * time.Millisecond - - BeforeEach(func() { - acceptStopped = make(chan struct{}) - serverConfig = &quic.Config{} - }) - - AfterEach(func() { - Expect(proxy.Close()).To(Succeed()) - Expect(server.Close()).To(Succeed()) - <-acceptStopped - }) - - runServerAndProxy := func() { - var err error - // start the server - server, err = quic.ListenAddr("localhost:0", testdata.GetTLSConfig(), serverConfig) - Expect(err).ToNot(HaveOccurred()) - // start the proxy - proxy, err = quicproxy.NewQuicProxy("localhost:0", protocol.VersionWhatever, &quicproxy.Opts{ - RemoteAddr: server.Addr().String(), - DelayPacket: func(_ quicproxy.Direction, _ uint64) time.Duration { return rtt / 2 }, - }) - Expect(err).ToNot(HaveOccurred()) - - testStartedAt = time.Now() - - go func() { - defer GinkgoRecover() - defer close(acceptStopped) - for { - _, err := server.Accept() - if err != nil { - return - } - } - }() - } - - expectDurationInRTTs := func(num int) { - testDuration := time.Since(testStartedAt) - rtts := float32(testDuration) / float32(rtt) - Expect(rtts).To(SatisfyAll( - BeNumerically(">=", num), - BeNumerically("<", num+1), - )) - } - - It("fails when there's no matching version, after 1 RTT", func() { - if len(protocol.SupportedVersions) == 1 { - Skip("Test requires at least 2 supported versions.") - } - serverConfig.Versions = protocol.SupportedVersions[:1] - runServerAndProxy() - clientConfig := &quic.Config{ - Versions: protocol.SupportedVersions[1:2], - } - _, err := quic.DialAddr(proxy.LocalAddr().String(), nil, clientConfig) - Expect(err).To(HaveOccurred()) - Expect(err.(qerr.ErrorCode)).To(Equal(qerr.InvalidVersion)) - expectDurationInRTTs(1) - }) - - Context("gQUIC", func() { - // 1 RTT for verifying the source address - // 1 RTT to become secure - // 1 RTT to become forward-secure - It("is forward-secure after 3 RTTs", func() { - runServerAndProxy() - _, err := quic.DialAddr(proxy.LocalAddr().String(), &tls.Config{InsecureSkipVerify: true}, nil) - Expect(err).ToNot(HaveOccurred()) - expectDurationInRTTs(3) - }) - - It("does version negotiation in 1 RTT, IETF QUIC => gQUIC", func() { - clientConfig := &quic.Config{ - Versions: []protocol.VersionNumber{protocol.VersionTLS, protocol.SupportedVersions[0]}, - } - runServerAndProxy() - _, err := quic.DialAddr( - proxy.LocalAddr().String(), - &tls.Config{InsecureSkipVerify: true}, - clientConfig, - ) - Expect(err).ToNot(HaveOccurred()) - expectDurationInRTTs(4) - }) - - It("is forward-secure after 2 RTTs when the server doesn't require a Cookie", func() { - serverConfig.AcceptCookie = func(_ net.Addr, _ *quic.Cookie) bool { - return true - } - runServerAndProxy() - _, err := quic.DialAddr(proxy.LocalAddr().String(), &tls.Config{InsecureSkipVerify: true}, nil) - Expect(err).ToNot(HaveOccurred()) - expectDurationInRTTs(2) - }) - - It("doesn't complete the handshake when the server never accepts the Cookie", func() { - serverConfig.AcceptCookie = func(_ net.Addr, _ *quic.Cookie) bool { - return false - } - runServerAndProxy() - _, err := quic.DialAddr(proxy.LocalAddr().String(), &tls.Config{InsecureSkipVerify: true}, nil) - Expect(err).To(HaveOccurred()) - Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.CryptoTooManyRejects)) - }) - - It("doesn't complete the handshake when the handshake timeout is too short", func() { - serverConfig.HandshakeTimeout = 2 * rtt - runServerAndProxy() - _, err := quic.DialAddr(proxy.LocalAddr().String(), &tls.Config{InsecureSkipVerify: true}, nil) - Expect(err).To(HaveOccurred()) - Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.HandshakeTimeout)) - // 2 RTTs during the timeout - // plus 1 RTT: the timer starts 0.5 RTTs after sending the first packet, and the CONNECTION_CLOSE needs another 0.5 RTTs to reach the client - expectDurationInRTTs(3) - }) - }) - - Context("IETF QUIC", func() { - var clientConfig *quic.Config - var clientTLSConfig *tls.Config - - BeforeEach(func() { - serverConfig.Versions = []protocol.VersionNumber{protocol.VersionTLS} - clientConfig = &quic.Config{Versions: []protocol.VersionNumber{protocol.VersionTLS}} - clientTLSConfig = &tls.Config{ - InsecureSkipVerify: true, - ServerName: "quic.clemente.io", - } - }) - - // 1 RTT for verifying the source address - // 1 RTT for the TLS handshake - It("is forward-secure after 2 RTTs", func() { - runServerAndProxy() - _, err := quic.DialAddr( - proxy.LocalAddr().String(), - clientTLSConfig, - clientConfig, - ) - Expect(err).ToNot(HaveOccurred()) - expectDurationInRTTs(2) - }) - - It("does version negotiation in 1 RTT, gQUIC => IETF QUIC", func() { - clientConfig.Versions = []protocol.VersionNumber{protocol.SupportedVersions[0], protocol.VersionTLS} - runServerAndProxy() - _, err := quic.DialAddr( - proxy.LocalAddr().String(), - clientTLSConfig, - clientConfig, - ) - Expect(err).ToNot(HaveOccurred()) - expectDurationInRTTs(3) - }) - - It("is forward-secure after 1 RTTs when the server doesn't require a Cookie", func() { - serverConfig.AcceptCookie = func(_ net.Addr, _ *quic.Cookie) bool { - return true - } - runServerAndProxy() - _, err := quic.DialAddr( - proxy.LocalAddr().String(), - clientTLSConfig, - clientConfig, - ) - Expect(err).ToNot(HaveOccurred()) - expectDurationInRTTs(1) - }) - - It("doesn't complete the handshake when the server never accepts the Cookie", func() { - serverConfig.AcceptCookie = func(_ net.Addr, _ *quic.Cookie) bool { - return false - } - runServerAndProxy() - _, err := quic.DialAddr( - proxy.LocalAddr().String(), - clientTLSConfig, - clientConfig, - ) - Expect(err).To(HaveOccurred()) - Expect(err.(qerr.ErrorCode)).To(Equal(qerr.CryptoTooManyRejects)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/self/handshake_test.go b/vendor/lucas-clemente/quic-go/integrationtests/self/handshake_test.go deleted file mode 100644 index b3a771940..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/self/handshake_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package self_test - -import ( - "crypto/tls" - "fmt" - "net" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type versioner interface { - GetVersion() protocol.VersionNumber -} - -var _ = Describe("Handshake tests", func() { - var ( - server quic.Listener - serverConfig *quic.Config - acceptStopped chan struct{} - ) - - BeforeEach(func() { - server = nil - acceptStopped = make(chan struct{}) - serverConfig = &quic.Config{} - }) - - AfterEach(func() { - if server != nil { - server.Close() - <-acceptStopped - } - }) - - runServer := func() { - var err error - // start the server - server, err = quic.ListenAddr("localhost:0", testdata.GetTLSConfig(), serverConfig) - Expect(err).ToNot(HaveOccurred()) - - go func() { - defer GinkgoRecover() - defer close(acceptStopped) - for { - _, err := server.Accept() - if err != nil { - return - } - } - }() - } - - Context("Version Negotiation", func() { - var supportedVersions []protocol.VersionNumber - - BeforeEach(func() { - supportedVersions = protocol.SupportedVersions - protocol.SupportedVersions = append(protocol.SupportedVersions, []protocol.VersionNumber{7, 8, 9, 10}...) - }) - - AfterEach(func() { - protocol.SupportedVersions = supportedVersions - }) - - It("when the server supports more versions than the client", func() { - // the server doesn't support the highest supported version, which is the first one the client will try - // but it supports a bunch of versions that the client doesn't speak - serverConfig.Versions = []protocol.VersionNumber{protocol.SupportedVersions[1], 7, 8, 9} - runServer() - sess, err := quic.DialAddr(server.Addr().String(), &tls.Config{InsecureSkipVerify: true}, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(sess.(versioner).GetVersion()).To(Equal(protocol.SupportedVersions[1])) - }) - - It("when the client supports more versions than the server supports", func() { - // the server doesn't support the highest supported version, which is the first one the client will try - // but it supports a bunch of versions that the client doesn't speak - serverConfig.Versions = supportedVersions - runServer() - conf := &quic.Config{ - Versions: []protocol.VersionNumber{7, 8, 9, protocol.SupportedVersions[1], 10}, - } - sess, err := quic.DialAddr(server.Addr().String(), &tls.Config{InsecureSkipVerify: true}, conf) - Expect(err).ToNot(HaveOccurred()) - Expect(sess.(versioner).GetVersion()).To(Equal(protocol.SupportedVersions[1])) - }) - }) - - Context("Certifiate validation", func() { - for _, v := range []protocol.VersionNumber{protocol.Version39, protocol.VersionTLS} { - version := v - - Context(fmt.Sprintf("using %s", version), func() { - var clientConfig *quic.Config - - BeforeEach(func() { - serverConfig.Versions = []protocol.VersionNumber{version} - clientConfig = &quic.Config{ - Versions: []protocol.VersionNumber{version}, - } - }) - - It("accepts the certificate", func() { - runServer() - _, err := quic.DialAddr(fmt.Sprintf("quic.clemente.io:%d", server.Addr().(*net.UDPAddr).Port), nil, clientConfig) - Expect(err).ToNot(HaveOccurred()) - }) - - It("errors if the server name doesn't match", func() { - runServer() - _, err := quic.DialAddr(fmt.Sprintf("127.0.0.1:%d", server.Addr().(*net.UDPAddr).Port), nil, clientConfig) - Expect(err).To(HaveOccurred()) - }) - - It("uses the ServerName in the tls.Config", func() { - runServer() - conf := &tls.Config{ServerName: "quic.clemente.io"} - _, err := quic.DialAddr(fmt.Sprintf("127.0.0.1:%d", server.Addr().(*net.UDPAddr).Port), conf, clientConfig) - Expect(err).ToNot(HaveOccurred()) - }) - }) - } - }) -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/self/multiplex_test.go b/vendor/lucas-clemente/quic-go/integrationtests/self/multiplex_test.go deleted file mode 100644 index 0960f49b5..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/self/multiplex_test.go +++ /dev/null @@ -1,232 +0,0 @@ -package self_test - -import ( - "fmt" - "io/ioutil" - "net" - "os" - "time" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testlog" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Multiplexing", func() { - for _, v := range append(protocol.SupportedVersions, protocol.VersionTLS) { - version := v - - // gQUIC 44 uses 0 byte connection IDs for packets sent to the client - // It's not possible to do demultiplexing. - if v == protocol.Version44 { - continue - } - - Context(fmt.Sprintf("with QUIC version %s", version), func() { - runServer := func(ln quic.Listener) { - go func() { - defer GinkgoRecover() - for { - sess, err := ln.Accept() - if err != nil { - return - } - go func() { - defer GinkgoRecover() - str, err := sess.OpenStream() - Expect(err).ToNot(HaveOccurred()) - defer str.Close() - _, err = str.Write(testserver.PRDataLong) - Expect(err).ToNot(HaveOccurred()) - }() - } - }() - } - - dial := func(conn net.PacketConn, addr net.Addr) { - sess, err := quic.Dial( - conn, - addr, - fmt.Sprintf("quic.clemente.io:%d", addr.(*net.UDPAddr).Port), - nil, - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - str, err := sess.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - data, err := ioutil.ReadAll(str) - Expect(err).ToNot(HaveOccurred()) - Expect(data).To(Equal(testserver.PRDataLong)) - } - - Context("multiplexing clients on the same conn", func() { - getListener := func() quic.Listener { - ln, err := quic.ListenAddr( - "localhost:0", - testdata.GetTLSConfig(), - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - return ln - } - - It("multiplexes connections to the same server", func() { - server := getListener() - runServer(server) - defer server.Close() - - addr, err := net.ResolveUDPAddr("udp", "localhost:0") - Expect(err).ToNot(HaveOccurred()) - conn, err := net.ListenUDP("udp", addr) - Expect(err).ToNot(HaveOccurred()) - defer conn.Close() - - done1 := make(chan struct{}) - done2 := make(chan struct{}) - go func() { - defer GinkgoRecover() - dial(conn, server.Addr()) - close(done1) - }() - go func() { - defer GinkgoRecover() - dial(conn, server.Addr()) - close(done2) - }() - timeout := 30 * time.Second - if testlog.Debug() { - timeout = time.Minute - } - Eventually(done1, timeout).Should(BeClosed()) - Eventually(done2, timeout).Should(BeClosed()) - }) - - It("multiplexes connections to different servers", func() { - server1 := getListener() - runServer(server1) - defer server1.Close() - server2 := getListener() - runServer(server2) - defer server2.Close() - - addr, err := net.ResolveUDPAddr("udp", "localhost:0") - Expect(err).ToNot(HaveOccurred()) - conn, err := net.ListenUDP("udp", addr) - Expect(err).ToNot(HaveOccurred()) - defer conn.Close() - - done1 := make(chan struct{}) - done2 := make(chan struct{}) - go func() { - defer GinkgoRecover() - dial(conn, server1.Addr()) - close(done1) - }() - go func() { - defer GinkgoRecover() - dial(conn, server2.Addr()) - close(done2) - }() - timeout := 30 * time.Second - if testlog.Debug() { - timeout = time.Minute - } - Eventually(done1, timeout).Should(BeClosed()) - Eventually(done2, timeout).Should(BeClosed()) - }) - }) - - Context("multiplexing server and client on the same conn", func() { - It("connects to itself", func() { - if version != protocol.VersionTLS { - Skip("Connecting to itself only works with IETF QUIC.") - } - - addr, err := net.ResolveUDPAddr("udp", "localhost:0") - Expect(err).ToNot(HaveOccurred()) - conn, err := net.ListenUDP("udp", addr) - Expect(err).ToNot(HaveOccurred()) - defer conn.Close() - - server, err := quic.Listen( - conn, - testdata.GetTLSConfig(), - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - runServer(server) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - dial(conn, server.Addr()) - close(done) - }() - timeout := 30 * time.Second - if testlog.Debug() { - timeout = time.Minute - } - Eventually(done, timeout).Should(BeClosed()) - }) - - It("runs a server and client on the same conn", func() { - if os.Getenv("CI") == "true" { - Skip("This test is flaky on CIs, see see https://github.com/golang/go/issues/17677.") - } - addr1, err := net.ResolveUDPAddr("udp", "localhost:0") - Expect(err).ToNot(HaveOccurred()) - conn1, err := net.ListenUDP("udp", addr1) - Expect(err).ToNot(HaveOccurred()) - defer conn1.Close() - - addr2, err := net.ResolveUDPAddr("udp", "localhost:0") - Expect(err).ToNot(HaveOccurred()) - conn2, err := net.ListenUDP("udp", addr2) - Expect(err).ToNot(HaveOccurred()) - defer conn2.Close() - - server1, err := quic.Listen( - conn1, - testdata.GetTLSConfig(), - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - runServer(server1) - defer server1.Close() - - server2, err := quic.Listen( - conn2, - testdata.GetTLSConfig(), - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - runServer(server2) - defer server2.Close() - - done1 := make(chan struct{}) - done2 := make(chan struct{}) - go func() { - defer GinkgoRecover() - dial(conn2, server1.Addr()) - close(done1) - }() - go func() { - defer GinkgoRecover() - dial(conn1, server2.Addr()) - close(done2) - }() - timeout := 30 * time.Second - if testlog.Debug() { - timeout = time.Minute - } - Eventually(done1, timeout).Should(BeClosed()) - Eventually(done2, timeout).Should(BeClosed()) - }) - }) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/self/rtt_test.go b/vendor/lucas-clemente/quic-go/integrationtests/self/rtt_test.go deleted file mode 100644 index 40cca5b9d..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/self/rtt_test.go +++ /dev/null @@ -1,83 +0,0 @@ -package self - -import ( - "fmt" - "io/ioutil" - "net" - "time" - - _ "github.com/lucas-clemente/quic-clients" // download clients - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/integrationtests/tools/proxy" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("non-zero RTT", func() { - for _, v := range append(protocol.SupportedVersions, protocol.VersionTLS) { - version := v - - Context(fmt.Sprintf("with QUIC version %s", version), func() { - roundTrips := [...]time.Duration{ - 10 * time.Millisecond, - 50 * time.Millisecond, - 100 * time.Millisecond, - 200 * time.Millisecond, - } - - for _, r := range roundTrips { - rtt := r - - It(fmt.Sprintf("downloads a message with %s RTT", rtt), func() { - ln, err := quic.ListenAddr( - "localhost:0", - testdata.GetTLSConfig(), - &quic.Config{ - Versions: []protocol.VersionNumber{version}, - }, - ) - Expect(err).ToNot(HaveOccurred()) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess, err := ln.Accept() - Expect(err).ToNot(HaveOccurred()) - str, err := sess.OpenStream() - Expect(err).ToNot(HaveOccurred()) - _, err = str.Write(testserver.PRData) - Expect(err).ToNot(HaveOccurred()) - str.Close() - close(done) - }() - serverPort := ln.Addr().(*net.UDPAddr).Port - proxy, err := quicproxy.NewQuicProxy("localhost:0", version, &quicproxy.Opts{ - RemoteAddr: fmt.Sprintf("localhost:%d", serverPort), - DelayPacket: func(d quicproxy.Direction, p uint64) time.Duration { - return rtt / 2 - }, - }) - Expect(err).ToNot(HaveOccurred()) - defer proxy.Close() - - sess, err := quic.DialAddr( - fmt.Sprintf("quic.clemente.io:%d", proxy.LocalPort()), - nil, - &quic.Config{Versions: []protocol.VersionNumber{version}}, - ) - Expect(err).ToNot(HaveOccurred()) - str, err := sess.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - data, err := ioutil.ReadAll(str) - Expect(err).ToNot(HaveOccurred()) - Expect(data).To(Equal(testserver.PRData)) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - } - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/self/self_suite_test.go b/vendor/lucas-clemente/quic-go/integrationtests/self/self_suite_test.go deleted file mode 100644 index dd607a843..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/self/self_suite_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package self_test - -import ( - "math/rand" - "testing" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - _ "github.com/lucas-clemente/quic-go/integrationtests/tools/testlog" -) - -func TestSelf(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Self integration tests") -} - -var _ = BeforeSuite(func() { - rand.Seed(GinkgoRandomSeed()) -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/self/stream_test.go b/vendor/lucas-clemente/quic-go/integrationtests/self/stream_test.go deleted file mode 100644 index 640396987..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/self/stream_test.go +++ /dev/null @@ -1,152 +0,0 @@ -package self_test - -import ( - "fmt" - "io/ioutil" - "net" - "sync" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Bidirectional streams", func() { - const numStreams = 300 - - var ( - server quic.Listener - serverAddr string - qconf *quic.Config - ) - - for _, v := range []protocol.VersionNumber{protocol.VersionTLS} { - version := v - - Context(fmt.Sprintf("with QUIC %s", version), func() { - BeforeEach(func() { - var err error - qconf = &quic.Config{ - Versions: []protocol.VersionNumber{version}, - MaxIncomingStreams: 0, - } - server, err = quic.ListenAddr("localhost:0", testdata.GetTLSConfig(), qconf) - Expect(err).ToNot(HaveOccurred()) - serverAddr = fmt.Sprintf("quic.clemente.io:%d", server.Addr().(*net.UDPAddr).Port) - }) - - AfterEach(func() { - server.Close() - }) - - runSendingPeer := func(sess quic.Session) { - var wg sync.WaitGroup - wg.Add(numStreams) - for i := 0; i < numStreams; i++ { - str, err := sess.OpenStreamSync() - Expect(err).ToNot(HaveOccurred()) - data := testserver.GeneratePRData(25 * i) - go func() { - defer GinkgoRecover() - _, err := str.Write(data) - Expect(err).ToNot(HaveOccurred()) - Expect(str.Close()).To(Succeed()) - }() - go func() { - defer GinkgoRecover() - defer wg.Done() - dataRead, err := ioutil.ReadAll(str) - Expect(err).ToNot(HaveOccurred()) - Expect(dataRead).To(Equal(data)) - }() - } - wg.Wait() - } - - runReceivingPeer := func(sess quic.Session) { - var wg sync.WaitGroup - wg.Add(numStreams) - for i := 0; i < numStreams; i++ { - str, err := sess.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - go func() { - defer GinkgoRecover() - defer wg.Done() - // shouldn't use io.Copy here - // we should read from the stream as early as possible, to free flow control credit - data, err := ioutil.ReadAll(str) - Expect(err).ToNot(HaveOccurred()) - _, err = str.Write(data) - Expect(err).ToNot(HaveOccurred()) - Expect(str.Close()).To(Succeed()) - }() - } - wg.Wait() - } - - It(fmt.Sprintf("client opening %d streams to a server", numStreams), func() { - var sess quic.Session - go func() { - defer GinkgoRecover() - var err error - sess, err = server.Accept() - Expect(err).ToNot(HaveOccurred()) - runReceivingPeer(sess) - }() - - client, err := quic.DialAddr(serverAddr, nil, qconf) - Expect(err).ToNot(HaveOccurred()) - runSendingPeer(client) - }) - - It(fmt.Sprintf("server opening %d streams to a client", numStreams), func() { - go func() { - defer GinkgoRecover() - sess, err := server.Accept() - Expect(err).ToNot(HaveOccurred()) - runSendingPeer(sess) - sess.Close() - }() - - client, err := quic.DialAddr(serverAddr, nil, qconf) - Expect(err).ToNot(HaveOccurred()) - runReceivingPeer(client) - Eventually(client.Context().Done()).Should(BeClosed()) - }) - - It(fmt.Sprintf("client and server opening %d each and sending data to the peer", numStreams), func() { - done1 := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess, err := server.Accept() - Expect(err).ToNot(HaveOccurred()) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - runReceivingPeer(sess) - close(done) - }() - runSendingPeer(sess) - <-done - close(done1) - }() - - client, err := quic.DialAddr(serverAddr, nil, qconf) - Expect(err).ToNot(HaveOccurred()) - done2 := make(chan struct{}) - go func() { - defer GinkgoRecover() - runSendingPeer(client) - close(done2) - }() - runReceivingPeer(client) - <-done1 - <-done2 - }) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/self/uni_stream_test.go b/vendor/lucas-clemente/quic-go/integrationtests/self/uni_stream_test.go deleted file mode 100644 index ba3d7e4d3..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/self/uni_stream_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package self_test - -import ( - "fmt" - "io/ioutil" - "net" - "sync" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/integrationtests/tools/testserver" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Unidirectional Streams", func() { - const numStreams = 500 - - var ( - server quic.Listener - serverAddr string - qconf *quic.Config - ) - - BeforeEach(func() { - var err error - qconf = &quic.Config{Versions: []protocol.VersionNumber{protocol.VersionTLS}} - server, err = quic.ListenAddr("localhost:0", testdata.GetTLSConfig(), qconf) - Expect(err).ToNot(HaveOccurred()) - serverAddr = fmt.Sprintf("quic.clemente.io:%d", server.Addr().(*net.UDPAddr).Port) - }) - - AfterEach(func() { - server.Close() - }) - - dataForStream := func(id protocol.StreamID) []byte { - return testserver.GeneratePRData(10 * int(id)) - } - - runSendingPeer := func(sess quic.Session) { - for i := 0; i < numStreams; i++ { - str, err := sess.OpenUniStreamSync() - Expect(err).ToNot(HaveOccurred()) - go func() { - defer GinkgoRecover() - _, err := str.Write(dataForStream(str.StreamID())) - Expect(err).ToNot(HaveOccurred()) - Expect(str.Close()).To(Succeed()) - }() - } - } - - runReceivingPeer := func(sess quic.Session) { - var wg sync.WaitGroup - wg.Add(numStreams) - for i := 0; i < numStreams; i++ { - str, err := sess.AcceptUniStream() - Expect(err).ToNot(HaveOccurred()) - go func() { - defer GinkgoRecover() - defer wg.Done() - data, err := ioutil.ReadAll(str) - Expect(err).ToNot(HaveOccurred()) - Expect(data).To(Equal(dataForStream(str.StreamID()))) - }() - } - wg.Wait() - } - - It(fmt.Sprintf("client opening %d streams to a server", numStreams), func() { - var sess quic.Session - go func() { - defer GinkgoRecover() - var err error - sess, err = server.Accept() - Expect(err).ToNot(HaveOccurred()) - runReceivingPeer(sess) - sess.Close() - }() - - client, err := quic.DialAddr(serverAddr, nil, qconf) - Expect(err).ToNot(HaveOccurred()) - runSendingPeer(client) - <-client.Context().Done() - }) - - It(fmt.Sprintf("server opening %d streams to a client", numStreams), func() { - go func() { - defer GinkgoRecover() - sess, err := server.Accept() - Expect(err).ToNot(HaveOccurred()) - runSendingPeer(sess) - }() - - client, err := quic.DialAddr(serverAddr, nil, qconf) - Expect(err).ToNot(HaveOccurred()) - runReceivingPeer(client) - }) - - It(fmt.Sprintf("client and server opening %d streams each and sending data to the peer", numStreams), func() { - done1 := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess, err := server.Accept() - Expect(err).ToNot(HaveOccurred()) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - runReceivingPeer(sess) - close(done) - }() - runSendingPeer(sess) - <-done - close(done1) - }() - - client, err := quic.DialAddr(serverAddr, nil, qconf) - Expect(err).ToNot(HaveOccurred()) - done2 := make(chan struct{}) - go func() { - defer GinkgoRecover() - runSendingPeer(client) - close(done2) - }() - runReceivingPeer(client) - <-done1 - <-done2 - }) -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/tools/proxy/proxy.go b/vendor/lucas-clemente/quic-go/integrationtests/tools/proxy/proxy.go deleted file mode 100644 index d0bd97109..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/tools/proxy/proxy.go +++ /dev/null @@ -1,270 +0,0 @@ -package quicproxy - -import ( - "net" - "sync" - "sync/atomic" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" -) - -// Connection is a UDP connection -type connection struct { - ClientAddr *net.UDPAddr // Address of the client - ServerConn *net.UDPConn // UDP connection to server - - incomingPacketCounter uint64 - outgoingPacketCounter uint64 -} - -// Direction is the direction a packet is sent. -type Direction int - -const ( - // DirectionIncoming is the direction from the client to the server. - DirectionIncoming Direction = iota - // DirectionOutgoing is the direction from the server to the client. - DirectionOutgoing - // DirectionBoth is both incoming and outgoing - DirectionBoth -) - -func (d Direction) String() string { - switch d { - case DirectionIncoming: - return "incoming" - case DirectionOutgoing: - return "outgoing" - case DirectionBoth: - return "both" - default: - panic("unknown direction") - } -} - -// Is says if one direction matches another direction. -// For example, incoming matches both incoming and both, but not outgoing. -func (d Direction) Is(dir Direction) bool { - if d == DirectionBoth || dir == DirectionBoth { - return true - } - return d == dir -} - -// DropCallback is a callback that determines which packet gets dropped. -type DropCallback func(dir Direction, packetCount uint64) bool - -// NoDropper doesn't drop packets. -var NoDropper DropCallback = func(Direction, uint64) bool { - return false -} - -// DelayCallback is a callback that determines how much delay to apply to a packet. -type DelayCallback func(dir Direction, packetCount uint64) time.Duration - -// NoDelay doesn't apply a delay. -var NoDelay DelayCallback = func(Direction, uint64) time.Duration { - return 0 -} - -// Opts are proxy options. -type Opts struct { - // The address this proxy proxies packets to. - RemoteAddr string - // DropPacket determines whether a packet gets dropped. - DropPacket DropCallback - // DelayPacket determines how long a packet gets delayed. This allows - // simulating a connection with non-zero RTTs. - // Note that the RTT is the sum of the delay for the incoming and the outgoing packet. - DelayPacket DelayCallback -} - -// QuicProxy is a QUIC proxy that can drop and delay packets. -type QuicProxy struct { - mutex sync.Mutex - - version protocol.VersionNumber - - conn *net.UDPConn - serverAddr *net.UDPAddr - - dropPacket DropCallback - delayPacket DelayCallback - - // Mapping from client addresses (as host:port) to connection - clientDict map[string]*connection - - logger utils.Logger -} - -// NewQuicProxy creates a new UDP proxy -func NewQuicProxy(local string, version protocol.VersionNumber, opts *Opts) (*QuicProxy, error) { - if opts == nil { - opts = &Opts{} - } - laddr, err := net.ResolveUDPAddr("udp", local) - if err != nil { - return nil, err - } - conn, err := net.ListenUDP("udp", laddr) - if err != nil { - return nil, err - } - raddr, err := net.ResolveUDPAddr("udp", opts.RemoteAddr) - if err != nil { - return nil, err - } - - packetDropper := NoDropper - if opts.DropPacket != nil { - packetDropper = opts.DropPacket - } - - packetDelayer := NoDelay - if opts.DelayPacket != nil { - packetDelayer = opts.DelayPacket - } - - p := QuicProxy{ - clientDict: make(map[string]*connection), - conn: conn, - serverAddr: raddr, - dropPacket: packetDropper, - delayPacket: packetDelayer, - version: version, - logger: utils.DefaultLogger.WithPrefix("proxy"), - } - - p.logger.Debugf("Starting UDP Proxy %s <-> %s", conn.LocalAddr(), raddr) - go p.runProxy() - return &p, nil -} - -// Close stops the UDP Proxy -func (p *QuicProxy) Close() error { - p.mutex.Lock() - defer p.mutex.Unlock() - for _, c := range p.clientDict { - if err := c.ServerConn.Close(); err != nil { - return err - } - } - return p.conn.Close() -} - -// LocalAddr is the address the proxy is listening on. -func (p *QuicProxy) LocalAddr() net.Addr { - return p.conn.LocalAddr() -} - -// LocalPort is the UDP port number the proxy is listening on. -func (p *QuicProxy) LocalPort() int { - return p.conn.LocalAddr().(*net.UDPAddr).Port -} - -func (p *QuicProxy) newConnection(cliAddr *net.UDPAddr) (*connection, error) { - srvudp, err := net.DialUDP("udp", nil, p.serverAddr) - if err != nil { - return nil, err - } - return &connection{ - ClientAddr: cliAddr, - ServerConn: srvudp, - }, nil -} - -// runProxy listens on the proxy address and handles incoming packets. -func (p *QuicProxy) runProxy() error { - for { - buffer := make([]byte, protocol.MaxReceivePacketSize) - n, cliaddr, err := p.conn.ReadFromUDP(buffer) - if err != nil { - return err - } - raw := buffer[0:n] - - saddr := cliaddr.String() - p.mutex.Lock() - conn, ok := p.clientDict[saddr] - - if !ok { - conn, err = p.newConnection(cliaddr) - if err != nil { - p.mutex.Unlock() - return err - } - p.clientDict[saddr] = conn - go p.runConnection(conn) - } - p.mutex.Unlock() - - packetCount := atomic.AddUint64(&conn.incomingPacketCounter, 1) - - if p.dropPacket(DirectionIncoming, packetCount) { - if p.logger.Debug() { - p.logger.Debugf("dropping incoming packet %d (%d bytes)", packetCount, n) - } - continue - } - - // Send the packet to the server - delay := p.delayPacket(DirectionIncoming, packetCount) - if delay != 0 { - if p.logger.Debug() { - p.logger.Debugf("delaying incoming packet %d (%d bytes) to %s by %s", packetCount, n, conn.ServerConn.RemoteAddr(), delay) - } - time.AfterFunc(delay, func() { - // TODO: handle error - _, _ = conn.ServerConn.Write(raw) - }) - } else { - if p.logger.Debug() { - p.logger.Debugf("forwarding incoming packet %d (%d bytes) to %s", packetCount, n, conn.ServerConn.RemoteAddr()) - } - if _, err := conn.ServerConn.Write(raw); err != nil { - return err - } - } - } -} - -// runConnection handles packets from server to a single client -func (p *QuicProxy) runConnection(conn *connection) error { - for { - buffer := make([]byte, protocol.MaxReceivePacketSize) - n, err := conn.ServerConn.Read(buffer) - if err != nil { - return err - } - raw := buffer[0:n] - - packetCount := atomic.AddUint64(&conn.outgoingPacketCounter, 1) - - if p.dropPacket(DirectionOutgoing, packetCount) { - if p.logger.Debug() { - p.logger.Debugf("dropping outgoing packet %d (%d bytes)", packetCount, n) - } - continue - } - - delay := p.delayPacket(DirectionOutgoing, packetCount) - if delay != 0 { - if p.logger.Debug() { - p.logger.Debugf("delaying outgoing packet %d (%d bytes) to %s by %s", packetCount, n, conn.ClientAddr, delay) - } - time.AfterFunc(delay, func() { - // TODO: handle error - _, _ = p.conn.WriteToUDP(raw, conn.ClientAddr) - }) - } else { - if p.logger.Debug() { - p.logger.Debugf("forwarding outgoing packet %d (%d bytes) to %s", packetCount, n, conn.ClientAddr) - } - if _, err := p.conn.WriteToUDP(raw, conn.ClientAddr); err != nil { - return err - } - } - } -} diff --git a/vendor/lucas-clemente/quic-go/integrationtests/tools/proxy/proxy_suite_test.go b/vendor/lucas-clemente/quic-go/integrationtests/tools/proxy/proxy_suite_test.go deleted file mode 100644 index 6e413a82f..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/tools/proxy/proxy_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package quicproxy - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestQuicGo(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "QUIC Proxy") -} diff --git a/vendor/lucas-clemente/quic-go/integrationtests/tools/proxy/proxy_test.go b/vendor/lucas-clemente/quic-go/integrationtests/tools/proxy/proxy_test.go deleted file mode 100644 index 945a9c48d..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/tools/proxy/proxy_test.go +++ /dev/null @@ -1,394 +0,0 @@ -package quicproxy - -import ( - "bytes" - "net" - "runtime/pprof" - "strconv" - "strings" - "sync/atomic" - "time" - - "fmt" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type packetData []byte - -var _ = Describe("QUIC Proxy", func() { - makePacket := func(p protocol.PacketNumber, payload []byte) []byte { - b := &bytes.Buffer{} - hdr := wire.Header{ - PacketNumber: p, - PacketNumberLen: protocol.PacketNumberLen6, - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0, 0, 0x13, 0x37}, - SrcConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0, 0, 0x13, 0x37}, - } - hdr.Write(b, protocol.PerspectiveServer, protocol.VersionWhatever) - raw := b.Bytes() - raw = append(raw, payload...) - return raw - } - - Context("Proxy setup and teardown", func() { - It("sets up the UDPProxy", func() { - proxy, err := NewQuicProxy("localhost:0", protocol.VersionWhatever, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(proxy.clientDict).To(HaveLen(0)) - - // check that the proxy port is in use - addr, err := net.ResolveUDPAddr("udp", "localhost:"+strconv.Itoa(proxy.LocalPort())) - Expect(err).ToNot(HaveOccurred()) - _, err = net.ListenUDP("udp", addr) - Expect(err).To(MatchError(fmt.Sprintf("listen udp 127.0.0.1:%d: bind: address already in use", proxy.LocalPort()))) - Expect(proxy.Close()).To(Succeed()) // stopping is tested in the next test - }) - - It("stops the UDPProxy", func() { - isProxyRunning := func() bool { - var b bytes.Buffer - pprof.Lookup("goroutine").WriteTo(&b, 1) - return strings.Contains(b.String(), "proxy.(*QuicProxy).runProxy") - } - - proxy, err := NewQuicProxy("localhost:0", protocol.VersionWhatever, nil) - Expect(err).ToNot(HaveOccurred()) - port := proxy.LocalPort() - Expect(isProxyRunning()).To(BeTrue()) - err = proxy.Close() - Expect(err).ToNot(HaveOccurred()) - - // check that the proxy port is not in use anymore - addr, err := net.ResolveUDPAddr("udp", "localhost:"+strconv.Itoa(port)) - Expect(err).ToNot(HaveOccurred()) - // sometimes it takes a while for the OS to free the port - Eventually(func() error { - ln, err := net.ListenUDP("udp", addr) - if err != nil { - return err - } - ln.Close() - return nil - }).ShouldNot(HaveOccurred()) - Eventually(isProxyRunning).Should(BeFalse()) - }) - - It("stops listening for proxied connections", func() { - isConnRunning := func() bool { - var b bytes.Buffer - pprof.Lookup("goroutine").WriteTo(&b, 1) - return strings.Contains(b.String(), "proxy.(*QuicProxy).runConnection") - } - - serverAddr, err := net.ResolveUDPAddr("udp", "localhost:0") - Expect(err).ToNot(HaveOccurred()) - serverConn, err := net.ListenUDP("udp", serverAddr) - Expect(err).ToNot(HaveOccurred()) - defer serverConn.Close() - - proxy, err := NewQuicProxy("localhost:0", protocol.VersionWhatever, &Opts{RemoteAddr: serverConn.LocalAddr().String()}) - Expect(err).ToNot(HaveOccurred()) - Expect(isConnRunning()).To(BeFalse()) - - // check that the proxy port is not in use anymore - conn, err := net.DialUDP("udp", nil, proxy.LocalAddr().(*net.UDPAddr)) - Expect(err).ToNot(HaveOccurred()) - _, err = conn.Write(makePacket(1, []byte("foobar"))) - Expect(err).ToNot(HaveOccurred()) - Eventually(isConnRunning).Should(BeTrue()) - Expect(proxy.Close()).To(Succeed()) - Eventually(isConnRunning).Should(BeFalse()) - }) - - It("has the correct LocalAddr and LocalPort", func() { - proxy, err := NewQuicProxy("localhost:0", protocol.VersionWhatever, nil) - Expect(err).ToNot(HaveOccurred()) - - Expect(proxy.LocalAddr().String()).To(Equal("127.0.0.1:" + strconv.Itoa(proxy.LocalPort()))) - Expect(proxy.LocalPort()).ToNot(BeZero()) - - Expect(proxy.Close()).To(Succeed()) - }) - }) - - Context("Proxy tests", func() { - var ( - serverConn *net.UDPConn - serverNumPacketsSent int32 - serverReceivedPackets chan packetData - clientConn *net.UDPConn - proxy *QuicProxy - ) - - startProxy := func(opts *Opts) { - var err error - proxy, err = NewQuicProxy("localhost:0", protocol.VersionWhatever, opts) - Expect(err).ToNot(HaveOccurred()) - clientConn, err = net.DialUDP("udp", nil, proxy.LocalAddr().(*net.UDPAddr)) - Expect(err).ToNot(HaveOccurred()) - } - - // getClientDict returns a copy of the clientDict map - getClientDict := func() map[string]*connection { - d := make(map[string]*connection) - proxy.mutex.Lock() - defer proxy.mutex.Unlock() - for k, v := range proxy.clientDict { - d[k] = v - } - return d - } - - BeforeEach(func() { - serverReceivedPackets = make(chan packetData, 100) - atomic.StoreInt32(&serverNumPacketsSent, 0) - - // setup a dump UDP server - // in production this would be a QUIC server - raddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0") - Expect(err).ToNot(HaveOccurred()) - serverConn, err = net.ListenUDP("udp", raddr) - Expect(err).ToNot(HaveOccurred()) - - go func() { - for { - buf := make([]byte, protocol.MaxReceivePacketSize) - // the ReadFromUDP will error as soon as the UDP conn is closed - n, addr, err2 := serverConn.ReadFromUDP(buf) - if err2 != nil { - return - } - data := buf[0:n] - serverReceivedPackets <- packetData(data) - // echo the packet - serverConn.WriteToUDP(data, addr) - atomic.AddInt32(&serverNumPacketsSent, 1) - } - }() - }) - - AfterEach(func() { - err := proxy.Close() - Expect(err).ToNot(HaveOccurred()) - err = serverConn.Close() - Expect(err).ToNot(HaveOccurred()) - err = clientConn.Close() - Expect(err).ToNot(HaveOccurred()) - time.Sleep(200 * time.Millisecond) - }) - - Context("no packet drop", func() { - It("relays packets from the client to the server", func() { - startProxy(&Opts{RemoteAddr: serverConn.LocalAddr().String()}) - // send the first packet - _, err := clientConn.Write(makePacket(1, []byte("foobar"))) - Expect(err).ToNot(HaveOccurred()) - - Eventually(getClientDict).Should(HaveLen(1)) - var conn *connection - for _, conn = range getClientDict() { - Eventually(func() uint64 { return atomic.LoadUint64(&conn.incomingPacketCounter) }).Should(Equal(uint64(1))) - } - - // send the second packet - _, err = clientConn.Write(makePacket(2, []byte("decafbad"))) - Expect(err).ToNot(HaveOccurred()) - - Eventually(serverReceivedPackets).Should(HaveLen(2)) - Expect(getClientDict()).To(HaveLen(1)) - Expect(string(<-serverReceivedPackets)).To(ContainSubstring("foobar")) - Expect(string(<-serverReceivedPackets)).To(ContainSubstring("decafbad")) - }) - - It("relays packets from the server to the client", func() { - startProxy(&Opts{RemoteAddr: serverConn.LocalAddr().String()}) - // send the first packet - _, err := clientConn.Write(makePacket(1, []byte("foobar"))) - Expect(err).ToNot(HaveOccurred()) - - Eventually(getClientDict).Should(HaveLen(1)) - var key string - var conn *connection - for key, conn = range getClientDict() { - Eventually(func() uint64 { return atomic.LoadUint64(&conn.outgoingPacketCounter) }).Should(Equal(uint64(1))) - } - - // send the second packet - _, err = clientConn.Write(makePacket(2, []byte("decafbad"))) - Expect(err).ToNot(HaveOccurred()) - - Expect(getClientDict()).To(HaveLen(1)) - Eventually(func() uint64 { - conn := getClientDict()[key] - return atomic.LoadUint64(&conn.outgoingPacketCounter) - }).Should(BeEquivalentTo(2)) - - clientReceivedPackets := make(chan packetData, 2) - // receive the packets echoed by the server on client side - go func() { - for { - buf := make([]byte, protocol.MaxReceivePacketSize) - // the ReadFromUDP will error as soon as the UDP conn is closed - n, _, err2 := clientConn.ReadFromUDP(buf) - if err2 != nil { - return - } - data := buf[0:n] - clientReceivedPackets <- packetData(data) - } - }() - - Eventually(serverReceivedPackets).Should(HaveLen(2)) - Expect(atomic.LoadInt32(&serverNumPacketsSent)).To(BeEquivalentTo(2)) - Eventually(clientReceivedPackets).Should(HaveLen(2)) - Expect(string(<-clientReceivedPackets)).To(ContainSubstring("foobar")) - Expect(string(<-clientReceivedPackets)).To(ContainSubstring("decafbad")) - }) - }) - - Context("Drop Callbacks", func() { - It("drops incoming packets", func() { - opts := &Opts{ - RemoteAddr: serverConn.LocalAddr().String(), - DropPacket: func(d Direction, p uint64) bool { - return d == DirectionIncoming && p%2 == 0 - }, - } - startProxy(opts) - - for i := 1; i <= 6; i++ { - _, err := clientConn.Write(makePacket(protocol.PacketNumber(i), []byte("foobar"+strconv.Itoa(i)))) - Expect(err).ToNot(HaveOccurred()) - } - Eventually(serverReceivedPackets).Should(HaveLen(3)) - Consistently(serverReceivedPackets).Should(HaveLen(3)) - }) - - It("drops outgoing packets", func() { - const numPackets = 6 - opts := &Opts{ - RemoteAddr: serverConn.LocalAddr().String(), - DropPacket: func(d Direction, p uint64) bool { - return d == DirectionOutgoing && p%2 == 0 - }, - } - startProxy(opts) - - clientReceivedPackets := make(chan packetData, numPackets) - // receive the packets echoed by the server on client side - go func() { - for { - buf := make([]byte, protocol.MaxReceivePacketSize) - // the ReadFromUDP will error as soon as the UDP conn is closed - n, _, err2 := clientConn.ReadFromUDP(buf) - if err2 != nil { - return - } - data := buf[0:n] - clientReceivedPackets <- packetData(data) - } - }() - - for i := 1; i <= numPackets; i++ { - _, err := clientConn.Write(makePacket(protocol.PacketNumber(i), []byte("foobar"+strconv.Itoa(i)))) - Expect(err).ToNot(HaveOccurred()) - } - - Eventually(clientReceivedPackets).Should(HaveLen(numPackets / 2)) - Consistently(clientReceivedPackets).Should(HaveLen(numPackets / 2)) - }) - }) - - Context("Delay Callback", func() { - expectDelay := func(startTime time.Time, rtt time.Duration, numRTTs int) { - expectedReceiveTime := startTime.Add(time.Duration(numRTTs) * rtt) - Expect(time.Now()).To(SatisfyAll( - BeTemporally(">=", expectedReceiveTime), - BeTemporally("<", expectedReceiveTime.Add(rtt/2)), - )) - } - - It("delays incoming packets", func() { - delay := 300 * time.Millisecond - opts := &Opts{ - RemoteAddr: serverConn.LocalAddr().String(), - // delay packet 1 by 200 ms - // delay packet 2 by 400 ms - // ... - DelayPacket: func(d Direction, p uint64) time.Duration { - if d == DirectionOutgoing { - return 0 - } - return time.Duration(p) * delay - }, - } - startProxy(opts) - - // send 3 packets - start := time.Now() - for i := 1; i <= 3; i++ { - _, err := clientConn.Write(makePacket(protocol.PacketNumber(i), []byte("foobar"+strconv.Itoa(i)))) - Expect(err).ToNot(HaveOccurred()) - } - Eventually(serverReceivedPackets).Should(HaveLen(1)) - expectDelay(start, delay, 1) - Eventually(serverReceivedPackets).Should(HaveLen(2)) - expectDelay(start, delay, 2) - Eventually(serverReceivedPackets).Should(HaveLen(3)) - expectDelay(start, delay, 3) - }) - - It("delays outgoing packets", func() { - const numPackets = 3 - delay := 300 * time.Millisecond - opts := &Opts{ - RemoteAddr: serverConn.LocalAddr().String(), - // delay packet 1 by 200 ms - // delay packet 2 by 400 ms - // ... - DelayPacket: func(d Direction, p uint64) time.Duration { - if d == DirectionIncoming { - return 0 - } - return time.Duration(p) * delay - }, - } - startProxy(opts) - - clientReceivedPackets := make(chan packetData, numPackets) - // receive the packets echoed by the server on client side - go func() { - for { - buf := make([]byte, protocol.MaxReceivePacketSize) - // the ReadFromUDP will error as soon as the UDP conn is closed - n, _, err2 := clientConn.ReadFromUDP(buf) - if err2 != nil { - return - } - data := buf[0:n] - clientReceivedPackets <- packetData(data) - } - }() - - start := time.Now() - for i := 1; i <= numPackets; i++ { - _, err := clientConn.Write(makePacket(protocol.PacketNumber(i), []byte("foobar"+strconv.Itoa(i)))) - Expect(err).ToNot(HaveOccurred()) - } - // the packets should have arrived immediately at the server - Eventually(serverReceivedPackets).Should(HaveLen(3)) - expectDelay(start, delay, 0) - Eventually(clientReceivedPackets).Should(HaveLen(1)) - expectDelay(start, delay, 1) - Eventually(clientReceivedPackets).Should(HaveLen(2)) - expectDelay(start, delay, 2) - Eventually(clientReceivedPackets).Should(HaveLen(3)) - expectDelay(start, delay, 3) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/integrationtests/tools/testlog/testlog.go b/vendor/lucas-clemente/quic-go/integrationtests/tools/testlog/testlog.go deleted file mode 100644 index d3206ba1a..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/tools/testlog/testlog.go +++ /dev/null @@ -1,46 +0,0 @@ -package testlog - -import ( - "flag" - "log" - "os" - - "github.com/lucas-clemente/quic-go/internal/utils" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var ( - logFileName string // the log file set in the ginkgo flags - logFile *os.File -) - -// read the logfile command line flag -// to set call ginkgo -- -logfile=log.txt -func init() { - flag.StringVar(&logFileName, "logfile", "", "log file") -} - -var _ = BeforeEach(func() { - log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) - - if len(logFileName) > 0 { - var err error - logFile, err = os.Create(logFileName) - Expect(err).ToNot(HaveOccurred()) - log.SetOutput(logFile) - utils.DefaultLogger.SetLogLevel(utils.LogLevelDebug) - } -}) - -var _ = AfterEach(func() { - if len(logFileName) > 0 { - _ = logFile.Close() - } -}) - -// Debug says if this test is being logged -func Debug() bool { - return len(logFileName) > 0 -} diff --git a/vendor/lucas-clemente/quic-go/integrationtests/tools/testserver/server.go b/vendor/lucas-clemente/quic-go/integrationtests/tools/testserver/server.go deleted file mode 100644 index 70ba2dda5..000000000 --- a/vendor/lucas-clemente/quic-go/integrationtests/tools/testserver/server.go +++ /dev/null @@ -1,119 +0,0 @@ -package testserver - -import ( - "io" - "io/ioutil" - "net" - "net/http" - "strconv" - - quic "github.com/lucas-clemente/quic-go" - "github.com/lucas-clemente/quic-go/h2quic" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -const ( - dataLen = 500 * 1024 // 500 KB - dataLenLong = 50 * 1024 * 1024 // 50 MB -) - -var ( - // PRData contains dataLen bytes of pseudo-random data. - PRData = GeneratePRData(dataLen) - // PRDataLong contains dataLenLong bytes of pseudo-random data. - PRDataLong = GeneratePRData(dataLenLong) - - server *h2quic.Server - stoppedServing chan struct{} - port string -) - -func init() { - http.HandleFunc("/prdata", func(w http.ResponseWriter, r *http.Request) { - defer GinkgoRecover() - sl := r.URL.Query().Get("len") - if sl != "" { - var err error - l, err := strconv.Atoi(sl) - Expect(err).NotTo(HaveOccurred()) - _, err = w.Write(GeneratePRData(l)) - Expect(err).NotTo(HaveOccurred()) - } else { - _, err := w.Write(PRData) - Expect(err).NotTo(HaveOccurred()) - } - }) - - http.HandleFunc("/prdatalong", func(w http.ResponseWriter, r *http.Request) { - defer GinkgoRecover() - _, err := w.Write(PRDataLong) - Expect(err).NotTo(HaveOccurred()) - }) - - http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { - defer GinkgoRecover() - _, err := io.WriteString(w, "Hello, World!\n") - Expect(err).NotTo(HaveOccurred()) - }) - - http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) { - defer GinkgoRecover() - body, err := ioutil.ReadAll(r.Body) - Expect(err).NotTo(HaveOccurred()) - _, err = w.Write(body) - Expect(err).NotTo(HaveOccurred()) - }) -} - -// See https://en.wikipedia.org/wiki/Lehmer_random_number_generator -func GeneratePRData(l int) []byte { - res := make([]byte, l) - seed := uint64(1) - for i := 0; i < l; i++ { - seed = seed * 48271 % 2147483647 - res[i] = byte(seed) - } - return res -} - -// StartQuicServer starts a h2quic.Server. -// versions is a slice of supported QUIC versions. It may be nil, then all supported versions are used. -func StartQuicServer(versions []protocol.VersionNumber) { - server = &h2quic.Server{ - Server: &http.Server{ - TLSConfig: testdata.GetTLSConfig(), - }, - QuicConfig: &quic.Config{ - Versions: versions, - }, - } - - addr, err := net.ResolveUDPAddr("udp", "0.0.0.0:0") - Expect(err).NotTo(HaveOccurred()) - conn, err := net.ListenUDP("udp", addr) - Expect(err).NotTo(HaveOccurred()) - port = strconv.Itoa(conn.LocalAddr().(*net.UDPAddr).Port) - - stoppedServing = make(chan struct{}) - - go func() { - defer GinkgoRecover() - server.Serve(conn) - close(stoppedServing) - }() -} - -// StopQuicServer stops the h2quic.Server. -func StopQuicServer() { - Expect(server.Close()).NotTo(HaveOccurred()) - Eventually(stoppedServing).Should(BeClosed()) -} - -// Port returns the UDP port of the QUIC server. -func Port() string { - return port -} diff --git a/vendor/lucas-clemente/quic-go/internal/ackhandler/ackhandler_suite_test.go b/vendor/lucas-clemente/quic-go/internal/ackhandler/ackhandler_suite_test.go deleted file mode 100644 index 9e7e07776..000000000 --- a/vendor/lucas-clemente/quic-go/internal/ackhandler/ackhandler_suite_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package ackhandler - -import ( - "github.com/golang/mock/gomock" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestCrypto(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "AckHandler Suite") -} - -var mockCtrl *gomock.Controller - -var _ = BeforeEach(func() { - mockCtrl = gomock.NewController(GinkgoT()) -}) - -var _ = AfterEach(func() { - mockCtrl.Finish() -}) diff --git a/vendor/lucas-clemente/quic-go/internal/ackhandler/received_packet_handler_test.go b/vendor/lucas-clemente/quic-go/internal/ackhandler/received_packet_handler_test.go deleted file mode 100644 index d845efe86..000000000 --- a/vendor/lucas-clemente/quic-go/internal/ackhandler/received_packet_handler_test.go +++ /dev/null @@ -1,382 +0,0 @@ -package ackhandler - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("receivedPacketHandler", func() { - var ( - handler *receivedPacketHandler - rttStats *congestion.RTTStats - ) - - BeforeEach(func() { - rttStats = &congestion.RTTStats{} - handler = NewReceivedPacketHandler(rttStats, utils.DefaultLogger, protocol.VersionWhatever).(*receivedPacketHandler) - }) - - Context("accepting packets", func() { - It("handles a packet that arrives late", func() { - err := handler.ReceivedPacket(protocol.PacketNumber(1), time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - err = handler.ReceivedPacket(protocol.PacketNumber(3), time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - err = handler.ReceivedPacket(protocol.PacketNumber(2), time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - }) - - It("saves the time when each packet arrived", func() { - err := handler.ReceivedPacket(protocol.PacketNumber(3), time.Now(), true) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.largestObservedReceivedTime).To(BeTemporally("~", time.Now(), 10*time.Millisecond)) - }) - - It("updates the largestObserved and the largestObservedReceivedTime", func() { - now := time.Now() - handler.largestObserved = 3 - handler.largestObservedReceivedTime = now.Add(-1 * time.Second) - err := handler.ReceivedPacket(5, now, true) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.largestObserved).To(Equal(protocol.PacketNumber(5))) - Expect(handler.largestObservedReceivedTime).To(Equal(now)) - }) - - It("doesn't update the largestObserved and the largestObservedReceivedTime for a belated packet", func() { - now := time.Now() - timestamp := now.Add(-1 * time.Second) - handler.largestObserved = 5 - handler.largestObservedReceivedTime = timestamp - err := handler.ReceivedPacket(4, now, true) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.largestObserved).To(Equal(protocol.PacketNumber(5))) - Expect(handler.largestObservedReceivedTime).To(Equal(timestamp)) - }) - - It("passes on errors from receivedPacketHistory", func() { - var err error - for i := protocol.PacketNumber(0); i < 5*protocol.MaxTrackedReceivedAckRanges; i++ { - err = handler.ReceivedPacket(2*i+1, time.Time{}, true) - // this will eventually return an error - // details about when exactly the receivedPacketHistory errors are tested there - if err != nil { - break - } - } - Expect(err).To(MatchError(errTooManyOutstandingReceivedAckRanges)) - }) - }) - - Context("ACKs", func() { - Context("queueing ACKs", func() { - receiveAndAck10Packets := func() { - for i := 1; i <= 10; i++ { - err := handler.ReceivedPacket(protocol.PacketNumber(i), time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - } - Expect(handler.GetAckFrame()).ToNot(BeNil()) - Expect(handler.ackQueued).To(BeFalse()) - } - - receiveAndAckPacketsUntilAckDecimation := func() { - for i := 1; i <= minReceivedBeforeAckDecimation; i++ { - err := handler.ReceivedPacket(protocol.PacketNumber(i), time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - } - Expect(handler.GetAckFrame()).ToNot(BeNil()) - Expect(handler.ackQueued).To(BeFalse()) - } - - It("always queues an ACK for the first packet", func() { - err := handler.ReceivedPacket(1, time.Time{}, false) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeTrue()) - Expect(handler.GetAlarmTimeout()).To(BeZero()) - }) - - It("works with packet number 0", func() { - err := handler.ReceivedPacket(0, time.Time{}, false) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeTrue()) - Expect(handler.GetAlarmTimeout()).To(BeZero()) - }) - - It("queues an ACK for every second retransmittable packet at the beginning", func() { - receiveAndAck10Packets() - p := protocol.PacketNumber(11) - for i := 0; i <= 20; i++ { - err := handler.ReceivedPacket(p, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeFalse()) - p++ - err = handler.ReceivedPacket(p, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeTrue()) - p++ - // dequeue the ACK frame - Expect(handler.GetAckFrame()).ToNot(BeNil()) - } - }) - - It("queues an ACK for every 10 retransmittable packet, if they are arriving fast", func() { - receiveAndAck10Packets() - p := protocol.PacketNumber(10000) - for i := 0; i < 9; i++ { - err := handler.ReceivedPacket(p, time.Now(), true) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeFalse()) - p++ - } - Expect(handler.GetAlarmTimeout()).NotTo(BeZero()) - err := handler.ReceivedPacket(p, time.Now(), true) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeTrue()) - Expect(handler.GetAlarmTimeout()).To(BeZero()) - }) - - It("only sets the timer when receiving a retransmittable packets", func() { - receiveAndAck10Packets() - err := handler.ReceivedPacket(11, time.Now(), false) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeFalse()) - Expect(handler.GetAlarmTimeout()).To(BeZero()) - rcvTime := time.Now().Add(10 * time.Millisecond) - err = handler.ReceivedPacket(12, rcvTime, true) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeFalse()) - Expect(handler.GetAlarmTimeout()).To(Equal(rcvTime.Add(ackSendDelay))) - }) - - It("queues an ACK if it was reported missing before", func() { - receiveAndAck10Packets() - err := handler.ReceivedPacket(11, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - err = handler.ReceivedPacket(13, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - ack := handler.GetAckFrame() // ACK: 1-11 and 13, missing: 12 - Expect(ack).ToNot(BeNil()) - Expect(ack.HasMissingRanges()).To(BeTrue()) - Expect(handler.ackQueued).To(BeFalse()) - err = handler.ReceivedPacket(12, time.Time{}, false) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeTrue()) - }) - - It("doesn't queue an ACK if it was reported missing before, but is below the threshold", func() { - receiveAndAck10Packets() - // 11 is missing - err := handler.ReceivedPacket(12, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - err = handler.ReceivedPacket(13, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - ack := handler.GetAckFrame() // ACK: 1-10, 12-13 - Expect(ack).ToNot(BeNil()) - // now receive 11 - handler.IgnoreBelow(12) - err = handler.ReceivedPacket(11, time.Time{}, false) - Expect(err).ToNot(HaveOccurred()) - ack = handler.GetAckFrame() - Expect(ack).To(BeNil()) - }) - - It("doesn't queue an ACK if the packet closes a gap that was not yet reported", func() { - receiveAndAckPacketsUntilAckDecimation() - p := protocol.PacketNumber(minReceivedBeforeAckDecimation + 1) - err := handler.ReceivedPacket(p+1, time.Now(), true) // p is missing now - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeFalse()) - Expect(handler.GetAlarmTimeout()).ToNot(BeZero()) - err = handler.ReceivedPacket(p, time.Now(), true) // p is not missing any more - Expect(err).ToNot(HaveOccurred()) - Expect(handler.ackQueued).To(BeFalse()) - }) - - It("sets an ACK alarm after 1/4 RTT if it creates a new missing range", func() { - now := time.Now().Add(-time.Hour) - rtt := 80 * time.Millisecond - rttStats.UpdateRTT(rtt, 0, now) - receiveAndAckPacketsUntilAckDecimation() - p := protocol.PacketNumber(minReceivedBeforeAckDecimation + 1) - for i := p; i < p+6; i++ { - err := handler.ReceivedPacket(i, now, true) - Expect(err).ToNot(HaveOccurred()) - } - err := handler.ReceivedPacket(p+10, now, true) // we now know that packets p+7, p+8 and p+9 - Expect(err).ToNot(HaveOccurred()) - Expect(rttStats.MinRTT()).To(Equal(rtt)) - Expect(handler.ackAlarm.Sub(now)).To(Equal(rtt / 8)) - ack := handler.GetAckFrame() - Expect(ack.HasMissingRanges()).To(BeTrue()) - Expect(ack).ToNot(BeNil()) - }) - }) - - Context("ACK generation", func() { - BeforeEach(func() { - handler.ackQueued = true - }) - - It("generates a simple ACK frame", func() { - err := handler.ReceivedPacket(1, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - err = handler.ReceivedPacket(2, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - ack := handler.GetAckFrame() - Expect(ack).ToNot(BeNil()) - Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(2))) - Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(1))) - Expect(ack.HasMissingRanges()).To(BeFalse()) - }) - - It("generates an ACK for packet number 0", func() { - err := handler.ReceivedPacket(0, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - ack := handler.GetAckFrame() - Expect(ack).ToNot(BeNil()) - Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(0))) - Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(0))) - Expect(ack.HasMissingRanges()).To(BeFalse()) - }) - - It("sets the delay time", func() { - err := handler.ReceivedPacket(1, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - err = handler.ReceivedPacket(2, time.Now().Add(-1337*time.Millisecond), true) - Expect(err).ToNot(HaveOccurred()) - ack := handler.GetAckFrame() - Expect(ack).ToNot(BeNil()) - Expect(ack.DelayTime).To(BeNumerically("~", 1337*time.Millisecond, 50*time.Millisecond)) - }) - - It("saves the last sent ACK", func() { - err := handler.ReceivedPacket(1, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - ack := handler.GetAckFrame() - Expect(ack).ToNot(BeNil()) - Expect(handler.lastAck).To(Equal(ack)) - err = handler.ReceivedPacket(2, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - handler.ackQueued = true - ack = handler.GetAckFrame() - Expect(ack).ToNot(BeNil()) - Expect(handler.lastAck).To(Equal(ack)) - }) - - It("generates an ACK frame with missing packets", func() { - err := handler.ReceivedPacket(1, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - err = handler.ReceivedPacket(4, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - ack := handler.GetAckFrame() - Expect(ack).ToNot(BeNil()) - Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(4))) - Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(1))) - Expect(ack.AckRanges).To(Equal([]wire.AckRange{ - {Smallest: 4, Largest: 4}, - {Smallest: 1, Largest: 1}, - })) - }) - - It("generates an ACK for packet number 0 and other packets", func() { - err := handler.ReceivedPacket(0, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - err = handler.ReceivedPacket(1, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - err = handler.ReceivedPacket(3, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - ack := handler.GetAckFrame() - Expect(ack).ToNot(BeNil()) - Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(3))) - Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(0))) - Expect(ack.AckRanges).To(Equal([]wire.AckRange{ - {Smallest: 3, Largest: 3}, - {Smallest: 0, Largest: 1}, - })) - }) - - It("accepts packets below the lower limit", func() { - handler.IgnoreBelow(6) - err := handler.ReceivedPacket(2, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - }) - - It("doesn't add delayed packets to the packetHistory", func() { - handler.IgnoreBelow(7) - err := handler.ReceivedPacket(4, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - err = handler.ReceivedPacket(10, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - ack := handler.GetAckFrame() - Expect(ack).ToNot(BeNil()) - Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(10))) - Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(10))) - }) - - It("deletes packets from the packetHistory when a lower limit is set", func() { - for i := 1; i <= 12; i++ { - err := handler.ReceivedPacket(protocol.PacketNumber(i), time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - } - handler.IgnoreBelow(7) - // check that the packets were deleted from the receivedPacketHistory by checking the values in an ACK frame - ack := handler.GetAckFrame() - Expect(ack).ToNot(BeNil()) - Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(12))) - Expect(ack.LowestAcked()).To(Equal(protocol.PacketNumber(7))) - Expect(ack.HasMissingRanges()).To(BeFalse()) - }) - - // TODO: remove this test when dropping support for STOP_WAITINGs - It("handles a lower limit of 0", func() { - handler.IgnoreBelow(0) - err := handler.ReceivedPacket(1337, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - ack := handler.GetAckFrame() - Expect(ack).ToNot(BeNil()) - Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(1337))) - }) - - It("resets all counters needed for the ACK queueing decision when sending an ACK", func() { - err := handler.ReceivedPacket(1, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - handler.ackAlarm = time.Now().Add(-time.Minute) - Expect(handler.GetAckFrame()).ToNot(BeNil()) - Expect(handler.packetsReceivedSinceLastAck).To(BeZero()) - Expect(handler.GetAlarmTimeout()).To(BeZero()) - Expect(handler.retransmittablePacketsReceivedSinceLastAck).To(BeZero()) - Expect(handler.ackQueued).To(BeFalse()) - }) - - It("doesn't generate an ACK when none is queued and the timer is not set", func() { - err := handler.ReceivedPacket(1, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - handler.ackQueued = false - handler.ackAlarm = time.Time{} - Expect(handler.GetAckFrame()).To(BeNil()) - }) - - It("doesn't generate an ACK when none is queued and the timer has not yet expired", func() { - err := handler.ReceivedPacket(1, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - handler.ackQueued = false - handler.ackAlarm = time.Now().Add(time.Minute) - Expect(handler.GetAckFrame()).To(BeNil()) - }) - - It("generates an ACK when the timer has expired", func() { - err := handler.ReceivedPacket(1, time.Time{}, true) - Expect(err).ToNot(HaveOccurred()) - handler.ackQueued = false - handler.ackAlarm = time.Now().Add(-time.Minute) - Expect(handler.GetAckFrame()).ToNot(BeNil()) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/ackhandler/received_packet_history_test.go b/vendor/lucas-clemente/quic-go/internal/ackhandler/received_packet_history_test.go deleted file mode 100644 index 4a24b95c4..000000000 --- a/vendor/lucas-clemente/quic-go/internal/ackhandler/received_packet_history_test.go +++ /dev/null @@ -1,248 +0,0 @@ -package ackhandler - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("receivedPacketHistory", func() { - var ( - hist *receivedPacketHistory - ) - - BeforeEach(func() { - hist = newReceivedPacketHistory() - }) - - Context("ranges", func() { - It("adds the first packet", func() { - hist.ReceivedPacket(4) - Expect(hist.ranges.Len()).To(Equal(1)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 4})) - }) - - It("doesn't care about duplicate packets", func() { - hist.ReceivedPacket(4) - Expect(hist.ranges.Len()).To(Equal(1)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 4})) - }) - - It("adds a few consecutive packets", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(5) - hist.ReceivedPacket(6) - Expect(hist.ranges.Len()).To(Equal(1)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 6})) - }) - - It("doesn't care about a duplicate packet contained in an existing range", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(5) - hist.ReceivedPacket(6) - hist.ReceivedPacket(5) - Expect(hist.ranges.Len()).To(Equal(1)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 6})) - }) - - It("extends a range at the front", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(3) - Expect(hist.ranges.Len()).To(Equal(1)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 3, End: 4})) - }) - - It("creates a new range when a packet is lost", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(6) - Expect(hist.ranges.Len()).To(Equal(2)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 4})) - Expect(hist.ranges.Back().Value).To(Equal(utils.PacketInterval{Start: 6, End: 6})) - }) - - It("creates a new range in between two ranges", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(10) - Expect(hist.ranges.Len()).To(Equal(2)) - hist.ReceivedPacket(7) - Expect(hist.ranges.Len()).To(Equal(3)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 4})) - Expect(hist.ranges.Front().Next().Value).To(Equal(utils.PacketInterval{Start: 7, End: 7})) - Expect(hist.ranges.Back().Value).To(Equal(utils.PacketInterval{Start: 10, End: 10})) - }) - - It("creates a new range before an existing range for a belated packet", func() { - hist.ReceivedPacket(6) - hist.ReceivedPacket(4) - Expect(hist.ranges.Len()).To(Equal(2)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 4})) - Expect(hist.ranges.Back().Value).To(Equal(utils.PacketInterval{Start: 6, End: 6})) - }) - - It("extends a previous range at the end", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(7) - hist.ReceivedPacket(5) - Expect(hist.ranges.Len()).To(Equal(2)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 5})) - Expect(hist.ranges.Back().Value).To(Equal(utils.PacketInterval{Start: 7, End: 7})) - }) - - It("extends a range at the front", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(7) - hist.ReceivedPacket(6) - Expect(hist.ranges.Len()).To(Equal(2)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 4})) - Expect(hist.ranges.Back().Value).To(Equal(utils.PacketInterval{Start: 6, End: 7})) - }) - - It("closes a range", func() { - hist.ReceivedPacket(6) - hist.ReceivedPacket(4) - Expect(hist.ranges.Len()).To(Equal(2)) - hist.ReceivedPacket(5) - Expect(hist.ranges.Len()).To(Equal(1)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 6})) - }) - - It("closes a range in the middle", func() { - hist.ReceivedPacket(1) - hist.ReceivedPacket(10) - hist.ReceivedPacket(4) - hist.ReceivedPacket(6) - Expect(hist.ranges.Len()).To(Equal(4)) - hist.ReceivedPacket(5) - Expect(hist.ranges.Len()).To(Equal(3)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 1, End: 1})) - Expect(hist.ranges.Front().Next().Value).To(Equal(utils.PacketInterval{Start: 4, End: 6})) - Expect(hist.ranges.Back().Value).To(Equal(utils.PacketInterval{Start: 10, End: 10})) - }) - }) - - Context("deleting", func() { - It("does nothing when the history is empty", func() { - hist.DeleteBelow(5) - Expect(hist.ranges.Len()).To(BeZero()) - }) - - It("deletes a range", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(5) - hist.ReceivedPacket(10) - hist.DeleteBelow(6) - Expect(hist.ranges.Len()).To(Equal(1)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 10, End: 10})) - }) - - It("deletes multiple ranges", func() { - hist.ReceivedPacket(1) - hist.ReceivedPacket(5) - hist.ReceivedPacket(10) - hist.DeleteBelow(8) - Expect(hist.ranges.Len()).To(Equal(1)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 10, End: 10})) - }) - - It("adjusts a range, if packets are delete from an existing range", func() { - hist.ReceivedPacket(3) - hist.ReceivedPacket(4) - hist.ReceivedPacket(5) - hist.ReceivedPacket(6) - hist.ReceivedPacket(7) - hist.DeleteBelow(5) - Expect(hist.ranges.Len()).To(Equal(1)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 5, End: 7})) - }) - - It("adjusts a range, if only one packet remains in the range", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(5) - hist.ReceivedPacket(10) - hist.DeleteBelow(5) - Expect(hist.ranges.Len()).To(Equal(2)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 5, End: 5})) - Expect(hist.ranges.Back().Value).To(Equal(utils.PacketInterval{Start: 10, End: 10})) - }) - - It("keeps a one-packet range, if deleting up to the packet directly below", func() { - hist.ReceivedPacket(4) - hist.DeleteBelow(4) - Expect(hist.ranges.Len()).To(Equal(1)) - Expect(hist.ranges.Front().Value).To(Equal(utils.PacketInterval{Start: 4, End: 4})) - }) - - Context("DoS protection", func() { - It("doesn't create more than MaxTrackedReceivedAckRanges ranges", func() { - for i := protocol.PacketNumber(1); i <= protocol.MaxTrackedReceivedAckRanges; i++ { - err := hist.ReceivedPacket(2 * i) - Expect(err).ToNot(HaveOccurred()) - } - err := hist.ReceivedPacket(2*protocol.MaxTrackedReceivedAckRanges + 2) - Expect(err).To(MatchError(errTooManyOutstandingReceivedAckRanges)) - }) - - It("doesn't consider already deleted ranges for MaxTrackedReceivedAckRanges", func() { - for i := protocol.PacketNumber(1); i <= protocol.MaxTrackedReceivedAckRanges; i++ { - err := hist.ReceivedPacket(2 * i) - Expect(err).ToNot(HaveOccurred()) - } - err := hist.ReceivedPacket(2*protocol.MaxTrackedReceivedAckRanges + 2) - Expect(err).To(MatchError(errTooManyOutstandingReceivedAckRanges)) - hist.DeleteBelow(protocol.MaxTrackedReceivedAckRanges) // deletes about half of the ranges - err = hist.ReceivedPacket(2*protocol.MaxTrackedReceivedAckRanges + 4) - Expect(err).ToNot(HaveOccurred()) - }) - }) - }) - - Context("ACK range export", func() { - It("returns nil if there are no ranges", func() { - Expect(hist.GetAckRanges()).To(BeNil()) - }) - - It("gets a single ACK range", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(5) - ackRanges := hist.GetAckRanges() - Expect(ackRanges).To(HaveLen(1)) - Expect(ackRanges[0]).To(Equal(wire.AckRange{Smallest: 4, Largest: 5})) - }) - - It("gets multiple ACK ranges", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(5) - hist.ReceivedPacket(6) - hist.ReceivedPacket(1) - hist.ReceivedPacket(11) - hist.ReceivedPacket(10) - hist.ReceivedPacket(2) - ackRanges := hist.GetAckRanges() - Expect(ackRanges).To(HaveLen(3)) - Expect(ackRanges[0]).To(Equal(wire.AckRange{Smallest: 10, Largest: 11})) - Expect(ackRanges[1]).To(Equal(wire.AckRange{Smallest: 4, Largest: 6})) - Expect(ackRanges[2]).To(Equal(wire.AckRange{Smallest: 1, Largest: 2})) - }) - }) - - Context("Getting the highest ACK range", func() { - It("returns the zero value if there are no ranges", func() { - Expect(hist.GetHighestAckRange()).To(BeZero()) - }) - - It("gets a single ACK range", func() { - hist.ReceivedPacket(4) - hist.ReceivedPacket(5) - Expect(hist.GetHighestAckRange()).To(Equal(wire.AckRange{Smallest: 4, Largest: 5})) - }) - - It("gets the highest of multiple ACK ranges", func() { - hist.ReceivedPacket(3) - hist.ReceivedPacket(6) - hist.ReceivedPacket(7) - Expect(hist.GetHighestAckRange()).To(Equal(wire.AckRange{Smallest: 6, Largest: 7})) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/ackhandler/retransmittable_test.go b/vendor/lucas-clemente/quic-go/internal/ackhandler/retransmittable_test.go deleted file mode 100644 index 63d0a589d..000000000 --- a/vendor/lucas-clemente/quic-go/internal/ackhandler/retransmittable_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package ackhandler - -import ( - "reflect" - - "github.com/lucas-clemente/quic-go/internal/wire" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("retransmittable frames", func() { - for fl, el := range map[wire.Frame]bool{ - &wire.AckFrame{}: false, - &wire.StopWaitingFrame{}: false, - &wire.BlockedFrame{}: true, - &wire.ConnectionCloseFrame{}: true, - &wire.GoawayFrame{}: true, - &wire.PingFrame{}: true, - &wire.RstStreamFrame{}: true, - &wire.StreamFrame{}: true, - &wire.MaxDataFrame{}: true, - &wire.MaxStreamDataFrame{}: true, - } { - f := fl - e := el - fName := reflect.ValueOf(f).Elem().Type().Name() - - It("works for "+fName, func() { - Expect(IsFrameRetransmittable(f)).To(Equal(e)) - }) - - It("stripping non-retransmittable frames works for "+fName, func() { - s := []wire.Frame{f} - if e { - Expect(stripNonRetransmittableFrames(s)).To(Equal([]wire.Frame{f})) - } else { - Expect(stripNonRetransmittableFrames(s)).To(BeEmpty()) - } - }) - - It("HasRetransmittableFrames works for "+fName, func() { - Expect(HasRetransmittableFrames([]wire.Frame{f})).To(Equal(e)) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/internal/ackhandler/send_mode_test.go b/vendor/lucas-clemente/quic-go/internal/ackhandler/send_mode_test.go deleted file mode 100644 index c267d38c1..000000000 --- a/vendor/lucas-clemente/quic-go/internal/ackhandler/send_mode_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package ackhandler - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Send Mode", func() { - It("has a string representation", func() { - Expect(SendNone.String()).To(Equal("none")) - Expect(SendAny.String()).To(Equal("any")) - Expect(SendAck.String()).To(Equal("ack")) - Expect(SendRTO.String()).To(Equal("rto")) - Expect(SendTLP.String()).To(Equal("tlp")) - Expect(SendRetransmission.String()).To(Equal("retransmission")) - Expect(SendMode(123).String()).To(Equal("invalid send mode: 123")) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/ackhandler/sent_packet_handler_test.go b/vendor/lucas-clemente/quic-go/internal/ackhandler/sent_packet_handler_test.go deleted file mode 100644 index 9960e5370..000000000 --- a/vendor/lucas-clemente/quic-go/internal/ackhandler/sent_packet_handler_test.go +++ /dev/null @@ -1,1080 +0,0 @@ -package ackhandler - -import ( - "time" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/mocks" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -func retransmittablePacket(p *Packet) *Packet { - if p.EncryptionLevel == protocol.EncryptionUnspecified { - p.EncryptionLevel = protocol.EncryptionForwardSecure - } - if p.Length == 0 { - p.Length = 1 - } - if p.SendTime.IsZero() { - p.SendTime = time.Now() - } - p.Frames = []wire.Frame{&wire.PingFrame{}} - return p -} - -func nonRetransmittablePacket(p *Packet) *Packet { - p = retransmittablePacket(p) - p.Frames = []wire.Frame{ - &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}}, - } - return p -} - -func handshakePacket(p *Packet) *Packet { - p = retransmittablePacket(p) - p.EncryptionLevel = protocol.EncryptionUnencrypted - return p -} - -var _ = Describe("SentPacketHandler", func() { - var ( - handler *sentPacketHandler - streamFrame wire.StreamFrame - ) - - BeforeEach(func() { - rttStats := &congestion.RTTStats{} - handler = NewSentPacketHandler(rttStats, utils.DefaultLogger, protocol.VersionWhatever).(*sentPacketHandler) - handler.SetHandshakeComplete() - streamFrame = wire.StreamFrame{ - StreamID: 5, - Data: []byte{0x13, 0x37}, - } - }) - - getPacket := func(pn protocol.PacketNumber) *Packet { - if el, ok := handler.packetHistory.packetMap[pn]; ok { - return &el.Value - } - return nil - } - - losePacket := func(pn protocol.PacketNumber) { - p := getPacket(pn) - ExpectWithOffset(1, p).ToNot(BeNil()) - handler.queuePacketForRetransmission(p) - if p.includedInBytesInFlight { - p.includedInBytesInFlight = false - handler.bytesInFlight -= p.Length - } - r := handler.DequeuePacketForRetransmission() - ExpectWithOffset(1, r).ToNot(BeNil()) - ExpectWithOffset(1, r.PacketNumber).To(Equal(pn)) - } - - expectInPacketHistory := func(expected []protocol.PacketNumber) { - ExpectWithOffset(1, handler.packetHistory.Len()).To(Equal(len(expected))) - for _, p := range expected { - ExpectWithOffset(1, handler.packetHistory.packetMap).To(HaveKey(p)) - } - } - - updateRTT := func(rtt time.Duration) { - handler.rttStats.UpdateRTT(rtt, 0, time.Now()) - ExpectWithOffset(1, handler.rttStats.SmoothedRTT()).To(Equal(rtt)) - } - - It("determines the packet number length", func() { - handler.largestAcked = 0x1337 - Expect(handler.GetPacketNumberLen(0x1338)).To(Equal(protocol.PacketNumberLen2)) - Expect(handler.GetPacketNumberLen(0xfffffff)).To(Equal(protocol.PacketNumberLen4)) - }) - - Context("registering sent packets", func() { - It("accepts two consecutive packets", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2})) - Expect(handler.lastSentPacketNumber).To(Equal(protocol.PacketNumber(2))) - expectInPacketHistory([]protocol.PacketNumber{1, 2}) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(2))) - Expect(handler.skippedPackets).To(BeEmpty()) - }) - - It("accepts packet number 0", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 0})) - Expect(handler.lastSentPacketNumber).To(BeZero()) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1})) - Expect(handler.lastSentPacketNumber).To(Equal(protocol.PacketNumber(1))) - expectInPacketHistory([]protocol.PacketNumber{0, 1}) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(2))) - Expect(handler.skippedPackets).To(BeEmpty()) - }) - - It("stores the sent time", func() { - sendTime := time.Now().Add(-time.Minute) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: sendTime})) - Expect(handler.lastSentRetransmittablePacketTime).To(Equal(sendTime)) - }) - - It("stores the sent time of handshake packets", func() { - sendTime := time.Now().Add(-time.Minute) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: sendTime, EncryptionLevel: protocol.EncryptionUnencrypted})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2, SendTime: sendTime.Add(time.Hour), EncryptionLevel: protocol.EncryptionForwardSecure})) - Expect(handler.lastSentHandshakePacketTime).To(Equal(sendTime)) - }) - - It("does not store non-retransmittable packets", func() { - handler.SentPacket(nonRetransmittablePacket(&Packet{PacketNumber: 1})) - Expect(handler.packetHistory.Len()).To(BeZero()) - Expect(handler.lastSentRetransmittablePacketTime).To(BeZero()) - Expect(handler.bytesInFlight).To(BeZero()) - }) - - Context("skipped packet numbers", func() { - It("works with non-consecutive packet numbers", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3})) - Expect(handler.lastSentPacketNumber).To(Equal(protocol.PacketNumber(3))) - expectInPacketHistory([]protocol.PacketNumber{1, 3}) - Expect(handler.skippedPackets).To(Equal([]protocol.PacketNumber{2})) - }) - - It("works with non-retransmittable packets", func() { - handler.SentPacket(nonRetransmittablePacket(&Packet{PacketNumber: 1})) - handler.SentPacket(nonRetransmittablePacket(&Packet{PacketNumber: 3})) - Expect(handler.skippedPackets).To(Equal([]protocol.PacketNumber{2})) - }) - - It("recognizes multiple skipped packets", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 5})) - Expect(handler.skippedPackets).To(Equal([]protocol.PacketNumber{2, 4})) - }) - - It("recognizes multiple consecutive skipped packets", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 4})) - Expect(handler.skippedPackets).To(Equal([]protocol.PacketNumber{2, 3})) - }) - - It("limits the lengths of the skipped packet slice", func() { - for i := protocol.PacketNumber(0); i < protocol.MaxTrackedSkippedPackets+5; i++ { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2*i + 1})) - } - Expect(handler.skippedPackets).To(HaveLen(protocol.MaxUndecryptablePackets)) - Expect(handler.skippedPackets[0]).To(Equal(protocol.PacketNumber(10))) - Expect(handler.skippedPackets[protocol.MaxTrackedSkippedPackets-1]).To(Equal(protocol.PacketNumber(10 + 2*(protocol.MaxTrackedSkippedPackets-1)))) - }) - - Context("garbage collection", func() { - It("keeps all packet numbers above the LargestAcked", func() { - handler.skippedPackets = []protocol.PacketNumber{2, 5, 8, 10} - handler.largestAcked = 1 - handler.garbageCollectSkippedPackets() - Expect(handler.skippedPackets).To(Equal([]protocol.PacketNumber{2, 5, 8, 10})) - }) - - It("doesn't keep packet numbers below the LargestAcked", func() { - handler.skippedPackets = []protocol.PacketNumber{1, 5, 8, 10} - handler.largestAcked = 5 - handler.garbageCollectSkippedPackets() - Expect(handler.skippedPackets).To(Equal([]protocol.PacketNumber{8, 10})) - }) - - It("deletes all packet numbers if LargestAcked is sufficiently high", func() { - handler.skippedPackets = []protocol.PacketNumber{1, 5, 10} - handler.largestAcked = 15 - handler.garbageCollectSkippedPackets() - Expect(handler.skippedPackets).To(BeEmpty()) - }) - }) - - Context("ACK handling", func() { - BeforeEach(func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 10})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 12})) - }) - - It("rejects ACKs for skipped packets", func() { - ack := &wire.AckFrame{ - AckRanges: []wire.AckRange{{Smallest: 10, Largest: 12}}, - } - err := handler.ReceivedAck(ack, 1337, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).To(MatchError("InvalidAckData: Received an ACK for a skipped packet number")) - }) - - It("accepts an ACK that correctly nacks a skipped packet", func() { - ack := &wire.AckFrame{ - AckRanges: []wire.AckRange{ - {Smallest: 12, Largest: 12}, - {Smallest: 10, Largest: 10}, - }, - } - err := handler.ReceivedAck(ack, 1337, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.largestAcked).ToNot(BeZero()) - }) - }) - }) - }) - - Context("ACK processing", func() { - BeforeEach(func() { - for i := protocol.PacketNumber(0); i < 10; i++ { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: i})) - } - // Increase RTT, because the tests would be flaky otherwise - updateRTT(time.Hour) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(10))) - }) - - Context("ACK validation", func() { - It("accepts ACKs sent in packet 0", func() { - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 0, Largest: 5}}} - err := handler.ReceivedAck(ack, 0, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.largestAcked).To(Equal(protocol.PacketNumber(5))) - }) - - It("rejects duplicate ACKs", func() { - ack1 := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 0, Largest: 3}}} - ack2 := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 0, Largest: 4}}} - err := handler.ReceivedAck(ack1, 1337, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.largestAcked).To(Equal(protocol.PacketNumber(3))) - // this wouldn't happen in practice - // for testing purposes, we pretend send a different ACK frame in a duplicated packet, to be able to verify that it actually doesn't get processed - err = handler.ReceivedAck(ack2, 1337, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.largestAcked).To(Equal(protocol.PacketNumber(3))) - }) - - It("rejects out of order ACKs", func() { - // acks packets 0, 1, 2, 3 - ack1 := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 0, Largest: 3}}} - ack2 := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 0, Largest: 4}}} - err := handler.ReceivedAck(ack1, 1337, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - // this wouldn't happen in practive - // a receiver wouldn't send an ACK for a lower largest acked in a packet sent later - err = handler.ReceivedAck(ack2, 1337-1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.largestAcked).To(Equal(protocol.PacketNumber(3))) - }) - - It("rejects ACKs with a too high LargestAcked packet number", func() { - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 0, Largest: 9999}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).To(MatchError("InvalidAckData: Received ACK for an unsent package")) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(10))) - }) - - It("ignores repeated ACKs", func() { - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 3}}} - err := handler.ReceivedAck(ack, 1337, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(7))) - err = handler.ReceivedAck(ack, 1337+1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.largestAcked).To(Equal(protocol.PacketNumber(3))) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(7))) - }) - }) - - Context("acks and nacks the right packets", func() { - It("adjusts the LargestAcked, and adjusts the bytes in flight", func() { - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 0, Largest: 5}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.largestAcked).To(Equal(protocol.PacketNumber(5))) - expectInPacketHistory([]protocol.PacketNumber{6, 7, 8, 9}) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(4))) - }) - - It("acks packet 0", func() { - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 0, Largest: 0}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(getPacket(0)).To(BeNil()) - expectInPacketHistory([]protocol.PacketNumber{1, 2, 3, 4, 5, 6, 7, 8, 9}) - }) - - It("handles an ACK frame with one missing packet range", func() { - ack := &wire.AckFrame{ // lose 4 and 5 - AckRanges: []wire.AckRange{ - {Smallest: 6, Largest: 9}, - {Smallest: 1, Largest: 3}, - }, - } - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{0, 4, 5}) - }) - - It("does not ack packets below the LowestAcked", func() { - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 3, Largest: 8}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{0, 1, 2, 9}) - }) - - It("handles an ACK with multiple missing packet ranges", func() { - ack := &wire.AckFrame{ // packets 2, 4 and 5, and 8 were lost - AckRanges: []wire.AckRange{ - {Smallest: 9, Largest: 9}, - {Smallest: 6, Largest: 7}, - {Smallest: 3, Largest: 3}, - {Smallest: 1, Largest: 1}, - }, - } - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{0, 2, 4, 5, 8}) - }) - - It("processes an ACK frame that would be sent after a late arrival of a packet", func() { - ack1 := &wire.AckFrame{ // 3 lost - AckRanges: []wire.AckRange{ - {Smallest: 4, Largest: 6}, - {Smallest: 1, Largest: 2}, - }, - } - err := handler.ReceivedAck(ack1, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{0, 3, 7, 8, 9}) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(5))) - ack2 := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 6}}} // now ack 3 - err = handler.ReceivedAck(ack2, 2, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{0, 7, 8, 9}) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(4))) - }) - - It("processes an ACK frame that would be sent after a late arrival of a packet and another packet", func() { - ack1 := &wire.AckFrame{ - AckRanges: []wire.AckRange{ - {Smallest: 4, Largest: 6}, - {Smallest: 0, Largest: 2}, - }, - } - err := handler.ReceivedAck(ack1, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{3, 7, 8, 9}) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(4))) - ack2 := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 7}}} - err = handler.ReceivedAck(ack2, 2, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(2))) - expectInPacketHistory([]protocol.PacketNumber{8, 9}) - }) - - It("processes an ACK that contains old ACK ranges", func() { - ack1 := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 6}}} - err := handler.ReceivedAck(ack1, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{0, 7, 8, 9}) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(4))) - ack2 := &wire.AckFrame{ - AckRanges: []wire.AckRange{ - {Smallest: 8, Largest: 8}, - {Smallest: 3, Largest: 3}, - {Smallest: 1, Largest: 1}, - }, - } - err = handler.ReceivedAck(ack2, 2, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{0, 7, 9}) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(3))) - }) - }) - - Context("calculating RTT", func() { - It("computes the RTT", func() { - now := time.Now() - // First, fake the sent times of the first, second and last packet - getPacket(1).SendTime = now.Add(-10 * time.Minute) - getPacket(2).SendTime = now.Add(-5 * time.Minute) - getPacket(6).SendTime = now.Add(-1 * time.Minute) - // Now, check that the proper times are used when calculating the deltas - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).NotTo(HaveOccurred()) - Expect(handler.rttStats.LatestRTT()).To(BeNumerically("~", 10*time.Minute, 1*time.Second)) - ack = &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 2}}} - err = handler.ReceivedAck(ack, 2, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).NotTo(HaveOccurred()) - Expect(handler.rttStats.LatestRTT()).To(BeNumerically("~", 5*time.Minute, 1*time.Second)) - ack = &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 6}}} - err = handler.ReceivedAck(ack, 3, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).NotTo(HaveOccurred()) - Expect(handler.rttStats.LatestRTT()).To(BeNumerically("~", 1*time.Minute, 1*time.Second)) - }) - - It("uses the DelayTime in the ACK frame", func() { - now := time.Now() - // make sure the rttStats have a min RTT, so that the delay is used - handler.rttStats.UpdateRTT(5*time.Minute, 0, time.Now()) - getPacket(1).SendTime = now.Add(-10 * time.Minute) - ack := &wire.AckFrame{ - AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}, - DelayTime: 5 * time.Minute, - } - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).NotTo(HaveOccurred()) - Expect(handler.rttStats.LatestRTT()).To(BeNumerically("~", 5*time.Minute, 1*time.Second)) - }) - }) - - Context("determining which ACKs we have received an ACK for", func() { - BeforeEach(func() { - ack1 := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 80, Largest: 100}}} - ack2 := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 50, Largest: 200}}} - morePackets := []*Packet{ - {PacketNumber: 13, Frames: []wire.Frame{ack1, &streamFrame}, Length: 1}, - {PacketNumber: 14, Frames: []wire.Frame{ack2, &streamFrame}, Length: 1}, - {PacketNumber: 15, Frames: []wire.Frame{&streamFrame}, Length: 1}, - } - for _, packet := range morePackets { - handler.SentPacket(packet) - } - }) - - It("determines which ACK we have received an ACK for", func() { - err := handler.ReceivedAck(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 13, Largest: 15}}}, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.GetLowestPacketNotConfirmedAcked()).To(Equal(protocol.PacketNumber(201))) - }) - - It("doesn't do anything when the acked packet didn't contain an ACK", func() { - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 13, Largest: 13}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.GetLowestPacketNotConfirmedAcked()).To(Equal(protocol.PacketNumber(101))) - ack = &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 15, Largest: 15}}} - err = handler.ReceivedAck(ack, 2, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.GetLowestPacketNotConfirmedAcked()).To(Equal(protocol.PacketNumber(101))) - }) - - It("doesn't decrease the value", func() { - err := handler.ReceivedAck(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 14, Largest: 14}}}, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.GetLowestPacketNotConfirmedAcked()).To(Equal(protocol.PacketNumber(201))) - err = handler.ReceivedAck(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 13, Largest: 13}}}, 2, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.GetLowestPacketNotConfirmedAcked()).To(Equal(protocol.PacketNumber(201))) - }) - }) - }) - - Context("ACK processing, for retransmitted packets", func() { - It("sends a packet as retransmission", func() { - // packet 5 was retransmitted as packet 6 - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 5, Length: 10})) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(10))) - losePacket(5) - Expect(handler.bytesInFlight).To(BeZero()) - handler.SentPacketsAsRetransmission([]*Packet{retransmittablePacket(&Packet{PacketNumber: 6, Length: 11})}, 5) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(11))) - }) - - It("removes a packet when it is acked", func() { - // packet 5 was retransmitted as packet 6 - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 5, Length: 10})) - losePacket(5) - handler.SentPacketsAsRetransmission([]*Packet{retransmittablePacket(&Packet{PacketNumber: 6, Length: 11})}, 5) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(11))) - // ack 5 - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 5, Largest: 5}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{6}) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(11))) - }) - - It("handles ACKs that ack the original packet as well as the retransmission", func() { - // packet 5 was retransmitted as packet 7 - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 5, Length: 10})) - losePacket(5) - handler.SentPacketsAsRetransmission([]*Packet{retransmittablePacket(&Packet{PacketNumber: 7, Length: 11})}, 5) - // ack 5 and 7 - ack := &wire.AckFrame{ - AckRanges: []wire.AckRange{ - {Smallest: 7, Largest: 7}, - {Smallest: 5, Largest: 5}, - }, - } - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.packetHistory.Len()).To(BeZero()) - Expect(handler.bytesInFlight).To(BeZero()) - }) - }) - - Context("Retransmission handling", func() { - It("does not dequeue a packet if no ack has been received", func() { - handler.SentPacket(&Packet{PacketNumber: 1}) - Expect(handler.DequeuePacketForRetransmission()).To(BeNil()) - }) - - Context("STOP_WAITINGs", func() { - It("gets a STOP_WAITING frame", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3})) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 3, Largest: 3}}} - err := handler.ReceivedAck(ack, 2, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.GetStopWaitingFrame(false)).To(Equal(&wire.StopWaitingFrame{LeastUnacked: 4})) - }) - - It("gets a STOP_WAITING frame after queueing a retransmission", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 5})) - handler.queuePacketForRetransmission(getPacket(5)) - Expect(handler.GetStopWaitingFrame(false)).To(Equal(&wire.StopWaitingFrame{LeastUnacked: 6})) - }) - }) - }) - - Context("congestion", func() { - var cong *mocks.MockSendAlgorithm - - BeforeEach(func() { - cong = mocks.NewMockSendAlgorithm(mockCtrl) - handler.congestion = cong - }) - - It("should call OnSent", func() { - cong.EXPECT().OnPacketSent( - gomock.Any(), - protocol.ByteCount(42), - protocol.PacketNumber(1), - protocol.ByteCount(42), - true, - ) - cong.EXPECT().TimeUntilSend(gomock.Any()) - p := &Packet{ - PacketNumber: 1, - Length: 42, - Frames: []wire.Frame{&wire.PingFrame{}}, - } - handler.SentPacket(p) - }) - - It("should call MaybeExitSlowStart and OnPacketAcked", func() { - rcvTime := time.Now().Add(-5 * time.Second) - cong.EXPECT().OnPacketSent(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(3) - cong.EXPECT().TimeUntilSend(gomock.Any()).Times(3) - gomock.InOrder( - cong.EXPECT().MaybeExitSlowStart(), // must be called before packets are acked - cong.EXPECT().OnPacketAcked(protocol.PacketNumber(1), protocol.ByteCount(1), protocol.ByteCount(3), rcvTime), - cong.EXPECT().OnPacketAcked(protocol.PacketNumber(2), protocol.ByteCount(1), protocol.ByteCount(3), rcvTime), - ) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3})) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 2}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, rcvTime) - Expect(err).NotTo(HaveOccurred()) - }) - - It("doesn't call OnPacketLost and OnRetransmissionTimeout when queuing RTOs", func() { - for i := protocol.PacketNumber(1); i < 3; i++ { - cong.EXPECT().OnPacketSent(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()) - cong.EXPECT().TimeUntilSend(gomock.Any()) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: i})) - } - handler.OnAlarm() // TLP - handler.OnAlarm() // TLP - handler.OnAlarm() // RTO - }) - - It("declares all lower packets lost and call OnRetransmissionTimeout when verifying an RTO", func() { - cong.EXPECT().OnPacketSent(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(5) - cong.EXPECT().TimeUntilSend(gomock.Any()).Times(5) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 4, SendTime: time.Now().Add(-time.Hour)})) - handler.OnAlarm() // TLP - handler.OnAlarm() // TLP - handler.OnAlarm() // RTO - // send one probe packet and receive an ACK for it - rcvTime := time.Now() - gomock.InOrder( - cong.EXPECT().MaybeExitSlowStart(), - cong.EXPECT().OnRetransmissionTimeout(true), - cong.EXPECT().OnPacketAcked(protocol.PacketNumber(5), protocol.ByteCount(1), protocol.ByteCount(5), rcvTime), - cong.EXPECT().OnPacketLost(protocol.PacketNumber(1), protocol.ByteCount(1), protocol.ByteCount(5)), - cong.EXPECT().OnPacketLost(protocol.PacketNumber(2), protocol.ByteCount(1), protocol.ByteCount(5)), - cong.EXPECT().OnPacketLost(protocol.PacketNumber(3), protocol.ByteCount(1), protocol.ByteCount(5)), - cong.EXPECT().OnPacketLost(protocol.PacketNumber(4), protocol.ByteCount(1), protocol.ByteCount(5)), - ) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 5})) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 5, Largest: 5}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, rcvTime) - Expect(err).ToNot(HaveOccurred()) - }) - - It("doesn't call OnRetransmissionTimeout when a spurious RTO occurs", func() { - cong.EXPECT().OnPacketSent(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(3) - cong.EXPECT().TimeUntilSend(gomock.Any()).Times(3) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2, SendTime: time.Now()})) - handler.OnAlarm() // TLP - handler.OnAlarm() // TLP - handler.OnAlarm() // RTO - - // send one probe packet - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3})) - // receive an ACK for a packet send *before* the probe packet - // don't EXPECT any call to OnRetransmissionTimeout - gomock.InOrder( - cong.EXPECT().MaybeExitSlowStart(), - cong.EXPECT().OnPacketAcked(protocol.PacketNumber(2), protocol.ByteCount(1), protocol.ByteCount(3), gomock.Any()), - cong.EXPECT().OnPacketLost(protocol.PacketNumber(1), protocol.ByteCount(1), protocol.ByteCount(3)), - ) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 2, Largest: 2}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - }) - - It("doesn't call OnPacketAcked when a retransmitted packet is acked", func() { - cong.EXPECT().OnPacketSent(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(2) - cong.EXPECT().TimeUntilSend(gomock.Any()).Times(2) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2})) - // lose packet 1 - gomock.InOrder( - cong.EXPECT().MaybeExitSlowStart(), - cong.EXPECT().OnPacketAcked(protocol.PacketNumber(2), protocol.ByteCount(1), protocol.ByteCount(2), gomock.Any()), - cong.EXPECT().OnPacketLost(protocol.PacketNumber(1), protocol.ByteCount(1), protocol.ByteCount(2)), - ) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 2, Largest: 2}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - // don't EXPECT any further calls to the congestion controller - ack = &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 2}}} - err = handler.ReceivedAck(ack, 2, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - }) - - It("calls OnPacketAcked and OnPacketLost with the right bytes_in_flight value", func() { - cong.EXPECT().OnPacketSent(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Times(4) - cong.EXPECT().TimeUntilSend(gomock.Any()).Times(4) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2, SendTime: time.Now().Add(-30 * time.Minute)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3, SendTime: time.Now().Add(-30 * time.Minute)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 4, SendTime: time.Now()})) - // receive the first ACK - gomock.InOrder( - cong.EXPECT().MaybeExitSlowStart(), - cong.EXPECT().OnPacketAcked(protocol.PacketNumber(2), protocol.ByteCount(1), protocol.ByteCount(4), gomock.Any()), - cong.EXPECT().OnPacketLost(protocol.PacketNumber(1), protocol.ByteCount(1), protocol.ByteCount(4)), - ) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 2, Largest: 2}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now().Add(-30*time.Minute)) - Expect(err).ToNot(HaveOccurred()) - // receive the second ACK - gomock.InOrder( - cong.EXPECT().MaybeExitSlowStart(), - cong.EXPECT().OnPacketAcked(protocol.PacketNumber(4), protocol.ByteCount(1), protocol.ByteCount(2), gomock.Any()), - cong.EXPECT().OnPacketLost(protocol.PacketNumber(3), protocol.ByteCount(1), protocol.ByteCount(2)), - ) - ack = &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 4, Largest: 4}}} - err = handler.ReceivedAck(ack, 2, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - }) - - It("only allows sending of ACKs when congestion limited", func() { - handler.bytesInFlight = 100 - cong.EXPECT().GetCongestionWindow().Return(protocol.ByteCount(200)) - Expect(handler.SendMode()).To(Equal(SendAny)) - cong.EXPECT().GetCongestionWindow().Return(protocol.ByteCount(75)) - Expect(handler.SendMode()).To(Equal(SendAck)) - }) - - It("only allows sending of ACKs when we're keeping track of MaxOutstandingSentPackets packets", func() { - cong.EXPECT().GetCongestionWindow().Return(protocol.MaxByteCount).AnyTimes() - cong.EXPECT().TimeUntilSend(gomock.Any()).AnyTimes() - cong.EXPECT().OnPacketSent(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes() - for i := protocol.PacketNumber(1); i < protocol.MaxOutstandingSentPackets; i++ { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: i})) - Expect(handler.SendMode()).To(Equal(SendAny)) - } - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: protocol.MaxOutstandingSentPackets})) - Expect(handler.SendMode()).To(Equal(SendAck)) - }) - - It("doesn't allow retransmission if congestion limited", func() { - handler.bytesInFlight = 100 - handler.retransmissionQueue = []*Packet{{PacketNumber: 3}} - cong.EXPECT().GetCongestionWindow().Return(protocol.ByteCount(50)) - Expect(handler.SendMode()).To(Equal(SendAck)) - }) - - It("allows sending retransmissions", func() { - cong.EXPECT().GetCongestionWindow().Return(protocol.MaxByteCount) - handler.retransmissionQueue = []*Packet{{PacketNumber: 3}} - Expect(handler.SendMode()).To(Equal(SendRetransmission)) - }) - - It("allow retransmissions, if we're keeping track of between MaxOutstandingSentPackets and MaxTrackedSentPackets packets", func() { - cong.EXPECT().GetCongestionWindow().Return(protocol.MaxByteCount) - Expect(protocol.MaxOutstandingSentPackets).To(BeNumerically("<", protocol.MaxTrackedSentPackets)) - handler.retransmissionQueue = make([]*Packet, protocol.MaxOutstandingSentPackets+10) - Expect(handler.SendMode()).To(Equal(SendRetransmission)) - handler.retransmissionQueue = make([]*Packet, protocol.MaxTrackedSentPackets) - Expect(handler.SendMode()).To(Equal(SendNone)) - }) - - It("allows RTOs, even when congestion limited", func() { - // note that we don't EXPECT a call to GetCongestionWindow - // that means retransmissions are sent without considering the congestion window - handler.numRTOs = 1 - handler.retransmissionQueue = []*Packet{{PacketNumber: 3}} - Expect(handler.SendMode()).To(Equal(SendRTO)) - }) - - It("gets the pacing delay", func() { - sendTime := time.Now().Add(-time.Minute) - handler.bytesInFlight = 100 - cong.EXPECT().OnPacketSent(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()) - cong.EXPECT().TimeUntilSend(protocol.ByteCount(100)).Return(time.Hour) - handler.SentPacket(&Packet{PacketNumber: 1, SendTime: sendTime}) - Expect(handler.TimeUntilSend()).To(Equal(sendTime.Add(time.Hour))) - }) - - It("allows sending of all RTO probe packets", func() { - handler.numRTOs = 5 - Expect(handler.ShouldSendNumPackets()).To(Equal(5)) - }) - - It("allows sending of one packet, if it should be sent immediately", func() { - cong.EXPECT().TimeUntilSend(gomock.Any()).Return(time.Duration(0)) - Expect(handler.ShouldSendNumPackets()).To(Equal(1)) - }) - - It("allows sending of multiple packets, if the pacing delay is smaller than the minimum", func() { - pacingDelay := protocol.MinPacingDelay / 10 - cong.EXPECT().TimeUntilSend(gomock.Any()).Return(pacingDelay) - Expect(handler.ShouldSendNumPackets()).To(Equal(10)) - }) - - It("allows sending of multiple packets, if the pacing delay is smaller than the minimum, and not a fraction", func() { - pacingDelay := protocol.MinPacingDelay * 2 / 5 - cong.EXPECT().TimeUntilSend(gomock.Any()).Return(pacingDelay) - Expect(handler.ShouldSendNumPackets()).To(Equal(3)) - }) - }) - - It("doesn't set an alarm if there are no outstanding packets", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 10})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 11})) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 10, Largest: 11}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.GetAlarmTimeout()).To(BeZero()) - }) - - It("does nothing on OnAlarm if there are no outstanding packets", func() { - Expect(handler.OnAlarm()).To(Succeed()) - Expect(handler.SendMode()).To(Equal(SendAny)) - }) - - Context("TLPs", func() { - It("uses the RTT from RTT stats", func() { - rtt := 2 * time.Second - updateRTT(rtt) - Expect(handler.computeTLPTimeout()).To(Equal(rtt * 3 / 2)) - }) - - It("uses the minTLPTimeout for short RTTs", func() { - rtt := 2 * time.Microsecond - updateRTT(rtt) - Expect(handler.computeTLPTimeout()).To(Equal(minTPLTimeout)) - }) - - It("sets the TLP send mode until one retransmittable packet is sent", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: time.Now().Add(-time.Hour)})) - handler.OnAlarm() - Expect(handler.SendMode()).To(Equal(SendTLP)) - // Send a non-retransmittable packet. - // It doesn't count as a probe packet. - handler.SentPacket(nonRetransmittablePacket(&Packet{PacketNumber: 2})) - Expect(handler.SendMode()).To(Equal(SendTLP)) - // Send a retransmittable packet. - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3})) - Expect(handler.SendMode()).ToNot(Equal(SendTLP)) - }) - - It("sends two TLPs, then RTOs", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2, SendTime: time.Now().Add(-time.Hour)})) - // first TLP - handler.OnAlarm() - Expect(handler.SendMode()).To(Equal(SendTLP)) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3})) - // second TLP - handler.OnAlarm() - Expect(handler.SendMode()).To(Equal(SendTLP)) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 4})) - // fire alarm a third time - handler.OnAlarm() - Expect(handler.SendMode()).To(Equal(SendRTO)) - }) - }) - - Context("RTOs", func() { - It("uses default RTO", func() { - Expect(handler.computeRTOTimeout()).To(Equal(defaultRTOTimeout)) - }) - - It("uses RTO from rttStats", func() { - rtt := time.Second - handler.rttStats.UpdateRTT(rtt, 0, time.Now()) - Expect(handler.rttStats.SmoothedRTT()).To(Equal(rtt)) - Expect(handler.rttStats.MeanDeviation()).To(Equal(rtt / 2)) - expected := rtt + rtt/2*4 - Expect(handler.computeRTOTimeout()).To(Equal(expected)) - }) - - It("limits RTO min", func() { - rtt := 3 * time.Millisecond - updateRTT(rtt) - Expect(handler.computeRTOTimeout()).To(Equal(minRTOTimeout)) - }) - - It("limits RTO max", func() { - updateRTT(time.Hour) - Expect(handler.computeRTOTimeout()).To(Equal(maxRTOTimeout)) - }) - - It("implements exponential backoff", func() { - handler.rtoCount = 0 - Expect(handler.computeRTOTimeout()).To(Equal(defaultRTOTimeout)) - handler.rtoCount = 1 - Expect(handler.computeRTOTimeout()).To(Equal(2 * defaultRTOTimeout)) - handler.rtoCount = 2 - Expect(handler.computeRTOTimeout()).To(Equal(4 * defaultRTOTimeout)) - }) - - It("gets two probe packets if RTO expires", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2})) - - updateRTT(time.Hour) - Expect(handler.lossTime.IsZero()).To(BeTrue()) - Expect(time.Until(handler.GetAlarmTimeout())).To(BeNumerically("~", handler.computeRTOTimeout(), time.Minute)) - - handler.OnAlarm() // TLP - handler.OnAlarm() // TLP - handler.OnAlarm() // RTO - p, err := handler.DequeueProbePacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).ToNot(BeNil()) - Expect(p.PacketNumber).To(Equal(protocol.PacketNumber(1))) - p, err = handler.DequeueProbePacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).ToNot(BeNil()) - Expect(p.PacketNumber).To(Equal(protocol.PacketNumber(2))) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(2))) - - Expect(handler.rtoCount).To(BeEquivalentTo(1)) - }) - - It("doesn't delete packets transmitted as RTO from the history", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2, SendTime: time.Now().Add(-time.Hour)})) - handler.rttStats.UpdateRTT(time.Second, 0, time.Now()) - handler.OnAlarm() // TLP - handler.OnAlarm() // TLP - handler.OnAlarm() // RTO - _, err := handler.DequeueProbePacket() - Expect(err).ToNot(HaveOccurred()) - _, err = handler.DequeueProbePacket() - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{1, 2}) - Expect(handler.bytesInFlight).To(Equal(protocol.ByteCount(2))) - // Send a probe packet and receive an ACK for it. - // This verifies the RTO. - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3})) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 3, Largest: 3}}} - err = handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.packetHistory.Len()).To(BeZero()) - Expect(handler.bytesInFlight).To(BeZero()) - Expect(handler.retransmissionQueue).To(BeEmpty()) // 1 and 2 were already sent as probe packets - }) - - It("allows sending of two probe packets", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: time.Now().Add(-time.Hour)})) - handler.OnAlarm() // TLP - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2})) // send the first TLP - handler.OnAlarm() // TLP - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3})) // send the second TLP - handler.OnAlarm() // RTO - Expect(handler.SendMode()).To(Equal(SendRTO)) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 4})) - Expect(handler.SendMode()).To(Equal(SendRTO)) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 5})) - Expect(handler.SendMode()).ToNot(Equal(SendRTO)) - }) - - It("gets packets sent before the probe packet for retransmission", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 4, SendTime: time.Now().Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 5, SendTime: time.Now().Add(-time.Hour)})) - handler.OnAlarm() // TLP - handler.OnAlarm() // TLP - handler.OnAlarm() // RTO - _, err := handler.DequeueProbePacket() - Expect(err).ToNot(HaveOccurred()) - _, err = handler.DequeueProbePacket() - Expect(err).ToNot(HaveOccurred()) - expectInPacketHistory([]protocol.PacketNumber{1, 2, 3, 4, 5}) - // Send a probe packet and receive an ACK for it. - // This verifies the RTO. - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 6})) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 6, Largest: 6}}} - err = handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - Expect(handler.packetHistory.Len()).To(BeZero()) - Expect(handler.bytesInFlight).To(BeZero()) - Expect(handler.retransmissionQueue).To(HaveLen(3)) // packets 3, 4, 5 - }) - - It("handles ACKs for the original packet", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 5, SendTime: time.Now().Add(-time.Hour)})) - handler.rttStats.UpdateRTT(time.Second, 0, time.Now()) - handler.OnAlarm() // TLP - handler.OnAlarm() // TLP - handler.OnAlarm() // RTO - handler.SentPacketsAsRetransmission([]*Packet{retransmittablePacket(&Packet{PacketNumber: 6})}, 5) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 5, Largest: 5}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, time.Now()) - Expect(err).ToNot(HaveOccurred()) - err = handler.OnAlarm() - Expect(err).ToNot(HaveOccurred()) - }) - - It("handles ACKs for the original packet", func() { - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 5, SendTime: time.Now().Add(-time.Hour)})) - handler.rttStats.UpdateRTT(time.Second, 0, time.Now()) - err := handler.OnAlarm() - Expect(err).ToNot(HaveOccurred()) - err = handler.OnAlarm() - Expect(err).ToNot(HaveOccurred()) - }) - }) - - Context("Delay-based loss detection", func() { - It("immediately detects old packets as lost when receiving an ACK", func() { - now := time.Now() - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: now.Add(-time.Hour)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2, SendTime: now.Add(-time.Second)})) - Expect(handler.lossTime.IsZero()).To(BeTrue()) - - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 2, Largest: 2}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, now) - Expect(err).NotTo(HaveOccurred()) - Expect(handler.DequeuePacketForRetransmission()).ToNot(BeNil()) - Expect(handler.DequeuePacketForRetransmission()).To(BeNil()) - // no need to set an alarm, since packet 1 was already declared lost - Expect(handler.lossTime.IsZero()).To(BeTrue()) - Expect(handler.bytesInFlight).To(BeZero()) - }) - - It("sets the early retransmit alarm", func() { - now := time.Now() - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 1, SendTime: now.Add(-2 * time.Second)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2, SendTime: now.Add(-2 * time.Second)})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 3, SendTime: now.Add(-time.Second)})) - Expect(handler.lossTime.IsZero()).To(BeTrue()) - - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 2, Largest: 2}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, now.Add(-time.Second)) - Expect(err).NotTo(HaveOccurred()) - Expect(handler.rttStats.SmoothedRTT()).To(Equal(time.Second)) - - // Packet 1 should be considered lost (1+1/8) RTTs after it was sent. - Expect(handler.lossTime.IsZero()).To(BeFalse()) - Expect(handler.lossTime.Sub(getPacket(1).SendTime)).To(Equal(time.Second * 9 / 8)) - - err = handler.OnAlarm() - Expect(err).ToNot(HaveOccurred()) - Expect(handler.DequeuePacketForRetransmission()).NotTo(BeNil()) - // make sure this is not an RTO: only packet 1 is retransmissted - Expect(handler.DequeuePacketForRetransmission()).To(BeNil()) - }) - }) - - Context("handshake packets", func() { - BeforeEach(func() { - handler.handshakeComplete = false - }) - - It("detects the handshake timeout", func() { - now := time.Now() - sendTime := now.Add(-time.Minute) - lastHandshakePacketSendTime := now.Add(-30 * time.Second) - // send handshake packets: 1, 3 - // send a forward-secure packet: 2 - handler.SentPacket(handshakePacket(&Packet{PacketNumber: 1, SendTime: sendTime})) - handler.SentPacket(retransmittablePacket(&Packet{PacketNumber: 2, SendTime: sendTime})) - handler.SentPacket(handshakePacket(&Packet{PacketNumber: 3, SendTime: sendTime})) - - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionForwardSecure, now) - // RTT is now 1 minute - Expect(handler.rttStats.SmoothedRTT()).To(Equal(time.Minute)) - Expect(err).NotTo(HaveOccurred()) - Expect(handler.lossTime.IsZero()).To(BeTrue()) - Expect(handler.GetAlarmTimeout().Sub(sendTime)).To(Equal(2 * time.Minute)) - - err = handler.OnAlarm() - Expect(err).ToNot(HaveOccurred()) - p := handler.DequeuePacketForRetransmission() - Expect(p).ToNot(BeNil()) - Expect(p.PacketNumber).To(Equal(protocol.PacketNumber(3))) - Expect(handler.handshakeCount).To(BeEquivalentTo(1)) - handler.SentPacket(handshakePacket(&Packet{PacketNumber: 4, SendTime: lastHandshakePacketSendTime})) - // make sure the exponential backoff is used - Expect(handler.GetAlarmTimeout().Sub(lastHandshakePacketSendTime)).To(Equal(4 * time.Minute)) - }) - - It("rejects an ACK that acks packets with a higher encryption level", func() { - handler.SentPacket(&Packet{ - PacketNumber: 13, - EncryptionLevel: protocol.EncryptionForwardSecure, - Frames: []wire.Frame{&streamFrame}, - Length: 1, - }) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 13, Largest: 13}}} - err := handler.ReceivedAck(ack, 1, protocol.EncryptionSecure, time.Now()) - Expect(err).To(MatchError("Received ACK with encryption level encrypted (not forward-secure) that acks a packet 13 (encryption level forward-secure)")) - }) - - It("deletes non forward-secure packets when the handshake completes", func() { - for i := protocol.PacketNumber(1); i <= 6; i++ { - p := retransmittablePacket(&Packet{PacketNumber: i}) - p.EncryptionLevel = protocol.EncryptionSecure - handler.SentPacket(p) - } - handler.queuePacketForRetransmission(getPacket(1)) - handler.queuePacketForRetransmission(getPacket(3)) - handler.SetHandshakeComplete() - Expect(handler.packetHistory.Len()).To(BeZero()) - packet := handler.DequeuePacketForRetransmission() - Expect(packet).To(BeNil()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/ackhandler/sent_packet_history_test.go b/vendor/lucas-clemente/quic-go/internal/ackhandler/sent_packet_history_test.go deleted file mode 100644 index dc6ed5dd4..000000000 --- a/vendor/lucas-clemente/quic-go/internal/ackhandler/sent_packet_history_test.go +++ /dev/null @@ -1,297 +0,0 @@ -package ackhandler - -import ( - "errors" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("SentPacketHistory", func() { - var hist *sentPacketHistory - - expectInHistory := func(packetNumbers []protocol.PacketNumber) { - ExpectWithOffset(1, hist.packetMap).To(HaveLen(len(packetNumbers))) - ExpectWithOffset(1, hist.packetList.Len()).To(Equal(len(packetNumbers))) - i := 0 - hist.Iterate(func(p *Packet) (bool, error) { - pn := packetNumbers[i] - ExpectWithOffset(1, p.PacketNumber).To(Equal(pn)) - ExpectWithOffset(1, hist.packetMap[pn].Value.PacketNumber).To(Equal(pn)) - i++ - return true, nil - }) - } - - BeforeEach(func() { - hist = newSentPacketHistory() - }) - - It("saves sent packets", func() { - hist.SentPacket(&Packet{PacketNumber: 1}) - hist.SentPacket(&Packet{PacketNumber: 3}) - hist.SentPacket(&Packet{PacketNumber: 4}) - expectInHistory([]protocol.PacketNumber{1, 3, 4}) - }) - - It("gets the length", func() { - hist.SentPacket(&Packet{PacketNumber: 1}) - hist.SentPacket(&Packet{PacketNumber: 10}) - Expect(hist.Len()).To(Equal(2)) - }) - - Context("getting the first outstanding packet", func() { - It("gets nil, if there are no packets", func() { - Expect(hist.FirstOutstanding()).To(BeNil()) - }) - - It("gets the first outstanding packet", func() { - hist.SentPacket(&Packet{PacketNumber: 2}) - hist.SentPacket(&Packet{PacketNumber: 3}) - front := hist.FirstOutstanding() - Expect(front).ToNot(BeNil()) - Expect(front.PacketNumber).To(Equal(protocol.PacketNumber(2))) - }) - - It("gets the second packet if the first one is retransmitted", func() { - hist.SentPacket(&Packet{PacketNumber: 1, canBeRetransmitted: true}) - hist.SentPacket(&Packet{PacketNumber: 3, canBeRetransmitted: true}) - hist.SentPacket(&Packet{PacketNumber: 4, canBeRetransmitted: true}) - front := hist.FirstOutstanding() - Expect(front).ToNot(BeNil()) - Expect(front.PacketNumber).To(Equal(protocol.PacketNumber(1))) - // Queue the first packet for retransmission. - // The first outstanding packet should now be 3. - err := hist.MarkCannotBeRetransmitted(1) - Expect(err).ToNot(HaveOccurred()) - front = hist.FirstOutstanding() - Expect(front).ToNot(BeNil()) - Expect(front.PacketNumber).To(Equal(protocol.PacketNumber(3))) - }) - - It("gets the third packet if the first two are retransmitted", func() { - hist.SentPacket(&Packet{PacketNumber: 1, canBeRetransmitted: true}) - hist.SentPacket(&Packet{PacketNumber: 3, canBeRetransmitted: true}) - hist.SentPacket(&Packet{PacketNumber: 4, canBeRetransmitted: true}) - front := hist.FirstOutstanding() - Expect(front).ToNot(BeNil()) - Expect(front.PacketNumber).To(Equal(protocol.PacketNumber(1))) - // Queue the second packet for retransmission. - // The first outstanding packet should still be 3. - err := hist.MarkCannotBeRetransmitted(3) - Expect(err).ToNot(HaveOccurred()) - front = hist.FirstOutstanding() - Expect(front).ToNot(BeNil()) - Expect(front.PacketNumber).To(Equal(protocol.PacketNumber(1))) - // Queue the first packet for retransmission. - // The first outstanding packet should still be 4. - err = hist.MarkCannotBeRetransmitted(1) - Expect(err).ToNot(HaveOccurred()) - front = hist.FirstOutstanding() - Expect(front).ToNot(BeNil()) - Expect(front.PacketNumber).To(Equal(protocol.PacketNumber(4))) - }) - }) - - It("gets a packet by packet number", func() { - p := &Packet{PacketNumber: 2} - hist.SentPacket(p) - Expect(hist.GetPacket(2)).To(Equal(p)) - }) - - It("returns nil if the packet doesn't exist", func() { - Expect(hist.GetPacket(1337)).To(BeNil()) - }) - - It("removes packets", func() { - hist.SentPacket(&Packet{PacketNumber: 1}) - hist.SentPacket(&Packet{PacketNumber: 4}) - hist.SentPacket(&Packet{PacketNumber: 8}) - err := hist.Remove(4) - Expect(err).ToNot(HaveOccurred()) - expectInHistory([]protocol.PacketNumber{1, 8}) - }) - - It("errors when trying to remove a non existing packet", func() { - hist.SentPacket(&Packet{PacketNumber: 1}) - err := hist.Remove(2) - Expect(err).To(MatchError("packet 2 not found in sent packet history")) - }) - - Context("iterating", func() { - BeforeEach(func() { - hist.SentPacket(&Packet{PacketNumber: 10}) - hist.SentPacket(&Packet{PacketNumber: 14}) - hist.SentPacket(&Packet{PacketNumber: 18}) - }) - - It("iterates over all packets", func() { - var iterations []protocol.PacketNumber - err := hist.Iterate(func(p *Packet) (bool, error) { - iterations = append(iterations, p.PacketNumber) - return true, nil - }) - Expect(err).ToNot(HaveOccurred()) - Expect(iterations).To(Equal([]protocol.PacketNumber{10, 14, 18})) - }) - - It("stops iterating", func() { - var iterations []protocol.PacketNumber - err := hist.Iterate(func(p *Packet) (bool, error) { - iterations = append(iterations, p.PacketNumber) - return p.PacketNumber != 14, nil - }) - Expect(err).ToNot(HaveOccurred()) - Expect(iterations).To(Equal([]protocol.PacketNumber{10, 14})) - }) - - It("returns the error", func() { - testErr := errors.New("test error") - var iterations []protocol.PacketNumber - err := hist.Iterate(func(p *Packet) (bool, error) { - iterations = append(iterations, p.PacketNumber) - if p.PacketNumber == 14 { - return false, testErr - } - return true, nil - }) - Expect(err).To(MatchError(testErr)) - Expect(iterations).To(Equal([]protocol.PacketNumber{10, 14})) - }) - }) - - Context("retransmissions", func() { - BeforeEach(func() { - for i := protocol.PacketNumber(1); i <= 5; i++ { - hist.SentPacket(&Packet{PacketNumber: i}) - } - }) - - It("errors if the packet doesn't exist", func() { - err := hist.MarkCannotBeRetransmitted(100) - Expect(err).To(MatchError("sent packet history: packet 100 not found")) - }) - - It("adds a sent packets as a retransmission", func() { - hist.SentPacketsAsRetransmission([]*Packet{{PacketNumber: 13}}, 2) - expectInHistory([]protocol.PacketNumber{1, 2, 3, 4, 5, 13}) - Expect(hist.GetPacket(13).isRetransmission).To(BeTrue()) - Expect(hist.GetPacket(13).retransmissionOf).To(Equal(protocol.PacketNumber(2))) - Expect(hist.GetPacket(2).retransmittedAs).To(Equal([]protocol.PacketNumber{13})) - }) - - It("adds multiple packets sent as a retransmission", func() { - hist.SentPacketsAsRetransmission([]*Packet{{PacketNumber: 13}, {PacketNumber: 15}}, 2) - expectInHistory([]protocol.PacketNumber{1, 2, 3, 4, 5, 13, 15}) - Expect(hist.GetPacket(13).isRetransmission).To(BeTrue()) - Expect(hist.GetPacket(13).retransmissionOf).To(Equal(protocol.PacketNumber(2))) - Expect(hist.GetPacket(15).retransmissionOf).To(Equal(protocol.PacketNumber(2))) - Expect(hist.GetPacket(2).retransmittedAs).To(Equal([]protocol.PacketNumber{13, 15})) - }) - - It("adds a packet as a normal packet if the retransmitted packet doesn't exist", func() { - hist.SentPacketsAsRetransmission([]*Packet{{PacketNumber: 13}}, 7) - expectInHistory([]protocol.PacketNumber{1, 2, 3, 4, 5, 13}) - Expect(hist.GetPacket(13).isRetransmission).To(BeFalse()) - Expect(hist.GetPacket(13).retransmissionOf).To(BeZero()) - }) - }) - - Context("outstanding packets", func() { - It("says if it has outstanding handshake packets", func() { - Expect(hist.HasOutstandingHandshakePackets()).To(BeFalse()) - hist.SentPacket(&Packet{ - EncryptionLevel: protocol.EncryptionUnencrypted, - canBeRetransmitted: true, - }) - Expect(hist.HasOutstandingHandshakePackets()).To(BeTrue()) - }) - - It("says if it has outstanding packets", func() { - Expect(hist.HasOutstandingHandshakePackets()).To(BeFalse()) - Expect(hist.HasOutstandingPackets()).To(BeFalse()) - hist.SentPacket(&Packet{ - EncryptionLevel: protocol.EncryptionForwardSecure, - canBeRetransmitted: true, - }) - Expect(hist.HasOutstandingHandshakePackets()).To(BeFalse()) - Expect(hist.HasOutstandingPackets()).To(BeTrue()) - }) - - It("doesn't consider non-retransmittable packets as outstanding", func() { - hist.SentPacket(&Packet{ - EncryptionLevel: protocol.EncryptionUnencrypted, - }) - Expect(hist.HasOutstandingHandshakePackets()).To(BeFalse()) - Expect(hist.HasOutstandingPackets()).To(BeFalse()) - }) - - It("accounts for deleted handshake packets", func() { - hist.SentPacket(&Packet{ - PacketNumber: 5, - EncryptionLevel: protocol.EncryptionSecure, - canBeRetransmitted: true, - }) - Expect(hist.HasOutstandingHandshakePackets()).To(BeTrue()) - err := hist.Remove(5) - Expect(err).ToNot(HaveOccurred()) - Expect(hist.HasOutstandingHandshakePackets()).To(BeFalse()) - }) - - It("accounts for deleted packets", func() { - hist.SentPacket(&Packet{ - PacketNumber: 10, - EncryptionLevel: protocol.EncryptionForwardSecure, - canBeRetransmitted: true, - }) - Expect(hist.HasOutstandingPackets()).To(BeTrue()) - err := hist.Remove(10) - Expect(err).ToNot(HaveOccurred()) - Expect(hist.HasOutstandingPackets()).To(BeFalse()) - }) - - It("doesn't count handshake packets marked as non-retransmittable", func() { - hist.SentPacket(&Packet{ - PacketNumber: 5, - EncryptionLevel: protocol.EncryptionUnencrypted, - canBeRetransmitted: true, - }) - Expect(hist.HasOutstandingHandshakePackets()).To(BeTrue()) - err := hist.MarkCannotBeRetransmitted(5) - Expect(err).ToNot(HaveOccurred()) - Expect(hist.HasOutstandingHandshakePackets()).To(BeFalse()) - }) - - It("doesn't count packets marked as non-retransmittable", func() { - hist.SentPacket(&Packet{ - PacketNumber: 10, - EncryptionLevel: protocol.EncryptionForwardSecure, - canBeRetransmitted: true, - }) - Expect(hist.HasOutstandingPackets()).To(BeTrue()) - err := hist.MarkCannotBeRetransmitted(10) - Expect(err).ToNot(HaveOccurred()) - Expect(hist.HasOutstandingPackets()).To(BeFalse()) - }) - - It("counts the number of packets", func() { - hist.SentPacket(&Packet{ - PacketNumber: 10, - EncryptionLevel: protocol.EncryptionForwardSecure, - canBeRetransmitted: true, - }) - hist.SentPacket(&Packet{ - PacketNumber: 11, - EncryptionLevel: protocol.EncryptionForwardSecure, - canBeRetransmitted: true, - }) - err := hist.Remove(11) - Expect(err).ToNot(HaveOccurred()) - Expect(hist.HasOutstandingPackets()).To(BeTrue()) - err = hist.Remove(10) - Expect(err).ToNot(HaveOccurred()) - Expect(hist.HasOutstandingPackets()).To(BeFalse()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/ackhandler/stop_waiting_manager_test.go b/vendor/lucas-clemente/quic-go/internal/ackhandler/stop_waiting_manager_test.go deleted file mode 100644 index c549bee8a..000000000 --- a/vendor/lucas-clemente/quic-go/internal/ackhandler/stop_waiting_manager_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package ackhandler - -import ( - "github.com/lucas-clemente/quic-go/internal/wire" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("StopWaitingManager", func() { - var manager *stopWaitingManager - BeforeEach(func() { - manager = &stopWaitingManager{} - }) - - It("returns nil in the beginning", func() { - Expect(manager.GetStopWaitingFrame(false)).To(BeNil()) - Expect(manager.GetStopWaitingFrame(true)).To(BeNil()) - }) - - It("returns a StopWaitingFrame, when a new ACK arrives", func() { - manager.ReceivedAck(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}) - Expect(manager.GetStopWaitingFrame(false)).To(Equal(&wire.StopWaitingFrame{LeastUnacked: 11})) - }) - - It("does not decrease the LeastUnacked", func() { - manager.ReceivedAck(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}) - manager.ReceivedAck(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 9}}}) - Expect(manager.GetStopWaitingFrame(false)).To(Equal(&wire.StopWaitingFrame{LeastUnacked: 11})) - }) - - It("does not send the same StopWaitingFrame twice", func() { - manager.ReceivedAck(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}) - Expect(manager.GetStopWaitingFrame(false)).ToNot(BeNil()) - Expect(manager.GetStopWaitingFrame(false)).To(BeNil()) - }) - - It("gets the same StopWaitingFrame twice, if forced", func() { - manager.ReceivedAck(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}) - Expect(manager.GetStopWaitingFrame(false)).ToNot(BeNil()) - Expect(manager.GetStopWaitingFrame(true)).ToNot(BeNil()) - Expect(manager.GetStopWaitingFrame(true)).ToNot(BeNil()) - }) - - It("increases the LeastUnacked when a retransmission is queued", func() { - manager.ReceivedAck(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}) - manager.QueuedRetransmissionForPacketNumber(20) - Expect(manager.GetStopWaitingFrame(false)).To(Equal(&wire.StopWaitingFrame{LeastUnacked: 21})) - }) - - It("does not decrease the LeastUnacked when a retransmission is queued", func() { - manager.ReceivedAck(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}) - manager.QueuedRetransmissionForPacketNumber(9) - Expect(manager.GetStopWaitingFrame(false)).To(Equal(&wire.StopWaitingFrame{LeastUnacked: 11})) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/congestion/bandwidth_test.go b/vendor/lucas-clemente/quic-go/internal/congestion/bandwidth_test.go deleted file mode 100644 index 031627476..000000000 --- a/vendor/lucas-clemente/quic-go/internal/congestion/bandwidth_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package congestion - -import ( - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Bandwidth", func() { - It("converts from time delta", func() { - Expect(BandwidthFromDelta(1, time.Millisecond)).To(Equal(1000 * BytesPerSecond)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/congestion/congestion_suite_test.go b/vendor/lucas-clemente/quic-go/internal/congestion/congestion_suite_test.go deleted file mode 100644 index 577ee5bf7..000000000 --- a/vendor/lucas-clemente/quic-go/internal/congestion/congestion_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package congestion - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestCongestion(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Congestion Suite") -} diff --git a/vendor/lucas-clemente/quic-go/internal/congestion/cubic_sender_test.go b/vendor/lucas-clemente/quic-go/internal/congestion/cubic_sender_test.go deleted file mode 100644 index de3b74fcc..000000000 --- a/vendor/lucas-clemente/quic-go/internal/congestion/cubic_sender_test.go +++ /dev/null @@ -1,640 +0,0 @@ -package congestion - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -const initialCongestionWindowPackets = 10 -const defaultWindowTCP = protocol.ByteCount(initialCongestionWindowPackets) * protocol.DefaultTCPMSS - -type mockClock time.Time - -func (c *mockClock) Now() time.Time { - return time.Time(*c) -} - -func (c *mockClock) Advance(d time.Duration) { - *c = mockClock(time.Time(*c).Add(d)) -} - -const MaxCongestionWindow protocol.ByteCount = 200 * protocol.DefaultTCPMSS - -var _ = Describe("Cubic Sender", func() { - var ( - sender SendAlgorithmWithDebugInfo - clock mockClock - bytesInFlight protocol.ByteCount - packetNumber protocol.PacketNumber - ackedPacketNumber protocol.PacketNumber - rttStats *RTTStats - ) - - BeforeEach(func() { - bytesInFlight = 0 - packetNumber = 1 - ackedPacketNumber = 0 - clock = mockClock{} - rttStats = NewRTTStats() - sender = NewCubicSender(&clock, rttStats, true /*reno*/, initialCongestionWindowPackets*protocol.DefaultTCPMSS, MaxCongestionWindow) - }) - - canSend := func() bool { - return bytesInFlight < sender.GetCongestionWindow() - } - - SendAvailableSendWindowLen := func(packetLength protocol.ByteCount) int { - packetsSent := 0 - for canSend() { - sender.OnPacketSent(clock.Now(), bytesInFlight, packetNumber, packetLength, true) - packetNumber++ - packetsSent++ - bytesInFlight += packetLength - } - return packetsSent - } - - // Normal is that TCP acks every other segment. - AckNPackets := func(n int) { - rttStats.UpdateRTT(60*time.Millisecond, 0, clock.Now()) - sender.MaybeExitSlowStart() - for i := 0; i < n; i++ { - ackedPacketNumber++ - sender.OnPacketAcked(ackedPacketNumber, protocol.DefaultTCPMSS, bytesInFlight, clock.Now()) - } - bytesInFlight -= protocol.ByteCount(n) * protocol.DefaultTCPMSS - clock.Advance(time.Millisecond) - } - - LoseNPacketsLen := func(n int, packetLength protocol.ByteCount) { - for i := 0; i < n; i++ { - ackedPacketNumber++ - sender.OnPacketLost(ackedPacketNumber, packetLength, bytesInFlight) - } - bytesInFlight -= protocol.ByteCount(n) * packetLength - } - - // Does not increment acked_packet_number_. - LosePacket := func(number protocol.PacketNumber) { - sender.OnPacketLost(number, protocol.DefaultTCPMSS, bytesInFlight) - bytesInFlight -= protocol.DefaultTCPMSS - } - - SendAvailableSendWindow := func() int { return SendAvailableSendWindowLen(protocol.DefaultTCPMSS) } - LoseNPackets := func(n int) { LoseNPacketsLen(n, protocol.DefaultTCPMSS) } - - It("has the right values at startup", func() { - // At startup make sure we are at the default. - Expect(sender.GetCongestionWindow()).To(Equal(defaultWindowTCP)) - // Make sure we can send. - Expect(sender.TimeUntilSend(0)).To(BeZero()) - Expect(canSend()).To(BeTrue()) - // And that window is un-affected. - Expect(sender.GetCongestionWindow()).To(Equal(defaultWindowTCP)) - - // Fill the send window with data, then verify that we can't send. - SendAvailableSendWindow() - Expect(canSend()).To(BeFalse()) - }) - - It("paces", func() { - clock.Advance(time.Hour) - // Fill the send window with data, then verify that we can't send. - SendAvailableSendWindow() - AckNPackets(1) - delay := sender.TimeUntilSend(bytesInFlight) - Expect(delay).ToNot(BeZero()) - Expect(delay).ToNot(Equal(utils.InfDuration)) - }) - - It("application limited slow start", func() { - // Send exactly 10 packets and ensure the CWND ends at 14 packets. - const numberOfAcks = 5 - // At startup make sure we can send. - Expect(sender.TimeUntilSend(0)).To(BeZero()) - // Make sure we can send. - Expect(sender.TimeUntilSend(0)).To(BeZero()) - - SendAvailableSendWindow() - for i := 0; i < numberOfAcks; i++ { - AckNPackets(2) - } - bytesToSend := sender.GetCongestionWindow() - // It's expected 2 acks will arrive when the bytes_in_flight are greater than - // half the CWND. - Expect(bytesToSend).To(Equal(defaultWindowTCP + protocol.DefaultTCPMSS*2*2)) - }) - - It("exponential slow start", func() { - const numberOfAcks = 20 - // At startup make sure we can send. - Expect(sender.TimeUntilSend(0)).To(BeZero()) - Expect(sender.BandwidthEstimate()).To(BeZero()) - // Make sure we can send. - Expect(sender.TimeUntilSend(0)).To(BeZero()) - - for i := 0; i < numberOfAcks; i++ { - // Send our full send window. - SendAvailableSendWindow() - AckNPackets(2) - } - cwnd := sender.GetCongestionWindow() - Expect(cwnd).To(Equal(defaultWindowTCP + protocol.DefaultTCPMSS*2*numberOfAcks)) - Expect(sender.BandwidthEstimate()).To(Equal(BandwidthFromDelta(cwnd, rttStats.SmoothedRTT()))) - }) - - It("slow start packet loss", func() { - sender.SetNumEmulatedConnections(1) - const numberOfAcks = 10 - for i := 0; i < numberOfAcks; i++ { - // Send our full send window. - SendAvailableSendWindow() - AckNPackets(2) - } - SendAvailableSendWindow() - expectedSendWindow := defaultWindowTCP + (protocol.DefaultTCPMSS * 2 * numberOfAcks) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Lose a packet to exit slow start. - LoseNPackets(1) - packetsInRecoveryWindow := expectedSendWindow / protocol.DefaultTCPMSS - - // We should now have fallen out of slow start with a reduced window. - expectedSendWindow = protocol.ByteCount(float32(expectedSendWindow) * renoBeta) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Recovery phase. We need to ack every packet in the recovery window before - // we exit recovery. - numberOfPacketsInWindow := expectedSendWindow / protocol.DefaultTCPMSS - AckNPackets(int(packetsInRecoveryWindow)) - SendAvailableSendWindow() - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // We need to ack an entire window before we increase CWND by 1. - AckNPackets(int(numberOfPacketsInWindow) - 2) - SendAvailableSendWindow() - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Next ack should increase cwnd by 1. - AckNPackets(1) - expectedSendWindow += protocol.DefaultTCPMSS - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Now RTO and ensure slow start gets reset. - Expect(sender.HybridSlowStart().Started()).To(BeTrue()) - sender.OnRetransmissionTimeout(true) - Expect(sender.HybridSlowStart().Started()).To(BeFalse()) - }) - - It("slow start packet loss with large reduction", func() { - sender.SetSlowStartLargeReduction(true) - - sender.SetNumEmulatedConnections(1) - const numberOfAcks = 10 - for i := 0; i < numberOfAcks; i++ { - // Send our full send window. - SendAvailableSendWindow() - AckNPackets(2) - } - SendAvailableSendWindow() - expectedSendWindow := defaultWindowTCP + (protocol.DefaultTCPMSS * 2 * numberOfAcks) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Lose a packet to exit slow start. We should now have fallen out of - // slow start with a window reduced by 1. - LoseNPackets(1) - expectedSendWindow -= protocol.DefaultTCPMSS - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Lose 5 packets in recovery and verify that congestion window is reduced - // further. - LoseNPackets(5) - expectedSendWindow -= 5 * protocol.DefaultTCPMSS - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - packetsInRecoveryWindow := expectedSendWindow / protocol.DefaultTCPMSS - - // Recovery phase. We need to ack every packet in the recovery window before - // we exit recovery. - numberOfPacketsInWindow := expectedSendWindow / protocol.DefaultTCPMSS - AckNPackets(int(packetsInRecoveryWindow)) - SendAvailableSendWindow() - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // We need to ack the rest of the window before cwnd increases by 1. - AckNPackets(int(numberOfPacketsInWindow - 1)) - SendAvailableSendWindow() - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Next ack should increase cwnd by 1. - AckNPackets(1) - expectedSendWindow += protocol.DefaultTCPMSS - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Now RTO and ensure slow start gets reset. - Expect(sender.HybridSlowStart().Started()).To(BeTrue()) - sender.OnRetransmissionTimeout(true) - Expect(sender.HybridSlowStart().Started()).To(BeFalse()) - }) - - It("slow start half packet loss with large reduction", func() { - sender.SetSlowStartLargeReduction(true) - - sender.SetNumEmulatedConnections(1) - const numberOfAcks = 10 - for i := 0; i < numberOfAcks; i++ { - // Send our full send window in half sized packets. - SendAvailableSendWindowLen(protocol.DefaultTCPMSS / 2) - AckNPackets(2) - } - SendAvailableSendWindowLen(protocol.DefaultTCPMSS / 2) - expectedSendWindow := defaultWindowTCP + (protocol.DefaultTCPMSS * 2 * numberOfAcks) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Lose a packet to exit slow start. We should now have fallen out of - // slow start with a window reduced by 1. - LoseNPackets(1) - expectedSendWindow -= protocol.DefaultTCPMSS - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Lose 10 packets in recovery and verify that congestion window is reduced - // by 5 packets. - LoseNPacketsLen(10, protocol.DefaultTCPMSS/2) - expectedSendWindow -= 5 * protocol.DefaultTCPMSS - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - }) - - // this test doesn't work any more after introducing the pacing needed for QUIC - PIt("no PRR when less than one packet in flight", func() { - SendAvailableSendWindow() - LoseNPackets(int(initialCongestionWindowPackets) - 1) - AckNPackets(1) - // PRR will allow 2 packets for every ack during recovery. - Expect(SendAvailableSendWindow()).To(Equal(2)) - // Simulate abandoning all packets by supplying a bytes_in_flight of 0. - // PRR should now allow a packet to be sent, even though prr's state - // variables believe it has sent enough packets. - Expect(sender.TimeUntilSend(0)).To(BeZero()) - }) - - It("slow start packet loss PRR", func() { - sender.SetNumEmulatedConnections(1) - // Test based on the first example in RFC6937. - // Ack 10 packets in 5 acks to raise the CWND to 20, as in the example. - const numberOfAcks = 5 - for i := 0; i < numberOfAcks; i++ { - // Send our full send window. - SendAvailableSendWindow() - AckNPackets(2) - } - SendAvailableSendWindow() - expectedSendWindow := defaultWindowTCP + (protocol.DefaultTCPMSS * 2 * numberOfAcks) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - LoseNPackets(1) - - // We should now have fallen out of slow start with a reduced window. - sendWindowBeforeLoss := expectedSendWindow - expectedSendWindow = protocol.ByteCount(float32(expectedSendWindow) * renoBeta) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Testing TCP proportional rate reduction. - // We should send packets paced over the received acks for the remaining - // outstanding packets. The number of packets before we exit recovery is the - // original CWND minus the packet that has been lost and the one which - // triggered the loss. - remainingPacketsInRecovery := sendWindowBeforeLoss/protocol.DefaultTCPMSS - 2 - - for i := protocol.ByteCount(0); i < remainingPacketsInRecovery; i++ { - AckNPackets(1) - SendAvailableSendWindow() - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - } - - // We need to ack another window before we increase CWND by 1. - numberOfPacketsInWindow := expectedSendWindow / protocol.DefaultTCPMSS - for i := protocol.ByteCount(0); i < numberOfPacketsInWindow; i++ { - AckNPackets(1) - Expect(SendAvailableSendWindow()).To(Equal(1)) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - } - - AckNPackets(1) - expectedSendWindow += protocol.DefaultTCPMSS - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - }) - - It("slow start burst packet loss PRR", func() { - sender.SetNumEmulatedConnections(1) - // Test based on the second example in RFC6937, though we also implement - // forward acknowledgements, so the first two incoming acks will trigger - // PRR immediately. - // Ack 20 packets in 10 acks to raise the CWND to 30. - const numberOfAcks = 10 - for i := 0; i < numberOfAcks; i++ { - // Send our full send window. - SendAvailableSendWindow() - AckNPackets(2) - } - SendAvailableSendWindow() - expectedSendWindow := defaultWindowTCP + (protocol.DefaultTCPMSS * 2 * numberOfAcks) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Lose one more than the congestion window reduction, so that after loss, - // bytes_in_flight is lesser than the congestion window. - sendWindowAfterLoss := protocol.ByteCount(renoBeta * float32(expectedSendWindow)) - numPacketsToLose := (expectedSendWindow-sendWindowAfterLoss)/protocol.DefaultTCPMSS + 1 - LoseNPackets(int(numPacketsToLose)) - // Immediately after the loss, ensure at least one packet can be sent. - // Losses without subsequent acks can occur with timer based loss detection. - Expect(sender.TimeUntilSend(bytesInFlight)).To(BeZero()) - AckNPackets(1) - - // We should now have fallen out of slow start with a reduced window. - expectedSendWindow = protocol.ByteCount(float32(expectedSendWindow) * renoBeta) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Only 2 packets should be allowed to be sent, per PRR-SSRB - Expect(SendAvailableSendWindow()).To(Equal(2)) - - // Ack the next packet, which triggers another loss. - LoseNPackets(1) - AckNPackets(1) - - // Send 2 packets to simulate PRR-SSRB. - Expect(SendAvailableSendWindow()).To(Equal(2)) - - // Ack the next packet, which triggers another loss. - LoseNPackets(1) - AckNPackets(1) - - // Send 2 packets to simulate PRR-SSRB. - Expect(SendAvailableSendWindow()).To(Equal(2)) - - // Exit recovery and return to sending at the new rate. - for i := 0; i < numberOfAcks; i++ { - AckNPackets(1) - Expect(SendAvailableSendWindow()).To(Equal(1)) - } - }) - - It("RTO congestion window", func() { - Expect(sender.GetCongestionWindow()).To(Equal(defaultWindowTCP)) - Expect(sender.SlowstartThreshold()).To(Equal(MaxCongestionWindow)) - - // Expect the window to decrease to the minimum once the RTO fires - // and slow start threshold to be set to 1/2 of the CWND. - sender.OnRetransmissionTimeout(true) - Expect(sender.GetCongestionWindow()).To(Equal(2 * protocol.DefaultTCPMSS)) - Expect(sender.SlowstartThreshold()).To(Equal(5 * protocol.DefaultTCPMSS)) - }) - - It("RTO congestion window no retransmission", func() { - Expect(sender.GetCongestionWindow()).To(Equal(defaultWindowTCP)) - - // Expect the window to remain unchanged if the RTO fires but no - // packets are retransmitted. - sender.OnRetransmissionTimeout(false) - Expect(sender.GetCongestionWindow()).To(Equal(defaultWindowTCP)) - }) - - It("tcp cubic reset epoch on quiescence", func() { - const maxCongestionWindow = 50 - const maxCongestionWindowBytes = maxCongestionWindow * protocol.DefaultTCPMSS - sender = NewCubicSender(&clock, rttStats, false, initialCongestionWindowPackets*protocol.DefaultTCPMSS, maxCongestionWindowBytes) - - numSent := SendAvailableSendWindow() - - // Make sure we fall out of slow start. - savedCwnd := sender.GetCongestionWindow() - LoseNPackets(1) - Expect(savedCwnd).To(BeNumerically(">", sender.GetCongestionWindow())) - - // Ack the rest of the outstanding packets to get out of recovery. - for i := 1; i < numSent; i++ { - AckNPackets(1) - } - Expect(bytesInFlight).To(BeZero()) - - // Send a new window of data and ack all; cubic growth should occur. - savedCwnd = sender.GetCongestionWindow() - numSent = SendAvailableSendWindow() - for i := 0; i < numSent; i++ { - AckNPackets(1) - } - Expect(savedCwnd).To(BeNumerically("<", sender.GetCongestionWindow())) - Expect(maxCongestionWindowBytes).To(BeNumerically(">", sender.GetCongestionWindow())) - Expect(bytesInFlight).To(BeZero()) - - // Quiescent time of 100 seconds - clock.Advance(100 * time.Second) - - // Send new window of data and ack one packet. Cubic epoch should have - // been reset; ensure cwnd increase is not dramatic. - savedCwnd = sender.GetCongestionWindow() - SendAvailableSendWindow() - AckNPackets(1) - Expect(savedCwnd).To(BeNumerically("~", sender.GetCongestionWindow(), protocol.DefaultTCPMSS)) - Expect(maxCongestionWindowBytes).To(BeNumerically(">", sender.GetCongestionWindow())) - }) - - It("multiple losses in one window", func() { - SendAvailableSendWindow() - initialWindow := sender.GetCongestionWindow() - LosePacket(ackedPacketNumber + 1) - postLossWindow := sender.GetCongestionWindow() - Expect(initialWindow).To(BeNumerically(">", postLossWindow)) - LosePacket(ackedPacketNumber + 3) - Expect(sender.GetCongestionWindow()).To(Equal(postLossWindow)) - LosePacket(packetNumber - 1) - Expect(sender.GetCongestionWindow()).To(Equal(postLossWindow)) - - // Lose a later packet and ensure the window decreases. - LosePacket(packetNumber) - Expect(postLossWindow).To(BeNumerically(">", sender.GetCongestionWindow())) - }) - - It("2 connection congestion avoidance at end of recovery", func() { - sender.SetNumEmulatedConnections(2) - // Ack 10 packets in 5 acks to raise the CWND to 20. - const numberOfAcks = 5 - for i := 0; i < numberOfAcks; i++ { - // Send our full send window. - SendAvailableSendWindow() - AckNPackets(2) - } - SendAvailableSendWindow() - expectedSendWindow := defaultWindowTCP + (protocol.DefaultTCPMSS * 2 * numberOfAcks) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - LoseNPackets(1) - - // We should now have fallen out of slow start with a reduced window. - expectedSendWindow = protocol.ByteCount(float32(expectedSendWindow) * sender.RenoBeta()) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // No congestion window growth should occur in recovery phase, i.e., until the - // currently outstanding 20 packets are acked. - for i := 0; i < 10; i++ { - // Send our full send window. - SendAvailableSendWindow() - Expect(sender.InRecovery()).To(BeTrue()) - AckNPackets(2) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - } - Expect(sender.InRecovery()).To(BeFalse()) - - // Out of recovery now. Congestion window should not grow for half an RTT. - packetsInSendWindow := expectedSendWindow / protocol.DefaultTCPMSS - SendAvailableSendWindow() - AckNPackets(int(packetsInSendWindow/2 - 2)) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Next ack should increase congestion window by 1MSS. - SendAvailableSendWindow() - AckNPackets(2) - expectedSendWindow += protocol.DefaultTCPMSS - packetsInSendWindow++ - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Congestion window should remain steady again for half an RTT. - SendAvailableSendWindow() - AckNPackets(int(packetsInSendWindow/2 - 1)) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Next ack should cause congestion window to grow by 1MSS. - SendAvailableSendWindow() - AckNPackets(2) - expectedSendWindow += protocol.DefaultTCPMSS - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - }) - - It("1 connection congestion avoidance at end of recovery", func() { - sender.SetNumEmulatedConnections(1) - // Ack 10 packets in 5 acks to raise the CWND to 20. - const numberOfAcks = 5 - for i := 0; i < numberOfAcks; i++ { - // Send our full send window. - SendAvailableSendWindow() - AckNPackets(2) - } - SendAvailableSendWindow() - expectedSendWindow := defaultWindowTCP + (protocol.DefaultTCPMSS * 2 * numberOfAcks) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - LoseNPackets(1) - - // We should now have fallen out of slow start with a reduced window. - expectedSendWindow = protocol.ByteCount(float32(expectedSendWindow) * renoBeta) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // No congestion window growth should occur in recovery phase, i.e., until the - // currently outstanding 20 packets are acked. - for i := 0; i < 10; i++ { - // Send our full send window. - SendAvailableSendWindow() - Expect(sender.InRecovery()).To(BeTrue()) - AckNPackets(2) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - } - Expect(sender.InRecovery()).To(BeFalse()) - - // Out of recovery now. Congestion window should not grow during RTT. - for i := protocol.ByteCount(0); i < expectedSendWindow/protocol.DefaultTCPMSS-2; i += 2 { - // Send our full send window. - SendAvailableSendWindow() - AckNPackets(2) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - } - - // Next ack should cause congestion window to grow by 1MSS. - SendAvailableSendWindow() - AckNPackets(2) - expectedSendWindow += protocol.DefaultTCPMSS - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - }) - - It("reset after connection migration", func() { - Expect(sender.GetCongestionWindow()).To(Equal(defaultWindowTCP)) - Expect(sender.SlowstartThreshold()).To(Equal(MaxCongestionWindow)) - - // Starts with slow start. - sender.SetNumEmulatedConnections(1) - const numberOfAcks = 10 - for i := 0; i < numberOfAcks; i++ { - // Send our full send window. - SendAvailableSendWindow() - AckNPackets(2) - } - SendAvailableSendWindow() - expectedSendWindow := defaultWindowTCP + (protocol.DefaultTCPMSS * 2 * numberOfAcks) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - - // Loses a packet to exit slow start. - LoseNPackets(1) - - // We should now have fallen out of slow start with a reduced window. Slow - // start threshold is also updated. - expectedSendWindow = protocol.ByteCount(float32(expectedSendWindow) * renoBeta) - Expect(sender.GetCongestionWindow()).To(Equal(expectedSendWindow)) - Expect(sender.SlowstartThreshold()).To(Equal(expectedSendWindow)) - - // Resets cwnd and slow start threshold on connection migrations. - sender.OnConnectionMigration() - Expect(sender.GetCongestionWindow()).To(Equal(defaultWindowTCP)) - Expect(sender.SlowstartThreshold()).To(Equal(MaxCongestionWindow)) - Expect(sender.HybridSlowStart().Started()).To(BeFalse()) - }) - - It("default max cwnd", func() { - sender = NewCubicSender(&clock, rttStats, true /*reno*/, initialCongestionWindowPackets*protocol.DefaultTCPMSS, protocol.DefaultMaxCongestionWindow) - - defaultMaxCongestionWindowPackets := protocol.DefaultMaxCongestionWindow / protocol.DefaultTCPMSS - for i := 1; i < int(defaultMaxCongestionWindowPackets); i++ { - sender.MaybeExitSlowStart() - sender.OnPacketAcked(protocol.PacketNumber(i), 1350, sender.GetCongestionWindow(), clock.Now()) - } - Expect(sender.GetCongestionWindow()).To(Equal(protocol.DefaultMaxCongestionWindow)) - }) - - It("limit cwnd increase in congestion avoidance", func() { - // Enable Cubic. - sender = NewCubicSender(&clock, rttStats, false, initialCongestionWindowPackets*protocol.DefaultTCPMSS, MaxCongestionWindow) - numSent := SendAvailableSendWindow() - - // Make sure we fall out of slow start. - savedCwnd := sender.GetCongestionWindow() - LoseNPackets(1) - Expect(savedCwnd).To(BeNumerically(">", sender.GetCongestionWindow())) - - // Ack the rest of the outstanding packets to get out of recovery. - for i := 1; i < numSent; i++ { - AckNPackets(1) - } - Expect(bytesInFlight).To(BeZero()) - - savedCwnd = sender.GetCongestionWindow() - SendAvailableSendWindow() - - // Ack packets until the CWND increases. - for sender.GetCongestionWindow() == savedCwnd { - AckNPackets(1) - SendAvailableSendWindow() - } - // Bytes in flight may be larger than the CWND if the CWND isn't an exact - // multiple of the packet sizes being sent. - Expect(bytesInFlight).To(BeNumerically(">=", sender.GetCongestionWindow())) - savedCwnd = sender.GetCongestionWindow() - - // Advance time 2 seconds waiting for an ack. - clock.Advance(2 * time.Second) - - // Ack two packets. The CWND should increase by only one packet. - AckNPackets(2) - Expect(sender.GetCongestionWindow()).To(Equal(savedCwnd + protocol.DefaultTCPMSS)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/congestion/cubic_test.go b/vendor/lucas-clemente/quic-go/internal/congestion/cubic_test.go deleted file mode 100644 index 52cae1456..000000000 --- a/vendor/lucas-clemente/quic-go/internal/congestion/cubic_test.go +++ /dev/null @@ -1,236 +0,0 @@ -package congestion - -import ( - "math" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -const numConnections uint32 = 2 -const nConnectionBeta float32 = (float32(numConnections) - 1 + beta) / float32(numConnections) -const nConnectionBetaLastMax float32 = (float32(numConnections) - 1 + betaLastMax) / float32(numConnections) -const nConnectionAlpha float32 = 3 * float32(numConnections) * float32(numConnections) * (1 - nConnectionBeta) / (1 + nConnectionBeta) -const maxCubicTimeInterval = 30 * time.Millisecond - -var _ = Describe("Cubic", func() { - var ( - clock mockClock - cubic *Cubic - ) - - BeforeEach(func() { - clock = mockClock{} - cubic = NewCubic(&clock) - }) - - renoCwnd := func(currentCwnd protocol.ByteCount) protocol.ByteCount { - return currentCwnd + protocol.ByteCount(float32(protocol.DefaultTCPMSS)*nConnectionAlpha*float32(protocol.DefaultTCPMSS)/float32(currentCwnd)) - } - - cubicConvexCwnd := func(initialCwnd protocol.ByteCount, rtt, elapsedTime time.Duration) protocol.ByteCount { - offset := protocol.ByteCount((elapsedTime+rtt)/time.Microsecond) << 10 / 1000000 - deltaCongestionWindow := 410 * offset * offset * offset * protocol.DefaultTCPMSS >> 40 - return initialCwnd + deltaCongestionWindow - } - - It("works above origin (with tighter bounds)", func() { - // Convex growth. - const rttMin = 100 * time.Millisecond - const rttMinS = float32(rttMin/time.Millisecond) / 1000.0 - currentCwnd := 10 * protocol.DefaultTCPMSS - initialCwnd := currentCwnd - - clock.Advance(time.Millisecond) - initialTime := clock.Now() - expectedFirstCwnd := renoCwnd(currentCwnd) - currentCwnd = cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, initialTime) - Expect(expectedFirstCwnd).To(Equal(currentCwnd)) - - // Normal TCP phase. - // The maximum number of expected reno RTTs can be calculated by - // finding the point where the cubic curve and the reno curve meet. - maxRenoRtts := int(math.Sqrt(float64(nConnectionAlpha/(0.4*rttMinS*rttMinS*rttMinS))) - 2) - for i := 0; i < maxRenoRtts; i++ { - // Alternatively, we expect it to increase by one, every time we - // receive current_cwnd/Alpha acks back. (This is another way of - // saying we expect cwnd to increase by approximately Alpha once - // we receive current_cwnd number ofacks back). - numAcksThisEpoch := int(float32(currentCwnd/protocol.DefaultTCPMSS) / nConnectionAlpha) - - initialCwndThisEpoch := currentCwnd - for n := 0; n < numAcksThisEpoch; n++ { - // Call once per ACK. - expectedNextCwnd := renoCwnd(currentCwnd) - currentCwnd = cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - Expect(currentCwnd).To(Equal(expectedNextCwnd)) - } - // Our byte-wise Reno implementation is an estimate. We expect - // the cwnd to increase by approximately one MSS every - // cwnd/kDefaultTCPMSS/Alpha acks, but it may be off by as much as - // half a packet for smaller values of current_cwnd. - cwndChangeThisEpoch := currentCwnd - initialCwndThisEpoch - Expect(cwndChangeThisEpoch).To(BeNumerically("~", protocol.DefaultTCPMSS, protocol.DefaultTCPMSS/2)) - clock.Advance(100 * time.Millisecond) - } - - for i := 0; i < 54; i++ { - maxAcksThisEpoch := currentCwnd / protocol.DefaultTCPMSS - interval := time.Duration(100*1000/maxAcksThisEpoch) * time.Microsecond - for n := 0; n < int(maxAcksThisEpoch); n++ { - clock.Advance(interval) - currentCwnd = cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - expectedCwnd := cubicConvexCwnd(initialCwnd, rttMin, clock.Now().Sub(initialTime)) - // If we allow per-ack updates, every update is a small cubic update. - Expect(currentCwnd).To(Equal(expectedCwnd)) - } - } - expectedCwnd := cubicConvexCwnd(initialCwnd, rttMin, clock.Now().Sub(initialTime)) - currentCwnd = cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - Expect(currentCwnd).To(Equal(expectedCwnd)) - }) - - It("works above the origin with fine grained cubing", func() { - // Start the test with an artificially large cwnd to prevent Reno - // from over-taking cubic. - currentCwnd := 1000 * protocol.DefaultTCPMSS - initialCwnd := currentCwnd - rttMin := 100 * time.Millisecond - clock.Advance(time.Millisecond) - initialTime := clock.Now() - - currentCwnd = cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - clock.Advance(600 * time.Millisecond) - currentCwnd = cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - - // We expect the algorithm to perform only non-zero, fine-grained cubic - // increases on every ack in this case. - for i := 0; i < 100; i++ { - clock.Advance(10 * time.Millisecond) - expectedCwnd := cubicConvexCwnd(initialCwnd, rttMin, clock.Now().Sub(initialTime)) - nextCwnd := cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - // Make sure we are performing cubic increases. - Expect(nextCwnd).To(Equal(expectedCwnd)) - // Make sure that these are non-zero, less-than-packet sized increases. - Expect(nextCwnd).To(BeNumerically(">", currentCwnd)) - cwndDelta := nextCwnd - currentCwnd - Expect(protocol.DefaultTCPMSS / 10).To(BeNumerically(">", cwndDelta)) - currentCwnd = nextCwnd - } - }) - - It("handles per ack updates", func() { - // Start the test with a large cwnd and RTT, to force the first - // increase to be a cubic increase. - initialCwndPackets := 150 - currentCwnd := protocol.ByteCount(initialCwndPackets) * protocol.DefaultTCPMSS - rttMin := 350 * time.Millisecond - - // Initialize the epoch - clock.Advance(time.Millisecond) - // Keep track of the growth of the reno-equivalent cwnd. - rCwnd := renoCwnd(currentCwnd) - currentCwnd = cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - initialCwnd := currentCwnd - - // Simulate the return of cwnd packets in less than - // MaxCubicInterval() time. - maxAcks := int(float32(initialCwndPackets) / nConnectionAlpha) - interval := maxCubicTimeInterval / time.Duration(maxAcks+1) - - // In this scenario, the first increase is dictated by the cubic - // equation, but it is less than one byte, so the cwnd doesn't - // change. Normally, without per-ack increases, any cwnd plateau - // will cause the cwnd to be pinned for MaxCubicTimeInterval(). If - // we enable per-ack updates, the cwnd will continue to grow, - // regardless of the temporary plateau. - clock.Advance(interval) - rCwnd = renoCwnd(rCwnd) - Expect(cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now())).To(Equal(currentCwnd)) - for i := 1; i < maxAcks; i++ { - clock.Advance(interval) - nextCwnd := cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - rCwnd = renoCwnd(rCwnd) - // The window shoud increase on every ack. - Expect(nextCwnd).To(BeNumerically(">", currentCwnd)) - Expect(nextCwnd).To(Equal(rCwnd)) - currentCwnd = nextCwnd - } - - // After all the acks are returned from the epoch, we expect the - // cwnd to have increased by nearly one packet. (Not exactly one - // packet, because our byte-wise Reno algorithm is always a slight - // under-estimation). Without per-ack updates, the current_cwnd - // would otherwise be unchanged. - minimumExpectedIncrease := protocol.DefaultTCPMSS * 9 / 10 - Expect(currentCwnd).To(BeNumerically(">", initialCwnd+minimumExpectedIncrease)) - }) - - It("handles loss events", func() { - rttMin := 100 * time.Millisecond - currentCwnd := 422 * protocol.DefaultTCPMSS - expectedCwnd := renoCwnd(currentCwnd) - // Initialize the state. - clock.Advance(time.Millisecond) - Expect(cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now())).To(Equal(expectedCwnd)) - - // On the first loss, the last max congestion window is set to the - // congestion window before the loss. - preLossCwnd := currentCwnd - Expect(cubic.lastMaxCongestionWindow).To(BeZero()) - expectedCwnd = protocol.ByteCount(float32(currentCwnd) * nConnectionBeta) - Expect(cubic.CongestionWindowAfterPacketLoss(currentCwnd)).To(Equal(expectedCwnd)) - Expect(cubic.lastMaxCongestionWindow).To(Equal(preLossCwnd)) - currentCwnd = expectedCwnd - - // On the second loss, the current congestion window has not yet - // reached the last max congestion window. The last max congestion - // window will be reduced by an additional backoff factor to allow - // for competition. - preLossCwnd = currentCwnd - expectedCwnd = protocol.ByteCount(float32(currentCwnd) * nConnectionBeta) - Expect(cubic.CongestionWindowAfterPacketLoss(currentCwnd)).To(Equal(expectedCwnd)) - currentCwnd = expectedCwnd - Expect(preLossCwnd).To(BeNumerically(">", cubic.lastMaxCongestionWindow)) - expectedLastMax := protocol.ByteCount(float32(preLossCwnd) * nConnectionBetaLastMax) - Expect(cubic.lastMaxCongestionWindow).To(Equal(expectedLastMax)) - Expect(expectedCwnd).To(BeNumerically("<", cubic.lastMaxCongestionWindow)) - // Simulate an increase, and check that we are below the origin. - currentCwnd = cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - Expect(cubic.lastMaxCongestionWindow).To(BeNumerically(">", currentCwnd)) - - // On the final loss, simulate the condition where the congestion - // window had a chance to grow nearly to the last congestion window. - currentCwnd = cubic.lastMaxCongestionWindow - 1 - preLossCwnd = currentCwnd - expectedCwnd = protocol.ByteCount(float32(currentCwnd) * nConnectionBeta) - Expect(cubic.CongestionWindowAfterPacketLoss(currentCwnd)).To(Equal(expectedCwnd)) - expectedLastMax = preLossCwnd - Expect(cubic.lastMaxCongestionWindow).To(Equal(expectedLastMax)) - }) - - It("works below origin", func() { - // Concave growth. - rttMin := 100 * time.Millisecond - currentCwnd := 422 * protocol.DefaultTCPMSS - expectedCwnd := renoCwnd(currentCwnd) - // Initialize the state. - clock.Advance(time.Millisecond) - Expect(cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now())).To(Equal(expectedCwnd)) - - expectedCwnd = protocol.ByteCount(float32(currentCwnd) * nConnectionBeta) - Expect(cubic.CongestionWindowAfterPacketLoss(currentCwnd)).To(Equal(expectedCwnd)) - currentCwnd = expectedCwnd - // First update after loss to initialize the epoch. - currentCwnd = cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - // Cubic phase. - for i := 0; i < 40; i++ { - clock.Advance(100 * time.Millisecond) - currentCwnd = cubic.CongestionWindowAfterAck(protocol.DefaultTCPMSS, currentCwnd, rttMin, clock.Now()) - } - expectedCwnd = 553632 - Expect(currentCwnd).To(Equal(expectedCwnd)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/congestion/hybrid_slow_start_test.go b/vendor/lucas-clemente/quic-go/internal/congestion/hybrid_slow_start_test.go deleted file mode 100644 index fee8945e2..000000000 --- a/vendor/lucas-clemente/quic-go/internal/congestion/hybrid_slow_start_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package congestion - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Hybrid slow start", func() { - var ( - slowStart HybridSlowStart - ) - - BeforeEach(func() { - slowStart = HybridSlowStart{} - }) - - It("works in a simple case", func() { - packetNumber := protocol.PacketNumber(1) - endPacketNumber := protocol.PacketNumber(3) - slowStart.StartReceiveRound(endPacketNumber) - - packetNumber++ - Expect(slowStart.IsEndOfRound(packetNumber)).To(BeFalse()) - - // Test duplicates. - Expect(slowStart.IsEndOfRound(packetNumber)).To(BeFalse()) - - packetNumber++ - Expect(slowStart.IsEndOfRound(packetNumber)).To(BeFalse()) - packetNumber++ - Expect(slowStart.IsEndOfRound(packetNumber)).To(BeTrue()) - - // Test without a new registered end_packet_number; - packetNumber++ - Expect(slowStart.IsEndOfRound(packetNumber)).To(BeTrue()) - - endPacketNumber = 20 - slowStart.StartReceiveRound(endPacketNumber) - for packetNumber < endPacketNumber { - packetNumber++ - Expect(slowStart.IsEndOfRound(packetNumber)).To(BeFalse()) - } - packetNumber++ - Expect(slowStart.IsEndOfRound(packetNumber)).To(BeTrue()) - }) - - It("works with delay", func() { - rtt := 60 * time.Millisecond - // We expect to detect the increase at +1/8 of the RTT; hence at a typical - // RTT of 60ms the detection will happen at 67.5 ms. - const hybridStartMinSamples = 8 // Number of acks required to trigger. - - endPacketNumber := protocol.PacketNumber(1) - endPacketNumber++ - slowStart.StartReceiveRound(endPacketNumber) - - // Will not trigger since our lowest RTT in our burst is the same as the long - // term RTT provided. - for n := 0; n < hybridStartMinSamples; n++ { - Expect(slowStart.ShouldExitSlowStart(rtt+time.Duration(n)*time.Millisecond, rtt, 100)).To(BeFalse()) - } - endPacketNumber++ - slowStart.StartReceiveRound(endPacketNumber) - for n := 1; n < hybridStartMinSamples; n++ { - Expect(slowStart.ShouldExitSlowStart(rtt+(time.Duration(n)+10)*time.Millisecond, rtt, 100)).To(BeFalse()) - } - // Expect to trigger since all packets in this burst was above the long term - // RTT provided. - Expect(slowStart.ShouldExitSlowStart(rtt+10*time.Millisecond, rtt, 100)).To(BeTrue()) - }) - -}) diff --git a/vendor/lucas-clemente/quic-go/internal/congestion/prr_sender_test.go b/vendor/lucas-clemente/quic-go/internal/congestion/prr_sender_test.go deleted file mode 100644 index 0786b9bd0..000000000 --- a/vendor/lucas-clemente/quic-go/internal/congestion/prr_sender_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package congestion - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "github.com/lucas-clemente/quic-go/internal/protocol" -) - -var _ = Describe("PRR sender", func() { - var ( - prr PrrSender - ) - - BeforeEach(func() { - prr = PrrSender{} - }) - - It("single loss results in send on every other ack", func() { - numPacketsInFlight := protocol.ByteCount(50) - bytesInFlight := numPacketsInFlight * protocol.DefaultTCPMSS - sshthreshAfterLoss := numPacketsInFlight / 2 - congestionWindow := sshthreshAfterLoss * protocol.DefaultTCPMSS - - prr.OnPacketLost(bytesInFlight) - // Ack a packet. PRR allows one packet to leave immediately. - prr.OnPacketAcked(protocol.DefaultTCPMSS) - bytesInFlight -= protocol.DefaultTCPMSS - Expect(prr.CanSend(congestionWindow, bytesInFlight, sshthreshAfterLoss*protocol.DefaultTCPMSS)).To(BeTrue()) - // Send retransmission. - prr.OnPacketSent(protocol.DefaultTCPMSS) - // PRR shouldn't allow sending any more packets. - Expect(prr.CanSend(congestionWindow, bytesInFlight, sshthreshAfterLoss*protocol.DefaultTCPMSS)).To(BeFalse()) - - // One packet is lost, and one ack was consumed above. PRR now paces - // transmissions through the remaining 48 acks. PRR will alternatively - // disallow and allow a packet to be sent in response to an ack. - for i := protocol.ByteCount(0); i < sshthreshAfterLoss-1; i++ { - // Ack a packet. PRR shouldn't allow sending a packet in response. - prr.OnPacketAcked(protocol.DefaultTCPMSS) - bytesInFlight -= protocol.DefaultTCPMSS - Expect(prr.CanSend(congestionWindow, bytesInFlight, sshthreshAfterLoss*protocol.DefaultTCPMSS)).To(BeFalse()) - // Ack another packet. PRR should now allow sending a packet in response. - prr.OnPacketAcked(protocol.DefaultTCPMSS) - bytesInFlight -= protocol.DefaultTCPMSS - Expect(prr.CanSend(congestionWindow, bytesInFlight, sshthreshAfterLoss*protocol.DefaultTCPMSS)).To(BeTrue()) - // Send a packet in response. - prr.OnPacketSent(protocol.DefaultTCPMSS) - bytesInFlight += protocol.DefaultTCPMSS - } - - // Since bytes_in_flight is now equal to congestion_window, PRR now maintains - // packet conservation, allowing one packet to be sent in response to an ack. - Expect(bytesInFlight).To(Equal(congestionWindow)) - for i := 0; i < 10; i++ { - // Ack a packet. - prr.OnPacketAcked(protocol.DefaultTCPMSS) - bytesInFlight -= protocol.DefaultTCPMSS - Expect(prr.CanSend(congestionWindow, bytesInFlight, sshthreshAfterLoss*protocol.DefaultTCPMSS)).To(BeTrue()) - // Send a packet in response, since PRR allows it. - prr.OnPacketSent(protocol.DefaultTCPMSS) - bytesInFlight += protocol.DefaultTCPMSS - - // Since bytes_in_flight is equal to the congestion_window, - // PRR disallows sending. - Expect(bytesInFlight).To(Equal(congestionWindow)) - Expect(prr.CanSend(congestionWindow, bytesInFlight, sshthreshAfterLoss*protocol.DefaultTCPMSS)).To(BeFalse()) - } - - }) - - It("burst loss results in slow start", func() { - bytesInFlight := protocol.ByteCount(20 * protocol.DefaultTCPMSS) - const numPacketsLost = 13 - const ssthreshAfterLoss = 10 - const congestionWindow = ssthreshAfterLoss * protocol.DefaultTCPMSS - - // Lose 13 packets. - bytesInFlight -= numPacketsLost * protocol.DefaultTCPMSS - prr.OnPacketLost(bytesInFlight) - - // PRR-SSRB will allow the following 3 acks to send up to 2 packets. - for i := 0; i < 3; i++ { - prr.OnPacketAcked(protocol.DefaultTCPMSS) - bytesInFlight -= protocol.DefaultTCPMSS - // PRR-SSRB should allow two packets to be sent. - for j := 0; j < 2; j++ { - Expect(prr.CanSend(congestionWindow, bytesInFlight, ssthreshAfterLoss*protocol.DefaultTCPMSS)).To(BeTrue()) - // Send a packet in response. - prr.OnPacketSent(protocol.DefaultTCPMSS) - bytesInFlight += protocol.DefaultTCPMSS - } - // PRR should allow no more than 2 packets in response to an ack. - Expect(prr.CanSend(congestionWindow, bytesInFlight, ssthreshAfterLoss*protocol.DefaultTCPMSS)).To(BeFalse()) - } - - // Out of SSRB mode, PRR allows one send in response to each ack. - for i := 0; i < 10; i++ { - prr.OnPacketAcked(protocol.DefaultTCPMSS) - bytesInFlight -= protocol.DefaultTCPMSS - Expect(prr.CanSend(congestionWindow, bytesInFlight, ssthreshAfterLoss*protocol.DefaultTCPMSS)).To(BeTrue()) - // Send a packet in response. - prr.OnPacketSent(protocol.DefaultTCPMSS) - bytesInFlight += protocol.DefaultTCPMSS - } - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/congestion/rtt_stats_test.go b/vendor/lucas-clemente/quic-go/internal/congestion/rtt_stats_test.go deleted file mode 100644 index e8f8c69c9..000000000 --- a/vendor/lucas-clemente/quic-go/internal/congestion/rtt_stats_test.go +++ /dev/null @@ -1,131 +0,0 @@ -package congestion - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("RTT stats", func() { - var ( - rttStats *RTTStats - ) - - BeforeEach(func() { - rttStats = NewRTTStats() - }) - - It("DefaultsBeforeUpdate", func() { - Expect(rttStats.MinRTT()).To(Equal(time.Duration(0))) - Expect(rttStats.SmoothedRTT()).To(Equal(time.Duration(0))) - }) - - It("SmoothedRTT", func() { - // Verify that ack_delay is ignored in the first measurement. - rttStats.UpdateRTT((300 * time.Millisecond), (100 * time.Millisecond), time.Time{}) - Expect(rttStats.LatestRTT()).To(Equal((300 * time.Millisecond))) - Expect(rttStats.SmoothedRTT()).To(Equal((300 * time.Millisecond))) - // Verify that Smoothed RTT includes max ack delay if it's reasonable. - rttStats.UpdateRTT((350 * time.Millisecond), (50 * time.Millisecond), time.Time{}) - Expect(rttStats.LatestRTT()).To(Equal((300 * time.Millisecond))) - Expect(rttStats.SmoothedRTT()).To(Equal((300 * time.Millisecond))) - // Verify that large erroneous ack_delay does not change Smoothed RTT. - rttStats.UpdateRTT((200 * time.Millisecond), (300 * time.Millisecond), time.Time{}) - Expect(rttStats.LatestRTT()).To(Equal((200 * time.Millisecond))) - Expect(rttStats.SmoothedRTT()).To(Equal((287500 * time.Microsecond))) - }) - - It("SmoothedOrInitialRTT", func() { - Expect(rttStats.SmoothedOrInitialRTT()).To(Equal(defaultInitialRTT)) - rttStats.UpdateRTT((300 * time.Millisecond), (100 * time.Millisecond), time.Time{}) - Expect(rttStats.SmoothedOrInitialRTT()).To(Equal((300 * time.Millisecond))) - }) - - It("MinRTT", func() { - rttStats.UpdateRTT((200 * time.Millisecond), 0, time.Time{}) - Expect(rttStats.MinRTT()).To(Equal((200 * time.Millisecond))) - rttStats.UpdateRTT((10 * time.Millisecond), 0, time.Time{}.Add((10 * time.Millisecond))) - Expect(rttStats.MinRTT()).To(Equal((10 * time.Millisecond))) - rttStats.UpdateRTT((50 * time.Millisecond), 0, time.Time{}.Add((20 * time.Millisecond))) - Expect(rttStats.MinRTT()).To(Equal((10 * time.Millisecond))) - rttStats.UpdateRTT((50 * time.Millisecond), 0, time.Time{}.Add((30 * time.Millisecond))) - Expect(rttStats.MinRTT()).To(Equal((10 * time.Millisecond))) - rttStats.UpdateRTT((50 * time.Millisecond), 0, time.Time{}.Add((40 * time.Millisecond))) - Expect(rttStats.MinRTT()).To(Equal((10 * time.Millisecond))) - // Verify that ack_delay does not go into recording of MinRTT_. - rttStats.UpdateRTT((7 * time.Millisecond), (2 * time.Millisecond), time.Time{}.Add((50 * time.Millisecond))) - Expect(rttStats.MinRTT()).To(Equal((7 * time.Millisecond))) - }) - - It("ExpireSmoothedMetrics", func() { - initialRtt := (10 * time.Millisecond) - rttStats.UpdateRTT(initialRtt, 0, time.Time{}) - Expect(rttStats.MinRTT()).To(Equal(initialRtt)) - Expect(rttStats.SmoothedRTT()).To(Equal(initialRtt)) - - Expect(rttStats.MeanDeviation()).To(Equal(initialRtt / 2)) - - // Update once with a 20ms RTT. - doubledRtt := initialRtt * (2) - rttStats.UpdateRTT(doubledRtt, 0, time.Time{}) - Expect(rttStats.SmoothedRTT()).To(Equal(time.Duration(float32(initialRtt) * 1.125))) - - // Expire the smoothed metrics, increasing smoothed rtt and mean deviation. - rttStats.ExpireSmoothedMetrics() - Expect(rttStats.SmoothedRTT()).To(Equal(doubledRtt)) - Expect(rttStats.MeanDeviation()).To(Equal(time.Duration(float32(initialRtt) * 0.875))) - - // Now go back down to 5ms and expire the smoothed metrics, and ensure the - // mean deviation increases to 15ms. - halfRtt := initialRtt / 2 - rttStats.UpdateRTT(halfRtt, 0, time.Time{}) - Expect(doubledRtt).To(BeNumerically(">", rttStats.SmoothedRTT())) - Expect(initialRtt).To(BeNumerically("<", rttStats.MeanDeviation())) - }) - - It("UpdateRTTWithBadSendDeltas", func() { - // Make sure we ignore bad RTTs. - // base::test::MockLog log; - - initialRtt := (10 * time.Millisecond) - rttStats.UpdateRTT(initialRtt, 0, time.Time{}) - Expect(rttStats.MinRTT()).To(Equal(initialRtt)) - Expect(rttStats.SmoothedRTT()).To(Equal(initialRtt)) - - badSendDeltas := []time.Duration{ - 0, - utils.InfDuration, - -1000 * time.Microsecond, - } - // log.StartCapturingLogs(); - - for _, badSendDelta := range badSendDeltas { - // SCOPED_TRACE(Message() << "bad_send_delta = " - // << bad_send_delta.ToMicroseconds()); - // EXPECT_CALL(log, Log(LOG_WARNING, _, _, _, HasSubstr("Ignoring"))); - rttStats.UpdateRTT(badSendDelta, 0, time.Time{}) - Expect(rttStats.MinRTT()).To(Equal(initialRtt)) - Expect(rttStats.SmoothedRTT()).To(Equal(initialRtt)) - } - }) - - It("ResetAfterConnectionMigrations", func() { - rttStats.UpdateRTT((200 * time.Millisecond), 0, time.Time{}) - Expect(rttStats.LatestRTT()).To(Equal((200 * time.Millisecond))) - Expect(rttStats.SmoothedRTT()).To(Equal((200 * time.Millisecond))) - Expect(rttStats.MinRTT()).To(Equal((200 * time.Millisecond))) - rttStats.UpdateRTT((300 * time.Millisecond), (100 * time.Millisecond), time.Time{}) - Expect(rttStats.LatestRTT()).To(Equal((200 * time.Millisecond))) - Expect(rttStats.SmoothedRTT()).To(Equal((200 * time.Millisecond))) - Expect(rttStats.MinRTT()).To(Equal((200 * time.Millisecond))) - - // Reset rtt stats on connection migrations. - rttStats.OnConnectionMigration() - Expect(rttStats.LatestRTT()).To(Equal(time.Duration(0))) - Expect(rttStats.SmoothedRTT()).To(Equal(time.Duration(0))) - Expect(rttStats.MinRTT()).To(Equal(time.Duration(0))) - }) - -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/aesgcm12_aead_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/aesgcm12_aead_test.go deleted file mode 100644 index 6b896a521..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/aesgcm12_aead_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package crypto - -import ( - "crypto/rand" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("AES-GCM", func() { - var ( - alice, bob AEAD - keyAlice, keyBob, ivAlice, ivBob []byte - ) - - BeforeEach(func() { - keyAlice = make([]byte, 16) - keyBob = make([]byte, 16) - ivAlice = make([]byte, 4) - ivBob = make([]byte, 4) - rand.Reader.Read(keyAlice) - rand.Reader.Read(keyBob) - rand.Reader.Read(ivAlice) - rand.Reader.Read(ivBob) - var err error - alice, err = NewAEADAESGCM12(keyBob, keyAlice, ivBob, ivAlice) - Expect(err).ToNot(HaveOccurred()) - bob, err = NewAEADAESGCM12(keyAlice, keyBob, ivAlice, ivBob) - Expect(err).ToNot(HaveOccurred()) - }) - - It("seals and opens", func() { - b := alice.Seal(nil, []byte("foobar"), 42, []byte("aad")) - text, err := bob.Open(nil, b, 42, []byte("aad")) - Expect(err).ToNot(HaveOccurred()) - Expect(text).To(Equal([]byte("foobar"))) - }) - - It("seals and opens reverse", func() { - b := bob.Seal(nil, []byte("foobar"), 42, []byte("aad")) - text, err := alice.Open(nil, b, 42, []byte("aad")) - Expect(err).ToNot(HaveOccurred()) - Expect(text).To(Equal([]byte("foobar"))) - }) - - It("has the proper length", func() { - b := bob.Seal(nil, []byte("foobar"), 42, []byte("aad")) - Expect(b).To(HaveLen(6 + bob.Overhead())) - }) - - It("fails with wrong aad", func() { - b := alice.Seal(nil, []byte("foobar"), 42, []byte("aad")) - _, err := bob.Open(nil, b, 42, []byte("aad2")) - Expect(err).To(HaveOccurred()) - }) - - It("rejects wrong key and iv sizes", func() { - var err error - e := "AES-GCM: expected 16-byte keys and 4-byte IVs" - _, err = NewAEADAESGCM12(keyBob[1:], keyAlice, ivBob, ivAlice) - Expect(err).To(MatchError(e)) - _, err = NewAEADAESGCM12(keyBob, keyAlice[1:], ivBob, ivAlice) - Expect(err).To(MatchError(e)) - _, err = NewAEADAESGCM12(keyBob, keyAlice, ivBob[1:], ivAlice) - Expect(err).To(MatchError(e)) - _, err = NewAEADAESGCM12(keyBob, keyAlice, ivBob, ivAlice[1:]) - Expect(err).To(MatchError(e)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/aesgcm_aead_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/aesgcm_aead_test.go deleted file mode 100644 index 6b7fa1007..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/aesgcm_aead_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package crypto - -import ( - "crypto/rand" - "fmt" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("AES-GCM", func() { - var ( - alice, bob AEAD - keyAlice, keyBob, ivAlice, ivBob []byte - ) - - BeforeEach(func() { - ivAlice = make([]byte, 12) - ivBob = make([]byte, 12) - }) - - // 16 bytes for TLS_AES_128_GCM_SHA256 - // 32 bytes for TLS_AES_256_GCM_SHA384 - for _, ks := range []int{16, 32} { - keySize := ks - - Context(fmt.Sprintf("with %d byte keys", keySize), func() { - BeforeEach(func() { - keyAlice = make([]byte, keySize) - keyBob = make([]byte, keySize) - rand.Reader.Read(keyAlice) - rand.Reader.Read(keyBob) - rand.Reader.Read(ivAlice) - rand.Reader.Read(ivBob) - var err error - alice, err = NewAEADAESGCM(keyBob, keyAlice, ivBob, ivAlice) - Expect(err).ToNot(HaveOccurred()) - bob, err = NewAEADAESGCM(keyAlice, keyBob, ivAlice, ivBob) - Expect(err).ToNot(HaveOccurred()) - }) - - It("seals and opens", func() { - b := alice.Seal(nil, []byte("foobar"), 42, []byte("aad")) - text, err := bob.Open(nil, b, 42, []byte("aad")) - Expect(err).ToNot(HaveOccurred()) - Expect(text).To(Equal([]byte("foobar"))) - }) - - It("seals and opens reverse", func() { - b := bob.Seal(nil, []byte("foobar"), 42, []byte("aad")) - text, err := alice.Open(nil, b, 42, []byte("aad")) - Expect(err).ToNot(HaveOccurred()) - Expect(text).To(Equal([]byte("foobar"))) - }) - - It("has the proper length", func() { - b := bob.Seal(nil, []byte("foobar"), 42, []byte("aad")) - Expect(b).To(HaveLen(6 + bob.Overhead())) - }) - - It("fails with wrong aad", func() { - b := alice.Seal(nil, []byte("foobar"), 42, []byte("aad")) - _, err := bob.Open(nil, b, 42, []byte("aad2")) - Expect(err).To(HaveOccurred()) - }) - - It("rejects wrong key and iv sizes", func() { - e := "AES-GCM: expected 12 byte IVs" - var err error - _, err = NewAEADAESGCM(keyBob, keyAlice, ivBob[1:], ivAlice) - Expect(err).To(MatchError(e)) - _, err = NewAEADAESGCM(keyBob, keyAlice, ivBob, ivAlice[1:]) - Expect(err).To(MatchError(e)) - }) - }) - } - - It("errors when an invalid key size is used", func() { - keyAlice = make([]byte, 17) - keyBob = make([]byte, 17) - _, err := NewAEADAESGCM(keyBob, keyAlice, ivBob, ivAlice) - Expect(err).To(MatchError("crypto/aes: invalid key size 17")) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/cert_cache_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/cert_cache_test.go deleted file mode 100644 index 1ecc26f63..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/cert_cache_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package crypto - -import ( - lru "github.com/hashicorp/golang-lru" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Certificate cache", func() { - BeforeEach(func() { - var err error - compressedCertsCache, err = lru.New(2) - Expect(err).NotTo(HaveOccurred()) - }) - - It("gives a compressed cert", func() { - chain := [][]byte{{0xde, 0xca, 0xfb, 0xad}} - expected, err := compressChain(chain, nil, nil) - Expect(err).NotTo(HaveOccurred()) - compressed, err := getCompressedCert(chain, nil, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(compressed).To(Equal(expected)) - }) - - It("gets the same result multiple times", func() { - chain := [][]byte{{0xde, 0xca, 0xfb, 0xad}} - compressed, err := getCompressedCert(chain, nil, nil) - Expect(err).NotTo(HaveOccurred()) - compressed2, err := getCompressedCert(chain, nil, nil) - Expect(err).NotTo(HaveOccurred()) - Expect(compressed).To(Equal(compressed2)) - }) - - It("stores cached values", func() { - chain := [][]byte{{0xde, 0xca, 0xfb, 0xad}} - _, err := getCompressedCert(chain, nil, nil) - Expect(err).NotTo(HaveOccurred()) - Expect(compressedCertsCache.Len()).To(Equal(1)) - Expect(compressedCertsCache.Contains(uint64(3838929964809501833))).To(BeTrue()) - }) - - It("evicts old values", func() { - _, err := getCompressedCert([][]byte{{0x00}}, nil, nil) - Expect(err).NotTo(HaveOccurred()) - _, err = getCompressedCert([][]byte{{0x01}}, nil, nil) - Expect(err).NotTo(HaveOccurred()) - _, err = getCompressedCert([][]byte{{0x02}}, nil, nil) - Expect(err).NotTo(HaveOccurred()) - Expect(compressedCertsCache.Len()).To(Equal(2)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/cert_chain_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/cert_chain_test.go deleted file mode 100644 index fd60a46a2..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/cert_chain_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package crypto - -import ( - "bytes" - "compress/flate" - "compress/zlib" - "crypto/tls" - "reflect" - - "github.com/lucas-clemente/quic-go/internal/testdata" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Proof", func() { - var ( - cc *certChain - config *tls.Config - cert tls.Certificate - ) - - BeforeEach(func() { - cert = testdata.GetCertificate() - config = &tls.Config{} - cc = NewCertChain(config).(*certChain) - }) - - Context("certificate compression", func() { - It("compresses certs", func() { - cert := []byte{0xde, 0xca, 0xfb, 0xad} - certZlib := &bytes.Buffer{} - z, err := zlib.NewWriterLevelDict(certZlib, flate.BestCompression, certDictZlib) - Expect(err).ToNot(HaveOccurred()) - z.Write([]byte{0x04, 0x00, 0x00, 0x00}) - z.Write(cert) - z.Close() - kd := &certChain{ - config: &tls.Config{ - Certificates: []tls.Certificate{ - {Certificate: [][]byte{cert}}, - }, - }, - } - certCompressed, err := kd.GetCertsCompressed("", nil, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(certCompressed).To(Equal(append([]byte{ - 0x01, 0x00, - 0x08, 0x00, 0x00, 0x00, - }, certZlib.Bytes()...))) - }) - - It("errors when it can't retrieve a certificate", func() { - _, err := cc.GetCertsCompressed("invalid domain", nil, nil) - Expect(err).To(MatchError(errNoMatchingCertificate)) - }) - }) - - Context("signing server configs", func() { - It("errors when it can't retrieve a certificate for the requested SNI", func() { - _, err := cc.SignServerProof("invalid", []byte("chlo"), []byte("scfg")) - Expect(err).To(MatchError(errNoMatchingCertificate)) - }) - - It("signs the server config", func() { - config.Certificates = []tls.Certificate{cert} - proof, err := cc.SignServerProof("", []byte("chlo"), []byte("scfg")) - Expect(err).ToNot(HaveOccurred()) - Expect(proof).ToNot(BeEmpty()) - }) - }) - - Context("retrieving certificates", func() { - It("errors without certificates", func() { - _, err := cc.getCertForSNI("") - Expect(err).To(MatchError(errNoMatchingCertificate)) - }) - - It("uses first certificate in config.Certificates", func() { - config.Certificates = []tls.Certificate{cert} - cert, err := cc.getCertForSNI("") - Expect(err).ToNot(HaveOccurred()) - Expect(cert.PrivateKey).ToNot(BeNil()) - Expect(cert.Certificate[0]).ToNot(BeNil()) - }) - - It("uses NameToCertificate entries", func() { - config.Certificates = []tls.Certificate{cert, cert} // two entries so the long path is used - config.NameToCertificate = map[string]*tls.Certificate{ - "quic.clemente.io": &cert, - } - cert, err := cc.getCertForSNI("quic.clemente.io") - Expect(err).ToNot(HaveOccurred()) - Expect(cert.PrivateKey).ToNot(BeNil()) - Expect(cert.Certificate[0]).ToNot(BeNil()) - }) - - It("uses NameToCertificate entries with wildcard", func() { - config.Certificates = []tls.Certificate{cert, cert} // two entries so the long path is used - config.NameToCertificate = map[string]*tls.Certificate{ - "*.clemente.io": &cert, - } - cert, err := cc.getCertForSNI("quic.clemente.io") - Expect(err).ToNot(HaveOccurred()) - Expect(cert.PrivateKey).ToNot(BeNil()) - Expect(cert.Certificate[0]).ToNot(BeNil()) - }) - - It("uses GetCertificate", func() { - config.GetCertificate = func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { - Expect(clientHello.ServerName).To(Equal("quic.clemente.io")) - return &cert, nil - } - cert, err := cc.getCertForSNI("quic.clemente.io") - Expect(err).ToNot(HaveOccurred()) - Expect(cert.PrivateKey).ToNot(BeNil()) - Expect(cert.Certificate[0]).ToNot(BeNil()) - }) - - It("gets leaf certificates", func() { - config.Certificates = []tls.Certificate{cert} - cert2, err := cc.GetLeafCert("") - Expect(err).ToNot(HaveOccurred()) - Expect(cert2).To(Equal(cert.Certificate[0])) - }) - - It("errors when it can't retrieve a leaf certificate", func() { - _, err := cc.GetLeafCert("invalid domain") - Expect(err).To(MatchError(errNoMatchingCertificate)) - }) - - It("respects GetConfigForClient", func() { - if !reflect.ValueOf(tls.Config{}).FieldByName("GetConfigForClient").IsValid() { - // Pre 1.8, we don't have to do anything - return - } - nestedConfig := &tls.Config{Certificates: []tls.Certificate{cert}} - l := func(chi *tls.ClientHelloInfo) (*tls.Config, error) { - Expect(chi.ServerName).To(Equal("quic.clemente.io")) - return nestedConfig, nil - } - reflect.ValueOf(config).Elem().FieldByName("GetConfigForClient").Set(reflect.ValueOf(l)) - resultCert, err := cc.getCertForSNI("quic.clemente.io") - Expect(err).NotTo(HaveOccurred()) - Expect(*resultCert).To(Equal(cert)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/cert_compression_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/cert_compression_test.go deleted file mode 100644 index 74744d2d3..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/cert_compression_test.go +++ /dev/null @@ -1,294 +0,0 @@ -package crypto - -import ( - "bytes" - "compress/flate" - "compress/zlib" - "encoding/binary" - "errors" - "hash/fnv" - - "github.com/lucas-clemente/quic-go-certificates" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -func byteHash(d []byte) []byte { - h := fnv.New64a() - h.Write(d) - s := h.Sum64() - res := make([]byte, 8) - binary.LittleEndian.PutUint64(res, s) - return res -} - -var _ = Describe("Cert compression and decompression", func() { - var certSetsOld map[uint64]certSet - - BeforeEach(func() { - certSetsOld = make(map[uint64]certSet) - for s := range certSets { - certSetsOld[s] = certSets[s] - } - }) - - AfterEach(func() { - certSets = certSetsOld - }) - - It("compresses empty", func() { - compressed, err := compressChain(nil, nil, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(compressed).To(Equal([]byte{0})) - }) - - It("decompresses empty", func() { - compressed, err := compressChain(nil, nil, nil) - Expect(err).ToNot(HaveOccurred()) - uncompressed, err := decompressChain(compressed) - Expect(err).ToNot(HaveOccurred()) - Expect(uncompressed).To(BeEmpty()) - }) - - It("gives correct single cert", func() { - cert := []byte{0xde, 0xca, 0xfb, 0xad} - certZlib := &bytes.Buffer{} - z, err := zlib.NewWriterLevelDict(certZlib, flate.BestCompression, certDictZlib) - Expect(err).ToNot(HaveOccurred()) - z.Write([]byte{0x04, 0x00, 0x00, 0x00}) - z.Write(cert) - z.Close() - chain := [][]byte{cert} - compressed, err := compressChain(chain, nil, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(compressed).To(Equal(append([]byte{ - 0x01, 0x00, - 0x08, 0x00, 0x00, 0x00, - }, certZlib.Bytes()...))) - }) - - It("decompresses a single cert", func() { - cert := []byte{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe} - chain := [][]byte{cert} - compressed, err := compressChain(chain, nil, nil) - Expect(err).ToNot(HaveOccurred()) - uncompressed, err := decompressChain(compressed) - Expect(err).ToNot(HaveOccurred()) - Expect(uncompressed).To(Equal(chain)) - }) - - It("gives correct cert and intermediate", func() { - cert1 := []byte{0xde, 0xca, 0xfb, 0xad} - cert2 := []byte{0xde, 0xad, 0xbe, 0xef} - certZlib := &bytes.Buffer{} - z, err := zlib.NewWriterLevelDict(certZlib, flate.BestCompression, certDictZlib) - Expect(err).ToNot(HaveOccurred()) - z.Write([]byte{0x04, 0x00, 0x00, 0x00}) - z.Write(cert1) - z.Write([]byte{0x04, 0x00, 0x00, 0x00}) - z.Write(cert2) - z.Close() - chain := [][]byte{cert1, cert2} - compressed, err := compressChain(chain, nil, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(compressed).To(Equal(append([]byte{ - 0x01, 0x01, 0x00, - 0x10, 0x00, 0x00, 0x00, - }, certZlib.Bytes()...))) - }) - - It("decompresses the chain with a cert and an intermediate", func() { - cert1 := []byte{0xde, 0xca, 0xfb, 0xad} - cert2 := []byte{0xde, 0xad, 0xbe, 0xef} - chain := [][]byte{cert1, cert2} - compressed, err := compressChain(chain, nil, nil) - Expect(err).ToNot(HaveOccurred()) - decompressed, err := decompressChain(compressed) - Expect(err).ToNot(HaveOccurred()) - Expect(decompressed).To(Equal(chain)) - }) - - It("uses cached certificates", func() { - cert := []byte{0xde, 0xca, 0xfb, 0xad} - certHash := byteHash(cert) - chain := [][]byte{cert} - compressed, err := compressChain(chain, nil, certHash) - Expect(err).ToNot(HaveOccurred()) - expected := append([]byte{0x02}, certHash...) - expected = append(expected, 0x00) - Expect(compressed).To(Equal(expected)) - }) - - It("uses cached certificates and compressed combined", func() { - cert1 := []byte{0xde, 0xca, 0xfb, 0xad} - cert2 := []byte{0xde, 0xad, 0xbe, 0xef} - cert2Hash := byteHash(cert2) - certZlib := &bytes.Buffer{} - z, err := zlib.NewWriterLevelDict(certZlib, flate.BestCompression, append(cert2, certDictZlib...)) - Expect(err).ToNot(HaveOccurred()) - z.Write([]byte{0x04, 0x00, 0x00, 0x00}) - z.Write(cert1) - z.Close() - chain := [][]byte{cert1, cert2} - compressed, err := compressChain(chain, nil, cert2Hash) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x01, 0x02} - expected = append(expected, cert2Hash...) - expected = append(expected, 0x00) - expected = append(expected, []byte{0x08, 0, 0, 0}...) - expected = append(expected, certZlib.Bytes()...) - Expect(compressed).To(Equal(expected)) - }) - - It("uses common certificate sets", func() { - cert := certsets.CertSet3[42] - setHash := make([]byte, 8) - binary.LittleEndian.PutUint64(setHash, certsets.CertSet3Hash) - chain := [][]byte{cert} - compressed, err := compressChain(chain, setHash, nil) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x03} - expected = append(expected, setHash...) - expected = append(expected, []byte{42, 0, 0, 0}...) - expected = append(expected, 0x00) - Expect(compressed).To(Equal(expected)) - }) - - It("decompresses a single cert form a common certificate set", func() { - cert := certsets.CertSet3[42] - setHash := make([]byte, 8) - binary.LittleEndian.PutUint64(setHash, certsets.CertSet3Hash) - chain := [][]byte{cert} - compressed, err := compressChain(chain, setHash, nil) - Expect(err).ToNot(HaveOccurred()) - decompressed, err := decompressChain(compressed) - Expect(err).ToNot(HaveOccurred()) - Expect(decompressed).To(Equal(chain)) - }) - - It("decompresses multiple certs form common certificate sets", func() { - cert1 := certsets.CertSet3[42] - cert2 := certsets.CertSet2[24] - setHash := make([]byte, 16) - binary.LittleEndian.PutUint64(setHash[0:8], certsets.CertSet3Hash) - binary.LittleEndian.PutUint64(setHash[8:16], certsets.CertSet2Hash) - chain := [][]byte{cert1, cert2} - compressed, err := compressChain(chain, setHash, nil) - Expect(err).ToNot(HaveOccurred()) - decompressed, err := decompressChain(compressed) - Expect(err).ToNot(HaveOccurred()) - Expect(decompressed).To(Equal(chain)) - }) - - It("ignores uncommon certificate sets", func() { - cert := []byte{0xde, 0xca, 0xfb, 0xad} - setHash := make([]byte, 8) - binary.LittleEndian.PutUint64(setHash, 0xdeadbeef) - chain := [][]byte{cert} - compressed, err := compressChain(chain, setHash, nil) - Expect(err).ToNot(HaveOccurred()) - certZlib := &bytes.Buffer{} - z, err := zlib.NewWriterLevelDict(certZlib, flate.BestCompression, certDictZlib) - Expect(err).ToNot(HaveOccurred()) - z.Write([]byte{0x04, 0x00, 0x00, 0x00}) - z.Write(cert) - z.Close() - Expect(compressed).To(Equal(append([]byte{ - 0x01, 0x00, - 0x08, 0x00, 0x00, 0x00, - }, certZlib.Bytes()...))) - }) - - It("errors if a common set does not exist", func() { - cert := certsets.CertSet3[42] - setHash := make([]byte, 8) - binary.LittleEndian.PutUint64(setHash, certsets.CertSet3Hash) - chain := [][]byte{cert} - compressed, err := compressChain(chain, setHash, nil) - Expect(err).ToNot(HaveOccurred()) - delete(certSets, certsets.CertSet3Hash) - _, err = decompressChain(compressed) - Expect(err).To(MatchError(errors.New("unknown certSet"))) - }) - - It("errors if a cert in a common set does not exist", func() { - certSet := [][]byte{ - {0x1, 0x2, 0x3, 0x4}, - {0x5, 0x6, 0x7, 0x8}, - } - certSets[0x1337] = certSet - cert := certSet[1] - setHash := make([]byte, 8) - binary.LittleEndian.PutUint64(setHash, 0x1337) - chain := [][]byte{cert} - compressed, err := compressChain(chain, setHash, nil) - Expect(err).ToNot(HaveOccurred()) - certSets[0x1337] = certSet[:1] // delete the last certificate from the certSet - _, err = decompressChain(compressed) - Expect(err).To(MatchError(errors.New("certificate not found in certSet"))) - }) - - It("uses common certificates and compressed combined", func() { - cert1 := []byte{0xde, 0xca, 0xfb, 0xad} - cert2 := certsets.CertSet3[42] - setHash := make([]byte, 8) - binary.LittleEndian.PutUint64(setHash, certsets.CertSet3Hash) - certZlib := &bytes.Buffer{} - z, err := zlib.NewWriterLevelDict(certZlib, flate.BestCompression, append(cert2, certDictZlib...)) - Expect(err).ToNot(HaveOccurred()) - z.Write([]byte{0x04, 0x00, 0x00, 0x00}) - z.Write(cert1) - z.Close() - chain := [][]byte{cert1, cert2} - compressed, err := compressChain(chain, setHash, nil) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x01, 0x03} - expected = append(expected, setHash...) - expected = append(expected, []byte{42, 0, 0, 0}...) - expected = append(expected, 0x00) - expected = append(expected, []byte{0x08, 0, 0, 0}...) - expected = append(expected, certZlib.Bytes()...) - Expect(compressed).To(Equal(expected)) - }) - - It("decompresses a certficate from a common set and a compressed cert combined", func() { - cert1 := []byte{0xde, 0xca, 0xfb, 0xad} - cert2 := certsets.CertSet3[42] - setHash := make([]byte, 8) - binary.LittleEndian.PutUint64(setHash, certsets.CertSet3Hash) - chain := [][]byte{cert1, cert2} - compressed, err := compressChain(chain, setHash, nil) - Expect(err).ToNot(HaveOccurred()) - decompressed, err := decompressChain(compressed) - Expect(err).ToNot(HaveOccurred()) - Expect(decompressed).To(Equal(chain)) - }) - - It("rejects invalid CCS / CCRT hashes", func() { - cert := []byte{0xde, 0xca, 0xfb, 0xad} - chain := [][]byte{cert} - _, err := compressChain(chain, []byte("foo"), nil) - Expect(err).To(MatchError("expected a multiple of 8 bytes for CCS / CCRT hashes")) - _, err = compressChain(chain, nil, []byte("foo")) - Expect(err).To(MatchError("expected a multiple of 8 bytes for CCS / CCRT hashes")) - }) - - Context("common certificate hashes", func() { - It("gets the hashes", func() { - ccs := getCommonCertificateHashes() - Expect(ccs).ToNot(BeEmpty()) - hashes, err := splitHashes(ccs) - Expect(err).ToNot(HaveOccurred()) - for _, hash := range hashes { - Expect(certSets).To(HaveKey(hash)) - } - }) - - It("returns an empty slice if there are not common sets", func() { - certSets = make(map[uint64]certSet) - ccs := getCommonCertificateHashes() - Expect(ccs).ToNot(BeNil()) - Expect(ccs).To(HaveLen(0)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/cert_manager_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/cert_manager_test.go deleted file mode 100644 index 25a49bc7d..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/cert_manager_test.go +++ /dev/null @@ -1,348 +0,0 @@ -package crypto - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "math/big" - "runtime" - "time" - - "github.com/lucas-clemente/quic-go/internal/testdata" - "github.com/lucas-clemente/quic-go/qerr" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Cert Manager", func() { - var cm *certManager - var key1, key2 *rsa.PrivateKey - var cert1, cert2 []byte - - BeforeEach(func() { - var err error - cm = NewCertManager(nil).(*certManager) - key1, err = rsa.GenerateKey(rand.Reader, 768) - Expect(err).ToNot(HaveOccurred()) - key2, err = rsa.GenerateKey(rand.Reader, 768) - Expect(err).ToNot(HaveOccurred()) - template := &x509.Certificate{SerialNumber: big.NewInt(1)} - cert1, err = x509.CreateCertificate(rand.Reader, template, template, &key1.PublicKey, key1) - Expect(err).ToNot(HaveOccurred()) - cert2, err = x509.CreateCertificate(rand.Reader, template, template, &key2.PublicKey, key2) - Expect(err).ToNot(HaveOccurred()) - }) - - It("saves a client TLS config", func() { - tlsConf := &tls.Config{ServerName: "quic.clemente.io"} - cm = NewCertManager(tlsConf).(*certManager) - Expect(cm.config.ServerName).To(Equal("quic.clemente.io")) - }) - - It("errors when given invalid data", func() { - err := cm.SetData([]byte("foobar")) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidCryptoMessageParameter, "Certificate data invalid"))) - }) - - It("gets the common certificate hashes", func() { - ccs := cm.GetCommonCertificateHashes() - Expect(ccs).ToNot(BeEmpty()) - }) - - Context("setting the data", func() { - It("decompresses a certificate chain", func() { - chain := [][]byte{cert1, cert2} - compressed, err := compressChain(chain, nil, nil) - Expect(err).ToNot(HaveOccurred()) - err = cm.SetData(compressed) - Expect(err).ToNot(HaveOccurred()) - Expect(cm.chain[0].Raw).To(Equal(cert1)) - Expect(cm.chain[1].Raw).To(Equal(cert2)) - }) - - It("errors if it can't decompress the chain", func() { - err := cm.SetData([]byte("invalid data")) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidCryptoMessageParameter, "Certificate data invalid"))) - }) - - It("errors if it can't parse a certificate", func() { - chain := [][]byte{[]byte("cert1"), []byte("cert2")} - compressed, err := compressChain(chain, nil, nil) - Expect(err).ToNot(HaveOccurred()) - err = cm.SetData(compressed) - _, ok := err.(asn1.StructuralError) - Expect(ok).To(BeTrue()) - }) - }) - - Context("getting the leaf cert", func() { - It("gets it", func() { - xcert1, err := x509.ParseCertificate(cert1) - Expect(err).ToNot(HaveOccurred()) - xcert2, err := x509.ParseCertificate(cert2) - Expect(err).ToNot(HaveOccurred()) - cm.chain = []*x509.Certificate{xcert1, xcert2} - leafCert := cm.GetLeafCert() - Expect(leafCert).To(Equal(cert1)) - }) - - It("returns nil if the chain hasn't been set yet", func() { - leafCert := cm.GetLeafCert() - Expect(leafCert).To(BeNil()) - }) - }) - - Context("getting the leaf cert hash", func() { - It("calculates the FVN1a 64 hash", func() { - cm.chain = make([]*x509.Certificate, 1) - cm.chain[0] = &x509.Certificate{ - Raw: []byte("test fnv hash"), - } - hash, err := cm.GetLeafCertHash() - Expect(err).ToNot(HaveOccurred()) - // hash calculated on http://www.nitrxgen.net/hashgen/ - Expect(hash).To(Equal(uint64(0x4770f6141fa0f5ad))) - }) - - It("errors if the certificate chain is not loaded", func() { - _, err := cm.GetLeafCertHash() - Expect(err).To(MatchError(errNoCertificateChain)) - }) - }) - - Context("verifying the server config signature", func() { - It("returns false when the chain hasn't been set yet", func() { - valid := cm.VerifyServerProof([]byte("proof"), []byte("chlo"), []byte("scfg")) - Expect(valid).To(BeFalse()) - }) - - It("verifies the signature", func() { - chlo := []byte("client hello") - scfg := []byte("server config data") - xcert1, err := x509.ParseCertificate(cert1) - Expect(err).ToNot(HaveOccurred()) - cm.chain = []*x509.Certificate{xcert1} - proof, err := signServerProof(&tls.Certificate{PrivateKey: key1}, chlo, scfg) - Expect(err).ToNot(HaveOccurred()) - valid := cm.VerifyServerProof(proof, chlo, scfg) - Expect(valid).To(BeTrue()) - }) - - It("rejects an invalid signature", func() { - xcert1, err := x509.ParseCertificate(cert1) - Expect(err).ToNot(HaveOccurred()) - cm.chain = []*x509.Certificate{xcert1} - valid := cm.VerifyServerProof([]byte("invalid proof"), []byte("chlo"), []byte("scfg")) - Expect(valid).To(BeFalse()) - }) - }) - - Context("verifying the certificate chain", func() { - generateCertificate := func(template, parent *x509.Certificate, pubKey *rsa.PublicKey, privKey *rsa.PrivateKey) *x509.Certificate { - certDER, err := x509.CreateCertificate(rand.Reader, template, parent, pubKey, privKey) - Expect(err).ToNot(HaveOccurred()) - cert, err := x509.ParseCertificate(certDER) - Expect(err).ToNot(HaveOccurred()) - return cert - } - - getCertificate := func(template *x509.Certificate) (*rsa.PrivateKey, *x509.Certificate) { - key, err := rsa.GenerateKey(rand.Reader, 1024) - Expect(err).ToNot(HaveOccurred()) - return key, generateCertificate(template, template, &key.PublicKey, key) - } - - It("accepts a valid certificate", func() { - cc := NewCertChain(testdata.GetTLSConfig()).(*certChain) - tlsCert, err := cc.getCertForSNI("quic.clemente.io") - Expect(err).ToNot(HaveOccurred()) - for _, data := range tlsCert.Certificate { - var cert *x509.Certificate - cert, err = x509.ParseCertificate(data) - Expect(err).ToNot(HaveOccurred()) - cm.chain = append(cm.chain, cert) - } - err = cm.Verify("quic.clemente.io") - Expect(err).ToNot(HaveOccurred()) - }) - - It("doesn't accept an expired certificate", func() { - if runtime.GOOS == "windows" { - // certificate validation works different on windows, see https://golang.org/src/crypto/x509/verify.go line 238 - Skip("windows") - } - - template := &x509.Certificate{ - SerialNumber: big.NewInt(1), - NotBefore: time.Now().Add(-25 * time.Hour), - NotAfter: time.Now().Add(-time.Hour), - } - _, leafCert := getCertificate(template) - - cm.chain = []*x509.Certificate{leafCert} - err := cm.Verify("") - Expect(err).To(HaveOccurred()) - Expect(err.(x509.CertificateInvalidError).Reason).To(Equal(x509.Expired)) - }) - - It("doesn't accept a certificate that is not yet valid", func() { - if runtime.GOOS == "windows" { - // certificate validation works different on windows, see https://golang.org/src/crypto/x509/verify.go line 238 - Skip("windows") - } - - template := &x509.Certificate{ - SerialNumber: big.NewInt(1), - NotBefore: time.Now().Add(time.Hour), - NotAfter: time.Now().Add(25 * time.Hour), - } - _, leafCert := getCertificate(template) - - cm.chain = []*x509.Certificate{leafCert} - err := cm.Verify("") - Expect(err).To(HaveOccurred()) - Expect(err.(x509.CertificateInvalidError).Reason).To(Equal(x509.Expired)) - }) - - It("doesn't accept an certificate for the wrong hostname", func() { - if runtime.GOOS == "windows" { - // certificate validation works different on windows, see https://golang.org/src/crypto/x509/verify.go line 238 - Skip("windows") - } - - template := &x509.Certificate{ - SerialNumber: big.NewInt(1), - NotBefore: time.Now().Add(-time.Hour), - NotAfter: time.Now().Add(time.Hour), - Subject: pkix.Name{CommonName: "google.com"}, - } - _, leafCert := getCertificate(template) - - cm.chain = []*x509.Certificate{leafCert} - err := cm.Verify("quic.clemente.io") - Expect(err).To(HaveOccurred()) - _, ok := err.(x509.HostnameError) - Expect(ok).To(BeTrue()) - }) - - It("errors if the chain hasn't been set yet", func() { - err := cm.Verify("example.com") - Expect(err).To(HaveOccurred()) - }) - - // this tests relies on LetsEncrypt not being contained in the Root CAs - It("rejects valid certificate with missing certificate chain", func() { - if runtime.GOOS == "windows" { - Skip("LetsEncrypt Root CA is included in Windows") - } - - cert := testdata.GetCertificate() - xcert, err := x509.ParseCertificate(cert.Certificate[0]) - Expect(err).ToNot(HaveOccurred()) - cm.chain = []*x509.Certificate{xcert} - err = cm.Verify("quic.clemente.io") - _, ok := err.(x509.UnknownAuthorityError) - Expect(ok).To(BeTrue()) - }) - - It("doesn't do any certificate verification if InsecureSkipVerify is set", func() { - if runtime.GOOS == "windows" { - // certificate validation works different on windows, see https://golang.org/src/crypto/x509/verify.go line 238 - Skip("windows") - } - - template := &x509.Certificate{ - SerialNumber: big.NewInt(1), - } - - _, leafCert := getCertificate(template) - cm.config = &tls.Config{ - InsecureSkipVerify: true, - } - cm.chain = []*x509.Certificate{leafCert} - err := cm.Verify("quic.clemente.io") - Expect(err).ToNot(HaveOccurred()) - }) - - It("uses the time specified in a client TLS config", func() { - if runtime.GOOS == "windows" { - // certificate validation works different on windows, see https://golang.org/src/crypto/x509/verify.go line 238 - Skip("windows") - } - - template := &x509.Certificate{ - SerialNumber: big.NewInt(1), - NotBefore: time.Now().Add(-25 * time.Hour), - NotAfter: time.Now().Add(-23 * time.Hour), - Subject: pkix.Name{CommonName: "quic.clemente.io"}, - } - _, leafCert := getCertificate(template) - cm.chain = []*x509.Certificate{leafCert} - cm.config = &tls.Config{ - Time: func() time.Time { return time.Now().Add(-24 * time.Hour) }, - } - err := cm.Verify("quic.clemente.io") - _, ok := err.(x509.UnknownAuthorityError) - Expect(ok).To(BeTrue()) - }) - - It("rejects certificates that are expired at the time specified in a client TLS config", func() { - if runtime.GOOS == "windows" { - // certificate validation works different on windows, see https://golang.org/src/crypto/x509/verify.go line 238 - Skip("windows") - } - - template := &x509.Certificate{ - SerialNumber: big.NewInt(1), - NotBefore: time.Now().Add(-time.Hour), - NotAfter: time.Now().Add(time.Hour), - } - _, leafCert := getCertificate(template) - cm.chain = []*x509.Certificate{leafCert} - cm.config = &tls.Config{ - Time: func() time.Time { return time.Now().Add(-24 * time.Hour) }, - } - err := cm.Verify("quic.clemente.io") - Expect(err.(x509.CertificateInvalidError).Reason).To(Equal(x509.Expired)) - }) - - It("uses the Root CA given in the client config", func() { - if runtime.GOOS == "windows" { - // certificate validation works different on windows, see https://golang.org/src/crypto/x509/verify.go line 238 - Skip("windows") - } - - templateRoot := &x509.Certificate{ - SerialNumber: big.NewInt(1), - NotBefore: time.Now().Add(-time.Hour), - NotAfter: time.Now().Add(time.Hour), - IsCA: true, - BasicConstraintsValid: true, - } - rootKey, rootCert := getCertificate(templateRoot) - template := &x509.Certificate{ - SerialNumber: big.NewInt(1), - NotBefore: time.Now().Add(-time.Hour), - NotAfter: time.Now().Add(time.Hour), - Subject: pkix.Name{CommonName: "google.com"}, - } - key, err := rsa.GenerateKey(rand.Reader, 1024) - Expect(err).ToNot(HaveOccurred()) - leafCert := generateCertificate(template, rootCert, &key.PublicKey, rootKey) - - rootCAPool := x509.NewCertPool() - rootCAPool.AddCert(rootCert) - - cm.chain = []*x509.Certificate{leafCert} - cm.config = &tls.Config{ - RootCAs: rootCAPool, - } - err = cm.Verify("google.com") - Expect(err).ToNot(HaveOccurred()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/chacha20poly1305_aead_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/chacha20poly1305_aead_test.go deleted file mode 100644 index 9d5197bd5..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/chacha20poly1305_aead_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// +build ignore - -package crypto - -import ( - "crypto/rand" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Chacha20poly1305", func() { - var ( - alice, bob AEAD - keyAlice, keyBob, ivAlice, ivBob []byte - ) - - BeforeEach(func() { - keyAlice = make([]byte, 32) - keyBob = make([]byte, 32) - ivAlice = make([]byte, 4) - ivBob = make([]byte, 4) - rand.Reader.Read(keyAlice) - rand.Reader.Read(keyBob) - rand.Reader.Read(ivAlice) - rand.Reader.Read(ivBob) - var err error - alice, err = NewAEADChacha20Poly1305(keyBob, keyAlice, ivBob, ivAlice) - Expect(err).ToNot(HaveOccurred()) - bob, err = NewAEADChacha20Poly1305(keyAlice, keyBob, ivAlice, ivBob) - Expect(err).ToNot(HaveOccurred()) - }) - - It("seals and opens", func() { - b := alice.Seal(nil, []byte("foobar"), 42, []byte("aad")) - text, err := bob.Open(nil, b, 42, []byte("aad")) - Expect(err).ToNot(HaveOccurred()) - Expect(text).To(Equal([]byte("foobar"))) - }) - - It("seals and opens reverse", func() { - b := bob.Seal(nil, []byte("foobar"), 42, []byte("aad")) - text, err := alice.Open(nil, b, 42, []byte("aad")) - Expect(err).ToNot(HaveOccurred()) - Expect(text).To(Equal([]byte("foobar"))) - }) - - It("has the proper length", func() { - b := bob.Seal(nil, []byte("foobar"), 42, []byte("aad")) - Expect(b).To(HaveLen(6 + 12)) - }) - - It("fails with wrong aad", func() { - b := alice.Seal(nil, []byte("foobar"), 42, []byte("aad")) - _, err := bob.Open(nil, b, 42, []byte("aad2")) - Expect(err).To(HaveOccurred()) - }) - - It("rejects wrong key and iv sizes", func() { - var err error - e := "chacha20poly1305: expected 32-byte keys and 4-byte IVs" - _, err = NewAEADChacha20Poly1305(keyBob[1:], keyAlice, ivBob, ivAlice) - Expect(err).To(MatchError(e)) - _, err = NewAEADChacha20Poly1305(keyBob, keyAlice[1:], ivBob, ivAlice) - Expect(err).To(MatchError(e)) - _, err = NewAEADChacha20Poly1305(keyBob, keyAlice, ivBob[1:], ivAlice) - Expect(err).To(MatchError(e)) - _, err = NewAEADChacha20Poly1305(keyBob, keyAlice, ivBob, ivAlice[1:]) - Expect(err).To(MatchError(e)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/crypto_suite_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/crypto_suite_test.go deleted file mode 100644 index 23989a3ea..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/crypto_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package crypto - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestCrypto(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Crypto Suite") -} diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/curve_25519_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/curve_25519_test.go deleted file mode 100644 index 44d1d11fa..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/curve_25519_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package crypto - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ProofRsa", func() { - It("works", func() { - a, err := NewCurve25519KEX() - Expect(err).ToNot(HaveOccurred()) - b, err := NewCurve25519KEX() - Expect(err).ToNot(HaveOccurred()) - sA, err := a.CalculateSharedKey(b.PublicKey()) - Expect(err).ToNot(HaveOccurred()) - sB, err := b.CalculateSharedKey(a.PublicKey()) - Expect(err).ToNot(HaveOccurred()) - Expect(sA).To(Equal(sB)) - }) - - It("rejects short public keys", func() { - a, err := NewCurve25519KEX() - Expect(err).ToNot(HaveOccurred()) - _, err = a.CalculateSharedKey(nil) - Expect(err).To(MatchError("Curve25519: expected public key of 32 byte")) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/key_derivation_quic_crypto_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/key_derivation_quic_crypto_test.go deleted file mode 100644 index d866121ca..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/key_derivation_quic_crypto_test.go +++ /dev/null @@ -1,197 +0,0 @@ -package crypto - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("QUIC Crypto Key Derivation", func() { - // Context("chacha20poly1305", func() { - // It("derives non-fs keys", func() { - // aead, err := DeriveKeysChacha20( - // protocol.Version32, - // false, - // []byte("0123456789012345678901"), - // []byte("nonce"), - // protocol.ConnectionID(42), - // []byte("chlo"), - // []byte("scfg"), - // []byte("cert"), - // nil, - // ) - // Expect(err).ToNot(HaveOccurred()) - // chacha := aead.(*aeadChacha20Poly1305) - // // If the IVs match, the keys will match too, since the keys are read earlier - // Expect(chacha.myIV).To(Equal([]byte{0xf0, 0xf5, 0x4c, 0xa8})) - // Expect(chacha.otherIV).To(Equal([]byte{0x75, 0xd8, 0xa2, 0x8d})) - // }) - // - // It("derives fs keys", func() { - // aead, err := DeriveKeysChacha20( - // protocol.Version32, - // true, - // []byte("0123456789012345678901"), - // []byte("nonce"), - // protocol.ConnectionID(42), - // []byte("chlo"), - // []byte("scfg"), - // []byte("cert"), - // nil, - // ) - // Expect(err).ToNot(HaveOccurred()) - // chacha := aead.(*aeadChacha20Poly1305) - // // If the IVs match, the keys will match too, since the keys are read earlier - // Expect(chacha.myIV).To(Equal([]byte{0xf5, 0x73, 0x11, 0x79})) - // Expect(chacha.otherIV).To(Equal([]byte{0xf7, 0x26, 0x4d, 0x2c})) - // }) - // - // It("does not use diversification nonces in FS key derivation", func() { - // aead, err := DeriveKeysChacha20( - // protocol.Version33, - // true, - // []byte("0123456789012345678901"), - // []byte("nonce"), - // protocol.ConnectionID(42), - // []byte("chlo"), - // []byte("scfg"), - // []byte("cert"), - // []byte("divnonce"), - // ) - // Expect(err).ToNot(HaveOccurred()) - // chacha := aead.(*aeadChacha20Poly1305) - // // If the IVs match, the keys will match too, since the keys are read earlier - // Expect(chacha.myIV).To(Equal([]byte{0xf5, 0x73, 0x11, 0x79})) - // Expect(chacha.otherIV).To(Equal([]byte{0xf7, 0x26, 0x4d, 0x2c})) - // }) - // - // It("uses diversification nonces in initial key derivation", func() { - // aead, err := DeriveKeysChacha20( - // protocol.Version33, - // false, - // []byte("0123456789012345678901"), - // []byte("nonce"), - // protocol.ConnectionID(42), - // []byte("chlo"), - // []byte("scfg"), - // []byte("cert"), - // []byte("divnonce"), - // ) - // Expect(err).ToNot(HaveOccurred()) - // chacha := aead.(*aeadChacha20Poly1305) - // // If the IVs match, the keys will match too, since the keys are read earlier - // Expect(chacha.myIV).To(Equal([]byte{0xc4, 0x12, 0x25, 0x64})) - // Expect(chacha.otherIV).To(Equal([]byte{0x75, 0xd8, 0xa2, 0x8d})) - // }) - // }) - - Context("AES-GCM", func() { - It("derives non-forward secure keys", func() { - aead, err := DeriveQuicCryptoAESKeys( - false, - []byte("0123456789012345678901"), - []byte("nonce"), - protocol.ConnectionID([]byte{42, 0, 0, 0, 0, 0, 0, 0}), - []byte("chlo"), - []byte("scfg"), - []byte("cert"), - []byte("divnonce"), - protocol.PerspectiveServer, - ) - Expect(err).ToNot(HaveOccurred()) - aesgcm := aead.(*aeadAESGCM12) - // If the IVs match, the keys will match too, since the keys are read earlier - Expect(aesgcm.myIV).To(Equal([]byte{0x1c, 0xec, 0xac, 0x9b})) - Expect(aesgcm.otherIV).To(Equal([]byte{0x64, 0xef, 0x3c, 0x9})) - }) - - It("uses the diversification nonce when generating non-forwared secure keys", func() { - aead1, err := DeriveQuicCryptoAESKeys( - false, - []byte("0123456789012345678901"), - []byte("nonce"), - protocol.ConnectionID([]byte{42, 0, 0, 0, 0, 0, 0, 0}), - []byte("chlo"), - []byte("scfg"), - []byte("cert"), - []byte("divnonce"), - protocol.PerspectiveServer, - ) - Expect(err).ToNot(HaveOccurred()) - aead2, err := DeriveQuicCryptoAESKeys( - false, - []byte("0123456789012345678901"), - []byte("nonce"), - protocol.ConnectionID([]byte{42, 0, 0, 0, 0, 0, 0, 0}), - []byte("chlo"), - []byte("scfg"), - []byte("cert"), - []byte("ecnonvid"), - protocol.PerspectiveServer, - ) - Expect(err).ToNot(HaveOccurred()) - aesgcm1 := aead1.(*aeadAESGCM12) - aesgcm2 := aead2.(*aeadAESGCM12) - Expect(aesgcm1.myIV).ToNot(Equal(aesgcm2.myIV)) - Expect(aesgcm1.otherIV).To(Equal(aesgcm2.otherIV)) - }) - - It("derives non-forward secure keys, for the other side", func() { - aead, err := DeriveQuicCryptoAESKeys( - false, - []byte("0123456789012345678901"), - []byte("nonce"), - protocol.ConnectionID([]byte{42, 0, 0, 0, 0, 0, 0, 0}), - []byte("chlo"), - []byte("scfg"), - []byte("cert"), - []byte("divnonce"), - protocol.PerspectiveClient, - ) - Expect(err).ToNot(HaveOccurred()) - aesgcm := aead.(*aeadAESGCM12) - // If the IVs match, the keys will match too, since the keys are read earlier - Expect(aesgcm.otherIV).To(Equal([]byte{0x1c, 0xec, 0xac, 0x9b})) - Expect(aesgcm.myIV).To(Equal([]byte{0x64, 0xef, 0x3c, 0x9})) - }) - - It("derives forward secure keys", func() { - aead, err := DeriveQuicCryptoAESKeys( - true, - []byte("0123456789012345678901"), - []byte("nonce"), - protocol.ConnectionID([]byte{42, 0, 0, 0, 0, 0, 0, 0}), - []byte("chlo"), - []byte("scfg"), - []byte("cert"), - nil, - protocol.PerspectiveServer, - ) - Expect(err).ToNot(HaveOccurred()) - aesgcm := aead.(*aeadAESGCM12) - // If the IVs match, the keys will match too, since the keys are read earlier - Expect(aesgcm.myIV).To(Equal([]byte{0x7, 0xad, 0xab, 0xb8})) - Expect(aesgcm.otherIV).To(Equal([]byte{0xf2, 0x7a, 0xcc, 0x42})) - }) - - It("does not use div-nonce for FS key derivation", func() { - aead, err := DeriveQuicCryptoAESKeys( - true, - []byte("0123456789012345678901"), - []byte("nonce"), - protocol.ConnectionID([]byte{42, 0, 0, 0, 0, 0, 0, 0}), - []byte("chlo"), - []byte("scfg"), - []byte("cert"), - []byte("divnonce"), - protocol.PerspectiveServer, - ) - Expect(err).ToNot(HaveOccurred()) - aesgcm := aead.(*aeadAESGCM12) - // If the IVs match, the keys will match too, since the keys are read earlier - Expect(aesgcm.myIV).To(Equal([]byte{0x7, 0xad, 0xab, 0xb8})) - Expect(aesgcm.otherIV).To(Equal([]byte{0xf2, 0x7a, 0xcc, 0x42})) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/key_derivation_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/key_derivation_test.go deleted file mode 100644 index 5b530ff8b..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/key_derivation_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package crypto - -import ( - "crypto" - "errors" - - "github.com/bifurcation/mint" - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type mockTLSExporter struct { - hash crypto.Hash - computerError error -} - -var _ TLSExporter = &mockTLSExporter{} - -func (c *mockTLSExporter) Handshake() mint.Alert { panic("not implemented") } - -func (c *mockTLSExporter) ConnectionState() mint.ConnectionState { - return mint.ConnectionState{ - CipherSuite: mint.CipherSuiteParams{ - Hash: c.hash, - KeyLen: 32, - IvLen: 12, - }, - } -} - -func (c *mockTLSExporter) ComputeExporter(label string, context []byte, keyLength int) ([]byte, error) { - if c.computerError != nil { - return nil, c.computerError - } - return append([]byte(label), context...), nil -} - -var _ = Describe("Key Derivation", func() { - It("derives keys", func() { - clientAEAD, err := DeriveAESKeys(&mockTLSExporter{hash: crypto.SHA256}, protocol.PerspectiveClient) - Expect(err).ToNot(HaveOccurred()) - serverAEAD, err := DeriveAESKeys(&mockTLSExporter{hash: crypto.SHA256}, protocol.PerspectiveServer) - Expect(err).ToNot(HaveOccurred()) - ciphertext := clientAEAD.Seal(nil, []byte("foobar"), 0, []byte("aad")) - data, err := serverAEAD.Open(nil, ciphertext, 0, []byte("aad")) - Expect(err).ToNot(HaveOccurred()) - Expect(data).To(Equal([]byte("foobar"))) - }) - - It("fails when computing the exporter fails", func() { - testErr := errors.New("test error") - _, err := DeriveAESKeys(&mockTLSExporter{hash: crypto.SHA256, computerError: testErr}, protocol.PerspectiveClient) - Expect(err).To(MatchError(testErr)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/null_aead_aesgcm_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/null_aead_aesgcm_test.go deleted file mode 100644 index 8f45a956a..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/null_aead_aesgcm_test.go +++ /dev/null @@ -1,86 +0,0 @@ -package crypto - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("NullAEAD using AES-GCM", func() { - // values taken from https://github.com/quicwg/base-drafts/wiki/Test-Vector-for-the-Clear-Text-AEAD-key-derivation - Context("using the test vector from the QUIC WG Wiki", func() { - connID := protocol.ConnectionID([]byte{0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08}) - - It("computes the secrets", func() { - clientSecret, serverSecret := computeSecrets(connID) - Expect(clientSecret).To(Equal([]byte{ - 0x83, 0x55, 0xf2, 0x1a, 0x3d, 0x8f, 0x83, 0xec, - 0xb3, 0xd0, 0xf9, 0x71, 0x08, 0xd3, 0xf9, 0x5e, - 0x0f, 0x65, 0xb4, 0xd8, 0xae, 0x88, 0xa0, 0x61, - 0x1e, 0xe4, 0x9d, 0xb0, 0xb5, 0x23, 0x59, 0x1d, - })) - Expect(serverSecret).To(Equal([]byte{ - 0xf8, 0x0e, 0x57, 0x71, 0x48, 0x4b, 0x21, 0xcd, - 0xeb, 0xb5, 0xaf, 0xe0, 0xa2, 0x56, 0xa3, 0x17, - 0x41, 0xef, 0xe2, 0xb5, 0xc6, 0xb6, 0x17, 0xba, - 0xe1, 0xb2, 0xf1, 0x5a, 0x83, 0x04, 0x83, 0xd6, - })) - }) - - It("computes the client key and IV", func() { - clientSecret, _ := computeSecrets(connID) - key, iv := computeNullAEADKeyAndIV(clientSecret) - Expect(key).To(Equal([]byte{ - 0x3a, 0xd0, 0x54, 0x2c, 0x4a, 0x85, 0x84, 0x74, - 0x00, 0x63, 0x04, 0x9e, 0x3b, 0x3c, 0xaa, 0xb2, - })) - Expect(iv).To(Equal([]byte{ - 0xd1, 0xfd, 0x26, 0x05, 0x42, 0x75, 0x3a, 0xba, - 0x38, 0x58, 0x9b, 0xad, - })) - }) - - It("computes the server key and IV", func() { - _, serverSecret := computeSecrets(connID) - key, iv := computeNullAEADKeyAndIV(serverSecret) - Expect(key).To(Equal([]byte{ - 0xbe, 0xe4, 0xc2, 0x4d, 0x2a, 0xf1, 0x33, 0x80, - 0xa9, 0xfa, 0x24, 0xa5, 0xe2, 0xba, 0x2c, 0xff, - })) - Expect(iv).To(Equal([]byte{ - 0x25, 0xb5, 0x8e, 0x24, 0x6d, 0x9e, 0x7d, 0x5f, - 0xfe, 0x43, 0x23, 0xfe, - })) - }) - }) - - It("seals and opens", func() { - connectionID := protocol.ConnectionID([]byte{0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef}) - clientAEAD, err := newNullAEADAESGCM(connectionID, protocol.PerspectiveClient) - Expect(err).ToNot(HaveOccurred()) - serverAEAD, err := newNullAEADAESGCM(connectionID, protocol.PerspectiveServer) - Expect(err).ToNot(HaveOccurred()) - - clientMessage := clientAEAD.Seal(nil, []byte("foobar"), 42, []byte("aad")) - m, err := serverAEAD.Open(nil, clientMessage, 42, []byte("aad")) - Expect(err).ToNot(HaveOccurred()) - Expect(m).To(Equal([]byte("foobar"))) - serverMessage := serverAEAD.Seal(nil, []byte("raboof"), 99, []byte("daa")) - m, err = clientAEAD.Open(nil, serverMessage, 99, []byte("daa")) - Expect(err).ToNot(HaveOccurred()) - Expect(m).To(Equal([]byte("raboof"))) - }) - - It("doesn't work if initialized with different connection IDs", func() { - c1 := protocol.ConnectionID([]byte{0, 0, 0, 0, 0, 0, 0, 1}) - c2 := protocol.ConnectionID([]byte{0, 0, 0, 0, 0, 0, 0, 2}) - clientAEAD, err := newNullAEADAESGCM(c1, protocol.PerspectiveClient) - Expect(err).ToNot(HaveOccurred()) - serverAEAD, err := newNullAEADAESGCM(c2, protocol.PerspectiveServer) - Expect(err).ToNot(HaveOccurred()) - - clientMessage := clientAEAD.Seal(nil, []byte("foobar"), 42, []byte("aad")) - _, err = serverAEAD.Open(nil, clientMessage, 42, []byte("aad")) - Expect(err).To(MatchError("cipher: message authentication failed")) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/null_aead_fnv128a_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/null_aead_fnv128a_test.go deleted file mode 100644 index 1a8fcc6a1..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/null_aead_fnv128a_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package crypto - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("NullAEAD using FNV128a", func() { - aad := []byte("All human beings are born free and equal in dignity and rights.") - plainText := []byte("They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood.") - hash36 := []byte{0x98, 0x9b, 0x33, 0x3f, 0xe8, 0xde, 0x32, 0x5c, 0xa6, 0x7f, 0x9c, 0xf7} - - var aeadServer AEAD - var aeadClient AEAD - - BeforeEach(func() { - aeadServer = &nullAEADFNV128a{protocol.PerspectiveServer} - aeadClient = &nullAEADFNV128a{protocol.PerspectiveClient} - }) - - It("seals and opens, client => server", func() { - cipherText := aeadClient.Seal(nil, plainText, 0, aad) - res, err := aeadServer.Open(nil, cipherText, 0, aad) - Expect(err).ToNot(HaveOccurred()) - Expect(res).To(Equal([]byte("They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood."))) - }) - - It("seals and opens, server => client", func() { - cipherText := aeadServer.Seal(nil, plainText, 0, aad) - res, err := aeadClient.Open(nil, cipherText, 0, aad) - Expect(err).ToNot(HaveOccurred()) - Expect(res).To(Equal([]byte("They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood."))) - }) - - It("rejects short ciphertexts", func() { - _, err := aeadServer.Open(nil, nil, 0, nil) - Expect(err).To(MatchError("NullAEAD: ciphertext cannot be less than 12 bytes long")) - }) - - It("seals in-place", func() { - buf := make([]byte, 6, 12+6) - copy(buf, []byte("foobar")) - res := aeadServer.Seal(buf[0:0], buf, 0, nil) - buf = buf[:12+6] - Expect(buf[12:]).To(Equal([]byte("foobar"))) - Expect(res[12:]).To(Equal([]byte("foobar"))) - }) - - It("fails", func() { - cipherText := append(append(hash36, plainText...), byte(0x42)) - _, err := aeadClient.Open(nil, cipherText, 0, aad) - Expect(err).To(HaveOccurred()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/null_aead_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/null_aead_test.go deleted file mode 100644 index ce3a12a01..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/null_aead_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package crypto - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("NullAEAD", func() { - It("selects the right FVN variant", func() { - connID := protocol.ConnectionID([]byte{0x42, 0, 0, 0, 0, 0, 0, 0}) - Expect(NewNullAEAD(protocol.PerspectiveClient, connID, protocol.Version39)).To(Equal(&nullAEADFNV128a{ - perspective: protocol.PerspectiveClient, - })) - Expect(NewNullAEAD(protocol.PerspectiveClient, connID, protocol.VersionTLS)).To(BeAssignableToTypeOf(&aeadAESGCM{})) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/crypto/server_proof_test.go b/vendor/lucas-clemente/quic-go/internal/crypto/server_proof_test.go deleted file mode 100644 index aecd63e3e..000000000 --- a/vendor/lucas-clemente/quic-go/internal/crypto/server_proof_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package crypto - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "encoding/asn1" - "math/big" - - "github.com/lucas-clemente/quic-go/internal/testdata" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Proof", func() { - It("gives valid signatures with the key in internal/testdata", func() { - key := &testdata.GetTLSConfig().Certificates[0] - signature, err := signServerProof(key, []byte{'C', 'H', 'L', 'O'}, []byte{'S', 'C', 'F', 'G'}) - Expect(err).ToNot(HaveOccurred()) - // Generated with: - // ruby -e 'require "digest"; p Digest::SHA256.digest("QUIC CHLO and server config signature\x00" + "\x20\x00\x00\x00" + Digest::SHA256.digest("CHLO") + "SCFG")' - data := []byte("W\xA6\xFC\xDE\xC7\xD2>c\xE6\xB5\xF6\tq\x9E|<~1\xA33\x01\xCA=\x19\xBD\xC1\xE4\xB0\xBA\x9B\x16%") - err = rsa.VerifyPSS(key.PrivateKey.(*rsa.PrivateKey).Public().(*rsa.PublicKey), crypto.SHA256, data, signature, &rsa.PSSOptions{SaltLength: 32}) - Expect(err).ToNot(HaveOccurred()) - }) - - Context("when using RSA", func() { - generateCert := func() (*rsa.PrivateKey, *x509.Certificate) { - key, err := rsa.GenerateKey(rand.Reader, 1024) - Expect(err).NotTo(HaveOccurred()) - - certTemplate := x509.Certificate{SerialNumber: big.NewInt(1)} - certDER, err := x509.CreateCertificate(rand.Reader, &certTemplate, &certTemplate, &key.PublicKey, key) - Expect(err).ToNot(HaveOccurred()) - cert, err := x509.ParseCertificate(certDER) - Expect(err).ToNot(HaveOccurred()) - - return key, cert - } - - It("verifies a signature", func() { - key, cert := generateCert() - chlo := []byte("chlo") - scfg := []byte("scfg") - signature, err := signServerProof(&tls.Certificate{PrivateKey: key}, chlo, scfg) - Expect(err).ToNot(HaveOccurred()) - Expect(verifyServerProof(signature, cert, chlo, scfg)).To(BeTrue()) - }) - - It("rejects invalid signatures", func() { - key, cert := generateCert() - chlo := []byte("client hello") - scfg := []byte("sever config") - signature, err := signServerProof(&tls.Certificate{PrivateKey: key}, chlo, scfg) - Expect(err).ToNot(HaveOccurred()) - Expect(verifyServerProof(append(signature, byte(0x99)), cert, chlo, scfg)).To(BeFalse()) - Expect(verifyServerProof(signature, cert, chlo[:len(chlo)-2], scfg)).To(BeFalse()) - Expect(verifyServerProof(signature, cert, chlo, scfg[:len(scfg)-2])).To(BeFalse()) - }) - }) - - Context("when using ECDSA", func() { - generateCert := func() (*ecdsa.PrivateKey, *x509.Certificate) { - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - Expect(err).NotTo(HaveOccurred()) - - certTemplate := x509.Certificate{SerialNumber: big.NewInt(1)} - certDER, err := x509.CreateCertificate(rand.Reader, &certTemplate, &certTemplate, &key.PublicKey, key) - Expect(err).ToNot(HaveOccurred()) - cert, err := x509.ParseCertificate(certDER) - Expect(err).ToNot(HaveOccurred()) - - return key, cert - } - - It("gives valid signatures", func() { - key, _ := generateCert() - signature, err := signServerProof(&tls.Certificate{PrivateKey: key}, []byte{'C', 'H', 'L', 'O'}, []byte{'S', 'C', 'F', 'G'}) - Expect(err).ToNot(HaveOccurred()) - // Generated with: - // ruby -e 'require "digest"; p Digest::SHA256.digest("QUIC CHLO and server config signature\x00" + "\x20\x00\x00\x00" + Digest::SHA256.digest("CHLO") + "SCFG")' - data := []byte("W\xA6\xFC\xDE\xC7\xD2>c\xE6\xB5\xF6\tq\x9E|<~1\xA33\x01\xCA=\x19\xBD\xC1\xE4\xB0\xBA\x9B\x16%") - s := &ecdsaSignature{} - _, err = asn1.Unmarshal(signature, s) - Expect(err).NotTo(HaveOccurred()) - b := ecdsa.Verify(key.Public().(*ecdsa.PublicKey), data, s.R, s.S) - Expect(b).To(BeTrue()) - }) - - It("verifies a signature", func() { - key, cert := generateCert() - chlo := []byte("chlo") - scfg := []byte("server config") - signature, err := signServerProof(&tls.Certificate{PrivateKey: key}, chlo, scfg) - Expect(err).ToNot(HaveOccurred()) - Expect(verifyServerProof(signature, cert, chlo, scfg)).To(BeTrue()) - }) - - It("rejects invalid signatures", func() { - key, cert := generateCert() - chlo := []byte("client hello") - scfg := []byte("server config") - signature, err := signServerProof(&tls.Certificate{PrivateKey: key}, chlo, scfg) - Expect(err).ToNot(HaveOccurred()) - Expect(verifyServerProof(append(signature, byte(0x99)), cert, chlo, scfg)).To(BeFalse()) - Expect(verifyServerProof(signature, cert, chlo[:len(chlo)-2], scfg)).To(BeFalse()) - Expect(verifyServerProof(signature, cert, chlo, scfg[:len(scfg)-2])).To(BeFalse()) - }) - - It("rejects signatures generated with a different certificate", func() { - key1, cert1 := generateCert() - key2, cert2 := generateCert() - Expect(key1.PublicKey).ToNot(Equal(key2)) - Expect(cert1.Equal(cert2)).To(BeFalse()) - chlo := []byte("chlo") - scfg := []byte("sfcg") - signature, err := signServerProof(&tls.Certificate{PrivateKey: key1}, chlo, scfg) - Expect(err).ToNot(HaveOccurred()) - Expect(verifyServerProof(signature, cert2, chlo, scfg)).To(BeFalse()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/flowcontrol/base_flow_controller_test.go b/vendor/lucas-clemente/quic-go/internal/flowcontrol/base_flow_controller_test.go deleted file mode 100644 index 8e1da5a49..000000000 --- a/vendor/lucas-clemente/quic-go/internal/flowcontrol/base_flow_controller_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package flowcontrol - -import ( - "os" - "strconv" - "time" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -// on the CIs, the timing is a lot less precise, so scale every duration by this factor -func scaleDuration(t time.Duration) time.Duration { - scaleFactor := 1 - if f, err := strconv.Atoi(os.Getenv("TIMESCALE_FACTOR")); err == nil { // parsing "" errors, so this works fine if the env is not set - scaleFactor = f - } - Expect(scaleFactor).ToNot(BeZero()) - return time.Duration(scaleFactor) * t -} - -var _ = Describe("Base Flow controller", func() { - var controller *baseFlowController - - BeforeEach(func() { - controller = &baseFlowController{} - controller.rttStats = &congestion.RTTStats{} - }) - - Context("send flow control", func() { - It("adds bytes sent", func() { - controller.bytesSent = 5 - controller.AddBytesSent(6) - Expect(controller.bytesSent).To(Equal(protocol.ByteCount(5 + 6))) - }) - - It("gets the size of the remaining flow control window", func() { - controller.bytesSent = 5 - controller.sendWindow = 12 - Expect(controller.sendWindowSize()).To(Equal(protocol.ByteCount(12 - 5))) - }) - - It("updates the size of the flow control window", func() { - controller.AddBytesSent(5) - controller.UpdateSendWindow(15) - Expect(controller.sendWindow).To(Equal(protocol.ByteCount(15))) - Expect(controller.sendWindowSize()).To(Equal(protocol.ByteCount(15 - 5))) - }) - - It("says that the window size is 0 if we sent more than we were allowed to", func() { - controller.AddBytesSent(15) - controller.UpdateSendWindow(10) - Expect(controller.sendWindowSize()).To(BeZero()) - }) - - It("does not decrease the flow control window", func() { - controller.UpdateSendWindow(20) - Expect(controller.sendWindowSize()).To(Equal(protocol.ByteCount(20))) - controller.UpdateSendWindow(10) - Expect(controller.sendWindowSize()).To(Equal(protocol.ByteCount(20))) - }) - - It("says when it's blocked", func() { - controller.UpdateSendWindow(100) - Expect(controller.IsNewlyBlocked()).To(BeFalse()) - controller.AddBytesSent(100) - blocked, offset := controller.IsNewlyBlocked() - Expect(blocked).To(BeTrue()) - Expect(offset).To(Equal(protocol.ByteCount(100))) - }) - - It("doesn't say that it's newly blocked multiple times for the same offset", func() { - controller.UpdateSendWindow(100) - controller.AddBytesSent(100) - newlyBlocked, offset := controller.IsNewlyBlocked() - Expect(newlyBlocked).To(BeTrue()) - Expect(offset).To(Equal(protocol.ByteCount(100))) - newlyBlocked, _ = controller.IsNewlyBlocked() - Expect(newlyBlocked).To(BeFalse()) - controller.UpdateSendWindow(150) - controller.AddBytesSent(150) - newlyBlocked, _ = controller.IsNewlyBlocked() - Expect(newlyBlocked).To(BeTrue()) - }) - }) - - Context("receive flow control", func() { - var ( - receiveWindow protocol.ByteCount = 10000 - receiveWindowSize protocol.ByteCount = 1000 - ) - - BeforeEach(func() { - controller.bytesRead = receiveWindow - receiveWindowSize - controller.receiveWindow = receiveWindow - controller.receiveWindowSize = receiveWindowSize - }) - - It("adds bytes read", func() { - controller.bytesRead = 5 - controller.AddBytesRead(6) - Expect(controller.bytesRead).To(Equal(protocol.ByteCount(5 + 6))) - }) - - It("triggers a window update when necessary", func() { - bytesConsumed := float64(receiveWindowSize)*protocol.WindowUpdateThreshold + 1 // consumed 1 byte more than the threshold - bytesRemaining := receiveWindowSize - protocol.ByteCount(bytesConsumed) - readPosition := receiveWindow - bytesRemaining - controller.bytesRead = readPosition - offset := controller.getWindowUpdate() - Expect(offset).To(Equal(readPosition + receiveWindowSize)) - Expect(controller.receiveWindow).To(Equal(readPosition + receiveWindowSize)) - }) - - It("doesn't trigger a window update when not necessary", func() { - bytesConsumed := float64(receiveWindowSize)*protocol.WindowUpdateThreshold - 1 // consumed 1 byte less than the threshold - bytesRemaining := receiveWindowSize - protocol.ByteCount(bytesConsumed) - readPosition := receiveWindow - bytesRemaining - controller.bytesRead = readPosition - offset := controller.getWindowUpdate() - Expect(offset).To(BeZero()) - }) - - Context("receive window size auto-tuning", func() { - var oldWindowSize protocol.ByteCount - - BeforeEach(func() { - oldWindowSize = controller.receiveWindowSize - controller.maxReceiveWindowSize = 5000 - }) - - // update the congestion such that it returns a given value for the smoothed RTT - setRtt := func(t time.Duration) { - controller.rttStats.UpdateRTT(t, 0, time.Now()) - Expect(controller.rttStats.SmoothedRTT()).To(Equal(t)) // make sure it worked - } - - It("doesn't increase the window size for a new stream", func() { - controller.maybeAdjustWindowSize() - Expect(controller.receiveWindowSize).To(Equal(oldWindowSize)) - }) - - It("doesn't increase the window size when no RTT estimate is available", func() { - setRtt(0) - controller.startNewAutoTuningEpoch() - controller.AddBytesRead(400) - offset := controller.getWindowUpdate() - Expect(offset).ToNot(BeZero()) // make sure a window update is sent - Expect(controller.receiveWindowSize).To(Equal(oldWindowSize)) - }) - - It("increases the window size if read so fast that the window would be consumed in less than 4 RTTs", func() { - bytesRead := controller.bytesRead - rtt := scaleDuration(20 * time.Millisecond) - setRtt(rtt) - // consume more than 2/3 of the window... - dataRead := receiveWindowSize*2/3 + 1 - // ... in 4*2/3 of the RTT - controller.epochStartOffset = controller.bytesRead - controller.epochStartTime = time.Now().Add(-rtt * 4 * 2 / 3) - controller.AddBytesRead(dataRead) - offset := controller.getWindowUpdate() - Expect(offset).ToNot(BeZero()) - // check that the window size was increased - newWindowSize := controller.receiveWindowSize - Expect(newWindowSize).To(Equal(2 * oldWindowSize)) - // check that the new window size was used to increase the offset - Expect(offset).To(Equal(protocol.ByteCount(bytesRead + dataRead + newWindowSize))) - }) - - It("doesn't increase the window size if data is read so fast that the window would be consumed in less than 4 RTTs, but less than half the window has been read", func() { - // this test only makes sense if a window update is triggered before half of the window has been consumed - Expect(protocol.WindowUpdateThreshold).To(BeNumerically(">", 1/3)) - bytesRead := controller.bytesRead - rtt := scaleDuration(20 * time.Millisecond) - setRtt(rtt) - // consume more than 2/3 of the window... - dataRead := receiveWindowSize*1/3 + 1 - // ... in 4*2/3 of the RTT - controller.epochStartOffset = controller.bytesRead - controller.epochStartTime = time.Now().Add(-rtt * 4 * 1 / 3) - controller.AddBytesRead(dataRead) - offset := controller.getWindowUpdate() - Expect(offset).ToNot(BeZero()) - // check that the window size was not increased - newWindowSize := controller.receiveWindowSize - Expect(newWindowSize).To(Equal(oldWindowSize)) - // check that the new window size was used to increase the offset - Expect(offset).To(Equal(protocol.ByteCount(bytesRead + dataRead + newWindowSize))) - }) - - It("doesn't increase the window size if read too slowly", func() { - bytesRead := controller.bytesRead - rtt := scaleDuration(20 * time.Millisecond) - setRtt(rtt) - // consume less than 2/3 of the window... - dataRead := receiveWindowSize*2/3 - 1 - // ... in 4*2/3 of the RTT - controller.epochStartOffset = controller.bytesRead - controller.epochStartTime = time.Now().Add(-rtt * 4 * 2 / 3) - controller.AddBytesRead(dataRead) - offset := controller.getWindowUpdate() - Expect(offset).ToNot(BeZero()) - // check that the window size was not increased - Expect(controller.receiveWindowSize).To(Equal(oldWindowSize)) - // check that the new window size was used to increase the offset - Expect(offset).To(Equal(protocol.ByteCount(bytesRead + dataRead + oldWindowSize))) - }) - - It("doesn't increase the window size to a value higher than the maxReceiveWindowSize", func() { - resetEpoch := func() { - // make sure the next call to maybeAdjustWindowSize will increase the window - controller.epochStartTime = time.Now().Add(-time.Millisecond) - controller.epochStartOffset = controller.bytesRead - controller.AddBytesRead(controller.receiveWindowSize/2 + 1) - } - setRtt(scaleDuration(20 * time.Millisecond)) - resetEpoch() - controller.maybeAdjustWindowSize() - Expect(controller.receiveWindowSize).To(Equal(2 * oldWindowSize)) // 2000 - // because the lastWindowUpdateTime is updated by MaybeTriggerWindowUpdate(), we can just call maybeAdjustWindowSize() multiple times and get an increase of the window size every time - resetEpoch() - controller.maybeAdjustWindowSize() - Expect(controller.receiveWindowSize).To(Equal(2 * 2 * oldWindowSize)) // 4000 - resetEpoch() - controller.maybeAdjustWindowSize() - Expect(controller.receiveWindowSize).To(Equal(controller.maxReceiveWindowSize)) // 5000 - controller.maybeAdjustWindowSize() - Expect(controller.receiveWindowSize).To(Equal(controller.maxReceiveWindowSize)) // 5000 - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/flowcontrol/connection_flow_controller_test.go b/vendor/lucas-clemente/quic-go/internal/flowcontrol/connection_flow_controller_test.go deleted file mode 100644 index 91edab427..000000000 --- a/vendor/lucas-clemente/quic-go/internal/flowcontrol/connection_flow_controller_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package flowcontrol - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Connection Flow controller", func() { - var ( - controller *connectionFlowController - queuedWindowUpdate bool - ) - - // update the congestion such that it returns a given value for the smoothed RTT - setRtt := func(t time.Duration) { - controller.rttStats.UpdateRTT(t, 0, time.Now()) - Expect(controller.rttStats.SmoothedRTT()).To(Equal(t)) // make sure it worked - } - - BeforeEach(func() { - controller = &connectionFlowController{} - controller.rttStats = &congestion.RTTStats{} - controller.logger = utils.DefaultLogger - controller.queueWindowUpdate = func() { queuedWindowUpdate = true } - }) - - Context("Constructor", func() { - rttStats := &congestion.RTTStats{} - - It("sets the send and receive windows", func() { - receiveWindow := protocol.ByteCount(2000) - maxReceiveWindow := protocol.ByteCount(3000) - - fc := NewConnectionFlowController(receiveWindow, maxReceiveWindow, nil, rttStats, utils.DefaultLogger).(*connectionFlowController) - Expect(fc.receiveWindow).To(Equal(receiveWindow)) - Expect(fc.maxReceiveWindowSize).To(Equal(maxReceiveWindow)) - }) - }) - - Context("receive flow control", func() { - It("increases the highestReceived by a given window size", func() { - controller.highestReceived = 1337 - controller.IncrementHighestReceived(123) - Expect(controller.highestReceived).To(Equal(protocol.ByteCount(1337 + 123))) - }) - - Context("getting window updates", func() { - BeforeEach(func() { - controller.receiveWindow = 100 - controller.receiveWindowSize = 60 - controller.maxReceiveWindowSize = 1000 - controller.bytesRead = 100 - 60 - }) - - It("queues window updates", func() { - controller.MaybeQueueWindowUpdate() - Expect(queuedWindowUpdate).To(BeFalse()) - controller.AddBytesRead(30) - controller.MaybeQueueWindowUpdate() - Expect(queuedWindowUpdate).To(BeTrue()) - Expect(controller.GetWindowUpdate()).ToNot(BeZero()) - queuedWindowUpdate = false - controller.MaybeQueueWindowUpdate() - Expect(queuedWindowUpdate).To(BeFalse()) - }) - - It("gets a window update", func() { - windowSize := controller.receiveWindowSize - oldOffset := controller.bytesRead - dataRead := windowSize/2 - 1 // make sure not to trigger auto-tuning - controller.AddBytesRead(dataRead) - offset := controller.GetWindowUpdate() - Expect(offset).To(Equal(protocol.ByteCount(oldOffset + dataRead + 60))) - }) - - It("autotunes the window", func() { - oldOffset := controller.bytesRead - oldWindowSize := controller.receiveWindowSize - rtt := scaleDuration(20 * time.Millisecond) - setRtt(rtt) - controller.epochStartTime = time.Now().Add(-time.Millisecond) - controller.epochStartOffset = oldOffset - dataRead := oldWindowSize/2 + 1 - controller.AddBytesRead(dataRead) - offset := controller.GetWindowUpdate() - newWindowSize := controller.receiveWindowSize - Expect(newWindowSize).To(Equal(2 * oldWindowSize)) - Expect(offset).To(Equal(protocol.ByteCount(oldOffset + dataRead + newWindowSize))) - }) - }) - }) - - Context("setting the minimum window size", func() { - var ( - oldWindowSize protocol.ByteCount - receiveWindow protocol.ByteCount = 10000 - receiveWindowSize protocol.ByteCount = 1000 - ) - - BeforeEach(func() { - controller.receiveWindow = receiveWindow - controller.receiveWindowSize = receiveWindowSize - oldWindowSize = controller.receiveWindowSize - controller.maxReceiveWindowSize = 3000 - }) - - It("sets the minimum window window size", func() { - controller.EnsureMinimumWindowSize(1800) - Expect(controller.receiveWindowSize).To(Equal(protocol.ByteCount(1800))) - }) - - It("doesn't reduce the window window size", func() { - controller.EnsureMinimumWindowSize(1) - Expect(controller.receiveWindowSize).To(Equal(oldWindowSize)) - }) - - It("doens't increase the window size beyond the maxReceiveWindowSize", func() { - max := controller.maxReceiveWindowSize - controller.EnsureMinimumWindowSize(2 * max) - Expect(controller.receiveWindowSize).To(Equal(max)) - }) - - It("starts a new epoch after the window size was increased", func() { - controller.EnsureMinimumWindowSize(1912) - Expect(controller.epochStartTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/flowcontrol/flowcontrol_suite_test.go b/vendor/lucas-clemente/quic-go/internal/flowcontrol/flowcontrol_suite_test.go deleted file mode 100644 index 16da9ed26..000000000 --- a/vendor/lucas-clemente/quic-go/internal/flowcontrol/flowcontrol_suite_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package flowcontrol - -import ( - "github.com/golang/mock/gomock" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestCrypto(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "FlowControl Suite") -} - -var mockCtrl *gomock.Controller - -var _ = BeforeEach(func() { - mockCtrl = gomock.NewController(GinkgoT()) -}) - -var _ = AfterEach(func() { - mockCtrl.Finish() -}) diff --git a/vendor/lucas-clemente/quic-go/internal/flowcontrol/stream_flow_controller_test.go b/vendor/lucas-clemente/quic-go/internal/flowcontrol/stream_flow_controller_test.go deleted file mode 100644 index 83dcbb0ee..000000000 --- a/vendor/lucas-clemente/quic-go/internal/flowcontrol/stream_flow_controller_test.go +++ /dev/null @@ -1,290 +0,0 @@ -package flowcontrol - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/congestion" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/qerr" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Stream Flow controller", func() { - var ( - controller *streamFlowController - queuedWindowUpdate bool - queuedConnWindowUpdate bool - ) - - BeforeEach(func() { - queuedWindowUpdate = false - queuedConnWindowUpdate = false - rttStats := &congestion.RTTStats{} - controller = &streamFlowController{ - streamID: 10, - connection: NewConnectionFlowController(1000, 1000, func() { queuedConnWindowUpdate = true }, rttStats, utils.DefaultLogger).(*connectionFlowController), - } - controller.maxReceiveWindowSize = 10000 - controller.rttStats = rttStats - controller.logger = utils.DefaultLogger - controller.queueWindowUpdate = func() { queuedWindowUpdate = true } - }) - - Context("Constructor", func() { - rttStats := &congestion.RTTStats{} - receiveWindow := protocol.ByteCount(2000) - maxReceiveWindow := protocol.ByteCount(3000) - sendWindow := protocol.ByteCount(4000) - - It("sets the send and receive windows", func() { - cc := NewConnectionFlowController(0, 0, nil, nil, utils.DefaultLogger) - fc := NewStreamFlowController(5, true, cc, receiveWindow, maxReceiveWindow, sendWindow, nil, rttStats, utils.DefaultLogger).(*streamFlowController) - Expect(fc.streamID).To(Equal(protocol.StreamID(5))) - Expect(fc.receiveWindow).To(Equal(receiveWindow)) - Expect(fc.maxReceiveWindowSize).To(Equal(maxReceiveWindow)) - Expect(fc.sendWindow).To(Equal(sendWindow)) - Expect(fc.contributesToConnection).To(BeTrue()) - }) - - It("queues window updates with the correction stream ID", func() { - var queued bool - queueWindowUpdate := func(id protocol.StreamID) { - Expect(id).To(Equal(protocol.StreamID(5))) - queued = true - } - - cc := NewConnectionFlowController(0, 0, nil, nil, utils.DefaultLogger) - fc := NewStreamFlowController(5, true, cc, receiveWindow, maxReceiveWindow, sendWindow, queueWindowUpdate, rttStats, utils.DefaultLogger).(*streamFlowController) - fc.AddBytesRead(receiveWindow) - fc.MaybeQueueWindowUpdate() - Expect(queued).To(BeTrue()) - }) - }) - - Context("receiving data", func() { - Context("registering received offsets", func() { - var receiveWindow protocol.ByteCount = 10000 - var receiveWindowSize protocol.ByteCount = 600 - - BeforeEach(func() { - controller.receiveWindow = receiveWindow - controller.receiveWindowSize = receiveWindowSize - }) - - It("updates the highestReceived", func() { - controller.highestReceived = 1337 - err := controller.UpdateHighestReceived(1338, false) - Expect(err).ToNot(HaveOccurred()) - Expect(controller.highestReceived).To(Equal(protocol.ByteCount(1338))) - }) - - It("informs the connection flow controller about received data", func() { - controller.highestReceived = 10 - controller.contributesToConnection = true - controller.connection.(*connectionFlowController).highestReceived = 100 - err := controller.UpdateHighestReceived(20, false) - Expect(err).ToNot(HaveOccurred()) - Expect(controller.connection.(*connectionFlowController).highestReceived).To(Equal(protocol.ByteCount(100 + 10))) - }) - - It("doesn't informs the connection flow controller about received data if it doesn't contribute", func() { - controller.highestReceived = 10 - controller.connection.(*connectionFlowController).highestReceived = 100 - err := controller.UpdateHighestReceived(20, false) - Expect(err).ToNot(HaveOccurred()) - Expect(controller.connection.(*connectionFlowController).highestReceived).To(Equal(protocol.ByteCount(100))) - }) - - It("does not decrease the highestReceived", func() { - controller.highestReceived = 1337 - err := controller.UpdateHighestReceived(1000, false) - Expect(err).ToNot(HaveOccurred()) - Expect(controller.highestReceived).To(Equal(protocol.ByteCount(1337))) - }) - - It("does nothing when setting the same byte offset", func() { - controller.highestReceived = 1337 - err := controller.UpdateHighestReceived(1337, false) - Expect(err).ToNot(HaveOccurred()) - }) - - It("does not give a flow control violation when using the window completely", func() { - err := controller.UpdateHighestReceived(receiveWindow, false) - Expect(err).ToNot(HaveOccurred()) - }) - - It("detects a flow control violation", func() { - err := controller.UpdateHighestReceived(receiveWindow+1, false) - Expect(err).To(MatchError("FlowControlReceivedTooMuchData: Received 10001 bytes on stream 10, allowed 10000 bytes")) - }) - - It("accepts a final offset higher than the highest received", func() { - controller.highestReceived = 100 - err := controller.UpdateHighestReceived(101, true) - Expect(err).ToNot(HaveOccurred()) - Expect(controller.highestReceived).To(Equal(protocol.ByteCount(101))) - }) - - It("errors when receiving a final offset smaller than the highest offset received so far", func() { - controller.highestReceived = 100 - err := controller.UpdateHighestReceived(99, true) - Expect(err).To(MatchError(qerr.StreamDataAfterTermination)) - }) - - It("accepts delayed data after receiving a final offset", func() { - err := controller.UpdateHighestReceived(300, true) - Expect(err).ToNot(HaveOccurred()) - err = controller.UpdateHighestReceived(250, false) - Expect(err).ToNot(HaveOccurred()) - }) - - It("errors when receiving a higher offset after receiving a final offset", func() { - err := controller.UpdateHighestReceived(200, true) - Expect(err).ToNot(HaveOccurred()) - err = controller.UpdateHighestReceived(250, false) - Expect(err).To(MatchError(qerr.StreamDataAfterTermination)) - }) - - It("accepts duplicate final offsets", func() { - err := controller.UpdateHighestReceived(200, true) - Expect(err).ToNot(HaveOccurred()) - err = controller.UpdateHighestReceived(200, true) - Expect(err).ToNot(HaveOccurred()) - Expect(controller.highestReceived).To(Equal(protocol.ByteCount(200))) - }) - - It("errors when receiving inconsistent final offsets", func() { - err := controller.UpdateHighestReceived(200, true) - Expect(err).ToNot(HaveOccurred()) - err = controller.UpdateHighestReceived(201, true) - Expect(err).To(MatchError("StreamDataAfterTermination: Received inconsistent final offset for stream 10 (old: 200, new: 201 bytes)")) - }) - }) - - Context("registering data read", func() { - It("saves when data is read, on a stream not contributing to the connection", func() { - controller.AddBytesRead(100) - Expect(controller.bytesRead).To(Equal(protocol.ByteCount(100))) - Expect(controller.connection.(*connectionFlowController).bytesRead).To(BeZero()) - }) - - It("saves when data is read, on a stream not contributing to the connection", func() { - controller.contributesToConnection = true - controller.AddBytesRead(200) - Expect(controller.bytesRead).To(Equal(protocol.ByteCount(200))) - Expect(controller.connection.(*connectionFlowController).bytesRead).To(Equal(protocol.ByteCount(200))) - }) - }) - - Context("generating window updates", func() { - var oldWindowSize protocol.ByteCount - - // update the congestion such that it returns a given value for the smoothed RTT - setRtt := func(t time.Duration) { - controller.rttStats.UpdateRTT(t, 0, time.Now()) - Expect(controller.rttStats.SmoothedRTT()).To(Equal(t)) // make sure it worked - } - - BeforeEach(func() { - controller.receiveWindow = 100 - controller.receiveWindowSize = 60 - controller.bytesRead = 100 - 60 - controller.connection.(*connectionFlowController).receiveWindow = 100 - controller.connection.(*connectionFlowController).receiveWindowSize = 120 - oldWindowSize = controller.receiveWindowSize - }) - - It("queues window updates", func() { - controller.MaybeQueueWindowUpdate() - Expect(queuedWindowUpdate).To(BeFalse()) - controller.AddBytesRead(30) - controller.MaybeQueueWindowUpdate() - Expect(queuedWindowUpdate).To(BeTrue()) - Expect(controller.GetWindowUpdate()).ToNot(BeZero()) - queuedWindowUpdate = false - controller.MaybeQueueWindowUpdate() - Expect(queuedWindowUpdate).To(BeFalse()) - }) - - It("queues connection-level window updates", func() { - controller.contributesToConnection = true - controller.MaybeQueueWindowUpdate() - Expect(queuedConnWindowUpdate).To(BeFalse()) - controller.AddBytesRead(60) - controller.MaybeQueueWindowUpdate() - Expect(queuedConnWindowUpdate).To(BeTrue()) - }) - - It("tells the connection flow controller when the window was autotuned", func() { - oldOffset := controller.bytesRead - controller.contributesToConnection = true - setRtt(scaleDuration(20 * time.Millisecond)) - controller.epochStartOffset = oldOffset - controller.epochStartTime = time.Now().Add(-time.Millisecond) - controller.AddBytesRead(55) - offset := controller.GetWindowUpdate() - Expect(offset).To(Equal(protocol.ByteCount(oldOffset + 55 + 2*oldWindowSize))) - Expect(controller.receiveWindowSize).To(Equal(2 * oldWindowSize)) - Expect(controller.connection.(*connectionFlowController).receiveWindowSize).To(Equal(protocol.ByteCount(float64(controller.receiveWindowSize) * protocol.ConnectionFlowControlMultiplier))) - }) - - It("doesn't tell the connection flow controller if it doesn't contribute", func() { - oldOffset := controller.bytesRead - controller.contributesToConnection = false - setRtt(scaleDuration(20 * time.Millisecond)) - controller.epochStartOffset = oldOffset - controller.epochStartTime = time.Now().Add(-time.Millisecond) - controller.AddBytesRead(55) - offset := controller.GetWindowUpdate() - Expect(offset).ToNot(BeZero()) - Expect(controller.receiveWindowSize).To(Equal(2 * oldWindowSize)) - Expect(controller.connection.(*connectionFlowController).receiveWindowSize).To(Equal(protocol.ByteCount(2 * oldWindowSize))) // unchanged - }) - - It("doesn't increase the window after a final offset was already received", func() { - controller.AddBytesRead(30) - err := controller.UpdateHighestReceived(90, true) - Expect(err).ToNot(HaveOccurred()) - controller.MaybeQueueWindowUpdate() - Expect(queuedWindowUpdate).To(BeFalse()) - offset := controller.GetWindowUpdate() - Expect(offset).To(BeZero()) - }) - }) - }) - - Context("sending data", func() { - It("gets the size of the send window", func() { - controller.UpdateSendWindow(15) - controller.AddBytesSent(5) - Expect(controller.SendWindowSize()).To(Equal(protocol.ByteCount(10))) - }) - - It("doesn't care about the connection-level window, if it doesn't contribute", func() { - controller.UpdateSendWindow(15) - controller.connection.UpdateSendWindow(1) - controller.AddBytesSent(5) - Expect(controller.SendWindowSize()).To(Equal(protocol.ByteCount(10))) - }) - - It("makes sure that it doesn't overflow the connection-level window", func() { - controller.contributesToConnection = true - controller.connection.UpdateSendWindow(12) - controller.UpdateSendWindow(20) - controller.AddBytesSent(10) - Expect(controller.SendWindowSize()).To(Equal(protocol.ByteCount(2))) - }) - - It("doesn't say that it's blocked, if only the connection is blocked", func() { - controller.contributesToConnection = true - controller.connection.UpdateSendWindow(50) - controller.UpdateSendWindow(100) - controller.AddBytesSent(50) - blocked, _ := controller.connection.IsNewlyBlocked() - Expect(blocked).To(BeTrue()) - Expect(controller.IsNewlyBlocked()).To(BeFalse()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/cookie_generator_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/cookie_generator_test.go deleted file mode 100644 index f04807019..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/cookie_generator_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package handshake - -import ( - "encoding/asn1" - "net" - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Cookie Generator", func() { - var cookieGen *CookieGenerator - - BeforeEach(func() { - var err error - cookieGen, err = NewCookieGenerator() - Expect(err).ToNot(HaveOccurred()) - }) - - It("generates a Cookie", func() { - ip := net.IPv4(127, 0, 0, 1) - token, err := cookieGen.NewToken(&net.UDPAddr{IP: ip, Port: 1337}) - Expect(err).ToNot(HaveOccurred()) - Expect(token).ToNot(BeEmpty()) - }) - - It("works with nil tokens", func() { - cookie, err := cookieGen.DecodeToken(nil) - Expect(err).ToNot(HaveOccurred()) - Expect(cookie).To(BeNil()) - }) - - It("accepts a valid cookie", func() { - ip := net.IPv4(192, 168, 0, 1) - token, err := cookieGen.NewToken(&net.UDPAddr{IP: ip, Port: 1337}) - Expect(err).ToNot(HaveOccurred()) - cookie, err := cookieGen.DecodeToken(token) - Expect(err).ToNot(HaveOccurred()) - Expect(cookie.RemoteAddr).To(Equal("192.168.0.1")) - // the time resolution of the Cookie is just 1 second - // if Cookie generation and this check happen in "different seconds", the difference will be between 1 and 2 seconds - Expect(cookie.SentTime).To(BeTemporally("~", time.Now(), 2*time.Second)) - }) - - It("rejects invalid tokens", func() { - _, err := cookieGen.DecodeToken([]byte("invalid token")) - Expect(err).To(HaveOccurred()) - }) - - It("rejects tokens that cannot be decoded", func() { - token, err := cookieGen.cookieProtector.NewToken([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - _, err = cookieGen.DecodeToken(token) - Expect(err).To(HaveOccurred()) - }) - - It("rejects tokens that can be decoded, but have additional payload", func() { - t, err := asn1.Marshal(token{Data: []byte("foobar")}) - Expect(err).ToNot(HaveOccurred()) - t = append(t, []byte("rest")...) - enc, err := cookieGen.cookieProtector.NewToken(t) - Expect(err).ToNot(HaveOccurred()) - _, err = cookieGen.DecodeToken(enc) - Expect(err).To(MatchError("rest when unpacking token: 4")) - }) - - // we don't generate tokens that have no data, but we should be able to handle them if we receive one for whatever reason - It("doesn't panic if a tokens has no data", func() { - t, err := asn1.Marshal(token{Data: []byte("")}) - Expect(err).ToNot(HaveOccurred()) - enc, err := cookieGen.cookieProtector.NewToken(t) - Expect(err).ToNot(HaveOccurred()) - _, err = cookieGen.DecodeToken(enc) - Expect(err).ToNot(HaveOccurred()) - }) - - It("works with an IPv6 addresses ", func() { - addresses := []string{ - "2001:db8::68", - "2001:0000:4136:e378:8000:63bf:3fff:fdd2", - "2001::1", - "ff01:0:0:0:0:0:0:2", - } - for _, addr := range addresses { - ip := net.ParseIP(addr) - Expect(ip).ToNot(BeNil()) - raddr := &net.UDPAddr{IP: ip, Port: 1337} - token, err := cookieGen.NewToken(raddr) - Expect(err).ToNot(HaveOccurred()) - cookie, err := cookieGen.DecodeToken(token) - Expect(err).ToNot(HaveOccurred()) - Expect(cookie.RemoteAddr).To(Equal(ip.String())) - // the time resolution of the Cookie is just 1 second - // if Cookie generation and this check happen in "different seconds", the difference will be between 1 and 2 seconds - Expect(cookie.SentTime).To(BeTemporally("~", time.Now(), 2*time.Second)) - } - }) - - It("uses the string representation an address that is not a UDP address", func() { - raddr := &net.TCPAddr{IP: net.IPv4(192, 168, 13, 37), Port: 1337} - token, err := cookieGen.NewToken(raddr) - Expect(err).ToNot(HaveOccurred()) - cookie, err := cookieGen.DecodeToken(token) - Expect(err).ToNot(HaveOccurred()) - Expect(cookie.RemoteAddr).To(Equal("192.168.13.37:1337")) - // the time resolution of the Cookie is just 1 second - // if Cookie generation and this check happen in "different seconds", the difference will be between 1 and 2 seconds - Expect(cookie.SentTime).To(BeTemporally("~", time.Now(), 2*time.Second)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/cookie_protector_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/cookie_protector_test.go deleted file mode 100644 index fbc7c27cf..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/cookie_protector_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package handshake - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Cookie Protector", func() { - var cp cookieProtector - - BeforeEach(func() { - var err error - cp, err = newCookieProtector() - Expect(err).ToNot(HaveOccurred()) - }) - - It("encodes and decodes tokens", func() { - token, err := cp.NewToken([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - Expect(token).ToNot(ContainSubstring("foobar")) - decoded, err := cp.DecodeToken(token) - Expect(err).ToNot(HaveOccurred()) - Expect(decoded).To(Equal([]byte("foobar"))) - }) - - It("fails deconding invalid tokens", func() { - token, err := cp.NewToken([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - token = token[1:] // remove the first byte - _, err = cp.DecodeToken(token) - Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("message authentication failed")) - }) - - It("errors when decoding too short tokens", func() { - _, err := cp.DecodeToken([]byte("foobar")) - Expect(err).To(MatchError("Token too short: 6")) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/crypto_setup_client_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/crypto_setup_client_test.go deleted file mode 100644 index 92633fe57..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/crypto_setup_client_test.go +++ /dev/null @@ -1,1011 +0,0 @@ -package handshake - -import ( - "bytes" - "crypto/x509" - "encoding/binary" - "errors" - "fmt" - "time" - - "github.com/lucas-clemente/quic-go/internal/crypto" - "github.com/lucas-clemente/quic-go/internal/mocks/crypto" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/qerr" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type keyDerivationValues struct { - forwardSecure bool - sharedSecret []byte - nonces []byte - connID protocol.ConnectionID - chlo []byte - scfg []byte - cert []byte - divNonce []byte - pers protocol.Perspective -} - -type mockCertManager struct { - setDataCalledWith []byte - setDataError error - - commonCertificateHashes []byte - - chain []*x509.Certificate - - leafCert []byte - leafCertHash uint64 - leafCertHashError error - - verifyServerProofResult bool - verifyServerProofCalled bool - - verifyError error - verifyCalled bool -} - -var _ crypto.CertManager = &mockCertManager{} - -func (m *mockCertManager) SetData(data []byte) error { - m.setDataCalledWith = data - return m.setDataError -} - -func (m *mockCertManager) GetCommonCertificateHashes() []byte { - return m.commonCertificateHashes -} - -func (m *mockCertManager) GetLeafCert() []byte { - return m.leafCert -} - -func (m *mockCertManager) GetLeafCertHash() (uint64, error) { - return m.leafCertHash, m.leafCertHashError -} - -func (m *mockCertManager) VerifyServerProof(proof, chlo, serverConfigData []byte) bool { - m.verifyServerProofCalled = true - return m.verifyServerProofResult -} - -func (m *mockCertManager) Verify(hostname string) error { - m.verifyCalled = true - return m.verifyError -} - -func (m *mockCertManager) GetChain() []*x509.Certificate { - return m.chain -} - -var _ = Describe("Client Crypto Setup", func() { - var ( - cs *cryptoSetupClient - certManager *mockCertManager - stream *mockStream - keyDerivationCalledWith *keyDerivationValues - shloMap map[Tag][]byte - handshakeEvent chan struct{} - paramsChan chan TransportParameters - ) - - BeforeEach(func() { - shloMap = map[Tag][]byte{ - TagPUBS: {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}, - TagVER: {}, - } - keyDerivation := func(forwardSecure bool, sharedSecret, nonces []byte, connID protocol.ConnectionID, chlo []byte, scfg []byte, cert []byte, divNonce []byte, pers protocol.Perspective) (crypto.AEAD, error) { - keyDerivationCalledWith = &keyDerivationValues{ - forwardSecure: forwardSecure, - sharedSecret: sharedSecret, - nonces: nonces, - connID: connID, - chlo: chlo, - scfg: scfg, - cert: cert, - divNonce: divNonce, - pers: pers, - } - return mockcrypto.NewMockAEAD(mockCtrl), nil - } - - stream = newMockStream() - certManager = &mockCertManager{} - version := protocol.Version39 - // use a buffered channel here, so that we can parse a SHLO without having to receive the TransportParameters to avoid blocking - paramsChan = make(chan TransportParameters, 1) - handshakeEvent = make(chan struct{}, 2) - csInt, err := NewCryptoSetupClient( - stream, - "hostname", - protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - version, - nil, - &TransportParameters{IdleTimeout: protocol.DefaultIdleTimeout}, - paramsChan, - handshakeEvent, - protocol.Version39, - nil, - utils.DefaultLogger, - ) - Expect(err).ToNot(HaveOccurred()) - cs = csInt.(*cryptoSetupClient) - cs.certManager = certManager - cs.keyDerivation = keyDerivation - cs.nullAEAD = mockcrypto.NewMockAEAD(mockCtrl) - cs.cryptoStream = stream - }) - - Context("Reading REJ", func() { - var tagMap map[Tag][]byte - - BeforeEach(func() { - tagMap = make(map[Tag][]byte) - }) - - It("rejects handshake messages with the wrong message tag", func() { - HandshakeMessage{Tag: TagCHLO, Data: tagMap}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.InvalidCryptoMessageType)) - }) - - It("errors on invalid handshake messages", func() { - stream.dataToRead.Write([]byte("invalid message")) - err := cs.HandleCryptoStream() - Expect(err).To(HaveOccurred()) - Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.HandshakeFailed)) - }) - - It("passes the message on for parsing, and reads the source address token", func() { - stk := []byte("foobar") - tagMap[TagSTK] = stk - HandshakeMessage{Tag: TagREJ, Data: tagMap}.Write(&stream.dataToRead) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.HandshakeFailed, errMockStreamClosing.Error()))) - close(done) - }() - Eventually(func() []byte { return cs.stk }).Should(Equal(stk)) - // make the go routine return - stream.close() - Eventually(done).Should(BeClosed()) - }) - - It("saves the proof", func() { - proof := []byte("signature for the server config") - tagMap[TagPROF] = proof - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(cs.proof).To(Equal(proof)) - }) - - It("saves the last sent CHLO for signature validation, when receiving the proof", func() { - chlo := []byte("last sent CHLO") - cs.lastSentCHLO = chlo - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(cs.chloForSignature).To(BeEmpty()) - tagMap[TagPROF] = []byte("signature") - err = cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(cs.chloForSignature).To(Equal(chlo)) - }) - - It("saves the server nonce", func() { - nonc := []byte("servernonce") - tagMap[TagSNO] = nonc - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(cs.sno).To(Equal(nonc)) - }) - - Context("validating the Version list", func() { - It("doesn't care about the version list if there was no version negotiation", func() { - Expect(cs.validateVersionList([]byte{0})).To(BeTrue()) - }) - - It("detects a downgrade attack if the number of versions is not equal", func() { - cs.negotiatedVersions = []protocol.VersionNumber{protocol.VersionWhatever} - Expect(cs.validateVersionList(bytes.Repeat([]byte{'f'}, 2*4))).To(BeFalse()) - }) - - It("detects a downgrade attack", func() { - cs.negotiatedVersions = []protocol.VersionNumber{12} - b := &bytes.Buffer{} - utils.BigEndian.WriteUint32(b, 11) - Expect(cs.validateVersionList(b.Bytes())).To(BeFalse()) - }) - - It("errors if the version tags are invalid", func() { - cs.negotiatedVersions = []protocol.VersionNumber{protocol.VersionWhatever} - Expect(cs.validateVersionList([]byte{0, 1, 2})).To(BeFalse()) // 1 byte too short - }) - - It("returns the right error when detecting a downgrade attack", func() { - cs.negotiatedVersions = []protocol.VersionNumber{protocol.VersionWhatever} - cs.receivedSecurePacket = true - _, err := cs.handleSHLOMessage(map[Tag][]byte{ - TagPUBS: {0}, - TagVER: {0, 1}, - }) - Expect(err).To(MatchError(qerr.Error(qerr.VersionNegotiationMismatch, "Downgrade attack detected"))) - }) - }) - - Context("Certificates", func() { - BeforeEach(func() { - cs.serverConfig = &serverConfigClient{} - }) - - It("passes the certificates to the CertManager", func() { - tagMap[TagCERT] = []byte("cert") - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(certManager.setDataCalledWith).To(Equal(tagMap[TagCERT])) - }) - - It("returns an InvalidCryptoMessageParameter error if it can't parse the cert chain", func() { - tagMap[TagCERT] = []byte("cert") - certManager.setDataError = errors.New("can't parse") - err := cs.handleREJMessage(tagMap) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidCryptoMessageParameter, "Certificate data invalid"))) - }) - - Context("verifying the certificate chain", func() { - It("returns a ProofInvalid error if the certificate chain is not valid", func() { - tagMap[TagCERT] = []byte("cert") - certManager.verifyError = errors.New("invalid") - err := cs.handleREJMessage(tagMap) - Expect(err).To(MatchError(qerr.ProofInvalid)) - }) - - It("verifies the certificate", func() { - certManager.verifyServerProofResult = true - tagMap[TagCERT] = []byte("cert") - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(certManager.verifyCalled).To(BeTrue()) - }) - }) - - Context("verifying the signature", func() { - BeforeEach(func() { - tagMap[TagCERT] = []byte("cert") - tagMap[TagPROF] = []byte("proof") - certManager.leafCert = []byte("leafcert") - }) - - It("rejects wrong signature", func() { - certManager.verifyServerProofResult = false - err := cs.handleREJMessage(tagMap) - Expect(err).To(MatchError(qerr.ProofInvalid)) - Expect(certManager.verifyServerProofCalled).To(BeTrue()) - }) - - It("accepts correct signatures", func() { - certManager.verifyServerProofResult = true - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(certManager.verifyServerProofCalled).To(BeTrue()) - }) - - It("doesn't try to verify the signature if the certificate is missing", func() { - delete(tagMap, TagCERT) - certManager.leafCert = nil - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(certManager.verifyServerProofCalled).To(BeFalse()) - }) - - It("doesn't try to verify the signature if the server config is missing", func() { - cs.serverConfig = nil - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(certManager.verifyServerProofCalled).To(BeFalse()) - }) - - It("doesn't try to verify the signature if the signature is missing", func() { - delete(tagMap, TagPROF) - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(certManager.verifyServerProofCalled).To(BeFalse()) - }) - }) - }) - - Context("Reading server configs", func() { - It("reads a server config", func() { - b := &bytes.Buffer{} - scfg := getDefaultServerConfigClient() - HandshakeMessage{Tag: TagSCFG, Data: scfg}.Write(b) - tagMap[TagSCFG] = b.Bytes() - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(cs.serverConfig).ToNot(BeNil()) - Expect(cs.serverConfig.ID).To(Equal(scfg[TagSCID])) - }) - - It("rejects expired server configs", func() { - b := &bytes.Buffer{} - scfg := getDefaultServerConfigClient() - scfg[TagEXPY] = []byte{0x80, 0x54, 0x72, 0x4F, 0, 0, 0, 0} // 2012-03-28 - HandshakeMessage{Tag: TagSCFG, Data: scfg}.Write(b) - tagMap[TagSCFG] = b.Bytes() - // make sure we actually set TagEXPY correct - serverConfig, err := parseServerConfig(b.Bytes()) - Expect(err).ToNot(HaveOccurred()) - Expect(serverConfig.expiry.Year()).To(Equal(2012)) - // now try to read this server config in the crypto setup - err = cs.handleREJMessage(tagMap) - Expect(err).To(MatchError(qerr.CryptoServerConfigExpired)) - }) - - It("generates a client nonce after reading a server config", func() { - b := &bytes.Buffer{} - HandshakeMessage{Tag: TagSCFG, Data: getDefaultServerConfigClient()}.Write(b) - tagMap[TagSCFG] = b.Bytes() - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(cs.nonc).To(HaveLen(32)) - }) - - It("only generates a client nonce once, when reading multiple server configs", func() { - b := &bytes.Buffer{} - HandshakeMessage{Tag: TagSCFG, Data: getDefaultServerConfigClient()}.Write(b) - tagMap[TagSCFG] = b.Bytes() - err := cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - nonc := cs.nonc - Expect(nonc).ToNot(BeEmpty()) - err = cs.handleREJMessage(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(cs.nonc).To(Equal(nonc)) - }) - - It("passes on errors from reading the server config", func() { - b := &bytes.Buffer{} - HandshakeMessage{Tag: TagSHLO, Data: make(map[Tag][]byte)}.Write(b) - tagMap[TagSCFG] = b.Bytes() - _, origErr := parseServerConfig(b.Bytes()) - err := cs.handleREJMessage(tagMap) - Expect(err).To(HaveOccurred()) - Expect(err).To(MatchError(origErr)) - }) - }) - }) - - Context("Reading SHLO", func() { - BeforeEach(func() { - kex, err := crypto.NewCurve25519KEX() - Expect(err).ToNot(HaveOccurred()) - serverConfig := &serverConfigClient{ - kex: kex, - } - cs.serverConfig = serverConfig - cs.receivedSecurePacket = true - }) - - It("rejects unencrypted SHLOs", func() { - cs.receivedSecurePacket = false - _, err := cs.handleSHLOMessage(shloMap) - Expect(err).To(MatchError(qerr.Error(qerr.CryptoEncryptionLevelIncorrect, "unencrypted SHLO message"))) - Expect(handshakeEvent).ToNot(Receive()) - Expect(handshakeEvent).ToNot(BeClosed()) - }) - - It("rejects SHLOs without a PUBS", func() { - delete(shloMap, TagPUBS) - _, err := cs.handleSHLOMessage(shloMap) - Expect(err).To(MatchError(qerr.Error(qerr.CryptoMessageParameterNotFound, "PUBS"))) - Expect(handshakeEvent).ToNot(BeClosed()) - }) - - It("rejects SHLOs without a version list", func() { - delete(shloMap, TagVER) - _, err := cs.handleSHLOMessage(shloMap) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidCryptoMessageParameter, "server hello missing version list"))) - Expect(handshakeEvent).ToNot(BeClosed()) - }) - - It("accepts a SHLO after a version negotiation", func() { - ver := protocol.SupportedVersions[0] - cs.negotiatedVersions = []protocol.VersionNumber{ver} - cs.receivedSecurePacket = true - b := &bytes.Buffer{} - utils.BigEndian.WriteUint32(b, uint32(ver)) - shloMap[TagVER] = b.Bytes() - _, err := cs.handleSHLOMessage(shloMap) - Expect(err).ToNot(HaveOccurred()) - }) - - It("reads the server nonce, if set", func() { - shloMap[TagSNO] = []byte("server nonce") - _, err := cs.handleSHLOMessage(shloMap) - Expect(err).ToNot(HaveOccurred()) - Expect(cs.sno).To(Equal(shloMap[TagSNO])) - }) - - It("creates a forwardSecureAEAD", func() { - shloMap[TagSNO] = []byte("server nonce") - _, err := cs.handleSHLOMessage(shloMap) - Expect(err).ToNot(HaveOccurred()) - Expect(cs.forwardSecureAEAD).ToNot(BeNil()) - }) - - It("reads the connection parameters", func() { - shloMap[TagICSL] = []byte{13, 0, 0, 0} // 13 seconds - params, err := cs.handleSHLOMessage(shloMap) - Expect(err).ToNot(HaveOccurred()) - Expect(params.IdleTimeout).To(Equal(13 * time.Second)) - }) - - It("closes the handshakeEvent chan when receiving an SHLO", func() { - HandshakeMessage{Tag: TagSHLO, Data: shloMap}.Write(&stream.dataToRead) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.HandshakeFailed, errMockStreamClosing.Error()))) - close(done) - }() - Eventually(handshakeEvent).Should(Receive()) - Eventually(handshakeEvent).Should(BeClosed()) - // make the go routine return - stream.close() - Eventually(done).Should(BeClosed()) - }) - - It("passes the transport parameters on the channel", func() { - shloMap[TagSFCW] = []byte{0x0d, 0x00, 0xdf, 0xba} - HandshakeMessage{Tag: TagSHLO, Data: shloMap}.Write(&stream.dataToRead) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.HandshakeFailed, errMockStreamClosing.Error()))) - close(done) - }() - var params TransportParameters - Eventually(paramsChan).Should(Receive(¶ms)) - Expect(params.StreamFlowControlWindow).To(Equal(protocol.ByteCount(0xbadf000d))) - // make the go routine return - stream.close() - Eventually(done).Should(BeClosed()) - }) - - It("errors if it can't read a connection parameter", func() { - shloMap[TagICSL] = []byte{3, 0, 0} // 1 byte too short - _, err := cs.handleSHLOMessage(shloMap) - Expect(err).To(MatchError(qerr.InvalidCryptoMessageParameter)) - }) - }) - - Context("CHLO generation", func() { - It("is longer than the miminum client hello size", func() { - err := cs.sendCHLO() - Expect(err).ToNot(HaveOccurred()) - Expect(cs.cryptoStream.(*mockStream).dataWritten.Len()).To(BeNumerically(">", protocol.MinClientHelloSize)) - }) - - It("doesn't overflow the packet with padding", func() { - tagMap := make(map[Tag][]byte) - tagMap[TagSCID] = bytes.Repeat([]byte{0}, protocol.MinClientHelloSize*6/10) - cs.addPadding(tagMap) - Expect(len(tagMap[TagPAD])).To(BeNumerically("<", protocol.MinClientHelloSize/2)) - }) - - It("saves the last sent CHLO", func() { - // send first CHLO - err := cs.sendCHLO() - Expect(err).ToNot(HaveOccurred()) - Expect(cs.cryptoStream.(*mockStream).dataWritten.Bytes()).To(Equal(cs.lastSentCHLO)) - cs.cryptoStream.(*mockStream).dataWritten.Reset() - firstCHLO := cs.lastSentCHLO - // send second CHLO - cs.sno = []byte("foobar") - err = cs.sendCHLO() - Expect(err).ToNot(HaveOccurred()) - Expect(cs.cryptoStream.(*mockStream).dataWritten.Bytes()).To(Equal(cs.lastSentCHLO)) - Expect(cs.lastSentCHLO).ToNot(Equal(firstCHLO)) - }) - - It("has the right values for an inchoate CHLO", func() { - cs.version = cs.initialVersion - 1 - cs.hostname = "sni-hostname" - certManager.commonCertificateHashes = []byte("common certs") - tags, err := cs.getTags() - Expect(err).ToNot(HaveOccurred()) - Expect(string(tags[TagSNI])).To(Equal(cs.hostname)) - Expect(tags[TagPDMD]).To(Equal([]byte("X509"))) - Expect(tags[TagVER]).To(Equal([]byte("Q039"))) - Expect(tags[TagCCS]).To(Equal(certManager.commonCertificateHashes)) - Expect(tags).ToNot(HaveKey(TagTCID)) - }) - - It("requests to omit the connection ID", func() { - cs.params.OmitConnectionID = true - tags, err := cs.getTags() - Expect(err).ToNot(HaveOccurred()) - Expect(tags).To(HaveKeyWithValue(TagTCID, []byte{0, 0, 0, 0})) - }) - - It("adds the tags returned from the connectionParametersManager to the CHLO", func() { - pnTags := cs.params.getHelloMap() - Expect(pnTags).ToNot(BeEmpty()) - tags, err := cs.getTags() - Expect(err).ToNot(HaveOccurred()) - for t := range pnTags { - Expect(tags).To(HaveKey(t)) - } - }) - - It("doesn't send a CCS if there are no common certificate sets available", func() { - certManager.commonCertificateHashes = nil - tags, err := cs.getTags() - Expect(err).ToNot(HaveOccurred()) - Expect(tags).ToNot(HaveKey(TagCCS)) - }) - - It("includes the server config id, if available", func() { - id := []byte("foobar") - cs.serverConfig = &serverConfigClient{ID: id} - tags, err := cs.getTags() - Expect(err).ToNot(HaveOccurred()) - Expect(tags[TagSCID]).To(Equal(id)) - }) - - It("includes the source address token, if available", func() { - cs.stk = []byte("sourceaddresstoken") - tags, err := cs.getTags() - Expect(err).ToNot(HaveOccurred()) - Expect(tags[TagSTK]).To(Equal(cs.stk)) - }) - - It("includes the server nonce, if available", func() { - cs.sno = []byte("foobar") - tags, err := cs.getTags() - Expect(err).ToNot(HaveOccurred()) - Expect(tags[TagSNO]).To(Equal(cs.sno)) - }) - - It("doesn't include optional values, if not available", func() { - tags, err := cs.getTags() - Expect(err).ToNot(HaveOccurred()) - Expect(tags).ToNot(HaveKey(TagSCID)) - Expect(tags).ToNot(HaveKey(TagSNO)) - Expect(tags).ToNot(HaveKey(TagSTK)) - }) - - It("doesn't change any values after reading the certificate, if the server config is missing", func() { - tags, err := cs.getTags() - Expect(err).ToNot(HaveOccurred()) - certManager.leafCert = []byte("leafcert") - Expect(cs.getTags()).To(Equal(tags)) - }) - - It("sends a the values needed for a full CHLO after reading the certificate and the server config", func() { - certManager.leafCert = []byte("leafcert") - cs.nonc = []byte("client-nonce") - kex, err := crypto.NewCurve25519KEX() - Expect(err).ToNot(HaveOccurred()) - cs.serverConfig = &serverConfigClient{kex: kex} - xlct := []byte{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8} - certManager.leafCertHash = binary.LittleEndian.Uint64(xlct) - tags, err := cs.getTags() - Expect(err).ToNot(HaveOccurred()) - Expect(tags[TagNONC]).To(Equal(cs.nonc)) - Expect(tags[TagPUBS]).To(Equal(kex.PublicKey())) - Expect(tags[TagXLCT]).To(Equal(xlct)) - Expect(tags[TagKEXS]).To(Equal([]byte("C255"))) - Expect(tags[TagAEAD]).To(Equal([]byte("AESG"))) - }) - - It("doesn't send more than MaxClientHellos CHLOs", func() { - Expect(cs.clientHelloCounter).To(BeZero()) - for i := 1; i <= protocol.MaxClientHellos; i++ { - err := cs.sendCHLO() - Expect(err).ToNot(HaveOccurred()) - Expect(cs.clientHelloCounter).To(Equal(i)) - } - err := cs.sendCHLO() - Expect(err).To(MatchError(qerr.Error(qerr.CryptoTooManyRejects, fmt.Sprintf("More than %d rejects", protocol.MaxClientHellos)))) - }) - }) - - Context("escalating crypto", func() { - doCompleteREJ := func() { - cs.serverVerified = true - err := cs.maybeUpgradeCrypto() - Expect(err).ToNot(HaveOccurred()) - Expect(cs.secureAEAD).ToNot(BeNil()) - } - - doSHLO := func() { - cs.receivedSecurePacket = true - _, err := cs.handleSHLOMessage(shloMap) - Expect(err).ToNot(HaveOccurred()) - } - - // sets all values necessary for escalating to secureAEAD - BeforeEach(func() { - kex, err := crypto.NewCurve25519KEX() - Expect(err).ToNot(HaveOccurred()) - cs.serverConfig = &serverConfigClient{ - kex: kex, - obit: []byte("obit"), - sharedSecret: []byte("sharedSecret"), - raw: []byte("rawserverconfig"), - } - cs.lastSentCHLO = []byte("lastSentCHLO") - cs.nonc = []byte("nonc") - cs.diversificationNonce = []byte("divnonce") - certManager.leafCert = []byte("leafCert") - }) - - It("creates a secureAEAD once it has all necessary values", func() { - cs.serverVerified = true - err := cs.maybeUpgradeCrypto() - Expect(err).ToNot(HaveOccurred()) - Expect(cs.secureAEAD).ToNot(BeNil()) - Expect(keyDerivationCalledWith.forwardSecure).To(BeFalse()) - Expect(keyDerivationCalledWith.sharedSecret).To(Equal(cs.serverConfig.sharedSecret)) - Expect(keyDerivationCalledWith.nonces).To(Equal(cs.nonc)) - Expect(keyDerivationCalledWith.connID).To(Equal(cs.connID)) - Expect(keyDerivationCalledWith.chlo).To(Equal(cs.lastSentCHLO)) - Expect(keyDerivationCalledWith.scfg).To(Equal(cs.serverConfig.Get())) - Expect(keyDerivationCalledWith.cert).To(Equal(certManager.leafCert)) - Expect(keyDerivationCalledWith.divNonce).To(Equal(cs.diversificationNonce)) - Expect(keyDerivationCalledWith.pers).To(Equal(protocol.PerspectiveClient)) - Expect(handshakeEvent).To(Receive()) - Expect(handshakeEvent).ToNot(Receive()) - Expect(handshakeEvent).ToNot(BeClosed()) - }) - - It("uses the server nonce, if the server sent one", func() { - cs.serverVerified = true - cs.sno = []byte("server nonce") - err := cs.maybeUpgradeCrypto() - Expect(err).ToNot(HaveOccurred()) - Expect(cs.secureAEAD).ToNot(BeNil()) - Expect(keyDerivationCalledWith.nonces).To(Equal(append(cs.nonc, cs.sno...))) - Expect(handshakeEvent).To(Receive()) - Expect(handshakeEvent).ToNot(Receive()) - Expect(handshakeEvent).ToNot(BeClosed()) - }) - - It("doesn't create a secureAEAD if the certificate is not yet verified, even if it has all necessary values", func() { - err := cs.maybeUpgradeCrypto() - Expect(err).ToNot(HaveOccurred()) - Expect(cs.secureAEAD).To(BeNil()) - Expect(handshakeEvent).ToNot(Receive()) - cs.serverVerified = true - // make sure we really had all necessary values before, and only serverVerified was missing - err = cs.maybeUpgradeCrypto() - Expect(err).ToNot(HaveOccurred()) - Expect(cs.secureAEAD).ToNot(BeNil()) - Expect(handshakeEvent).To(Receive()) - Expect(handshakeEvent).ToNot(Receive()) - Expect(handshakeEvent).ToNot(BeClosed()) - }) - - It("tries to escalate before reading a handshake message", func() { - Expect(cs.secureAEAD).To(BeNil()) - cs.serverVerified = true - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.HandshakeFailed, errMockStreamClosing.Error()))) - close(done) - }() - Eventually(handshakeEvent).Should(Receive()) - Expect(cs.secureAEAD).ToNot(BeNil()) - Expect(handshakeEvent).ToNot(Receive()) - Expect(handshakeEvent).ToNot(BeClosed()) - // make the go routine return - stream.close() - Eventually(done).Should(BeClosed()) - }) - - It("tries to escalate the crypto after receiving a diversification nonce", func() { - done := make(chan struct{}) - cs.diversificationNonce = nil - cs.serverVerified = true - go func() { - defer GinkgoRecover() - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.HandshakeFailed, errMockStreamClosing.Error()))) - close(done) - }() - Expect(cs.secureAEAD).To(BeNil()) - Expect(cs.SetDiversificationNonce([]byte("div"))).To(Succeed()) - Eventually(handshakeEvent).Should(Receive()) - Expect(cs.secureAEAD).ToNot(BeNil()) - Expect(handshakeEvent).ToNot(Receive()) - Expect(handshakeEvent).ToNot(BeClosed()) - // make the go routine return - stream.close() - Eventually(done).Should(BeClosed()) - }) - - Context("null encryption", func() { - It("is used initially", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(10), []byte{}).Return([]byte("foobar unencrypted")) - enc, sealer := cs.GetSealer() - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - d := sealer.Seal(nil, []byte("foobar"), 10, []byte{}) - Expect(d).To(Equal([]byte("foobar unencrypted"))) - }) - - It("is used for the crypto stream", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(1), []byte{}).Return([]byte("foobar unencrypted")) - enc, sealer := cs.GetSealerForCryptoStream() - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - d := sealer.Seal(nil, []byte("foobar"), 1, []byte{}) - Expect(d).To(Equal([]byte("foobar unencrypted"))) - }) - - It("is accepted initially", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("unencrypted"), protocol.PacketNumber(1), []byte{}).Return([]byte("decrypted"), nil) - d, enc, err := cs.Open(nil, []byte("unencrypted"), 1, []byte{}) - Expect(err).ToNot(HaveOccurred()) - Expect(d).To(Equal([]byte("decrypted"))) - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - }) - - It("is accepted before the server sent an encrypted packet", func() { - doCompleteREJ() - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("unencrypted"), protocol.PacketNumber(1), []byte{}).Return(nil, errors.New("authentication failed")) - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("unencrypted"), protocol.PacketNumber(1), []byte{}).Return([]byte("decrypted"), nil) - cs.receivedSecurePacket = false - Expect(cs.secureAEAD).ToNot(BeNil()) - d, enc, err := cs.Open(nil, []byte("unencrypted"), 1, []byte{}) - Expect(err).ToNot(HaveOccurred()) - Expect(d).To(Equal([]byte("decrypted"))) - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - }) - - It("is not accepted after the server sent an encrypted packet", func() { - doCompleteREJ() - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("unencrypted"), protocol.PacketNumber(3), []byte{}).Return(nil, errors.New("authentication failed")) - cs.receivedSecurePacket = true - _, enc, err := cs.Open(nil, []byte("unencrypted"), 3, []byte{}) - Expect(err).To(MatchError("authentication failed")) - Expect(enc).To(Equal(protocol.EncryptionUnspecified)) - }) - - It("errors if the has the wrong hash", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("not unencrypted"), protocol.PacketNumber(3), []byte{}).Return(nil, errors.New("authentication failed")) - _, enc, err := cs.Open(nil, []byte("not unencrypted"), 3, []byte{}) - Expect(err).To(MatchError("authentication failed")) - Expect(enc).To(Equal(protocol.EncryptionUnspecified)) - }) - }) - - Context("initial encryption", func() { - It("is used immediately when available", func() { - doCompleteREJ() - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(1), []byte{}).Return([]byte("foobar secure")) - cs.receivedSecurePacket = false - enc, sealer := cs.GetSealer() - Expect(enc).To(Equal(protocol.EncryptionSecure)) - d := sealer.Seal(nil, []byte("foobar"), 1, []byte{}) - Expect(d).To(Equal([]byte("foobar secure"))) - }) - - It("is accepted", func() { - doCompleteREJ() - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("encrypted"), protocol.PacketNumber(3), []byte{}).Return([]byte("decrypted"), nil) - d, enc, err := cs.Open(nil, []byte("encrypted"), 3, []byte{}) - Expect(err).ToNot(HaveOccurred()) - Expect(d).To(Equal([]byte("decrypted"))) - Expect(enc).To(Equal(protocol.EncryptionSecure)) - Expect(cs.receivedSecurePacket).To(BeTrue()) - }) - - It("is not used after receiving the SHLO", func() { - doSHLO() - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("encrypted"), protocol.PacketNumber(30), []byte{}).Return(nil, errors.New("authentication failed")) - _, enc, err := cs.Open(nil, []byte("encrypted"), 30, []byte{}) - Expect(err).To(MatchError("authentication failed")) - Expect(enc).To(Equal(protocol.EncryptionUnspecified)) - }) - - It("is not used for the crypto stream", func() { - doCompleteREJ() - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(3), []byte{}).Return([]byte("foobar unencrypted")) - enc, sealer := cs.GetSealerForCryptoStream() - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - d := sealer.Seal(nil, []byte("foobar"), 3, []byte{}) - Expect(d).To(Equal([]byte("foobar unencrypted"))) - }) - }) - - Context("forward-secure encryption", func() { - It("is used after receiving the SHLO", func() { - doSHLO() - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("shlo"), protocol.PacketNumber(4), []byte{}) - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(10), []byte{}).Return([]byte("foobar forward sec")) - _, enc, err := cs.Open(nil, []byte("shlo"), 4, []byte{}) - Expect(err).ToNot(HaveOccurred()) - Expect(enc).To(Equal(protocol.EncryptionForwardSecure)) - enc, sealer := cs.GetSealer() - Expect(enc).To(Equal(protocol.EncryptionForwardSecure)) - d := sealer.Seal(nil, []byte("foobar"), 10, []byte{}) - Expect(d).To(Equal([]byte("foobar forward sec"))) - }) - - It("is not used for the crypto stream", func() { - doSHLO() - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(3), []byte{}).Return([]byte("foobar unencrypted")) - enc, sealer := cs.GetSealerForCryptoStream() - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - d := sealer.Seal(nil, []byte("foobar"), 3, []byte{}) - Expect(d).To(Equal([]byte("foobar unencrypted"))) - }) - }) - - Context("reporting the connection state", func() { - It("reports the connection state before the handshake completes", func() { - chain := []*x509.Certificate{testdata.GetCertificate().Leaf} - certManager.chain = chain - state := cs.ConnectionState() - Expect(state.HandshakeComplete).To(BeFalse()) - Expect(state.PeerCertificates).To(Equal(chain)) - }) - - It("reports the connection state after the handshake completes", func() { - doSHLO() - state := cs.ConnectionState() - Expect(state.HandshakeComplete).To(BeTrue()) - }) - }) - - Context("forcing encryption levels", func() { - It("forces null encryption", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(4), []byte{}).Return([]byte("foobar unencrypted")) - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionUnencrypted) - Expect(err).ToNot(HaveOccurred()) - d := sealer.Seal(nil, []byte("foobar"), 4, []byte{}) - Expect(d).To(Equal([]byte("foobar unencrypted"))) - }) - - It("forces initial encryption", func() { - doCompleteREJ() - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(3), []byte{}).Return([]byte("foobar secure")) - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionSecure) - Expect(err).ToNot(HaveOccurred()) - d := sealer.Seal(nil, []byte("foobar"), 3, []byte{}) - Expect(d).To(Equal([]byte("foobar secure"))) - }) - - It("errors of no AEAD for initial encryption is available", func() { - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionSecure) - Expect(err).To(MatchError("CryptoSetupClient: no secureAEAD")) - Expect(sealer).To(BeNil()) - }) - - It("forces forward-secure encryption", func() { - doSHLO() - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(4), []byte{}).Return([]byte("foobar forward sec")) - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionForwardSecure) - Expect(err).ToNot(HaveOccurred()) - d := sealer.Seal(nil, []byte("foobar"), 4, []byte{}) - Expect(d).To(Equal([]byte("foobar forward sec"))) - }) - - It("errors of no AEAD for forward-secure encryption is available", func() { - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionForwardSecure) - Expect(err).To(MatchError("CryptoSetupClient: no forwardSecureAEAD")) - Expect(sealer).To(BeNil()) - }) - - It("errors if no encryption level is specified", func() { - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionUnspecified) - Expect(err).To(MatchError("CryptoSetupClient: no encryption level specified")) - Expect(sealer).To(BeNil()) - }) - }) - }) - - Context("Diversification Nonces", func() { - It("sets a diversification nonce", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.HandshakeFailed, errMockStreamClosing.Error()))) - close(done) - }() - nonce := []byte("foobar") - Expect(cs.SetDiversificationNonce(nonce)).To(Succeed()) - Eventually(func() []byte { return cs.diversificationNonce }).Should(Equal(nonce)) - // make the go routine return - stream.close() - Eventually(done).Should(BeClosed()) - }) - - It("doesn't do anything when called multiple times with the same nonce", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.HandshakeFailed, errMockStreamClosing.Error()))) - close(done) - }() - nonce := []byte("foobar") - Expect(cs.SetDiversificationNonce(nonce)).To(Succeed()) - Expect(cs.SetDiversificationNonce(nonce)).To(Succeed()) - Eventually(func() []byte { return cs.diversificationNonce }).Should(Equal(nonce)) - // make the go routine return - stream.close() - Eventually(done).Should(BeClosed()) - }) - - It("rejects a different diversification nonce", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.HandshakeFailed, errMockStreamClosing.Error()))) - close(done) - }() - nonce1 := []byte("foobar") - nonce2 := []byte("raboof") - err := cs.SetDiversificationNonce(nonce1) - Expect(err).ToNot(HaveOccurred()) - err = cs.SetDiversificationNonce(nonce2) - Expect(err).To(MatchError(errConflictingDiversificationNonces)) - // make the go routine return - stream.close() - Eventually(done).Should(BeClosed()) - }) - }) - - Context("Client Nonce generation", func() { - BeforeEach(func() { - cs.serverConfig = &serverConfigClient{} - cs.serverConfig.obit = []byte{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8} - }) - - It("generates a client nonce", func() { - now := time.Now() - err := cs.generateClientNonce() - Expect(cs.nonc).To(HaveLen(32)) - Expect(err).ToNot(HaveOccurred()) - Expect(time.Unix(int64(binary.BigEndian.Uint32(cs.nonc[0:4])), 0)).To(BeTemporally("~", now, 1*time.Second)) - Expect(cs.nonc[4:12]).To(Equal(cs.serverConfig.obit)) - }) - - It("uses random values for the last 20 bytes", func() { - err := cs.generateClientNonce() - Expect(err).ToNot(HaveOccurred()) - nonce1 := cs.nonc - cs.nonc = []byte{} - err = cs.generateClientNonce() - Expect(err).ToNot(HaveOccurred()) - nonce2 := cs.nonc - Expect(nonce1[4:12]).To(Equal(nonce2[4:12])) - Expect(nonce1[12:]).ToNot(Equal(nonce2[12:])) - }) - - It("errors if a client nonce has already been generated", func() { - err := cs.generateClientNonce() - Expect(err).ToNot(HaveOccurred()) - err = cs.generateClientNonce() - Expect(err).To(MatchError(errClientNonceAlreadyExists)) - }) - - It("errors if no OBIT value is available", func() { - cs.serverConfig.obit = []byte{} - err := cs.generateClientNonce() - Expect(err).To(MatchError(errNoObitForClientNonce)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/crypto_setup_server_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/crypto_setup_server_test.go deleted file mode 100644 index 7b4a0e94e..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/crypto_setup_server_test.go +++ /dev/null @@ -1,731 +0,0 @@ -package handshake - -import ( - "bytes" - "encoding/binary" - "errors" - "io" - "net" - "time" - - "github.com/lucas-clemente/quic-go/internal/crypto" - "github.com/lucas-clemente/quic-go/internal/mocks/crypto" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/qerr" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type mockKEX struct { - ephermal bool - sharedKeyError error -} - -func (m *mockKEX) PublicKey() []byte { - if m.ephermal { - return []byte("ephermal pub") - } - return []byte("initial public") -} - -func (m *mockKEX) CalculateSharedKey(otherPublic []byte) ([]byte, error) { - if m.sharedKeyError != nil { - return nil, m.sharedKeyError - } - if m.ephermal { - return []byte("shared ephermal"), nil - } - return []byte("shared key"), nil -} - -type mockSigner struct { - gotCHLO bool -} - -func (s *mockSigner) SignServerProof(sni string, chlo []byte, serverConfigData []byte) ([]byte, error) { - if len(chlo) > 0 { - s.gotCHLO = true - } - return []byte("proof"), nil -} -func (*mockSigner) GetCertsCompressed(sni string, common, cached []byte) ([]byte, error) { - return []byte("certcompressed"), nil -} -func (*mockSigner) GetLeafCert(sni string) ([]byte, error) { - return []byte("certuncompressed"), nil -} - -func mockQuicCryptoKeyDerivation(forwardSecure bool, sharedSecret, nonces []byte, connID protocol.ConnectionID, chlo []byte, scfg []byte, cert []byte, divNonce []byte, pers protocol.Perspective) (crypto.AEAD, error) { - return mockcrypto.NewMockAEAD(mockCtrl), nil -} - -type mockStream struct { - unblockRead chan struct{} - dataToRead bytes.Buffer - dataWritten bytes.Buffer -} - -var _ io.ReadWriter = &mockStream{} - -var errMockStreamClosing = errors.New("mock stream closing") - -func newMockStream() *mockStream { - return &mockStream{unblockRead: make(chan struct{})} -} - -// call Close to make Read return -func (s *mockStream) Read(p []byte) (int, error) { - n, _ := s.dataToRead.Read(p) - if n == 0 { // block if there's no data - <-s.unblockRead - return 0, errMockStreamClosing - } - return n, nil // never return an EOF -} - -func (s *mockStream) Write(p []byte) (int, error) { - return s.dataWritten.Write(p) -} - -func (s *mockStream) close() { - close(s.unblockRead) -} - -type mockCookieProtector struct { - decodeErr error -} - -var _ cookieProtector = &mockCookieProtector{} - -func (mockCookieProtector) NewToken(sourceAddr []byte) ([]byte, error) { - return append([]byte("token "), sourceAddr...), nil -} - -func (s mockCookieProtector) DecodeToken(data []byte) ([]byte, error) { - if s.decodeErr != nil { - return nil, s.decodeErr - } - if len(data) < 6 { - return nil, errors.New("token too short") - } - return data[6:], nil -} - -var _ = Describe("Server Crypto Setup", func() { - var ( - kex *mockKEX - signer *mockSigner - scfg *ServerConfig - cs *cryptoSetupServer - stream *mockStream - paramsChan chan TransportParameters - handshakeEvent chan struct{} - nonce32 []byte - versionTag []byte - validSTK []byte - aead []byte - kexs []byte - version protocol.VersionNumber - supportedVersions []protocol.VersionNumber - sourceAddrValid bool - ) - - const ( - expectedInitialNonceLen = 32 - expectedFSNonceLen = 64 - ) - - BeforeEach(func() { - var err error - remoteAddr := &net.UDPAddr{IP: net.IPv4(1, 2, 3, 4), Port: 1234} - - // use a buffered channel here, so that we can parse a CHLO without having to receive the TransportParameters to avoid blocking - paramsChan = make(chan TransportParameters, 1) - handshakeEvent = make(chan struct{}, 2) - stream = newMockStream() - kex = &mockKEX{} - signer = &mockSigner{} - scfg, err = NewServerConfig(kex, signer) - nonce32 = make([]byte, 32) - aead = []byte("AESG") - kexs = []byte("C255") - copy(nonce32[4:12], scfg.obit) // set the OBIT value at the right position - versionTag = make([]byte, 4) - binary.BigEndian.PutUint32(versionTag, uint32(protocol.VersionWhatever)) - Expect(err).NotTo(HaveOccurred()) - version = protocol.SupportedVersions[len(protocol.SupportedVersions)-1] - supportedVersions = []protocol.VersionNumber{version, 98, 99} - csInt, err := NewCryptoSetup( - stream, - protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - remoteAddr, - version, - make([]byte, 32), // div nonce - scfg, - &TransportParameters{IdleTimeout: protocol.DefaultIdleTimeout}, - supportedVersions, - nil, - paramsChan, - handshakeEvent, - utils.DefaultLogger, - ) - Expect(err).NotTo(HaveOccurred()) - cs = csInt.(*cryptoSetupServer) - cs.scfg.cookieGenerator.cookieProtector = &mockCookieProtector{} - validSTK, err = cs.scfg.cookieGenerator.NewToken(remoteAddr) - Expect(err).NotTo(HaveOccurred()) - sourceAddrValid = true - cs.acceptSTKCallback = func(_ net.Addr, _ *Cookie) bool { return sourceAddrValid } - cs.keyDerivation = mockQuicCryptoKeyDerivation - cs.keyExchange = func() (crypto.KeyExchange, error) { return &mockKEX{ephermal: true}, nil } - cs.nullAEAD = mockcrypto.NewMockAEAD(mockCtrl) - cs.cryptoStream = stream - }) - - Context("when responding to client messages", func() { - var cert []byte - var xlct []byte - var fullCHLO map[Tag][]byte - - BeforeEach(func() { - xlct = make([]byte, 8) - var err error - cert, err = cs.scfg.certChain.GetLeafCert("") - Expect(err).ToNot(HaveOccurred()) - binary.LittleEndian.PutUint64(xlct, crypto.HashCert(cert)) - fullCHLO = map[Tag][]byte{ - TagSCID: scfg.ID, - TagSNI: []byte("quic.clemente.io"), - TagNONC: nonce32, - TagSTK: validSTK, - TagXLCT: xlct, - TagAEAD: aead, - TagKEXS: kexs, - TagPUBS: bytes.Repeat([]byte{'e'}, 31), - TagVER: versionTag, - } - }) - - It("doesn't support Chrome's no STOP_WAITING experiment", func() { - HandshakeMessage{ - Tag: TagCHLO, - Data: map[Tag][]byte{ - TagNSTP: []byte("foobar"), - }, - }.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(ErrNSTPExperiment)) - }) - - It("reads the transport parameters sent by the client", func() { - sourceAddrValid = true - fullCHLO[TagICSL] = []byte{0x37, 0x13, 0, 0} - _, err := cs.handleMessage(bytes.Repeat([]byte{'a'}, protocol.MinClientHelloSize), fullCHLO) - Expect(err).ToNot(HaveOccurred()) - var params TransportParameters - Expect(paramsChan).To(Receive(¶ms)) - Expect(params.IdleTimeout).To(Equal(0x1337 * time.Second)) - }) - - It("generates REJ messages", func() { - sourceAddrValid = false - response, err := cs.handleInchoateCHLO("", bytes.Repeat([]byte{'a'}, protocol.MinClientHelloSize), nil) - Expect(err).ToNot(HaveOccurred()) - Expect(response).To(HavePrefix("REJ")) - Expect(response).To(ContainSubstring("initial public")) - Expect(response).ToNot(ContainSubstring("certcompressed")) - Expect(response).ToNot(ContainSubstring("proof")) - Expect(signer.gotCHLO).To(BeFalse()) - }) - - It("REJ messages don't include cert or proof without STK", func() { - sourceAddrValid = false - response, err := cs.handleInchoateCHLO("", bytes.Repeat([]byte{'a'}, protocol.MinClientHelloSize), nil) - Expect(err).ToNot(HaveOccurred()) - Expect(response).To(HavePrefix("REJ")) - Expect(response).ToNot(ContainSubstring("certcompressed")) - Expect(response).ToNot(ContainSubstring("proof")) - Expect(signer.gotCHLO).To(BeFalse()) - }) - - It("REJ messages include cert and proof with valid STK", func() { - sourceAddrValid = true - response, err := cs.handleInchoateCHLO("", bytes.Repeat([]byte{'a'}, protocol.MinClientHelloSize), map[Tag][]byte{ - TagSTK: validSTK, - TagSNI: []byte("foo"), - }) - Expect(err).ToNot(HaveOccurred()) - Expect(response).To(HavePrefix("REJ")) - Expect(response).To(ContainSubstring("certcompressed")) - Expect(response).To(ContainSubstring("proof")) - Expect(signer.gotCHLO).To(BeTrue()) - }) - - It("generates SHLO messages", func() { - var checkedSecure, checkedForwardSecure bool - cs.keyDerivation = func(forwardSecure bool, sharedSecret, nonces []byte, connID protocol.ConnectionID, chlo []byte, scfg []byte, cert []byte, divNonce []byte, pers protocol.Perspective) (crypto.AEAD, error) { - if forwardSecure { - Expect(nonces).To(HaveLen(expectedFSNonceLen)) - checkedForwardSecure = true - Expect(sharedSecret).To(Equal([]byte("shared ephermal"))) - } else { - Expect(nonces).To(HaveLen(expectedInitialNonceLen)) - Expect(sharedSecret).To(Equal([]byte("shared key"))) - checkedSecure = true - } - return mockcrypto.NewMockAEAD(mockCtrl), nil - } - - response, err := cs.handleCHLO("", []byte("chlo-data"), map[Tag][]byte{ - TagPUBS: []byte("pubs-c"), - TagNONC: nonce32, - TagAEAD: aead, - TagKEXS: kexs, - }) - Expect(err).ToNot(HaveOccurred()) - Expect(response).To(HavePrefix("SHLO")) - message, err := ParseHandshakeMessage(bytes.NewReader(response)) - Expect(err).ToNot(HaveOccurred()) - Expect(message.Data).To(HaveKeyWithValue(TagPUBS, []byte("ephermal pub"))) - Expect(message.Data).To(HaveKey(TagSNO)) - Expect(message.Data).To(HaveKey(TagVER)) - Expect(message.Data[TagVER]).To(HaveLen(4 * len(supportedVersions))) - for _, v := range supportedVersions { - b := &bytes.Buffer{} - utils.BigEndian.WriteUint32(b, uint32(v)) - Expect(message.Data[TagVER]).To(ContainSubstring(b.String())) - } - Expect(checkedSecure).To(BeTrue()) - Expect(checkedForwardSecure).To(BeTrue()) - }) - - It("handles long handshake", func() { - HandshakeMessage{ - Tag: TagCHLO, - Data: map[Tag][]byte{ - TagSNI: []byte("quic.clemente.io"), - TagSTK: validSTK, - TagPAD: bytes.Repeat([]byte{'a'}, protocol.MinClientHelloSize), - TagVER: versionTag, - }, - }.Write(&stream.dataToRead) - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).NotTo(HaveOccurred()) - Expect(stream.dataWritten.Bytes()).To(HavePrefix("REJ")) - Expect(handshakeEvent).To(Receive()) // for the switch to secure - Expect(stream.dataWritten.Bytes()).To(ContainSubstring("SHLO")) - Expect(handshakeEvent).To(Receive()) // for the switch to forward secure - Expect(handshakeEvent).ToNot(BeClosed()) - }) - - It("rejects client nonces that have the wrong length", func() { - fullCHLO[TagNONC] = []byte("too short client nonce") - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.InvalidCryptoMessageParameter, "invalid client nonce length"))) - }) - - It("rejects client nonces that have the wrong OBIT value", func() { - fullCHLO[TagNONC] = make([]byte, 32) // the OBIT value is nonce[4:12] and here just initialized to 0 - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.InvalidCryptoMessageParameter, "OBIT not matching"))) - }) - - It("errors if it can't calculate a shared key", func() { - testErr := errors.New("test error") - kex.sharedKeyError = testErr - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(testErr)) - }) - - It("handles 0-RTT handshake", func() { - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).NotTo(HaveOccurred()) - Expect(stream.dataWritten.Bytes()).To(HavePrefix("SHLO")) - Expect(stream.dataWritten.Bytes()).ToNot(ContainSubstring("REJ")) - Expect(handshakeEvent).To(Receive()) // for the switch to secure - Expect(handshakeEvent).To(Receive()) // for the switch to forward secure - Expect(handshakeEvent).ToNot(BeClosed()) - }) - - It("recognizes inchoate CHLOs missing SCID", func() { - delete(fullCHLO, TagSCID) - Expect(cs.isInchoateCHLO(fullCHLO, cert)).To(BeTrue()) - }) - - It("recognizes inchoate CHLOs missing PUBS", func() { - delete(fullCHLO, TagPUBS) - Expect(cs.isInchoateCHLO(fullCHLO, cert)).To(BeTrue()) - }) - - It("recognizes inchoate CHLOs with missing XLCT", func() { - delete(fullCHLO, TagXLCT) - Expect(cs.isInchoateCHLO(fullCHLO, cert)).To(BeTrue()) - }) - - It("recognizes inchoate CHLOs with wrong length XLCT", func() { - fullCHLO[TagXLCT] = bytes.Repeat([]byte{'f'}, 7) // should be 8 bytes - Expect(cs.isInchoateCHLO(fullCHLO, cert)).To(BeTrue()) - }) - - It("recognizes inchoate CHLOs with wrong XLCT", func() { - fullCHLO[TagXLCT] = bytes.Repeat([]byte{'f'}, 8) - Expect(cs.isInchoateCHLO(fullCHLO, cert)).To(BeTrue()) - }) - - It("recognizes inchoate CHLOs with an invalid STK", func() { - testErr := errors.New("STK invalid") - cs.scfg.cookieGenerator.cookieProtector.(*mockCookieProtector).decodeErr = testErr - Expect(cs.isInchoateCHLO(fullCHLO, cert)).To(BeTrue()) - }) - - It("recognizes proper CHLOs", func() { - Expect(cs.isInchoateCHLO(fullCHLO, cert)).To(BeFalse()) - }) - - It("rejects CHLOs without the version tag", func() { - HandshakeMessage{ - Tag: TagCHLO, - Data: map[Tag][]byte{ - TagSCID: scfg.ID, - TagSNI: []byte("quic.clemente.io"), - }, - }.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.InvalidCryptoMessageParameter, "client hello missing version tag"))) - }) - - It("rejects CHLOs with a version tag that has the wrong length", func() { - fullCHLO[TagVER] = []byte{0x13, 0x37} // should be 4 bytes - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.InvalidCryptoMessageParameter, "incorrect version tag"))) - }) - - It("detects version downgrade attacks", func() { - highestSupportedVersion := supportedVersions[len(supportedVersions)-1] - lowestSupportedVersion := supportedVersions[0] - Expect(highestSupportedVersion).ToNot(Equal(lowestSupportedVersion)) - cs.version = highestSupportedVersion - b := make([]byte, 4) - binary.BigEndian.PutUint32(b, uint32(lowestSupportedVersion)) - fullCHLO[TagVER] = b - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.VersionNegotiationMismatch, "Downgrade attack detected"))) - }) - - It("accepts a non-matching version tag in the CHLO, if it is an unsupported version", func() { - supportedVersion := protocol.SupportedVersions[0] - unsupportedVersion := supportedVersion + 1000 - Expect(protocol.IsSupportedVersion(supportedVersions, unsupportedVersion)).To(BeFalse()) - cs.version = supportedVersion - b := make([]byte, 4) - binary.BigEndian.PutUint32(b, uint32(unsupportedVersion)) - fullCHLO[TagVER] = b - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).ToNot(HaveOccurred()) - }) - - It("errors if the AEAD tag is missing", func() { - delete(fullCHLO, TagAEAD) - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.CryptoNoSupport, "Unsupported AEAD or KEXS"))) - }) - - It("errors if the AEAD tag has the wrong value", func() { - fullCHLO[TagAEAD] = []byte("wrong") - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.CryptoNoSupport, "Unsupported AEAD or KEXS"))) - }) - - It("errors if the KEXS tag is missing", func() { - delete(fullCHLO, TagKEXS) - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.CryptoNoSupport, "Unsupported AEAD or KEXS"))) - }) - - It("errors if the KEXS tag has the wrong value", func() { - fullCHLO[TagKEXS] = []byte("wrong") - HandshakeMessage{Tag: TagCHLO, Data: fullCHLO}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.Error(qerr.CryptoNoSupport, "Unsupported AEAD or KEXS"))) - }) - }) - - It("errors without SNI", func() { - HandshakeMessage{ - Tag: TagCHLO, - Data: map[Tag][]byte{ - TagSTK: validSTK, - }, - }.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError("CryptoMessageParameterNotFound: SNI required")) - }) - - It("errors with empty SNI", func() { - HandshakeMessage{ - Tag: TagCHLO, - Data: map[Tag][]byte{ - TagSTK: validSTK, - TagSNI: nil, - }, - }.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError("CryptoMessageParameterNotFound: SNI required")) - }) - - It("errors with invalid message", func() { - stream.dataToRead.Write([]byte("invalid message")) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.HandshakeFailed)) - }) - - It("errors with non-CHLO message", func() { - HandshakeMessage{Tag: TagPAD, Data: nil}.Write(&stream.dataToRead) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(qerr.InvalidCryptoMessageType)) - }) - - Context("escalating crypto", func() { - doCHLO := func() { - _, err := cs.handleCHLO("", []byte("chlo-data"), map[Tag][]byte{ - TagPUBS: []byte("pubs-c"), - TagNONC: nonce32, - TagAEAD: aead, - TagKEXS: kexs, - }) - Expect(err).ToNot(HaveOccurred()) - Expect(handshakeEvent).To(Receive()) // for the switch to secure - close(cs.sentSHLO) - } - - Context("null encryption", func() { - It("is used initially", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(10), []byte{}).Return([]byte("foobar signed")) - enc, sealer := cs.GetSealer() - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - d := sealer.Seal(nil, []byte("foobar"), 10, []byte{}) - Expect(d).To(Equal([]byte("foobar signed"))) - }) - - It("is used for the crypto stream", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(0), []byte{}) - enc, sealer := cs.GetSealerForCryptoStream() - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - sealer.Seal(nil, []byte("foobar"), 0, []byte{}) - }) - - It("is accepted initially", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("unencrypted"), protocol.PacketNumber(5), []byte{}).Return([]byte("decrypted"), nil) - d, enc, err := cs.Open(nil, []byte("unencrypted"), 5, []byte{}) - Expect(err).ToNot(HaveOccurred()) - Expect(d).To(Equal([]byte("decrypted"))) - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - }) - - It("errors if the has the wrong hash", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("not unencrypted"), protocol.PacketNumber(5), []byte{}).Return(nil, errors.New("authentication failed")) - _, enc, err := cs.Open(nil, []byte("not unencrypted"), 5, []byte{}) - Expect(err).To(MatchError("authentication failed")) - Expect(enc).To(Equal(protocol.EncryptionUnspecified)) - }) - - It("is still accepted after CHLO", func() { - doCHLO() - // it tries forward secure and secure decryption first - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("unencrypted"), protocol.PacketNumber(99), []byte{}).Return(nil, errors.New("authentication failed")) - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("unencrypted"), protocol.PacketNumber(99), []byte{}).Return(nil, errors.New("authentication failed")) - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("unencrypted"), protocol.PacketNumber(99), []byte{}) - Expect(cs.secureAEAD).ToNot(BeNil()) - _, enc, err := cs.Open(nil, []byte("unencrypted"), 99, []byte{}) - Expect(err).ToNot(HaveOccurred()) - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - }) - - It("is not accepted after receiving secure packet", func() { - doCHLO() - // first receive a secure packet - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("encrypted"), protocol.PacketNumber(98), []byte{}).Return(nil, errors.New("authentication failed")) - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("encrypted"), protocol.PacketNumber(98), []byte{}).Return([]byte("decrypted"), nil) - d, enc, err := cs.Open(nil, []byte("encrypted"), 98, []byte{}) - Expect(enc).To(Equal(protocol.EncryptionSecure)) - Expect(err).ToNot(HaveOccurred()) - Expect(d).To(Equal([]byte("decrypted"))) - // now receive an unencrypted packet - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("unencrypted"), protocol.PacketNumber(99), []byte{}).Return(nil, errors.New("authentication failed")) - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("unencrypted"), protocol.PacketNumber(99), []byte{}).Return(nil, errors.New("authentication failed")) - _, enc, err = cs.Open(nil, []byte("unencrypted"), 99, []byte{}) - Expect(err).To(MatchError("authentication failed")) - Expect(enc).To(Equal(protocol.EncryptionUnspecified)) - }) - - It("is not used after CHLO", func() { - doCHLO() - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(0), []byte{}) - enc, sealer := cs.GetSealer() - Expect(enc).ToNot(Equal(protocol.EncryptionUnencrypted)) - sealer.Seal(nil, []byte("foobar"), 0, []byte{}) - }) - }) - - Context("initial encryption", func() { - It("is accepted after CHLO", func() { - doCHLO() - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("encrypted"), protocol.PacketNumber(98), []byte{}).Return(nil, errors.New("authentication failed")) - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("encrypted"), protocol.PacketNumber(98), []byte{}).Return([]byte("decrypted"), nil) - d, enc, err := cs.Open(nil, []byte("encrypted"), 98, []byte{}) - Expect(enc).To(Equal(protocol.EncryptionSecure)) - Expect(err).ToNot(HaveOccurred()) - Expect(d).To(Equal([]byte("decrypted"))) - }) - - It("is not accepted after receiving forward secure packet", func() { - doCHLO() - // receive a forward secure packet - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("forward secure encrypted"), protocol.PacketNumber(11), []byte{}) - _, _, err := cs.Open(nil, []byte("forward secure encrypted"), 11, []byte{}) - Expect(err).ToNot(HaveOccurred()) - // receive a secure packet - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("encrypted"), protocol.PacketNumber(12), []byte{}).Return(nil, errors.New("authentication failed")) - _, enc, err := cs.Open(nil, []byte("encrypted"), 12, []byte{}) - Expect(err).To(MatchError("authentication failed")) - Expect(enc).To(Equal(protocol.EncryptionUnspecified)) - }) - - It("is used for the crypto stream", func() { - doCHLO() - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(1), []byte{}).Return([]byte("foobar crypto stream")) - enc, sealer := cs.GetSealerForCryptoStream() - Expect(enc).To(Equal(protocol.EncryptionSecure)) - d := sealer.Seal(nil, []byte("foobar"), 1, []byte{}) - Expect(d).To(Equal([]byte("foobar crypto stream"))) - }) - }) - - Context("forward secure encryption", func() { - It("is used after the CHLO", func() { - doCHLO() - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(20), []byte{}).Return([]byte("foobar forward sec")) - enc, sealer := cs.GetSealer() - Expect(enc).To(Equal(protocol.EncryptionForwardSecure)) - d := sealer.Seal(nil, []byte("foobar"), 20, []byte{}) - Expect(d).To(Equal([]byte("foobar forward sec"))) - }) - - It("regards the handshake as complete once it receives a forward encrypted packet", func() { - doCHLO() - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("forward secure encrypted"), protocol.PacketNumber(200), []byte{}) - _, _, err := cs.Open(nil, []byte("forward secure encrypted"), 200, []byte{}) - Expect(err).ToNot(HaveOccurred()) - Expect(handshakeEvent).To(BeClosed()) - }) - }) - - Context("reporting the connection state", func() { - It("reports before the handshake completes", func() { - cs.sni = "server name" - state := cs.ConnectionState() - Expect(state.HandshakeComplete).To(BeFalse()) - Expect(state.ServerName).To(Equal("server name")) - }) - - It("reports after the handshake completes", func() { - doCHLO() - // receive a forward secure packet - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("forward secure encrypted"), protocol.PacketNumber(11), []byte{}) - _, _, err := cs.Open(nil, []byte("forward secure encrypted"), 11, []byte{}) - Expect(err).ToNot(HaveOccurred()) - state := cs.ConnectionState() - Expect(state.HandshakeComplete).To(BeTrue()) - }) - }) - - Context("forcing encryption levels", func() { - It("forces null encryption", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(11), []byte{}).Return([]byte("foobar unencrypted")) - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionUnencrypted) - Expect(err).ToNot(HaveOccurred()) - d := sealer.Seal(nil, []byte("foobar"), 11, []byte{}) - Expect(d).To(Equal([]byte("foobar unencrypted"))) - }) - - It("forces initial encryption", func() { - doCHLO() - cs.secureAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(12), []byte{}).Return([]byte("foobar secure")) - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionSecure) - Expect(err).ToNot(HaveOccurred()) - d := sealer.Seal(nil, []byte("foobar"), 12, []byte{}) - Expect(d).To(Equal([]byte("foobar secure"))) - }) - - It("errors if no AEAD for initial encryption is available", func() { - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionSecure) - Expect(err).To(MatchError("CryptoSetupServer: no secureAEAD")) - Expect(sealer).To(BeNil()) - }) - - It("forces forward-secure encryption", func() { - doCHLO() - cs.forwardSecureAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(13), []byte{}).Return([]byte("foobar forward sec")) - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionForwardSecure) - Expect(err).ToNot(HaveOccurred()) - d := sealer.Seal(nil, []byte("foobar"), 13, []byte{}) - Expect(d).To(Equal([]byte("foobar forward sec"))) - }) - - It("errors of no AEAD for forward-secure encryption is available", func() { - seal, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionForwardSecure) - Expect(err).To(MatchError("CryptoSetupServer: no forwardSecureAEAD")) - Expect(seal).To(BeNil()) - }) - - It("errors if no encryption level is specified", func() { - seal, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionUnspecified) - Expect(err).To(MatchError("CryptoSetupServer: no encryption level specified")) - Expect(seal).To(BeNil()) - }) - }) - }) - - Context("STK verification and creation", func() { - It("requires STK", func() { - sourceAddrValid = false - done, err := cs.handleMessage( - bytes.Repeat([]byte{'a'}, protocol.MinClientHelloSize), - map[Tag][]byte{ - TagSNI: []byte("foo"), - TagVER: versionTag, - }, - ) - Expect(err).ToNot(HaveOccurred()) - Expect(done).To(BeFalse()) - Expect(stream.dataWritten.Bytes()).To(ContainSubstring(string(validSTK))) - Expect(cs.sni).To(Equal("foo")) - }) - - It("works with proper STK", func() { - sourceAddrValid = true - done, err := cs.handleMessage( - bytes.Repeat([]byte{'a'}, protocol.MinClientHelloSize), - map[Tag][]byte{ - TagSNI: []byte("foo"), - TagVER: versionTag, - }, - ) - Expect(err).ToNot(HaveOccurred()) - Expect(done).To(BeFalse()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/crypto_setup_tls_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/crypto_setup_tls_test.go deleted file mode 100644 index 85c087eac..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/crypto_setup_tls_test.go +++ /dev/null @@ -1,192 +0,0 @@ -package handshake - -import ( - "bytes" - "errors" - "fmt" - - "github.com/bifurcation/mint" - "github.com/lucas-clemente/quic-go/internal/crypto" - "github.com/lucas-clemente/quic-go/internal/mocks/crypto" - "github.com/lucas-clemente/quic-go/internal/protocol" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -func mockKeyDerivation(crypto.TLSExporter, protocol.Perspective) (crypto.AEAD, error) { - return mockcrypto.NewMockAEAD(mockCtrl), nil -} - -var _ = Describe("TLS Crypto Setup", func() { - var ( - cs *cryptoSetupTLS - handshakeEvent chan struct{} - ) - - BeforeEach(func() { - handshakeEvent = make(chan struct{}, 2) - css, err := NewCryptoSetupTLSServer( - newCryptoStreamConn(bytes.NewBuffer([]byte{})), - protocol.ConnectionID{}, - &mint.Config{}, - handshakeEvent, - protocol.VersionTLS, - ) - Expect(err).ToNot(HaveOccurred()) - cs = css.(*cryptoSetupTLS) - cs.nullAEAD = mockcrypto.NewMockAEAD(mockCtrl) - }) - - It("errors when the handshake fails", func() { - alert := mint.AlertBadRecordMAC - cs.tls = NewMockMintTLS(mockCtrl) - cs.tls.(*MockMintTLS).EXPECT().Handshake().Return(alert) - err := cs.HandleCryptoStream() - Expect(err).To(MatchError(fmt.Errorf("TLS handshake error: %s (Alert %d)", alert.String(), alert))) - }) - - It("derives keys", func() { - cs.tls = NewMockMintTLS(mockCtrl) - cs.tls.(*MockMintTLS).EXPECT().Handshake().Return(mint.AlertNoAlert) - cs.tls.(*MockMintTLS).EXPECT().ConnectionState().Return(mint.ConnectionState{HandshakeState: mint.StateServerConnected}) - cs.keyDerivation = mockKeyDerivation - err := cs.HandleCryptoStream() - Expect(err).ToNot(HaveOccurred()) - Expect(handshakeEvent).To(Receive()) - Expect(handshakeEvent).To(BeClosed()) - }) - - It("handshakes until it is connected", func() { - cs.tls = NewMockMintTLS(mockCtrl) - cs.tls.(*MockMintTLS).EXPECT().Handshake().Return(mint.AlertNoAlert).Times(10) - cs.tls.(*MockMintTLS).EXPECT().ConnectionState().Return(mint.ConnectionState{HandshakeState: mint.StateServerNegotiated}).Times(9) - cs.tls.(*MockMintTLS).EXPECT().ConnectionState().Return(mint.ConnectionState{HandshakeState: mint.StateServerConnected}) - cs.keyDerivation = mockKeyDerivation - err := cs.HandleCryptoStream() - Expect(err).ToNot(HaveOccurred()) - Expect(handshakeEvent).To(Receive()) - }) - - Context("reporting the handshake state", func() { - It("reports before the handshake compeletes", func() { - cs.tls = NewMockMintTLS(mockCtrl) - cs.tls.(*MockMintTLS).EXPECT().ConnectionState().Return(mint.ConnectionState{}) - state := cs.ConnectionState() - Expect(state.HandshakeComplete).To(BeFalse()) - Expect(state.PeerCertificates).To(BeNil()) - }) - - It("reports after the handshake completes", func() { - cs.tls = NewMockMintTLS(mockCtrl) - cs.tls.(*MockMintTLS).EXPECT().Handshake().Return(mint.AlertNoAlert) - cs.tls.(*MockMintTLS).EXPECT().ConnectionState().Return(mint.ConnectionState{HandshakeState: mint.StateServerConnected}).Times(2) - cs.keyDerivation = mockKeyDerivation - err := cs.HandleCryptoStream() - Expect(err).ToNot(HaveOccurred()) - state := cs.ConnectionState() - Expect(state.HandshakeComplete).To(BeTrue()) - Expect(state.PeerCertificates).To(BeNil()) - }) - }) - - Context("escalating crypto", func() { - doHandshake := func() { - cs.tls = NewMockMintTLS(mockCtrl) - cs.tls.(*MockMintTLS).EXPECT().Handshake().Return(mint.AlertNoAlert) - cs.tls.(*MockMintTLS).EXPECT().ConnectionState().Return(mint.ConnectionState{HandshakeState: mint.StateServerConnected}) - cs.keyDerivation = mockKeyDerivation - err := cs.HandleCryptoStream() - Expect(err).ToNot(HaveOccurred()) - } - - Context("null encryption", func() { - It("is used initially", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(5), []byte{}).Return([]byte("foobar signed")) - enc, sealer := cs.GetSealer() - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - d := sealer.Seal(nil, []byte("foobar"), 5, []byte{}) - Expect(d).To(Equal([]byte("foobar signed"))) - }) - - It("is used for opening", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("foobar enc"), protocol.PacketNumber(10), []byte{}).Return([]byte("foobar"), nil) - d, err := cs.OpenHandshake(nil, []byte("foobar enc"), 10, []byte{}) - Expect(err).ToNot(HaveOccurred()) - Expect(d).To(Equal([]byte("foobar"))) - }) - - It("is used for crypto stream", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(20), []byte{}).Return([]byte("foobar signed")) - enc, sealer := cs.GetSealerForCryptoStream() - Expect(enc).To(Equal(protocol.EncryptionUnencrypted)) - d := sealer.Seal(nil, []byte("foobar"), 20, []byte{}) - Expect(d).To(Equal([]byte("foobar signed"))) - }) - - It("errors if the has the wrong hash", func() { - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("foobar enc"), protocol.PacketNumber(10), []byte{}).Return(nil, errors.New("authentication failed")) - _, err := cs.OpenHandshake(nil, []byte("foobar enc"), 10, []byte{}) - Expect(err).To(MatchError("authentication failed")) - }) - }) - - Context("forward-secure encryption", func() { - It("is used for sealing after the handshake completes", func() { - doHandshake() - cs.aead.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(5), []byte{}).Return([]byte("foobar forward sec")) - enc, sealer := cs.GetSealer() - Expect(enc).To(Equal(protocol.EncryptionForwardSecure)) - d := sealer.Seal(nil, []byte("foobar"), 5, []byte{}) - Expect(d).To(Equal([]byte("foobar forward sec"))) - }) - - It("is used for opening", func() { - doHandshake() - cs.aead.(*mockcrypto.MockAEAD).EXPECT().Open(nil, []byte("encrypted"), protocol.PacketNumber(6), []byte{}).Return([]byte("decrypted"), nil) - d, err := cs.Open1RTT(nil, []byte("encrypted"), 6, []byte{}) - Expect(err).ToNot(HaveOccurred()) - Expect(d).To(Equal([]byte("decrypted"))) - }) - }) - - Context("forcing encryption levels", func() { - It("forces null encryption", func() { - doHandshake() - cs.nullAEAD.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(5), []byte{}).Return([]byte("foobar signed")) - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionUnencrypted) - Expect(err).ToNot(HaveOccurred()) - d := sealer.Seal(nil, []byte("foobar"), 5, []byte{}) - Expect(d).To(Equal([]byte("foobar signed"))) - }) - - It("forces forward-secure encryption", func() { - doHandshake() - cs.aead.(*mockcrypto.MockAEAD).EXPECT().Seal(nil, []byte("foobar"), protocol.PacketNumber(5), []byte{}).Return([]byte("foobar forward sec")) - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionForwardSecure) - Expect(err).ToNot(HaveOccurred()) - d := sealer.Seal(nil, []byte("foobar"), 5, []byte{}) - Expect(d).To(Equal([]byte("foobar forward sec"))) - }) - - It("errors if the forward-secure AEAD is not available", func() { - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionForwardSecure) - Expect(err).To(MatchError("CryptoSetup: no sealer with encryption level forward-secure")) - Expect(sealer).To(BeNil()) - }) - - It("never returns a secure AEAD (they don't exist with TLS)", func() { - doHandshake() - sealer, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionSecure) - Expect(err).To(MatchError("CryptoSetup: no sealer with encryption level encrypted (not forward-secure)")) - Expect(sealer).To(BeNil()) - }) - - It("errors if no encryption level is specified", func() { - seal, err := cs.GetSealerWithEncryptionLevel(protocol.EncryptionUnspecified) - Expect(err).To(MatchError("CryptoSetup: no sealer with encryption level unknown")) - Expect(seal).To(BeNil()) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/crypto_stream_conn_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/crypto_stream_conn_test.go deleted file mode 100644 index 64bb6cbd2..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/crypto_stream_conn_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package handshake - -import ( - "bytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Crypto Stream Conn", func() { - var ( - stream *bytes.Buffer - csc *cryptoStreamConn - ) - - BeforeEach(func() { - stream = &bytes.Buffer{} - csc = newCryptoStreamConn(stream) - }) - - It("buffers writes", func() { - _, err := csc.Write([]byte("foo")) - Expect(err).ToNot(HaveOccurred()) - Expect(stream.Len()).To(BeZero()) - _, err = csc.Write([]byte("bar")) - Expect(err).ToNot(HaveOccurred()) - Expect(stream.Len()).To(BeZero()) - - Expect(csc.Flush()).To(Succeed()) - Expect(stream.Bytes()).To(Equal([]byte("foobar"))) - }) - - It("reads from the stream", func() { - stream.Write([]byte("foobar")) - b := make([]byte, 6) - n, err := csc.Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(6)) - Expect(b).To(Equal([]byte("foobar"))) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/data_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/data_test.go deleted file mode 100644 index 238f70335..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/data_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package handshake - -import "strings" - -var sampleCHLO = []byte{0x43, 0x48, 0x4c, 0x4f, 0x10, 0x0, 0x0, 0x0, 0x50, 0x41, 0x44, 0x0, 0xf8, 0x3, 0x0, 0x0, 0x53, 0x4e, 0x49, 0x0, 0x7, 0x4, 0x0, 0x0, 0x56, 0x45, 0x52, 0x0, 0xb, 0x4, 0x0, 0x0, 0x43, 0x43, 0x53, 0x0, 0x1b, 0x4, 0x0, 0x0, 0x4d, 0x53, 0x50, 0x43, 0x1f, 0x4, 0x0, 0x0, 0x55, 0x41, 0x49, 0x44, 0x4c, 0x4, 0x0, 0x0, 0x54, 0x43, 0x49, 0x44, 0x50, 0x4, 0x0, 0x0, 0x50, 0x44, 0x4d, 0x44, 0x54, 0x4, 0x0, 0x0, 0x53, 0x52, 0x42, 0x46, 0x58, 0x4, 0x0, 0x0, 0x49, 0x43, 0x53, 0x4c, 0x5c, 0x4, 0x0, 0x0, 0x4e, 0x4f, 0x4e, 0x50, 0x7c, 0x4, 0x0, 0x0, 0x53, 0x43, 0x4c, 0x53, 0x80, 0x4, 0x0, 0x0, 0x43, 0x53, 0x43, 0x54, 0x80, 0x4, 0x0, 0x0, 0x43, 0x4f, 0x50, 0x54, 0x84, 0x4, 0x0, 0x0, 0x43, 0x46, 0x43, 0x57, 0x88, 0x4, 0x0, 0x0, 0x53, 0x46, 0x43, 0x57, 0x8c, 0x4, 0x0, 0x0, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x77, 0x77, 0x77, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x6f, 0x72, 0x67, 0x51, 0x30, 0x33, 0x30, 0x7b, 0x26, 0xe9, 0xe7, 0xe4, 0x5c, 0x71, 0xff, 0x1, 0xe8, 0x81, 0x60, 0x92, 0x92, 0x1a, 0xe8, 0x64, 0x0, 0x0, 0x0, 0x64, 0x65, 0x76, 0x20, 0x43, 0x68, 0x72, 0x6f, 0x6d, 0x65, 0x2f, 0x35, 0x31, 0x2e, 0x30, 0x2e, 0x32, 0x37, 0x30, 0x30, 0x2e, 0x30, 0x20, 0x49, 0x6e, 0x74, 0x65, 0x6c, 0x20, 0x4d, 0x61, 0x63, 0x20, 0x4f, 0x53, 0x20, 0x58, 0x20, 0x31, 0x30, 0x5f, 0x31, 0x31, 0x5f, 0x34, 0x0, 0x0, 0x0, 0x0, 0x58, 0x35, 0x30, 0x39, 0x0, 0x0, 0x10, 0x0, 0x1e, 0x0, 0x0, 0x0, 0xe1, 0x84, 0x54, 0x1b, 0xe3, 0xd6, 0x7c, 0x1f, 0x69, 0xb2, 0x4e, 0x9e, 0x46, 0xf4, 0x46, 0xdd, 0xab, 0xe5, 0xde, 0x66, 0x94, 0xf6, 0xb2, 0xee, 0x1, 0xc4, 0xa5, 0x77, 0xfe, 0xc9, 0xb, 0xa3, 0x1, 0x0, 0x0, 0x0, 0x46, 0x49, 0x58, 0x44, 0x0, 0x0, 0xf0, 0x0, 0x0, 0x0, 0x60, 0x0} - -var sampleCHLOMap = map[Tag][]byte{ - TagPAD: []byte(strings.Repeat("-", 1016)), - TagSNI: []byte("www.example.org"), - TagVER: []byte("Q030"), - TagCCS: []byte("{&\xe9\xe7\xe4\\q\xff\x01\xe8\x81`\x92\x92\x1a\xe8"), - TagMSPC: []byte("d\x00\x00\x00"), - TagUAID: []byte("dev Chrome/51.0.2700.0 Intel Mac OS X 10_11_4"), - TagTCID: []byte("\x00\x00\x00\x00"), - TagSRBF: []byte("\x00\x00\x10\x00"), - TagICSL: []byte("\x1e\x00\x00\x00"), - TagNONP: []byte("\xe1\x84T\x1b\xe3\xd6|\x1fi\xb2N\x9eF\xf4FÝ«\xe5\xdef\x94\xf6\xb2\xee\x01Ä¥w\xfe\xc9\v\xa3"), - TagSCLS: []byte("\x01\x00\x00\x00"), - TagCSCT: {}, - TagCOPT: []byte("FIXD"), - TagSFCW: []byte("\x00\x00`\x00"), - TagCFCW: []byte("\x00\x00\xf0\x00"), - TagPDMD: []byte("X509"), -} diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/ephermal_cache_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/ephermal_cache_test.go deleted file mode 100644 index 69eee338a..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/ephermal_cache_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package handshake - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Ephermal KEX", func() { - It("has a consistent KEX", func() { - kex1, err := getEphermalKEX() - Expect(err).ToNot(HaveOccurred()) - Expect(kex1).ToNot(BeNil()) - kex2, err := getEphermalKEX() - Expect(err).ToNot(HaveOccurred()) - Expect(kex2).ToNot(BeNil()) - Expect(kex1).To(Equal(kex2)) - }) - - It("changes KEX", func() { - kexLifetime = 10 * time.Millisecond - defer func() { - kexLifetime = protocol.EphermalKeyLifetime - }() - kex, err := getEphermalKEX() - Expect(err).ToNot(HaveOccurred()) - Expect(kex).ToNot(BeNil()) - time.Sleep(kexLifetime) - kex2, err := getEphermalKEX() - Expect(err).ToNot(HaveOccurred()) - Expect(kex2).ToNot(Equal(kex)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/handshake_message_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/handshake_message_test.go deleted file mode 100644 index fc96b120c..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/handshake_message_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package handshake - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/qerr" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Handshake Message", func() { - Context("when parsing", func() { - It("parses sample CHLO message", func() { - msg, err := ParseHandshakeMessage(bytes.NewReader(sampleCHLO)) - Expect(err).ToNot(HaveOccurred()) - Expect(msg.Tag).To(Equal(TagCHLO)) - Expect(msg.Data).To(Equal(sampleCHLOMap)) - }) - - It("rejects large numbers of pairs", func() { - r := bytes.NewReader([]byte("CHLO\xff\xff\xff\xff")) - _, err := ParseHandshakeMessage(r) - Expect(err).To(MatchError(qerr.CryptoTooManyEntries)) - }) - - It("rejects too long values", func() { - r := bytes.NewReader([]byte{ - 'C', 'H', 'L', 'O', - 1, 0, 0, 0, - 0, 0, 0, 0, - 0xff, 0xff, 0xff, 0xff, - }) - _, err := ParseHandshakeMessage(r) - Expect(err).To(MatchError(qerr.Error(qerr.CryptoInvalidValueLength, "value too long"))) - }) - }) - - Context("when writing", func() { - It("writes sample message", func() { - b := &bytes.Buffer{} - HandshakeMessage{Tag: TagCHLO, Data: sampleCHLOMap}.Write(b) - Expect(b.Bytes()).To(Equal(sampleCHLO)) - }) - }) - - Context("string representation", func() { - It("has a string representation", func() { - str := HandshakeMessage{ - Tag: TagSHLO, - Data: map[Tag][]byte{ - TagAEAD: []byte("foobar"), - TagEXPY: []byte("raboof"), - }, - }.String() - Expect(str[:4]).To(Equal("SHLO")) - Expect(str).To(ContainSubstring("AEAD: \"foobar\"")) - Expect(str).To(ContainSubstring("EXPY: \"raboof\"")) - }) - - It("lists padding separately", func() { - str := HandshakeMessage{ - Tag: TagSHLO, - Data: map[Tag][]byte{ - TagPAD: bytes.Repeat([]byte{0}, 1337), - }, - }.String() - Expect(str).To(ContainSubstring("PAD")) - Expect(str).To(ContainSubstring("1337 bytes")) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/handshake_suite_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/handshake_suite_test.go deleted file mode 100644 index 91f3d14ba..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/handshake_suite_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package handshake - -import ( - "github.com/golang/mock/gomock" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestQuicGo(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Handshake Suite") -} - -var mockCtrl *gomock.Controller - -var _ = BeforeEach(func() { - mockCtrl = gomock.NewController(GinkgoT()) -}) - -var _ = AfterEach(func() { - mockCtrl.Finish() -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/mock_mint_tls_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/mock_mint_tls_test.go deleted file mode 100644 index c6e7d50b8..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/mock_mint_tls_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go/internal/handshake (interfaces: MintTLS) - -// Package handshake is a generated GoMock package. -package handshake - -import ( - reflect "reflect" - - mint "github.com/bifurcation/mint" - gomock "github.com/golang/mock/gomock" -) - -// MockMintTLS is a mock of MintTLS interface -type MockMintTLS struct { - ctrl *gomock.Controller - recorder *MockMintTLSMockRecorder -} - -// MockMintTLSMockRecorder is the mock recorder for MockMintTLS -type MockMintTLSMockRecorder struct { - mock *MockMintTLS -} - -// NewMockMintTLS creates a new mock instance -func NewMockMintTLS(ctrl *gomock.Controller) *MockMintTLS { - mock := &MockMintTLS{ctrl: ctrl} - mock.recorder = &MockMintTLSMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockMintTLS) EXPECT() *MockMintTLSMockRecorder { - return m.recorder -} - -// ComputeExporter mocks base method -func (m *MockMintTLS) ComputeExporter(arg0 string, arg1 []byte, arg2 int) ([]byte, error) { - ret := m.ctrl.Call(m, "ComputeExporter", arg0, arg1, arg2) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ComputeExporter indicates an expected call of ComputeExporter -func (mr *MockMintTLSMockRecorder) ComputeExporter(arg0, arg1, arg2 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ComputeExporter", reflect.TypeOf((*MockMintTLS)(nil).ComputeExporter), arg0, arg1, arg2) -} - -// ConnectionState mocks base method -func (m *MockMintTLS) ConnectionState() mint.ConnectionState { - ret := m.ctrl.Call(m, "ConnectionState") - ret0, _ := ret[0].(mint.ConnectionState) - return ret0 -} - -// ConnectionState indicates an expected call of ConnectionState -func (mr *MockMintTLSMockRecorder) ConnectionState() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConnectionState", reflect.TypeOf((*MockMintTLS)(nil).ConnectionState)) -} - -// Handshake mocks base method -func (m *MockMintTLS) Handshake() mint.Alert { - ret := m.ctrl.Call(m, "Handshake") - ret0, _ := ret[0].(mint.Alert) - return ret0 -} - -// Handshake indicates an expected call of Handshake -func (mr *MockMintTLSMockRecorder) Handshake() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Handshake", reflect.TypeOf((*MockMintTLS)(nil).Handshake)) -} diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/server_config_client_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/server_config_client_test.go deleted file mode 100644 index d298e2f42..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/server_config_client_test.go +++ /dev/null @@ -1,266 +0,0 @@ -package handshake - -import ( - "bytes" - "time" - - "github.com/lucas-clemente/quic-go/internal/crypto" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -// This tagMap can be passed to parseValues and is garantueed to not cause any errors -func getDefaultServerConfigClient() map[Tag][]byte { - return map[Tag][]byte{ - TagSCID: bytes.Repeat([]byte{'F'}, 16), - TagKEXS: []byte("C255"), - TagAEAD: []byte("AESG"), - TagPUBS: append([]byte{0x20, 0x00, 0x00}, bytes.Repeat([]byte{0}, 32)...), - TagOBIT: bytes.Repeat([]byte{0}, 8), - TagEXPY: {0x0, 0x6c, 0x57, 0x78, 0, 0, 0, 0}, // 2033-12-24 - } -} - -var _ = Describe("Server Config", func() { - var tagMap map[Tag][]byte - - BeforeEach(func() { - tagMap = getDefaultServerConfigClient() - }) - - It("returns the parsed server config", func() { - tagMap[TagSCID] = []byte{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf} - b := &bytes.Buffer{} - HandshakeMessage{Tag: TagSCFG, Data: tagMap}.Write(b) - scfg, err := parseServerConfig(b.Bytes()) - Expect(err).ToNot(HaveOccurred()) - Expect(scfg.ID).To(Equal(tagMap[TagSCID])) - }) - - It("saves the raw server config", func() { - b := &bytes.Buffer{} - HandshakeMessage{Tag: TagSCFG, Data: tagMap}.Write(b) - scfg, err := parseServerConfig(b.Bytes()) - Expect(err).ToNot(HaveOccurred()) - Expect(scfg.raw).To(Equal(b.Bytes())) - }) - - It("tells if a server config is expired", func() { - scfg := &serverConfigClient{} - scfg.expiry = time.Now().Add(-time.Second) - Expect(scfg.IsExpired()).To(BeTrue()) - scfg.expiry = time.Now().Add(time.Second) - Expect(scfg.IsExpired()).To(BeFalse()) - }) - - Context("parsing the server config", func() { - It("rejects a handshake message with the wrong message tag", func() { - var serverConfig bytes.Buffer - HandshakeMessage{Tag: TagCHLO, Data: make(map[Tag][]byte)}.Write(&serverConfig) - _, err := parseServerConfig(serverConfig.Bytes()) - Expect(err).To(MatchError(errMessageNotServerConfig)) - }) - - It("errors on invalid handshake messages", func() { - var serverConfig bytes.Buffer - HandshakeMessage{Tag: TagSCFG, Data: make(map[Tag][]byte)}.Write(&serverConfig) - _, err := parseServerConfig(serverConfig.Bytes()[:serverConfig.Len()-2]) - Expect(err).To(MatchError("unexpected EOF")) - }) - - It("passes on errors encountered when reading the TagMap", func() { - var serverConfig bytes.Buffer - HandshakeMessage{Tag: TagSCFG, Data: make(map[Tag][]byte)}.Write(&serverConfig) - _, err := parseServerConfig(serverConfig.Bytes()) - Expect(err).To(MatchError("CryptoMessageParameterNotFound: SCID")) - }) - - It("reads an example Handshake Message", func() { - var serverConfig bytes.Buffer - HandshakeMessage{Tag: TagSCFG, Data: tagMap}.Write(&serverConfig) - scfg, err := parseServerConfig(serverConfig.Bytes()) - Expect(err).ToNot(HaveOccurred()) - Expect(scfg.ID).To(Equal(tagMap[TagSCID])) - Expect(scfg.obit).To(Equal(tagMap[TagOBIT])) - }) - }) - - Context("Reading values from the TagMap", func() { - var scfg *serverConfigClient - - BeforeEach(func() { - scfg = &serverConfigClient{} - }) - - Context("ServerConfig ID", func() { - It("parses the ServerConfig ID", func() { - id := []byte{0xb2, 0xa4, 0xbb, 0x8f, 0xf6, 0x51, 0x28, 0xfd, 0x4d, 0xf7, 0xb3, 0x9a, 0x91, 0xe7, 0x91, 0xfb} - tagMap[TagSCID] = id - err := scfg.parseValues(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(scfg.ID).To(Equal(id)) - }) - - It("errors if the ServerConfig ID is missing", func() { - delete(tagMap, TagSCID) - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoMessageParameterNotFound: SCID")) - }) - - It("rejects ServerConfig IDs that have the wrong length", func() { - tagMap[TagSCID] = bytes.Repeat([]byte{'F'}, 17) // 1 byte too long - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoInvalidValueLength: SCID")) - }) - }) - - Context("KEXS", func() { - It("rejects KEXS values that have the wrong length", func() { - tagMap[TagKEXS] = bytes.Repeat([]byte{'F'}, 5) // 1 byte too long - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoInvalidValueLength: KEXS")) - }) - - It("rejects KEXS values other than C255", func() { - tagMap[TagKEXS] = []byte("P256") - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoNoSupport: KEXS: Could not find C255, other key exchanges are not supported")) - }) - - It("errors if the KEXS is missing", func() { - delete(tagMap, TagKEXS) - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoMessageParameterNotFound: KEXS")) - }) - }) - - Context("AEAD", func() { - It("rejects AEAD values that have the wrong length", func() { - tagMap[TagAEAD] = bytes.Repeat([]byte{'F'}, 5) // 1 byte too long - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoInvalidValueLength: AEAD")) - }) - - It("rejects AEAD values other than AESG", func() { - tagMap[TagAEAD] = []byte("S20P") - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoNoSupport: AEAD")) - }) - - It("recognizes AESG in the list of AEADs, at the first position", func() { - tagMap[TagAEAD] = []byte("AESGS20P") - err := scfg.parseValues(tagMap) - Expect(err).ToNot(HaveOccurred()) - }) - - It("recognizes AESG in the list of AEADs, not at the first position", func() { - tagMap[TagAEAD] = []byte("S20PAESG") - err := scfg.parseValues(tagMap) - Expect(err).ToNot(HaveOccurred()) - }) - - It("errors if the AEAD is missing", func() { - delete(tagMap, TagAEAD) - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoMessageParameterNotFound: AEAD")) - }) - }) - - Context("PUBS", func() { - It("creates a Curve25519 key exchange", func() { - serverKex, err := crypto.NewCurve25519KEX() - Expect(err).ToNot(HaveOccurred()) - tagMap[TagPUBS] = append([]byte{0x20, 0x00, 0x00}, serverKex.PublicKey()...) - err = scfg.parseValues(tagMap) - Expect(err).ToNot(HaveOccurred()) - sharedSecret, err := serverKex.CalculateSharedKey(scfg.kex.PublicKey()) - Expect(err).ToNot(HaveOccurred()) - Expect(scfg.sharedSecret).To(Equal(sharedSecret)) - }) - - It("rejects PUBS values that have the wrong length", func() { - tagMap[TagPUBS] = bytes.Repeat([]byte{'F'}, 100) // completely wrong length - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoInvalidValueLength: PUBS")) - }) - - It("rejects PUBS values that have a zero length", func() { - tagMap[TagPUBS] = bytes.Repeat([]byte{0}, 100) // completely wrong length - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoInvalidValueLength: PUBS")) - }) - - It("ensure that C255 Pubs must not be at the first index", func() { - serverKex, err := crypto.NewCurve25519KEX() - Expect(err).ToNot(HaveOccurred()) - tagMap[TagKEXS] = []byte("P256C255") // have another KEXS before C255 - // 3 byte len + 1 byte empty + C255 - tagMap[TagPUBS] = append([]byte{0x01, 0x00, 0x00, 0x00}, append([]byte{0x20, 0x00, 0x00}, serverKex.PublicKey()...)...) - err = scfg.parseValues(tagMap) - Expect(err).ToNot(HaveOccurred()) - sharedSecret, err := serverKex.CalculateSharedKey(scfg.kex.PublicKey()) - Expect(err).ToNot(HaveOccurred()) - Expect(scfg.sharedSecret).To(Equal(sharedSecret)) - }) - - It("errors if the PUBS is missing", func() { - delete(tagMap, TagPUBS) - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoMessageParameterNotFound: PUBS")) - }) - }) - - Context("OBIT", func() { - It("parses the OBIT value", func() { - obit := []byte{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8} - tagMap[TagOBIT] = obit - err := scfg.parseValues(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(scfg.obit).To(Equal(obit)) - }) - - It("errors if the OBIT is missing", func() { - delete(tagMap, TagOBIT) - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoMessageParameterNotFound: OBIT")) - }) - - It("rejets OBIT values that have the wrong length", func() { - tagMap[TagOBIT] = bytes.Repeat([]byte{'F'}, 7) // 1 byte too short - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoInvalidValueLength: OBIT")) - }) - }) - - Context("EXPY", func() { - It("parses the expiry date", func() { - tagMap[TagEXPY] = []byte{0xdc, 0x89, 0x0e, 0x59, 0, 0, 0, 0} // UNIX Timestamp 0x590e89dc = 1494125020 - err := scfg.parseValues(tagMap) - Expect(err).ToNot(HaveOccurred()) - year, month, day := scfg.expiry.UTC().Date() - Expect(year).To(Equal(2017)) - Expect(month).To(Equal(time.Month(5))) - Expect(day).To(Equal(7)) - }) - - It("errors if the EXPY is missing", func() { - delete(tagMap, TagEXPY) - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoMessageParameterNotFound: EXPY")) - }) - - It("rejects EXPY values that have the wrong length", func() { - tagMap[TagEXPY] = bytes.Repeat([]byte{'F'}, 9) // 1 byte too long - err := scfg.parseValues(tagMap) - Expect(err).To(MatchError("CryptoInvalidValueLength: EXPY")) - }) - - It("deals with absurdly large timestamps", func() { - tagMap[TagEXPY] = bytes.Repeat([]byte{0xff}, 8) // this would overflow the int64 - err := scfg.parseValues(tagMap) - Expect(err).ToNot(HaveOccurred()) - Expect(scfg.expiry.After(time.Now())).To(BeTrue()) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/server_config_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/server_config_test.go deleted file mode 100644 index f942b4872..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/server_config_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package handshake - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/crypto" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ServerConfig", func() { - var ( - kex crypto.KeyExchange - ) - - BeforeEach(func() { - var err error - kex, err = crypto.NewCurve25519KEX() - Expect(err).NotTo(HaveOccurred()) - }) - - It("generates a random ID and OBIT", func() { - scfg1, err := NewServerConfig(kex, nil) - Expect(err).ToNot(HaveOccurred()) - scfg2, err := NewServerConfig(kex, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(scfg1.ID).ToNot(Equal(scfg2.ID)) - Expect(scfg1.obit).ToNot(Equal(scfg2.obit)) - Expect(scfg1.cookieGenerator).ToNot(Equal(scfg2.cookieGenerator)) - }) - - It("gets the proper binary representation", func() { - scfg, err := NewServerConfig(kex, nil) - Expect(err).NotTo(HaveOccurred()) - expected := bytes.NewBuffer([]byte{0x53, 0x43, 0x46, 0x47, 0x6, 0x0, 0x0, 0x0, 0x41, 0x45, 0x41, 0x44, 0x4, 0x0, 0x0, 0x0, 0x53, 0x43, 0x49, 0x44, 0x14, 0x0, 0x0, 0x0, 0x50, 0x55, 0x42, 0x53, 0x37, 0x0, 0x0, 0x0, 0x4b, 0x45, 0x58, 0x53, 0x3b, 0x0, 0x0, 0x0, 0x4f, 0x42, 0x49, 0x54, 0x43, 0x0, 0x0, 0x0, 0x45, 0x58, 0x50, 0x59, 0x4b, 0x0, 0x0, 0x0, 0x41, 0x45, 0x53, 0x47}) - expected.Write(scfg.ID) - expected.Write([]byte{0x20, 0x0, 0x0}) - expected.Write(kex.PublicKey()) - expected.Write([]byte{0x43, 0x32, 0x35, 0x35}) - expected.Write(scfg.obit) - expected.Write([]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}) - Expect(scfg.Get()).To(Equal(expected.Bytes())) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/tls_extension_handler_client_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/tls_extension_handler_client_test.go deleted file mode 100644 index bbb72f7cd..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/tls_extension_handler_client_test.go +++ /dev/null @@ -1,233 +0,0 @@ -package handshake - -import ( - "bytes" - "fmt" - "time" - - "github.com/bifurcation/mint" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("TLS Extension Handler, for the client", func() { - var ( - handler *extensionHandlerClient - el mint.ExtensionList - ) - - BeforeEach(func() { - handler = NewExtensionHandlerClient(&TransportParameters{}, protocol.VersionWhatever, nil, protocol.VersionWhatever, utils.DefaultLogger).(*extensionHandlerClient) - el = make(mint.ExtensionList, 0) - }) - - Context("sending", func() { - It("only adds TransportParameters for the ClientHello", func() { - // test 2 other handshake types - err := handler.Send(mint.HandshakeTypeCertificateRequest, &el) - Expect(err).ToNot(HaveOccurred()) - Expect(el).To(BeEmpty()) - err = handler.Send(mint.HandshakeTypeEndOfEarlyData, &el) - Expect(err).ToNot(HaveOccurred()) - Expect(el).To(BeEmpty()) - }) - - It("adds TransportParameters to the ClientHello", func() { - handler.initialVersion = 13 - err := handler.Send(mint.HandshakeTypeClientHello, &el) - Expect(err).ToNot(HaveOccurred()) - Expect(el).To(HaveLen(1)) - ext := &tlsExtensionBody{} - found, err := el.Find(ext) - Expect(err).ToNot(HaveOccurred()) - Expect(found).To(BeTrue()) - chtp := &clientHelloTransportParameters{} - err = chtp.Unmarshal(ext.data) - Expect(err).ToNot(HaveOccurred()) - Expect(chtp.InitialVersion).To(BeEquivalentTo(13)) - }) - }) - - Context("receiving", func() { - var fakeBody *tlsExtensionBody - var parameters TransportParameters - - addEncryptedExtensionsWithParameters := func(params TransportParameters) { - body := (&encryptedExtensionsTransportParameters{ - Parameters: params, - SupportedVersions: []protocol.VersionNumber{handler.version}, - }).Marshal() - Expect(el.Add(&tlsExtensionBody{data: body})).To(Succeed()) - } - - BeforeEach(func() { - fakeBody = &tlsExtensionBody{data: []byte("foobar foobar")} - parameters = TransportParameters{ - IdleTimeout: 0x1337 * time.Second, - StatelessResetToken: bytes.Repeat([]byte{0}, 16), - } - }) - - It("blocks until the transport parameters are read", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - addEncryptedExtensionsWithParameters(parameters) - err := handler.Receive(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - Consistently(done).ShouldNot(BeClosed()) - Expect(handler.GetPeerParams()).To(Receive()) - Eventually(done).Should(BeClosed()) - }) - - It("accepts the TransportParameters on the EncryptedExtensions message", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - addEncryptedExtensionsWithParameters(parameters) - err := handler.Receive(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - var params TransportParameters - Eventually(handler.GetPeerParams()).Should(Receive(¶ms)) - Expect(params.IdleTimeout).To(Equal(0x1337 * time.Second)) - Eventually(done).Should(BeClosed()) - }) - - It("errors if the EncryptedExtensions message doesn't contain TransportParameters", func() { - err := handler.Receive(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).To(MatchError("EncryptedExtensions message didn't contain a QUIC extension")) - }) - - It("rejects the TransportParameters on a wrong handshake types", func() { - err := el.Add(fakeBody) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeCertificate, &el) - Expect(err).To(MatchError(fmt.Sprintf("Unexpected QUIC extension in handshake message %d", mint.HandshakeTypeCertificate))) - }) - - It("ignores messages without TransportParameters, if they are not required", func() { - err := handler.Receive(mint.HandshakeTypeCertificate, &el) - Expect(err).ToNot(HaveOccurred()) - }) - - It("errors when it can't parse the TransportParameters", func() { - err := el.Add(fakeBody) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).To(HaveOccurred()) // this will be some kind of decoding error - }) - - It("rejects TransportParameters if they don't contain the stateless reset token", func() { - parameters.StatelessResetToken = nil - addEncryptedExtensionsWithParameters(parameters) - err := handler.Receive(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).To(MatchError("server didn't sent stateless_reset_token")) - }) - - Context("Version Negotiation", func() { - It("accepts a valid version negotiation", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - Eventually(handler.GetPeerParams()).Should(Receive()) - close(done) - }() - - handler.initialVersion = 13 - handler.version = 37 - handler.supportedVersions = []protocol.VersionNumber{13, 37, 42} - body := (&encryptedExtensionsTransportParameters{ - Parameters: parameters, - NegotiatedVersion: 37, - SupportedVersions: []protocol.VersionNumber{36, 37, 38}, - }).Marshal() - err := el.Add(&tlsExtensionBody{data: body}) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).ToNot(HaveOccurred()) - Eventually(done).Should(BeClosed()) - }) - - It("errors if the current version doesn't match negotiated_version", func() { - handler.initialVersion = 13 - handler.version = 37 - handler.supportedVersions = []protocol.VersionNumber{13, 37, 42} - body := (&encryptedExtensionsTransportParameters{ - Parameters: parameters, - NegotiatedVersion: 38, - SupportedVersions: []protocol.VersionNumber{36, 37, 38}, - }).Marshal() - err := el.Add(&tlsExtensionBody{data: body}) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).To(MatchError("VersionNegotiationMismatch: current version doesn't match negotiated_version")) - }) - - It("errors if the current version is not contained in the server's supported versions", func() { - handler.version = 42 - body := (&encryptedExtensionsTransportParameters{ - NegotiatedVersion: 42, - SupportedVersions: []protocol.VersionNumber{43, 44}, - }).Marshal() - err := el.Add(&tlsExtensionBody{data: body}) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).To(MatchError("VersionNegotiationMismatch: current version not included in the supported versions")) - }) - - It("errors if version negotiation was performed, but would have picked a different version based on the supported version list", func() { - handler.version = 42 - handler.initialVersion = 41 - handler.supportedVersions = []protocol.VersionNumber{43, 42, 41} - serverSupportedVersions := []protocol.VersionNumber{42, 43} - // check that version negotiation would have led us to pick version 43 - ver, ok := protocol.ChooseSupportedVersion(handler.supportedVersions, serverSupportedVersions) - Expect(ok).To(BeTrue()) - Expect(ver).To(Equal(protocol.VersionNumber(43))) - body := (&encryptedExtensionsTransportParameters{ - NegotiatedVersion: 42, - SupportedVersions: serverSupportedVersions, - }).Marshal() - err := el.Add(&tlsExtensionBody{data: body}) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).To(MatchError("VersionNegotiationMismatch: would have picked a different version")) - }) - - It("doesn't error if it would have picked a different version based on the supported version list, if no version negotiation was performed", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - Eventually(handler.GetPeerParams()).Should(Receive()) - close(done) - }() - - handler.version = 42 - handler.initialVersion = 42 // version == initialVersion means no version negotiation was performed - handler.supportedVersions = []protocol.VersionNumber{43, 42, 41} - serverSupportedVersions := []protocol.VersionNumber{42, 43} - // check that version negotiation would have led us to pick version 43 - ver, ok := protocol.ChooseSupportedVersion(handler.supportedVersions, serverSupportedVersions) - Expect(ok).To(BeTrue()) - Expect(ver).To(Equal(protocol.VersionNumber(43))) - body := (&encryptedExtensionsTransportParameters{ - Parameters: parameters, - NegotiatedVersion: 42, - SupportedVersions: serverSupportedVersions, - }).Marshal() - err := el.Add(&tlsExtensionBody{data: body}) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).ToNot(HaveOccurred()) - Eventually(done).Should(BeClosed()) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/tls_extension_handler_server_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/tls_extension_handler_server_test.go deleted file mode 100644 index 9563febe4..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/tls_extension_handler_server_test.go +++ /dev/null @@ -1,155 +0,0 @@ -package handshake - -import ( - "bytes" - "fmt" - "time" - - "github.com/bifurcation/mint" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("TLS Extension Handler, for the server", func() { - var ( - handler *extensionHandlerServer - el mint.ExtensionList - ) - - BeforeEach(func() { - handler = NewExtensionHandlerServer(&TransportParameters{}, nil, protocol.VersionWhatever, utils.DefaultLogger).(*extensionHandlerServer) - el = make(mint.ExtensionList, 0) - }) - - Context("sending", func() { - It("only adds TransportParameters for the ClientHello", func() { - // test 2 other handshake types - err := handler.Send(mint.HandshakeTypeCertificateRequest, &el) - Expect(err).ToNot(HaveOccurred()) - Expect(el).To(BeEmpty()) - err = handler.Send(mint.HandshakeTypeEndOfEarlyData, &el) - Expect(err).ToNot(HaveOccurred()) - Expect(el).To(BeEmpty()) - }) - - It("adds TransportParameters to the EncryptedExtensions message", func() { - handler.version = 666 - versions := []protocol.VersionNumber{13, 37, 42} - handler.supportedVersions = versions - err := handler.Send(mint.HandshakeTypeEncryptedExtensions, &el) - Expect(err).ToNot(HaveOccurred()) - Expect(el).To(HaveLen(1)) - ext := &tlsExtensionBody{} - found, err := el.Find(ext) - Expect(err).ToNot(HaveOccurred()) - Expect(found).To(BeTrue()) - eetp := &encryptedExtensionsTransportParameters{} - err = eetp.Unmarshal(ext.data) - Expect(err).ToNot(HaveOccurred()) - Expect(eetp.NegotiatedVersion).To(BeEquivalentTo(666)) - // the SupportedVersions will contain one reserved version number - Expect(eetp.SupportedVersions).To(HaveLen(len(versions) + 1)) - for _, version := range versions { - Expect(eetp.SupportedVersions).To(ContainElement(version)) - } - }) - }) - - Context("receiving", func() { - var ( - fakeBody *tlsExtensionBody - parameters TransportParameters - ) - - addClientHelloWithParameters := func(params TransportParameters) { - body := (&clientHelloTransportParameters{Parameters: params}).Marshal() - Expect(el.Add(&tlsExtensionBody{data: body})).To(Succeed()) - } - - BeforeEach(func() { - fakeBody = &tlsExtensionBody{data: []byte("foobar foobar")} - parameters = TransportParameters{IdleTimeout: 0x1337 * time.Second} - }) - - It("accepts the TransportParameters on the EncryptedExtensions message", func() { - addClientHelloWithParameters(parameters) - err := handler.Receive(mint.HandshakeTypeClientHello, &el) - Expect(err).ToNot(HaveOccurred()) - var params TransportParameters - Expect(handler.GetPeerParams()).To(Receive(¶ms)) - Expect(params.IdleTimeout).To(Equal(0x1337 * time.Second)) - }) - - It("errors if the ClientHello doesn't contain TransportParameters", func() { - err := handler.Receive(mint.HandshakeTypeClientHello, &el) - Expect(err).To(MatchError("ClientHello didn't contain a QUIC extension")) - }) - - It("ignores messages without TransportParameters, if they are not required", func() { - err := handler.Receive(mint.HandshakeTypeCertificate, &el) - Expect(err).ToNot(HaveOccurred()) - }) - - It("errors if it can't unmarshal the TransportParameters", func() { - err := el.Add(fakeBody) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeClientHello, &el) - Expect(err).To(HaveOccurred()) // this will be some kind of decoding error - }) - - It("rejects messages other than the ClientHello that contain TransportParameters", func() { - addClientHelloWithParameters(parameters) - err := handler.Receive(mint.HandshakeTypeCertificateRequest, &el) - Expect(err).To(MatchError(fmt.Sprintf("Unexpected QUIC extension in handshake message %d", mint.HandshakeTypeCertificateRequest))) - }) - - It("rejects messages that contain a stateless reset token", func() { - parameters.StatelessResetToken = bytes.Repeat([]byte{0}, 16) - addClientHelloWithParameters(parameters) - err := handler.Receive(mint.HandshakeTypeClientHello, &el) - Expect(err).To(MatchError("client sent a stateless reset token")) - }) - - Context("Version Negotiation", func() { - It("accepts a ClientHello, when no version negotiation was performed", func() { - handler.version = 42 - body := (&clientHelloTransportParameters{ - InitialVersion: 42, - Parameters: parameters, - }).Marshal() - err := el.Add(&tlsExtensionBody{data: body}) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeClientHello, &el) - Expect(err).ToNot(HaveOccurred()) - }) - - It("accepts a valid version negotiation", func() { - handler.version = 42 - handler.supportedVersions = []protocol.VersionNumber{13, 37, 42} - body := (&clientHelloTransportParameters{ - InitialVersion: 22, // this must be an unsupported version - Parameters: parameters, - }).Marshal() - err := el.Add(&tlsExtensionBody{data: body}) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeClientHello, &el) - Expect(err).ToNot(HaveOccurred()) - }) - - It("erros when a version negotiation was performed, although we already support the initial version", func() { - handler.supportedVersions = []protocol.VersionNumber{11, 12, 13} - handler.version = 13 - body := (&clientHelloTransportParameters{ - InitialVersion: 11, // this is an supported version - }).Marshal() - err := el.Add(&tlsExtensionBody{data: body}) - Expect(err).ToNot(HaveOccurred()) - err = handler.Receive(mint.HandshakeTypeClientHello, &el) - Expect(err).To(MatchError("VersionNegotiationMismatch: Client should have used the initial version")) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/tls_extension_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/tls_extension_test.go deleted file mode 100644 index ef0a6dc0f..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/tls_extension_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package handshake - -import ( - "math/rand" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("TLS extension body", func() { - Context("Client Hello Transport Parameters", func() { - It("marshals and unmarshals", func() { - chtp := &clientHelloTransportParameters{ - InitialVersion: 0x123456, - Parameters: TransportParameters{ - StreamFlowControlWindow: 0x42, - IdleTimeout: 0x1337 * time.Second, - }, - } - chtp2 := &clientHelloTransportParameters{} - Expect(chtp2.Unmarshal(chtp.Marshal())).To(Succeed()) - Expect(chtp2.InitialVersion).To(Equal(chtp.InitialVersion)) - Expect(chtp2.Parameters.StreamFlowControlWindow).To(Equal(chtp.Parameters.StreamFlowControlWindow)) - Expect(chtp2.Parameters.IdleTimeout).To(Equal(chtp.Parameters.IdleTimeout)) - }) - - It("fuzzes", func() { - rand := rand.New(rand.NewSource(GinkgoRandomSeed())) - b := make([]byte, 100) - for i := 0; i < 1000; i++ { - rand.Read(b) - chtp := &clientHelloTransportParameters{} - chtp.Unmarshal(b[:int(rand.Int31n(100))]) - } - }) - }) - - Context("Encrypted Extensions Transport Parameters", func() { - It("marshals and unmarshals", func() { - eetp := &encryptedExtensionsTransportParameters{ - NegotiatedVersion: 0x123456, - SupportedVersions: []protocol.VersionNumber{0x42, 0x4242}, - Parameters: TransportParameters{ - StreamFlowControlWindow: 0x42, - IdleTimeout: 0x1337 * time.Second, - }, - } - eetp2 := &encryptedExtensionsTransportParameters{} - Expect(eetp2.Unmarshal(eetp.Marshal())).To(Succeed()) - Expect(eetp2.NegotiatedVersion).To(Equal(eetp.NegotiatedVersion)) - Expect(eetp2.SupportedVersions).To(Equal(eetp.SupportedVersions)) - Expect(eetp2.Parameters.StreamFlowControlWindow).To(Equal(eetp.Parameters.StreamFlowControlWindow)) - Expect(eetp2.Parameters.IdleTimeout).To(Equal(eetp.Parameters.IdleTimeout)) - }) - - It("fuzzes", func() { - rand := rand.New(rand.NewSource(GinkgoRandomSeed())) - b := make([]byte, 100) - for i := 0; i < 1000; i++ { - rand.Read(b) - chtp := &encryptedExtensionsTransportParameters{} - chtp.Unmarshal(b[:int(rand.Int31n(100))]) - } - }) - }) - - Context("TLS Extension Body", func() { - var extBody *tlsExtensionBody - - BeforeEach(func() { - extBody = &tlsExtensionBody{} - }) - - It("has the right TLS extension type", func() { - Expect(extBody.Type()).To(BeEquivalentTo(quicTLSExtensionType)) - }) - - It("saves the body when unmarshalling", func() { - n, err := extBody.Unmarshal([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(6)) - Expect(extBody.data).To(Equal([]byte("foobar"))) - }) - - It("returns the body when marshalling", func() { - extBody.data = []byte("foo") - data, err := extBody.Marshal() - Expect(err).ToNot(HaveOccurred()) - Expect(data).To(Equal([]byte("foo"))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/handshake/transport_parameter_test.go b/vendor/lucas-clemente/quic-go/internal/handshake/transport_parameter_test.go deleted file mode 100644 index 34637a205..000000000 --- a/vendor/lucas-clemente/quic-go/internal/handshake/transport_parameter_test.go +++ /dev/null @@ -1,265 +0,0 @@ -package handshake - -import ( - "bytes" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Transport Parameters", func() { - Context("for gQUIC", func() { - Context("parsing", func() { - It("sets all values", func() { - values := map[Tag][]byte{ - TagSFCW: {0xad, 0xfb, 0xca, 0xde}, - TagCFCW: {0xef, 0xbe, 0xad, 0xde}, - TagICSL: {0x0d, 0xf0, 0xad, 0xba}, - TagMIDS: {0xff, 0x10, 0x00, 0xc0}, - } - params, err := readHelloMap(values) - Expect(err).ToNot(HaveOccurred()) - Expect(params.StreamFlowControlWindow).To(Equal(protocol.ByteCount(0xdecafbad))) - Expect(params.ConnectionFlowControlWindow).To(Equal(protocol.ByteCount(0xdeadbeef))) - Expect(params.IdleTimeout).To(Equal(time.Duration(0xbaadf00d) * time.Second)) - Expect(params.MaxStreams).To(Equal(uint32(0xc00010ff))) - Expect(params.OmitConnectionID).To(BeFalse()) - }) - - It("reads if the connection ID should be omitted", func() { - values := map[Tag][]byte{TagTCID: {0, 0, 0, 0}} - params, err := readHelloMap(values) - Expect(err).ToNot(HaveOccurred()) - Expect(params.OmitConnectionID).To(BeTrue()) - }) - - It("doesn't allow idle timeouts below the minimum remote idle timeout", func() { - t := 2 * time.Second - Expect(t).To(BeNumerically("<", protocol.MinRemoteIdleTimeout)) - values := map[Tag][]byte{ - TagICSL: {uint8(t.Seconds()), 0, 0, 0}, - } - params, err := readHelloMap(values) - Expect(err).ToNot(HaveOccurred()) - Expect(params.IdleTimeout).To(Equal(protocol.MinRemoteIdleTimeout)) - }) - - It("errors when given an invalid SFCW value", func() { - values := map[Tag][]byte{TagSFCW: {2, 0, 0}} // 1 byte too short - _, err := readHelloMap(values) - Expect(err).To(MatchError(errMalformedTag)) - }) - - It("errors when given an invalid CFCW value", func() { - values := map[Tag][]byte{TagCFCW: {2, 0, 0}} // 1 byte too short - _, err := readHelloMap(values) - Expect(err).To(MatchError(errMalformedTag)) - }) - - It("errors when given an invalid TCID value", func() { - values := map[Tag][]byte{TagTCID: {2, 0, 0}} // 1 byte too short - _, err := readHelloMap(values) - Expect(err).To(MatchError(errMalformedTag)) - }) - - It("errors when given an invalid ICSL value", func() { - values := map[Tag][]byte{TagICSL: {2, 0, 0}} // 1 byte too short - _, err := readHelloMap(values) - Expect(err).To(MatchError(errMalformedTag)) - }) - - It("errors when given an invalid MIDS value", func() { - values := map[Tag][]byte{TagMIDS: {2, 0, 0}} // 1 byte too short - _, err := readHelloMap(values) - Expect(err).To(MatchError(errMalformedTag)) - }) - }) - - Context("writing", func() { - It("returns all necessary parameters ", func() { - params := &TransportParameters{ - StreamFlowControlWindow: 0xdeadbeef, - ConnectionFlowControlWindow: 0xdecafbad, - IdleTimeout: 0xbaaaaaad * time.Second, - MaxStreams: 0x1337, - } - entryMap := params.getHelloMap() - Expect(entryMap).To(HaveLen(4)) - Expect(entryMap).ToNot(HaveKey(TagTCID)) - Expect(entryMap).To(HaveKeyWithValue(TagSFCW, []byte{0xef, 0xbe, 0xad, 0xde})) - Expect(entryMap).To(HaveKeyWithValue(TagCFCW, []byte{0xad, 0xfb, 0xca, 0xde})) - Expect(entryMap).To(HaveKeyWithValue(TagICSL, []byte{0xad, 0xaa, 0xaa, 0xba})) - Expect(entryMap).To(HaveKeyWithValue(TagMIDS, []byte{0x37, 0x13, 0, 0})) - }) - - It("requests omission of the connection ID", func() { - params := &TransportParameters{OmitConnectionID: true} - entryMap := params.getHelloMap() - Expect(entryMap).To(HaveKeyWithValue(TagTCID, []byte{0, 0, 0, 0})) - }) - }) - }) - - Context("for TLS", func() { - It("has a string representation", func() { - p := &TransportParameters{ - StreamFlowControlWindow: 0x1234, - ConnectionFlowControlWindow: 0x4321, - MaxBidiStreams: 1337, - MaxUniStreams: 7331, - IdleTimeout: 42 * time.Second, - } - Expect(p.String()).To(Equal("&handshake.TransportParameters{StreamFlowControlWindow: 0x1234, ConnectionFlowControlWindow: 0x4321, MaxBidiStreams: 1337, MaxUniStreams: 7331, IdleTimeout: 42s}")) - }) - - Context("parsing", func() { - var ( - params *TransportParameters - parameters map[transportParameterID][]byte - statelessResetToken []byte - ) - - marshal := func(p map[transportParameterID][]byte) []byte { - b := &bytes.Buffer{} - for id, val := range p { - utils.BigEndian.WriteUint16(b, uint16(id)) - utils.BigEndian.WriteUint16(b, uint16(len(val))) - b.Write(val) - } - return b.Bytes() - } - - BeforeEach(func() { - params = &TransportParameters{} - statelessResetToken = bytes.Repeat([]byte{42}, 16) - parameters = map[transportParameterID][]byte{ - initialMaxStreamDataParameterID: {0x11, 0x22, 0x33, 0x44}, - initialMaxDataParameterID: {0x22, 0x33, 0x44, 0x55}, - initialMaxBidiStreamsParameterID: {0x33, 0x44}, - initialMaxUniStreamsParameterID: {0x44, 0x55}, - idleTimeoutParameterID: {0x13, 0x37}, - maxPacketSizeParameterID: {0x73, 0x31}, - disableMigrationParameterID: {}, - statelessResetTokenParameterID: statelessResetToken, - } - }) - It("reads parameters", func() { - err := params.unmarshal(marshal(parameters)) - Expect(err).ToNot(HaveOccurred()) - Expect(params.StreamFlowControlWindow).To(Equal(protocol.ByteCount(0x11223344))) - Expect(params.ConnectionFlowControlWindow).To(Equal(protocol.ByteCount(0x22334455))) - Expect(params.MaxBidiStreams).To(Equal(uint16(0x3344))) - Expect(params.MaxUniStreams).To(Equal(uint16(0x4455))) - Expect(params.IdleTimeout).To(Equal(0x1337 * time.Second)) - Expect(params.OmitConnectionID).To(BeFalse()) - Expect(params.MaxPacketSize).To(Equal(protocol.ByteCount(0x7331))) - Expect(params.DisableMigration).To(BeTrue()) - Expect(params.StatelessResetToken).To(Equal(statelessResetToken)) - }) - - It("rejects the parameters if the idle_timeout is missing", func() { - delete(parameters, idleTimeoutParameterID) - err := params.unmarshal(marshal(parameters)) - Expect(err).To(MatchError("missing parameter")) - }) - - It("doesn't allow values below the minimum remote idle timeout", func() { - t := 2 * time.Second - Expect(t).To(BeNumerically("<", protocol.MinRemoteIdleTimeout)) - parameters[idleTimeoutParameterID] = []byte{0, uint8(t.Seconds())} - err := params.unmarshal(marshal(parameters)) - Expect(err).ToNot(HaveOccurred()) - Expect(params.IdleTimeout).To(Equal(protocol.MinRemoteIdleTimeout)) - }) - - It("rejects the parameters if the initial_max_stream_data has the wrong length", func() { - parameters[initialMaxStreamDataParameterID] = []byte{0x11, 0x22, 0x33} // should be 4 bytes - err := params.unmarshal(marshal(parameters)) - Expect(err).To(MatchError("wrong length for initial_max_stream_data: 3 (expected 4)")) - }) - - It("rejects the parameters if the initial_max_data has the wrong length", func() { - parameters[initialMaxDataParameterID] = []byte{0x11, 0x22, 0x33} // should be 4 bytes - err := params.unmarshal(marshal(parameters)) - Expect(err).To(MatchError("wrong length for initial_max_data: 3 (expected 4)")) - }) - - It("rejects the parameters if the initial_max_stream_id_bidi has the wrong length", func() { - parameters[initialMaxBidiStreamsParameterID] = []byte{0x11, 0x22, 0x33} // should be 2 bytes - err := params.unmarshal(marshal(parameters)) - Expect(err).To(MatchError("wrong length for initial_max_stream_id_bidi: 3 (expected 2)")) - }) - - It("rejects the parameters if the initial_max_stream_id_bidi has the wrong length", func() { - parameters[initialMaxUniStreamsParameterID] = []byte{0x11, 0x22, 0x33} // should be 2 bytes - err := params.unmarshal(marshal(parameters)) - Expect(err).To(MatchError("wrong length for initial_max_stream_id_uni: 3 (expected 2)")) - }) - - It("rejects the parameters if the initial_idle_timeout has the wrong length", func() { - parameters[idleTimeoutParameterID] = []byte{0x11, 0x22, 0x33} // should be 2 bytes - err := params.unmarshal(marshal(parameters)) - Expect(err).To(MatchError("wrong length for idle_timeout: 3 (expected 2)")) - }) - - It("rejects the parameters if max_packet_size has the wrong length", func() { - parameters[maxPacketSizeParameterID] = []byte{0x11} // should be 2 bytes - err := params.unmarshal(marshal(parameters)) - Expect(err).To(MatchError("wrong length for max_packet_size: 1 (expected 2)")) - }) - - It("rejects max_packet_sizes smaller than 1200 bytes", func() { - parameters[maxPacketSizeParameterID] = []byte{0x4, 0xaf} // 0x4af = 1199 - err := params.unmarshal(marshal(parameters)) - Expect(err).To(MatchError("invalid value for max_packet_size: 1199 (minimum 1200)")) - }) - - It("rejects the parameters if disable_connection_migration has the wrong length", func() { - parameters[disableMigrationParameterID] = []byte{0x11} // should empty - err := params.unmarshal(marshal(parameters)) - Expect(err).To(MatchError("wrong length for disable_migration: 1 (expected empty)")) - }) - - It("rejects the parameters if the stateless_reset_token has the wrong length", func() { - parameters[statelessResetTokenParameterID] = statelessResetToken[1:] - err := params.unmarshal(marshal(parameters)) - Expect(err).To(MatchError("wrong length for stateless_reset_token: 15 (expected 16)")) - }) - - It("ignores unknown parameters", func() { - parameters[1337] = []byte{42} - err := params.unmarshal(marshal(parameters)) - Expect(err).ToNot(HaveOccurred()) - }) - }) - - Context("marshalling", func() { - It("marshals", func() { - params := &TransportParameters{ - StreamFlowControlWindow: 0xdeadbeef, - ConnectionFlowControlWindow: 0xdecafbad, - IdleTimeout: 0xcafe * time.Second, - MaxBidiStreams: 0x1234, - MaxUniStreams: 0x4321, - DisableMigration: true, - StatelessResetToken: bytes.Repeat([]byte{100}, 16), - } - b := &bytes.Buffer{} - params.marshal(b) - - p := &TransportParameters{} - Expect(p.unmarshal(b.Bytes())).To(Succeed()) - Expect(p.StreamFlowControlWindow).To(Equal(params.StreamFlowControlWindow)) - Expect(p.ConnectionFlowControlWindow).To(Equal(params.ConnectionFlowControlWindow)) - Expect(p.MaxUniStreams).To(Equal(params.MaxUniStreams)) - Expect(p.MaxBidiStreams).To(Equal(params.MaxBidiStreams)) - Expect(p.IdleTimeout).To(Equal(params.IdleTimeout)) - Expect(p.DisableMigration).To(Equal(params.DisableMigration)) - Expect(p.StatelessResetToken).To(Equal(params.StatelessResetToken)) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/protocol/connection_id_test.go b/vendor/lucas-clemente/quic-go/internal/protocol/connection_id_test.go deleted file mode 100644 index f0c7f7cc4..000000000 --- a/vendor/lucas-clemente/quic-go/internal/protocol/connection_id_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package protocol - -import ( - "bytes" - "io" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Connection ID generation", func() { - It("generates random connection IDs", func() { - c1, err := GenerateConnectionID(8) - Expect(err).ToNot(HaveOccurred()) - Expect(c1).ToNot(BeZero()) - c2, err := GenerateConnectionID(8) - Expect(err).ToNot(HaveOccurred()) - Expect(c1).ToNot(Equal(c2)) - }) - - It("generates connection IDs with the requested length", func() { - c, err := GenerateConnectionID(5) - Expect(err).ToNot(HaveOccurred()) - Expect(c.Len()).To(Equal(5)) - }) - - It("generates random length destination connection IDs", func() { - var has8ByteConnID, has18ByteConnID bool - for i := 0; i < 1000; i++ { - c, err := GenerateConnectionIDForInitial() - Expect(err).ToNot(HaveOccurred()) - Expect(c.Len()).To(BeNumerically(">=", 8)) - Expect(c.Len()).To(BeNumerically("<=", 18)) - if c.Len() == 8 { - has8ByteConnID = true - } - if c.Len() == 18 { - has18ByteConnID = true - } - } - Expect(has8ByteConnID).To(BeTrue()) - Expect(has18ByteConnID).To(BeTrue()) - }) - - It("says if connection IDs are equal", func() { - c1 := ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - c2 := ConnectionID{8, 7, 6, 5, 4, 3, 2, 1} - Expect(c1.Equal(c1)).To(BeTrue()) - Expect(c2.Equal(c2)).To(BeTrue()) - Expect(c1.Equal(c2)).To(BeFalse()) - Expect(c2.Equal(c1)).To(BeFalse()) - }) - - It("reads the connection ID", func() { - buf := bytes.NewBuffer([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9}) - c, err := ReadConnectionID(buf, 9) - Expect(err).ToNot(HaveOccurred()) - Expect(c.Bytes()).To(Equal([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9})) - }) - - It("returns io.EOF if there's not enough data to read", func() { - buf := bytes.NewBuffer([]byte{1, 2, 3, 4}) - _, err := ReadConnectionID(buf, 5) - Expect(err).To(MatchError(io.EOF)) - }) - - It("returns nil for a 0 length connection ID", func() { - buf := bytes.NewBuffer([]byte{1, 2, 3, 4}) - c, err := ReadConnectionID(buf, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(c).To(BeNil()) - }) - - It("returns the length", func() { - c := ConnectionID{1, 2, 3, 4, 5, 6, 7} - Expect(c.Len()).To(Equal(7)) - }) - - It("has 0 length for the default value", func() { - var c ConnectionID - Expect(c.Len()).To(BeZero()) - }) - - It("returns the bytes", func() { - c := ConnectionID([]byte{1, 2, 3, 4, 5, 6, 7}) - Expect(c.Bytes()).To(Equal([]byte{1, 2, 3, 4, 5, 6, 7})) - }) - - It("returns a nil byte slice for the default value", func() { - var c ConnectionID - Expect(c.Bytes()).To(BeNil()) - }) - - It("has a string representation", func() { - c := ConnectionID([]byte{0xde, 0xad, 0xbe, 0xef, 0x42}) - Expect(c.String()).To(Equal("0xdeadbeef42")) - }) - - It("has a long string representation", func() { - c := ConnectionID{0x13, 0x37, 0, 0, 0xde, 0xca, 0xfb, 0xad} - Expect(c.String()).To(Equal("0x13370000decafbad")) - }) - - It("has a string representation for the default value", func() { - var c ConnectionID - Expect(c.String()).To(Equal("(empty)")) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/protocol/encryption_level_test.go b/vendor/lucas-clemente/quic-go/internal/protocol/encryption_level_test.go deleted file mode 100644 index 12a40d060..000000000 --- a/vendor/lucas-clemente/quic-go/internal/protocol/encryption_level_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package protocol - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Encryption Level", func() { - It("has the correct string representation", func() { - Expect(EncryptionUnspecified.String()).To(Equal("unknown")) - Expect(EncryptionUnencrypted.String()).To(Equal("unencrypted")) - Expect(EncryptionSecure.String()).To(Equal("encrypted (not forward-secure)")) - Expect(EncryptionForwardSecure.String()).To(Equal("forward-secure")) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/protocol/packet_number_test.go b/vendor/lucas-clemente/quic-go/internal/protocol/packet_number_test.go deleted file mode 100644 index ef5a5e9bd..000000000 --- a/vendor/lucas-clemente/quic-go/internal/protocol/packet_number_test.go +++ /dev/null @@ -1,244 +0,0 @@ -package protocol - -import ( - "fmt" - "math" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -// Tests taken and extended from chrome -var _ = Describe("packet number calculation", func() { - Context("infering a packet number", func() { - getEpoch := func(len PacketNumberLen, v VersionNumber) uint64 { - if v.UsesVarintPacketNumbers() { - switch len { - case PacketNumberLen1: - return uint64(1) << 7 - case PacketNumberLen2: - return uint64(1) << 14 - case PacketNumberLen4: - return uint64(1) << 30 - default: - Fail("invalid packet number len") - } - } - return uint64(1) << (len * 8) - } - check := func(length PacketNumberLen, expected, last uint64, v VersionNumber) { - epoch := getEpoch(length, v) - epochMask := epoch - 1 - wirePacketNumber := expected & epochMask - Expect(InferPacketNumber(length, PacketNumber(last), PacketNumber(wirePacketNumber), v)).To(Equal(PacketNumber(expected))) - } - - for _, v := range []VersionNumber{Version39, VersionTLS} { - version := v - - Context(fmt.Sprintf("using varint packet numbers: %t", version.UsesVarintPacketNumbers()), func() { - for _, l := range []PacketNumberLen{PacketNumberLen1, PacketNumberLen2, PacketNumberLen4} { - length := l - - Context(fmt.Sprintf("with %d bytes", length), func() { - epoch := getEpoch(length, version) - epochMask := epoch - 1 - - It("works near epoch start", func() { - // A few quick manual sanity check - check(length, 1, 0, version) - check(length, epoch+1, epochMask, version) - check(length, epoch, epochMask, version) - - // Cases where the last number was close to the start of the range. - for last := uint64(0); last < 10; last++ { - // Small numbers should not wrap (even if they're out of order). - for j := uint64(0); j < 10; j++ { - check(length, j, last, version) - } - - // Large numbers should not wrap either (because we're near 0 already). - for j := uint64(0); j < 10; j++ { - check(length, epoch-1-j, last, version) - } - } - }) - - It("works near epoch end", func() { - // Cases where the last number was close to the end of the range - for i := uint64(0); i < 10; i++ { - last := epoch - i - - // Small numbers should wrap. - for j := uint64(0); j < 10; j++ { - check(length, epoch+j, last, version) - } - - // Large numbers should not (even if they're out of order). - for j := uint64(0); j < 10; j++ { - check(length, epoch-1-j, last, version) - } - } - }) - - // Next check where we're in a non-zero epoch to verify we handle - // reverse wrapping, too. - It("works near previous epoch", func() { - prevEpoch := 1 * epoch - curEpoch := 2 * epoch - // Cases where the last number was close to the start of the range - for i := uint64(0); i < 10; i++ { - last := curEpoch + i - // Small number should not wrap (even if they're out of order). - for j := uint64(0); j < 10; j++ { - check(length, curEpoch+j, last, version) - } - - // But large numbers should reverse wrap. - for j := uint64(0); j < 10; j++ { - num := epoch - 1 - j - check(length, prevEpoch+num, last, version) - } - } - }) - - It("works near next epoch", func() { - curEpoch := 2 * epoch - nextEpoch := 3 * epoch - // Cases where the last number was close to the end of the range - for i := uint64(0); i < 10; i++ { - last := nextEpoch - 1 - i - - // Small numbers should wrap. - for j := uint64(0); j < 10; j++ { - check(length, nextEpoch+j, last, version) - } - - // but large numbers should not (even if they're out of order). - for j := uint64(0); j < 10; j++ { - num := epoch - 1 - j - check(length, curEpoch+num, last, version) - } - } - }) - - It("works near next max", func() { - maxNumber := uint64(math.MaxUint64) - maxEpoch := maxNumber & ^epochMask - - // Cases where the last number was close to the end of the range - for i := uint64(0); i < 10; i++ { - // Subtract 1, because the expected next packet number is 1 more than the - // last packet number. - last := maxNumber - i - 1 - - // Small numbers should not wrap, because they have nowhere to go. - for j := uint64(0); j < 10; j++ { - check(length, maxEpoch+j, last, version) - } - - // Large numbers should not wrap either. - for j := uint64(0); j < 10; j++ { - num := epoch - 1 - j - check(length, maxEpoch+num, last, version) - } - } - }) - }) - } - - Context("shortening a packet number for the header", func() { - Context("shortening", func() { - It("sends out low packet numbers as 2 byte", func() { - length := GetPacketNumberLengthForHeader(4, 2, version) - Expect(length).To(Equal(PacketNumberLen2)) - }) - - It("sends out high packet numbers as 2 byte, if all ACKs are received", func() { - length := GetPacketNumberLengthForHeader(0xdeadbeef, 0xdeadbeef-1, version) - Expect(length).To(Equal(PacketNumberLen2)) - }) - - It("sends out higher packet numbers as 4 bytes, if a lot of ACKs are missing", func() { - length := GetPacketNumberLengthForHeader(40000, 2, version) - Expect(length).To(Equal(PacketNumberLen4)) - }) - }) - - Context("self-consistency", func() { - It("works for small packet numbers", func() { - for i := uint64(1); i < 10000; i++ { - packetNumber := PacketNumber(i) - leastUnacked := PacketNumber(1) - length := GetPacketNumberLengthForHeader(packetNumber, leastUnacked, version) - wirePacketNumber := (uint64(packetNumber) << (64 - length*8)) >> (64 - length*8) - - inferedPacketNumber := InferPacketNumber(length, leastUnacked, PacketNumber(wirePacketNumber), version) - Expect(inferedPacketNumber).To(Equal(packetNumber)) - } - }) - - It("works for small packet numbers and increasing ACKed packets", func() { - for i := uint64(1); i < 10000; i++ { - packetNumber := PacketNumber(i) - leastUnacked := PacketNumber(i / 2) - length := GetPacketNumberLengthForHeader(packetNumber, leastUnacked, version) - epochMask := getEpoch(length, version) - 1 - wirePacketNumber := uint64(packetNumber) & epochMask - - inferedPacketNumber := InferPacketNumber(length, leastUnacked, PacketNumber(wirePacketNumber), version) - Expect(inferedPacketNumber).To(Equal(packetNumber)) - } - }) - - It("also works for larger packet numbers", func() { - var increment uint64 - for i := uint64(1); i < getEpoch(PacketNumberLen4, version); i += increment { - packetNumber := PacketNumber(i) - leastUnacked := PacketNumber(1) - length := GetPacketNumberLengthForHeader(packetNumber, leastUnacked, version) - epochMask := getEpoch(length, version) - 1 - wirePacketNumber := uint64(packetNumber) & epochMask - - inferedPacketNumber := InferPacketNumber(length, leastUnacked, PacketNumber(wirePacketNumber), version) - Expect(inferedPacketNumber).To(Equal(packetNumber)) - - increment = getEpoch(length, version) / 8 - } - }) - - It("works for packet numbers larger than 2^48", func() { - for i := (uint64(1) << 48); i < ((uint64(1) << 63) - 1); i += (uint64(1) << 48) { - packetNumber := PacketNumber(i) - leastUnacked := PacketNumber(i - 1000) - length := GetPacketNumberLengthForHeader(packetNumber, leastUnacked, version) - wirePacketNumber := (uint64(packetNumber) << (64 - length*8)) >> (64 - length*8) - - inferedPacketNumber := InferPacketNumber(length, leastUnacked, PacketNumber(wirePacketNumber), version) - Expect(inferedPacketNumber).To(Equal(packetNumber)) - } - }) - }) - }) - }) - } - }) - - Context("determining the minimum length of a packet number", func() { - It("1 byte", func() { - Expect(GetPacketNumberLength(0xFF)).To(Equal(PacketNumberLen1)) - }) - - It("2 byte", func() { - Expect(GetPacketNumberLength(0xFFFF)).To(Equal(PacketNumberLen2)) - }) - - It("4 byte", func() { - Expect(GetPacketNumberLength(0xFFFFFFFF)).To(Equal(PacketNumberLen4)) - }) - - It("6 byte", func() { - Expect(GetPacketNumberLength(0xFFFFFFFFFFFF)).To(Equal(PacketNumberLen6)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/protocol/perspective_test.go b/vendor/lucas-clemente/quic-go/internal/protocol/perspective_test.go deleted file mode 100644 index 0ae23d7c8..000000000 --- a/vendor/lucas-clemente/quic-go/internal/protocol/perspective_test.go +++ /dev/null @@ -1,19 +0,0 @@ -package protocol - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Perspective", func() { - It("has a string representation", func() { - Expect(PerspectiveClient.String()).To(Equal("Client")) - Expect(PerspectiveServer.String()).To(Equal("Server")) - Expect(Perspective(0).String()).To(Equal("invalid perspective")) - }) - - It("returns the opposite", func() { - Expect(PerspectiveClient.Opposite()).To(Equal(PerspectiveServer)) - Expect(PerspectiveServer.Opposite()).To(Equal(PerspectiveClient)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/protocol/protocol_suite_test.go b/vendor/lucas-clemente/quic-go/internal/protocol/protocol_suite_test.go deleted file mode 100644 index 204a3680e..000000000 --- a/vendor/lucas-clemente/quic-go/internal/protocol/protocol_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package protocol - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestProtocol(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Protocol Suite") -} diff --git a/vendor/lucas-clemente/quic-go/internal/protocol/protocol_test.go b/vendor/lucas-clemente/quic-go/internal/protocol/protocol_test.go deleted file mode 100644 index a89f732f1..000000000 --- a/vendor/lucas-clemente/quic-go/internal/protocol/protocol_test.go +++ /dev/null @@ -1,18 +0,0 @@ -package protocol - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Protocol", func() { - Context("Long Header Packet Types", func() { - It("has the correct string representation", func() { - Expect(PacketTypeInitial.String()).To(Equal("Initial")) - Expect(PacketTypeRetry.String()).To(Equal("Retry")) - Expect(PacketTypeHandshake.String()).To(Equal("Handshake")) - Expect(PacketType0RTT.String()).To(Equal("0-RTT Protected")) - Expect(PacketType(10).String()).To(Equal("unknown packet type: 10")) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/protocol/stream_id_test.go b/vendor/lucas-clemente/quic-go/internal/protocol/stream_id_test.go deleted file mode 100644 index cca4f9283..000000000 --- a/vendor/lucas-clemente/quic-go/internal/protocol/stream_id_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package protocol - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Stream ID", func() { - Context("bidirectional streams", func() { - It("doesn't allow any", func() { - Expect(MaxBidiStreamID(0, PerspectiveClient)).To(Equal(StreamID(0))) - Expect(MaxBidiStreamID(0, PerspectiveServer)).To(Equal(StreamID(0))) - }) - - It("allows one", func() { - Expect(MaxBidiStreamID(1, PerspectiveClient)).To(Equal(StreamID(1))) - Expect(MaxBidiStreamID(1, PerspectiveServer)).To(Equal(StreamID(4))) - }) - - It("allows many", func() { - Expect(MaxBidiStreamID(100, PerspectiveClient)).To(Equal(StreamID(397))) - Expect(MaxBidiStreamID(100, PerspectiveServer)).To(Equal(StreamID(400))) - }) - }) - - Context("unidirectional streams", func() { - It("doesn't allow any", func() { - Expect(MaxUniStreamID(0, PerspectiveClient)).To(Equal(StreamID(0))) - Expect(MaxUniStreamID(0, PerspectiveServer)).To(Equal(StreamID(0))) - }) - - It("allows one", func() { - Expect(MaxUniStreamID(1, PerspectiveClient)).To(Equal(StreamID(3))) - Expect(MaxUniStreamID(1, PerspectiveServer)).To(Equal(StreamID(2))) - }) - - It("allows many", func() { - Expect(MaxUniStreamID(100, PerspectiveClient)).To(Equal(StreamID(399))) - Expect(MaxUniStreamID(100, PerspectiveServer)).To(Equal(StreamID(398))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/protocol/version_test.go b/vendor/lucas-clemente/quic-go/internal/protocol/version_test.go deleted file mode 100644 index 6d118ad7c..000000000 --- a/vendor/lucas-clemente/quic-go/internal/protocol/version_test.go +++ /dev/null @@ -1,241 +0,0 @@ -package protocol - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Version", func() { - isReservedVersion := func(v VersionNumber) bool { - return v&0x0f0f0f0f == 0x0a0a0a0a - } - - // version numbers taken from the wiki: https://github.com/quicwg/base-drafts/wiki/QUIC-Versions - It("has the right gQUIC version number", func() { - Expect(Version39).To(BeEquivalentTo(0x51303339)) - Expect(Version43).To(BeEquivalentTo(0x51303433)) - Expect(Version44).To(BeEquivalentTo(0x51303434)) - }) - - It("says if a version is valid", func() { - Expect(IsValidVersion(Version39)).To(BeTrue()) - Expect(IsValidVersion(Version43)).To(BeTrue()) - Expect(IsValidVersion(Version44)).To(BeTrue()) - Expect(IsValidVersion(VersionTLS)).To(BeTrue()) - Expect(IsValidVersion(VersionMilestone0_10_0)).To(BeTrue()) - Expect(IsValidVersion(VersionWhatever)).To(BeFalse()) - Expect(IsValidVersion(VersionUnknown)).To(BeFalse()) - Expect(IsValidVersion(1234)).To(BeFalse()) - }) - - It("says if a version supports TLS", func() { - Expect(Version39.UsesTLS()).To(BeFalse()) - Expect(Version43.UsesTLS()).To(BeFalse()) - Expect(Version44.UsesTLS()).To(BeFalse()) - Expect(VersionMilestone0_10_0.UsesTLS()).To(BeTrue()) - Expect(VersionTLS.UsesTLS()).To(BeTrue()) - }) - - It("versions don't have reserved version numbers", func() { - Expect(isReservedVersion(Version39)).To(BeFalse()) - Expect(isReservedVersion(Version43)).To(BeFalse()) - Expect(isReservedVersion(Version44)).To(BeFalse()) - Expect(isReservedVersion(VersionTLS)).To(BeFalse()) - Expect(isReservedVersion(VersionMilestone0_10_0)).To(BeFalse()) - }) - - It("has the right string representation", func() { - Expect(Version39.String()).To(Equal("gQUIC 39")) - Expect(VersionTLS.String()).To(ContainSubstring("TLS")) - Expect(VersionMilestone0_10_0.String()).To(Equal("quic-go Milestone 0.10.0")) - Expect(VersionWhatever.String()).To(Equal("whatever")) - Expect(VersionUnknown.String()).To(Equal("unknown")) - // check with unsupported version numbers from the wiki - Expect(VersionNumber(0x51303039).String()).To(Equal("gQUIC 9")) - Expect(VersionNumber(0x51303133).String()).To(Equal("gQUIC 13")) - Expect(VersionNumber(0x51303235).String()).To(Equal("gQUIC 25")) - Expect(VersionNumber(0x51303438).String()).To(Equal("gQUIC 48")) - Expect(VersionNumber(0x01234567).String()).To(Equal("0x1234567")) - }) - - It("has the right representation for the H2 Alt-Svc tag", func() { - Expect(Version39.ToAltSvc()).To(Equal("39")) - Expect(Version43.ToAltSvc()).To(Equal("43")) - Expect(Version44.ToAltSvc()).To(Equal("44")) - Expect(VersionTLS.ToAltSvc()).To(Equal("101")) - // check with unsupported version numbers from the wiki - Expect(VersionNumber(0x51303133).ToAltSvc()).To(Equal("13")) - Expect(VersionNumber(0x51303235).ToAltSvc()).To(Equal("25")) - Expect(VersionNumber(0x51303438).ToAltSvc()).To(Equal("48")) - }) - - It("tells the Stream ID of the crypto stream", func() { - Expect(Version39.CryptoStreamID()).To(Equal(StreamID(1))) - Expect(Version43.CryptoStreamID()).To(Equal(StreamID(1))) - Expect(Version44.CryptoStreamID()).To(Equal(StreamID(1))) - Expect(VersionTLS.CryptoStreamID()).To(Equal(StreamID(0))) - Expect(VersionMilestone0_10_0.CryptoStreamID()).To(Equal(StreamID(0))) - }) - - It("tells if a version uses the IETF frame types", func() { - Expect(Version39.UsesIETFFrameFormat()).To(BeFalse()) - Expect(Version43.UsesIETFFrameFormat()).To(BeFalse()) - Expect(Version44.UsesIETFFrameFormat()).To(BeFalse()) - Expect(VersionTLS.UsesIETFFrameFormat()).To(BeTrue()) - Expect(VersionMilestone0_10_0.UsesIETFFrameFormat()).To(BeTrue()) - }) - - It("tells if a version uses the IETF header format", func() { - Expect(Version39.UsesIETFHeaderFormat()).To(BeFalse()) - Expect(Version43.UsesIETFHeaderFormat()).To(BeFalse()) - Expect(Version44.UsesIETFHeaderFormat()).To(BeTrue()) - Expect(VersionTLS.UsesIETFHeaderFormat()).To(BeTrue()) - Expect(VersionMilestone0_10_0.UsesIETFHeaderFormat()).To(BeTrue()) - }) - - It("tells if a version uses varint packet numbers", func() { - Expect(Version39.UsesVarintPacketNumbers()).To(BeFalse()) - Expect(Version43.UsesVarintPacketNumbers()).To(BeFalse()) - Expect(Version44.UsesVarintPacketNumbers()).To(BeFalse()) - Expect(VersionTLS.UsesVarintPacketNumbers()).To(BeTrue()) - Expect(VersionMilestone0_10_0.UsesVarintPacketNumbers()).To(BeTrue()) - }) - - It("tells if a version uses the Length field in the IETF header", func() { - Expect(Version44.UsesLengthInHeader()).To(BeFalse()) - Expect(VersionTLS.UsesLengthInHeader()).To(BeTrue()) - Expect(VersionMilestone0_10_0.UsesLengthInHeader()).To(BeTrue()) - }) - - It("tells if a version uses the Token field in the IETF header", func() { - Expect(Version44.UsesTokenInHeader()).To(BeFalse()) - Expect(VersionTLS.UsesTokenInHeader()).To(BeTrue()) - Expect(VersionMilestone0_10_0.UsesTokenInHeader()).To(BeTrue()) - }) - - It("tells if a version uses STOP_WAITING frames", func() { - Expect(Version39.UsesStopWaitingFrames()).To(BeTrue()) - Expect(Version43.UsesStopWaitingFrames()).To(BeTrue()) - Expect(Version44.UsesStopWaitingFrames()).To(BeFalse()) - Expect(VersionTLS.UsesStopWaitingFrames()).To(BeFalse()) - Expect(VersionMilestone0_10_0.UsesStopWaitingFrames()).To(BeFalse()) - }) - - It("says if a stream contributes to connection-level flowcontrol, for gQUIC", func() { - for _, v := range []VersionNumber{Version39, Version43, Version44} { - version := v - Expect(version.StreamContributesToConnectionFlowControl(1)).To(BeFalse()) - Expect(version.StreamContributesToConnectionFlowControl(2)).To(BeTrue()) - Expect(version.StreamContributesToConnectionFlowControl(3)).To(BeFalse()) - Expect(version.StreamContributesToConnectionFlowControl(4)).To(BeTrue()) - Expect(version.StreamContributesToConnectionFlowControl(5)).To(BeTrue()) - } - }) - - It("says if a stream contributes to connection-level flowcontrol, for TLS", func() { - Expect(VersionTLS.StreamContributesToConnectionFlowControl(0)).To(BeFalse()) - Expect(VersionTLS.StreamContributesToConnectionFlowControl(1)).To(BeTrue()) - Expect(VersionTLS.StreamContributesToConnectionFlowControl(2)).To(BeTrue()) - Expect(VersionTLS.StreamContributesToConnectionFlowControl(3)).To(BeTrue()) - Expect(VersionMilestone0_10_0.StreamContributesToConnectionFlowControl(0)).To(BeFalse()) - Expect(VersionMilestone0_10_0.StreamContributesToConnectionFlowControl(1)).To(BeTrue()) - Expect(VersionMilestone0_10_0.StreamContributesToConnectionFlowControl(2)).To(BeTrue()) - Expect(VersionMilestone0_10_0.StreamContributesToConnectionFlowControl(3)).To(BeTrue()) - }) - - It("recognizes supported versions", func() { - Expect(IsSupportedVersion(SupportedVersions, 0)).To(BeFalse()) - Expect(IsSupportedVersion(SupportedVersions, SupportedVersions[0])).To(BeTrue()) - Expect(IsSupportedVersion(SupportedVersions, SupportedVersions[len(SupportedVersions)-1])).To(BeTrue()) - }) - - It("has supported versions in sorted order", func() { - for i := 0; i < len(SupportedVersions)-1; i++ { - Expect(SupportedVersions[i]).To(BeNumerically(">", SupportedVersions[i+1])) - } - }) - - Context("highest supported version", func() { - It("finds the supported version", func() { - supportedVersions := []VersionNumber{1, 2, 3} - other := []VersionNumber{6, 5, 4, 3} - ver, ok := ChooseSupportedVersion(supportedVersions, other) - Expect(ok).To(BeTrue()) - Expect(ver).To(Equal(VersionNumber(3))) - }) - - It("picks the preferred version", func() { - supportedVersions := []VersionNumber{2, 1, 3} - other := []VersionNumber{3, 6, 1, 8, 2, 10} - ver, ok := ChooseSupportedVersion(supportedVersions, other) - Expect(ok).To(BeTrue()) - Expect(ver).To(Equal(VersionNumber(2))) - }) - - It("says when no matching version was found", func() { - _, ok := ChooseSupportedVersion([]VersionNumber{1}, []VersionNumber{2}) - Expect(ok).To(BeFalse()) - }) - - It("handles empty inputs", func() { - _, ok := ChooseSupportedVersion([]VersionNumber{102, 101}, []VersionNumber{}) - Expect(ok).To(BeFalse()) - _, ok = ChooseSupportedVersion([]VersionNumber{}, []VersionNumber{1, 2}) - Expect(ok).To(BeFalse()) - _, ok = ChooseSupportedVersion([]VersionNumber{}, []VersionNumber{}) - Expect(ok).To(BeFalse()) - }) - }) - - Context("reserved versions", func() { - It("adds a greased version if passed an empty slice", func() { - greased := GetGreasedVersions([]VersionNumber{}) - Expect(greased).To(HaveLen(1)) - Expect(isReservedVersion(greased[0])).To(BeTrue()) - }) - - It("strips greased versions", func() { - v := SupportedVersions[0] - greased := GetGreasedVersions([]VersionNumber{v}) - Expect(greased).To(HaveLen(2)) - stripped := StripGreasedVersions(greased) - Expect(stripped).To(HaveLen(1)) - Expect(stripped[0]).To(Equal(v)) - }) - - It("creates greased lists of version numbers", func() { - supported := []VersionNumber{10, 18, 29} - for _, v := range supported { - Expect(isReservedVersion(v)).To(BeFalse()) - } - var greasedVersionFirst, greasedVersionLast, greasedVersionMiddle int - // check that - // 1. the greased version sometimes appears first - // 2. the greased version sometimes appears in the middle - // 3. the greased version sometimes appears last - // 4. the supported versions are kept in order - for i := 0; i < 100; i++ { - greased := GetGreasedVersions(supported) - Expect(greased).To(HaveLen(4)) - var j int - for i, v := range greased { - if isReservedVersion(v) { - if i == 0 { - greasedVersionFirst++ - } - if i == len(greased)-1 { - greasedVersionLast++ - } - greasedVersionMiddle++ - continue - } - Expect(supported[j]).To(Equal(v)) - j++ - } - } - Expect(greasedVersionFirst).ToNot(BeZero()) - Expect(greasedVersionLast).ToNot(BeZero()) - Expect(greasedVersionMiddle).ToNot(BeZero()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/utils/atomic_bool_test.go b/vendor/lucas-clemente/quic-go/internal/utils/atomic_bool_test.go deleted file mode 100644 index 83a200c27..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/atomic_bool_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package utils - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Atomic Bool", func() { - var a *AtomicBool - - BeforeEach(func() { - a = &AtomicBool{} - }) - - It("has the right default value", func() { - Expect(a.Get()).To(BeFalse()) - }) - - It("sets the value to true", func() { - a.Set(true) - Expect(a.Get()).To(BeTrue()) - }) - - It("sets the value to false", func() { - a.Set(true) - a.Set(false) - Expect(a.Get()).To(BeFalse()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/utils/byteoder_big_endian_test.go b/vendor/lucas-clemente/quic-go/internal/utils/byteoder_big_endian_test.go deleted file mode 100644 index dec2e8418..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/byteoder_big_endian_test.go +++ /dev/null @@ -1,220 +0,0 @@ -package utils - -import ( - "bytes" - "io" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Big Endian encoding / decoding", func() { - Context("ReadUint16", func() { - It("reads a big endian", func() { - b := []byte{0x13, 0xEF} - val, err := BigEndian.ReadUint16(bytes.NewReader(b)) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint16(0x13EF))) - }) - - It("throws an error if less than 2 bytes are passed", func() { - b := []byte{0x13, 0xEF} - for i := 0; i < len(b); i++ { - _, err := BigEndian.ReadUint16(bytes.NewReader(b[:i])) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("ReadUint32", func() { - It("reads a big endian", func() { - b := []byte{0x12, 0x35, 0xAB, 0xFF} - val, err := BigEndian.ReadUint32(bytes.NewReader(b)) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint32(0x1235ABFF))) - }) - - It("throws an error if less than 4 bytes are passed", func() { - b := []byte{0x12, 0x35, 0xAB, 0xFF} - for i := 0; i < len(b); i++ { - _, err := BigEndian.ReadUint32(bytes.NewReader(b[:i])) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("ReadUint64", func() { - It("reads a big endian", func() { - b := []byte{0x12, 0x35, 0xAB, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE} - val, err := BigEndian.ReadUint64(bytes.NewReader(b)) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint64(0x1235ABFFEFBEADDE))) - }) - - It("throws an error if less than 8 bytes are passed", func() { - b := []byte{0x12, 0x35, 0xAB, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE} - for i := 0; i < len(b); i++ { - _, err := BigEndian.ReadUint64(bytes.NewReader(b[:i])) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("WriteUint16", func() { - It("outputs 2 bytes", func() { - b := &bytes.Buffer{} - BigEndian.WriteUint16(b, uint16(1)) - Expect(b.Len()).To(Equal(2)) - }) - - It("outputs a big endian", func() { - num := uint16(0xFF11) - b := &bytes.Buffer{} - BigEndian.WriteUint16(b, num) - Expect(b.Bytes()).To(Equal([]byte{0xFF, 0x11})) - }) - }) - - Context("WriteUint24", func() { - It("outputs 3 bytes", func() { - b := &bytes.Buffer{} - BigEndian.WriteUint24(b, uint32(1)) - Expect(b.Len()).To(Equal(3)) - }) - - It("outputs a big endian", func() { - num := uint32(0x010203) - b := &bytes.Buffer{} - BigEndian.WriteUint24(b, num) - Expect(b.Bytes()).To(Equal([]byte{0x01, 0x02, 0x03})) - }) - - It("panics if the value doesn't fit into 24 bits", func() { - num := uint32(0x01020304) - b := &bytes.Buffer{} - Expect(func() { BigEndian.WriteUint24(b, num) }).Should(Panic()) - }) - }) - - Context("WriteUint32", func() { - It("outputs 4 bytes", func() { - b := &bytes.Buffer{} - BigEndian.WriteUint32(b, uint32(1)) - Expect(b.Len()).To(Equal(4)) - }) - - It("outputs a big endian", func() { - num := uint32(0xEFAC3512) - b := &bytes.Buffer{} - BigEndian.WriteUint32(b, num) - Expect(b.Bytes()).To(Equal([]byte{0xEF, 0xAC, 0x35, 0x12})) - }) - }) - - Context("WriteUint40", func() { - It("outputs 5 bytes", func() { - b := &bytes.Buffer{} - BigEndian.WriteUint40(b, uint64(1)) - Expect(b.Len()).To(Equal(5)) - }) - - It("outputs a big endian", func() { - num := uint64(0xDECAFBAD42) - b := &bytes.Buffer{} - BigEndian.WriteUint40(b, num) - Expect(b.Bytes()).To(Equal([]byte{0xDE, 0xCA, 0xFB, 0xAD, 0x42})) - }) - - It("panics if the value doesn't fit into 40 bits", func() { - num := uint64(0x010203040506) - b := &bytes.Buffer{} - Expect(func() { BigEndian.WriteUint40(b, num) }).Should(Panic()) - }) - }) - - Context("WriteUint48", func() { - It("outputs 6 bytes", func() { - b := &bytes.Buffer{} - BigEndian.WriteUint48(b, uint64(1)) - Expect(b.Len()).To(Equal(6)) - }) - - It("outputs a big endian", func() { - num := uint64(0xDEADBEEFCAFE) - b := &bytes.Buffer{} - BigEndian.WriteUint48(b, num) - Expect(b.Bytes()).To(Equal([]byte{0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE})) - }) - - It("panics if the value doesn't fit into 48 bits", func() { - num := uint64(0xDEADBEEFCAFE01) - b := &bytes.Buffer{} - Expect(func() { BigEndian.WriteUint48(b, num) }).Should(Panic()) - }) - }) - - Context("WriteUint56", func() { - It("outputs 7 bytes", func() { - b := &bytes.Buffer{} - BigEndian.WriteUint56(b, uint64(1)) - Expect(b.Len()).To(Equal(7)) - }) - - It("outputs a big endian", func() { - num := uint64(0xEEDDCCBBAA9988) - b := &bytes.Buffer{} - BigEndian.WriteUint56(b, num) - Expect(b.Bytes()).To(Equal([]byte{0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88})) - }) - - It("panics if the value doesn't fit into 56 bits", func() { - num := uint64(0xEEDDCCBBAA998801) - b := &bytes.Buffer{} - Expect(func() { BigEndian.WriteUint56(b, num) }).Should(Panic()) - }) - }) - - Context("WriteUint64", func() { - It("outputs 8 bytes", func() { - b := &bytes.Buffer{} - BigEndian.WriteUint64(b, uint64(1)) - Expect(b.Len()).To(Equal(8)) - }) - - It("outputs a big endian", func() { - num := uint64(0xFFEEDDCCBBAA9988) - b := &bytes.Buffer{} - BigEndian.WriteUint64(b, num) - Expect(b.Bytes()).To(Equal([]byte{0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x99, 0x88})) - }) - }) - - Context("ReadUintN", func() { - - It("reads n bytes", func() { - m := map[uint8]uint64{ - 0: 0x0, - 1: 0x01, - 2: 0x0102, - 3: 0x010203, - 4: 0x01020304, - 5: 0x0102030405, - 6: 0x010203040506, - 7: 0x01020304050607, - 8: 0x0102030405060708, - } - for n, expected := range m { - b := bytes.NewReader([]byte{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8}) - i, err := BigEndian.ReadUintN(b, n) - Expect(err).ToNot(HaveOccurred()) - Expect(i).To(Equal(expected)) - } - }) - - It("errors", func() { - b := bytes.NewReader([]byte{0x1, 0x2}) - _, err := BigEndian.ReadUintN(b, 3) - Expect(err).To(HaveOccurred()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/utils/byteorder_little_endian_test.go b/vendor/lucas-clemente/quic-go/internal/utils/byteorder_little_endian_test.go deleted file mode 100644 index 60508aafb..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/byteorder_little_endian_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package utils - -import ( - "bytes" - "io" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Little Endian encoding / decoding", func() { - Context("ReadUint16", func() { - It("reads a little endian", func() { - b := []byte{0x13, 0xEF} - val, err := LittleEndian.ReadUint16(bytes.NewReader(b)) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint16(0xEF13))) - }) - - It("throws an error if less than 2 bytes are passed", func() { - b := []byte{0x13, 0xEF} - for i := 0; i < len(b); i++ { - _, err := LittleEndian.ReadUint16(bytes.NewReader(b[:i])) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("ReadUint32", func() { - It("reads a little endian", func() { - b := []byte{0x12, 0x35, 0xAB, 0xFF} - val, err := LittleEndian.ReadUint32(bytes.NewReader(b)) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint32(0xFFAB3512))) - }) - - It("throws an error if less than 4 bytes are passed", func() { - b := []byte{0x12, 0x35, 0xAB, 0xFF} - for i := 0; i < len(b); i++ { - _, err := LittleEndian.ReadUint32(bytes.NewReader(b[:i])) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("ReadUint64", func() { - It("reads a little endian", func() { - b := []byte{0x12, 0x35, 0xAB, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE} - val, err := LittleEndian.ReadUint64(bytes.NewReader(b)) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint64(0xDEADBEEFFFAB3512))) - }) - - It("throws an error if less than 8 bytes are passed", func() { - b := []byte{0x12, 0x35, 0xAB, 0xFF, 0xEF, 0xBE, 0xAD, 0xDE} - for i := 0; i < len(b); i++ { - _, err := LittleEndian.ReadUint64(bytes.NewReader(b[:i])) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("WriteUint16", func() { - It("outputs 2 bytes", func() { - b := &bytes.Buffer{} - LittleEndian.WriteUint16(b, uint16(1)) - Expect(b.Len()).To(Equal(2)) - }) - - It("outputs a little endian", func() { - num := uint16(0xFF11) - b := &bytes.Buffer{} - LittleEndian.WriteUint16(b, num) - Expect(b.Bytes()).To(Equal([]byte{0x11, 0xFF})) - }) - }) - - Context("WriteUint24", func() { - It("outputs 3 bytes", func() { - b := &bytes.Buffer{} - LittleEndian.WriteUint24(b, uint32(1)) - Expect(b.Len()).To(Equal(3)) - }) - - It("outputs a little endian", func() { - num := uint32(0x010203) - b := &bytes.Buffer{} - LittleEndian.WriteUint24(b, num) - Expect(b.Bytes()).To(Equal([]byte{0x03, 0x02, 0x01})) - }) - - It("panics if the value doesn't fit into 24 bits", func() { - num := uint32(0x01020304) - b := &bytes.Buffer{} - Expect(func() { LittleEndian.WriteUint24(b, num) }).Should(Panic()) - }) - }) - - Context("WriteUint32", func() { - It("outputs 4 bytes", func() { - b := &bytes.Buffer{} - LittleEndian.WriteUint32(b, uint32(1)) - Expect(b.Len()).To(Equal(4)) - }) - - It("outputs a little endian", func() { - num := uint32(0xEFAC3512) - b := &bytes.Buffer{} - LittleEndian.WriteUint32(b, num) - Expect(b.Bytes()).To(Equal([]byte{0x12, 0x35, 0xAC, 0xEF})) - }) - }) - - Context("WriteUint40", func() { - It("outputs 5 bytes", func() { - b := &bytes.Buffer{} - LittleEndian.WriteUint40(b, uint64(1)) - Expect(b.Len()).To(Equal(5)) - }) - - It("outputs a little endian", func() { - num := uint64(0x0102030405) - b := &bytes.Buffer{} - LittleEndian.WriteUint40(b, num) - Expect(b.Bytes()).To(Equal([]byte{0x05, 0x04, 0x03, 0x02, 0x01})) - }) - - It("panics if the value doesn't fit into 40 bits", func() { - num := uint64(0x010203040506) - b := &bytes.Buffer{} - Expect(func() { LittleEndian.WriteUint40(b, num) }).Should(Panic()) - }) - }) - - Context("WriteUint48", func() { - It("outputs 6 bytes", func() { - b := &bytes.Buffer{} - LittleEndian.WriteUint48(b, uint64(1)) - Expect(b.Len()).To(Equal(6)) - }) - - It("outputs a little endian", func() { - num := uint64(0xDEADBEEFCAFE) - b := &bytes.Buffer{} - LittleEndian.WriteUint48(b, num) - Expect(b.Bytes()).To(Equal([]byte{0xFE, 0xCA, 0xEF, 0xBE, 0xAD, 0xDE})) - }) - - It("panics if the value doesn't fit into 48 bits", func() { - num := uint64(0xDEADBEEFCAFE01) - b := &bytes.Buffer{} - Expect(func() { LittleEndian.WriteUint48(b, num) }).Should(Panic()) - }) - }) - - Context("WriteUint56", func() { - It("outputs 7 bytes", func() { - b := &bytes.Buffer{} - LittleEndian.WriteUint56(b, uint64(1)) - Expect(b.Len()).To(Equal(7)) - }) - - It("outputs a little endian", func() { - num := uint64(0xEEDDCCBBAA9988) - b := &bytes.Buffer{} - LittleEndian.WriteUint56(b, num) - Expect(b.Bytes()).To(Equal([]byte{0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE})) - }) - - It("panics if the value doesn't fit into 56 bits", func() { - num := uint64(0xEEDDCCBBAA998801) - b := &bytes.Buffer{} - Expect(func() { LittleEndian.WriteUint56(b, num) }).Should(Panic()) - }) - }) - - Context("WriteUint64", func() { - It("outputs 8 bytes", func() { - b := &bytes.Buffer{} - LittleEndian.WriteUint64(b, uint64(1)) - Expect(b.Len()).To(Equal(8)) - }) - - It("outputs a little endian", func() { - num := uint64(0xFFEEDDCCBBAA9988) - b := &bytes.Buffer{} - LittleEndian.WriteUint64(b, num) - Expect(b.Bytes()).To(Equal([]byte{0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF})) - }) - }) - - Context("ReadUintN", func() { - It("reads n bytes", func() { - m := map[uint8]uint64{ - 0: 0x0, 1: 0x01, 2: 0x0201, 3: 0x030201, 4: 0x04030201, 5: 0x0504030201, - 6: 0x060504030201, 7: 0x07060504030201, 8: 0x0807060504030201, - } - for n, expected := range m { - b := bytes.NewReader([]byte{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8}) - i, err := LittleEndian.ReadUintN(b, n) - Expect(err).ToNot(HaveOccurred()) - Expect(i).To(Equal(expected)) - } - }) - - It("errors", func() { - b := bytes.NewReader([]byte{0x1, 0x2}) - _, err := LittleEndian.ReadUintN(b, 3) - Expect(err).To(HaveOccurred()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/utils/float16_test.go b/vendor/lucas-clemente/quic-go/internal/utils/float16_test.go deleted file mode 100644 index 319fad24f..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/float16_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package utils - -import ( - "bytes" - "fmt" - "io" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("float16", func() { - for _, v := range []ByteOrder{LittleEndian, BigEndian} { - bo := v - name := "little endian" - if bo == BigEndian { - name = "big endian" - } - - Context(fmt.Sprintf("in %s", name), func() { - It("reads", func() { - testcases := []struct { - expected uint64 - binary uint16 - }{ - // There are fewer decoding test cases because encoding truncates, and - // decoding returns the smallest expansion. - // Small numbers represent themselves. - {0, 0}, - {1, 1}, - {2, 2}, - {3, 3}, - {4, 4}, - {5, 5}, - {6, 6}, - {7, 7}, - {15, 15}, - {31, 31}, - {42, 42}, - {123, 123}, - {1234, 1234}, - // Check transition through 2^11. - {2046, 2046}, - {2047, 2047}, - {2048, 2048}, - {2049, 2049}, - // Running out of mantissa at 2^12. - {4094, 4094}, - {4095, 4095}, - {4096, 4096}, - {4098, 4097}, - {4100, 4098}, - // Check transition through 2^13. - {8190, 6143}, - {8192, 6144}, - {8196, 6145}, - // Half-way through the exponents. - {0x7FF8000, 0x87FF}, - {0x8000000, 0x8800}, - {0xFFF0000, 0x8FFF}, - {0x10000000, 0x9000}, - // Transition into the largest exponent. - {0x1FFE0000000, 0xF7FF}, - {0x20000000000, 0xF800}, - {0x20040000000, 0xF801}, - // Transition into the max value. - {0x3FF80000000, 0xFFFE}, - {0x3FFC0000000, 0xFFFF}, - } - for _, testcase := range testcases { - b := &bytes.Buffer{} - bo.WriteUint16(b, testcase.binary) - val, err := bo.ReadUfloat16(b) - Expect(err).NotTo(HaveOccurred()) - Expect(val).To(Equal(testcase.expected)) - } - }) - - It("errors on eof", func() { - _, err := bo.ReadUfloat16(&bytes.Buffer{}) - Expect(err).To(MatchError(io.EOF)) - }) - - It("writes", func() { - testcases := []struct { - decoded uint64 - encoded uint16 - }{ - // Small numbers represent themselves. - {0, 0}, - {1, 1}, - {2, 2}, - {3, 3}, - {4, 4}, - {5, 5}, - {6, 6}, - {7, 7}, - {15, 15}, - {31, 31}, - {42, 42}, - {123, 123}, - {1234, 1234}, - // Check transition through 2^11. - {2046, 2046}, - {2047, 2047}, - {2048, 2048}, - {2049, 2049}, - // Running out of mantissa at 2^12. - {4094, 4094}, - {4095, 4095}, - {4096, 4096}, - {4097, 4096}, - {4098, 4097}, - {4099, 4097}, - {4100, 4098}, - {4101, 4098}, - // Check transition through 2^13. - {8190, 6143}, - {8191, 6143}, - {8192, 6144}, - {8193, 6144}, - {8194, 6144}, - {8195, 6144}, - {8196, 6145}, - {8197, 6145}, - // Half-way through the exponents. - {0x7FF8000, 0x87FF}, - {0x7FFFFFF, 0x87FF}, - {0x8000000, 0x8800}, - {0xFFF0000, 0x8FFF}, - {0xFFFFFFF, 0x8FFF}, - {0x10000000, 0x9000}, - // Transition into the largest exponent. - {0x1FFFFFFFFFE, 0xF7FF}, - {0x1FFFFFFFFFF, 0xF7FF}, - {0x20000000000, 0xF800}, - {0x20000000001, 0xF800}, - {0x2003FFFFFFE, 0xF800}, - {0x2003FFFFFFF, 0xF800}, - {0x20040000000, 0xF801}, - {0x20040000001, 0xF801}, - // Transition into the max value and clamping. - {0x3FF80000000, 0xFFFE}, - {0x3FFBFFFFFFF, 0xFFFE}, - {0x3FFC0000000, 0xFFFF}, - {0x3FFC0000001, 0xFFFF}, - {0x3FFFFFFFFFF, 0xFFFF}, - {0x40000000000, 0xFFFF}, - {0xFFFFFFFFFFFFFFFF, 0xFFFF}, - } - for _, testcase := range testcases { - b := &bytes.Buffer{} - bo.WriteUfloat16(b, testcase.decoded) - val, err := bo.ReadUint16(b) - Expect(err).NotTo(HaveOccurred()) - Expect(val).To(Equal(testcase.encoded)) - } - }) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/internal/utils/host_test.go b/vendor/lucas-clemente/quic-go/internal/utils/host_test.go deleted file mode 100644 index d7667eb3c..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/host_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package utils - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Hostname", func() { - It("gets the hostname from an URL", func() { - h, err := HostnameFromAddr("https://quic.clemente.io/file.dat?param=true¶m2=false") - Expect(err).ToNot(HaveOccurred()) - Expect(h).To(Equal("quic.clemente.io")) - }) - - It("gets the hostname from an URL with a port number", func() { - h, err := HostnameFromAddr("https://quic.clemente.io:6121/file.dat") - Expect(err).ToNot(HaveOccurred()) - Expect(h).To(Equal("quic.clemente.io")) - }) - - It("gets the hostname from an URL containing username and password", func() { - h, err := HostnameFromAddr("https://user:password@quic.clemente.io:6121/file.dat") - Expect(err).ToNot(HaveOccurred()) - Expect(h).To(Equal("quic.clemente.io")) - }) - - It("gets local hostnames", func() { - h, err := HostnameFromAddr("https://localhost/file.dat") - Expect(err).ToNot(HaveOccurred()) - Expect(h).To(Equal("localhost")) - }) - - It("gets the hostname for other protocols", func() { - h, err := HostnameFromAddr("ftp://quic.clemente.io:6121/file.dat") - Expect(err).ToNot(HaveOccurred()) - Expect(h).To(Equal("quic.clemente.io")) - }) - - It("gets an IP", func() { - h, err := HostnameFromAddr("https://1.3.3.7:6121/file.dat") - Expect(err).ToNot(HaveOccurred()) - Expect(h).To(Equal("1.3.3.7")) - }) - - It("errors on malformed URLs", func() { - _, err := HostnameFromAddr("://quic.clemente.io:6121/file.dat") - Expect(err).To(HaveOccurred()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/utils/log_test.go b/vendor/lucas-clemente/quic-go/internal/utils/log_test.go deleted file mode 100644 index 0cda45837..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/log_test.go +++ /dev/null @@ -1,144 +0,0 @@ -package utils - -import ( - "bytes" - "log" - "os" - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Log", func() { - var b *bytes.Buffer - - BeforeEach(func() { - b = &bytes.Buffer{} - log.SetOutput(b) - }) - - AfterEach(func() { - log.SetOutput(os.Stdout) - DefaultLogger.SetLogLevel(LogLevelNothing) - }) - - It("the log level has the correct numeric value", func() { - Expect(LogLevelNothing).To(BeEquivalentTo(0)) - Expect(LogLevelError).To(BeEquivalentTo(1)) - Expect(LogLevelInfo).To(BeEquivalentTo(2)) - Expect(LogLevelDebug).To(BeEquivalentTo(3)) - }) - - It("log level nothing", func() { - DefaultLogger.SetLogLevel(LogLevelNothing) - DefaultLogger.Debugf("debug") - DefaultLogger.Infof("info") - DefaultLogger.Errorf("err") - Expect(b.String()).To(BeEmpty()) - }) - - It("log level err", func() { - DefaultLogger.SetLogLevel(LogLevelError) - DefaultLogger.Debugf("debug") - DefaultLogger.Infof("info") - DefaultLogger.Errorf("err") - Expect(b.String()).To(ContainSubstring("err\n")) - Expect(b.String()).ToNot(ContainSubstring("info")) - Expect(b.String()).ToNot(ContainSubstring("debug")) - }) - - It("log level info", func() { - DefaultLogger.SetLogLevel(LogLevelInfo) - DefaultLogger.Debugf("debug") - DefaultLogger.Infof("info") - DefaultLogger.Errorf("err") - Expect(b.String()).To(ContainSubstring("err\n")) - Expect(b.String()).To(ContainSubstring("info\n")) - Expect(b.String()).ToNot(ContainSubstring("debug")) - }) - - It("log level debug", func() { - DefaultLogger.SetLogLevel(LogLevelDebug) - DefaultLogger.Debugf("debug") - DefaultLogger.Infof("info") - DefaultLogger.Errorf("err") - Expect(b.String()).To(ContainSubstring("err\n")) - Expect(b.String()).To(ContainSubstring("info\n")) - Expect(b.String()).To(ContainSubstring("debug\n")) - }) - - It("doesn't add a timestamp if the time format is empty", func() { - DefaultLogger.SetLogLevel(LogLevelDebug) - DefaultLogger.SetLogTimeFormat("") - DefaultLogger.Debugf("debug") - Expect(b.String()).To(Equal("debug\n")) - }) - - It("adds a timestamp", func() { - format := "Jan 2, 2006" - DefaultLogger.SetLogTimeFormat(format) - DefaultLogger.SetLogLevel(LogLevelInfo) - DefaultLogger.Infof("info") - t, err := time.Parse(format, string(b.String()[:b.Len()-6])) - Expect(err).ToNot(HaveOccurred()) - Expect(t).To(BeTemporally("~", time.Now(), 25*time.Hour)) - }) - - It("says whether debug is enabled", func() { - Expect(DefaultLogger.Debug()).To(BeFalse()) - DefaultLogger.SetLogLevel(LogLevelDebug) - Expect(DefaultLogger.Debug()).To(BeTrue()) - }) - - It("adds a prefix", func() { - DefaultLogger.SetLogLevel(LogLevelDebug) - prefixLogger := DefaultLogger.WithPrefix("prefix") - prefixLogger.Debugf("debug") - Expect(b.String()).To(ContainSubstring("prefix")) - Expect(b.String()).To(ContainSubstring("debug")) - }) - - It("adds multiple prefixes", func() { - DefaultLogger.SetLogLevel(LogLevelDebug) - prefixLogger := DefaultLogger.WithPrefix("prefix1") - prefixPrefixLogger := prefixLogger.WithPrefix("prefix2") - prefixPrefixLogger.Debugf("debug") - Expect(b.String()).To(ContainSubstring("prefix")) - Expect(b.String()).To(ContainSubstring("debug")) - }) - - Context("reading from env", func() { - BeforeEach(func() { - Expect(DefaultLogger.(*defaultLogger).logLevel).To(Equal(LogLevelNothing)) - }) - - It("reads DEBUG", func() { - os.Setenv(logEnv, "DEBUG") - Expect(readLoggingEnv()).To(Equal(LogLevelDebug)) - }) - - It("reads debug", func() { - os.Setenv(logEnv, "debug") - Expect(readLoggingEnv()).To(Equal(LogLevelDebug)) - }) - - It("reads INFO", func() { - os.Setenv(logEnv, "INFO") - readLoggingEnv() - Expect(readLoggingEnv()).To(Equal(LogLevelInfo)) - }) - - It("reads ERROR", func() { - os.Setenv(logEnv, "ERROR") - Expect(readLoggingEnv()).To(Equal(LogLevelError)) - }) - - It("does not error reading invalid log levels from env", func() { - os.Setenv(logEnv, "") - Expect(readLoggingEnv()).To(Equal(LogLevelNothing)) - os.Setenv(logEnv, "asdf") - Expect(readLoggingEnv()).To(Equal(LogLevelNothing)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/utils/minmax_test.go b/vendor/lucas-clemente/quic-go/internal/utils/minmax_test.go deleted file mode 100644 index 95816372d..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/minmax_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package utils - -import ( - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Min / Max", func() { - Context("Max", func() { - It("returns the maximum", func() { - Expect(Max(5, 7)).To(Equal(7)) - Expect(Max(7, 5)).To(Equal(7)) - }) - - It("returns the maximum uint32", func() { - Expect(MaxUint32(5, 7)).To(Equal(uint32(7))) - Expect(MaxUint32(7, 5)).To(Equal(uint32(7))) - }) - - It("returns the maximum uint64", func() { - Expect(MaxUint64(5, 7)).To(Equal(uint64(7))) - Expect(MaxUint64(7, 5)).To(Equal(uint64(7))) - }) - - It("returns the minimum uint64", func() { - Expect(MinUint64(5, 7)).To(Equal(uint64(5))) - Expect(MinUint64(7, 5)).To(Equal(uint64(5))) - }) - - It("returns the maximum int64", func() { - Expect(MaxInt64(5, 7)).To(Equal(int64(7))) - Expect(MaxInt64(7, 5)).To(Equal(int64(7))) - }) - - It("returns the maximum ByteCount", func() { - Expect(MaxByteCount(7, 5)).To(Equal(protocol.ByteCount(7))) - Expect(MaxByteCount(5, 7)).To(Equal(protocol.ByteCount(7))) - }) - - It("returns the maximum duration", func() { - Expect(MaxDuration(time.Microsecond, time.Nanosecond)).To(Equal(time.Microsecond)) - Expect(MaxDuration(time.Nanosecond, time.Microsecond)).To(Equal(time.Microsecond)) - }) - - It("returns the minimum duration", func() { - Expect(MinDuration(time.Microsecond, time.Nanosecond)).To(Equal(time.Nanosecond)) - Expect(MinDuration(time.Nanosecond, time.Microsecond)).To(Equal(time.Nanosecond)) - }) - - It("returns packet number max", func() { - Expect(MaxPacketNumber(1, 2)).To(Equal(protocol.PacketNumber(2))) - Expect(MaxPacketNumber(2, 1)).To(Equal(protocol.PacketNumber(2))) - }) - - It("returns the maximum time", func() { - a := time.Now() - b := a.Add(time.Second) - Expect(MaxTime(a, b)).To(Equal(b)) - Expect(MaxTime(b, a)).To(Equal(b)) - }) - }) - - Context("Min", func() { - It("returns the minimum", func() { - Expect(Min(5, 7)).To(Equal(5)) - Expect(Min(7, 5)).To(Equal(5)) - }) - - It("returns the minimum uint32", func() { - Expect(MinUint32(7, 5)).To(Equal(uint32(5))) - Expect(MinUint32(5, 7)).To(Equal(uint32(5))) - }) - - It("returns the minimum int64", func() { - Expect(MinInt64(7, 5)).To(Equal(int64(5))) - Expect(MinInt64(5, 7)).To(Equal(int64(5))) - }) - - It("returns the minimum ByteCount", func() { - Expect(MinByteCount(7, 5)).To(Equal(protocol.ByteCount(5))) - Expect(MinByteCount(5, 7)).To(Equal(protocol.ByteCount(5))) - }) - - It("returns packet number min", func() { - Expect(MinPacketNumber(1, 2)).To(Equal(protocol.PacketNumber(1))) - Expect(MinPacketNumber(2, 1)).To(Equal(protocol.PacketNumber(1))) - }) - - It("returns the minimum time", func() { - a := time.Now() - b := a.Add(time.Second) - Expect(MinTime(a, b)).To(Equal(a)) - Expect(MinTime(b, a)).To(Equal(a)) - }) - }) - - It("returns the abs time", func() { - Expect(AbsDuration(time.Microsecond)).To(Equal(time.Microsecond)) - Expect(AbsDuration(-time.Microsecond)).To(Equal(time.Microsecond)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/utils/timer_test.go b/vendor/lucas-clemente/quic-go/internal/utils/timer_test.go deleted file mode 100644 index c1581919d..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/timer_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package utils - -import ( - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Timer", func() { - const d = 10 * time.Millisecond - - It("works", func() { - t := NewTimer() - t.Reset(time.Now().Add(d)) - Eventually(t.Chan()).Should(Receive()) - }) - - It("works multiple times with reading", func() { - t := NewTimer() - for i := 0; i < 10; i++ { - t.Reset(time.Now().Add(d)) - Eventually(t.Chan()).Should(Receive()) - t.SetRead() - } - }) - - It("works multiple times without reading", func() { - t := NewTimer() - for i := 0; i < 10; i++ { - t.Reset(time.Now().Add(d)) - time.Sleep(d * 2) - } - Eventually(t.Chan()).Should(Receive()) - }) - - It("works when resetting without expiration", func() { - t := NewTimer() - for i := 0; i < 10; i++ { - t.Reset(time.Now().Add(time.Hour)) - } - t.Reset(time.Now().Add(d)) - Eventually(t.Chan()).Should(Receive()) - }) - - It("immediately fires the timer, if the deadlines has already passed", func() { - t := NewTimer() - t.Reset(time.Now().Add(-time.Second)) - Eventually(t.Chan()).Should(Receive()) - }) - - It("fires the timer twice, if reset to the same deadline", func() { - deadline := time.Now().Add(-time.Millisecond) - t := NewTimer() - t.Reset(deadline) - Eventually(t.Chan()).Should(Receive()) - t.SetRead() - t.Reset(deadline) - Eventually(t.Chan()).Should(Receive()) - }) - - It("only fires the timer once, if it is reset to the same deadline, but not read in between", func() { - deadline := time.Now().Add(-time.Millisecond) - t := NewTimer() - t.Reset(deadline) - Eventually(t.Chan()).Should(Receive()) - Consistently(t.Chan()).ShouldNot(Receive()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/utils/utils_suite_test.go b/vendor/lucas-clemente/quic-go/internal/utils/utils_suite_test.go deleted file mode 100644 index 2874819b8..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/utils_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package utils - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestCrypto(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Utils Suite") -} diff --git a/vendor/lucas-clemente/quic-go/internal/utils/varint_packetnumber_test.go b/vendor/lucas-clemente/quic-go/internal/utils/varint_packetnumber_test.go deleted file mode 100644 index d743b1ae3..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/varint_packetnumber_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package utils - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Varint packet number encoding / decoding", func() { - Context("Decoding", func() { - It("reads a 1 byte number", func() { - b := bytes.NewReader([]byte{0x19}) // 00011001 - p, len, err := ReadVarIntPacketNumber(b) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen1)) - Expect(p).To(Equal(protocol.PacketNumber(0x19))) - }) - - It("errors when given an empty reader", func() { - _, _, err := ReadVarIntPacketNumber(bytes.NewReader(nil)) - Expect(err).To(MatchError(io.EOF)) - }) - - It("reads a 2 byte number", func() { - b := bytes.NewReader([]byte{0xb7, 0x19}) // first byte: 10110111 - p, len, err := ReadVarIntPacketNumber(b) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen2)) - Expect(p).To(Equal(protocol.PacketNumber(0x3719))) - }) - - It("errors on EOF when reading a 2 byte number", func() { - b := bytes.NewReader([]byte{0xb7}) // first byte: 10110111 - _, _, err := ReadVarIntPacketNumber(b) - Expect(err).To(MatchError(io.EOF)) - }) - - It("reads a 4 byte number", func() { - b := bytes.NewReader([]byte{0xe5, 0x89, 0xfa, 0x19}) // first byte: 11100101 - p, len, err := ReadVarIntPacketNumber(b) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen4)) - Expect(p).To(Equal(protocol.PacketNumber(0x2589fa19))) - }) - - It("errors on EOF after the 3rd byte when reading a 4 byte number", func() { - b := bytes.NewReader([]byte{0xe5, 0x89}) // first byte: 11100101 - _, _, err := ReadVarIntPacketNumber(b) - Expect(err).To(MatchError(io.EOF)) - }) - - It("errors on EOF after the 4th byte when reading a 4 byte number", func() { - b := bytes.NewReader([]byte{0xe5, 0x89, 0xfa}) // first byte: 11100101 - _, _, err := ReadVarIntPacketNumber(b) - Expect(err).To(MatchError(io.EOF)) - }) - }) - - Context("Encoding", func() { - It("writes a 1 byte packet number", func() { - b := &bytes.Buffer{} - err := WriteVarIntPacketNumber(b, 0x42, protocol.PacketNumberLen1) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(1)) - p, len, err := ReadVarIntPacketNumber(bytes.NewReader(b.Bytes())) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen1)) - Expect(p).To(Equal(protocol.PacketNumber(0x42))) - }) - - It("only uses the least significant 7 bits when writing a 1 byte packet number", func() { - b := &bytes.Buffer{} - err := WriteVarIntPacketNumber(b, 0x1234ea, protocol.PacketNumberLen1) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(1)) - p, len, err := ReadVarIntPacketNumber(bytes.NewReader(b.Bytes())) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen1)) - Expect(p).To(Equal(protocol.PacketNumber(0x6a))) - }) - - It("writes a small 2 byte packet number", func() { - b := &bytes.Buffer{} - err := WriteVarIntPacketNumber(b, 0x42, protocol.PacketNumberLen2) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(2)) - p, len, err := ReadVarIntPacketNumber(bytes.NewReader(b.Bytes())) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen2)) - Expect(p).To(Equal(protocol.PacketNumber(0x42))) - }) - - It("writes a 2 byte packet number", func() { - b := &bytes.Buffer{} - err := WriteVarIntPacketNumber(b, 0x1337, protocol.PacketNumberLen2) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(2)) - p, len, err := ReadVarIntPacketNumber(bytes.NewReader(b.Bytes())) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen2)) - Expect(p).To(Equal(protocol.PacketNumber(0x1337))) - }) - - It("only uses the least significant 14 bits when writing a 2 byte packet number", func() { - b := &bytes.Buffer{} - err := WriteVarIntPacketNumber(b, 0x1234ff37, protocol.PacketNumberLen2) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(2)) - p, len, err := ReadVarIntPacketNumber(bytes.NewReader(b.Bytes())) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen2)) - Expect(p).To(Equal(protocol.PacketNumber(0x3f37))) - }) - - It("writes a small 4 byte packet number", func() { - b := &bytes.Buffer{} - err := WriteVarIntPacketNumber(b, 0xbeef, protocol.PacketNumberLen4) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(4)) - p, len, err := ReadVarIntPacketNumber(bytes.NewReader(b.Bytes())) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen4)) - Expect(p).To(Equal(protocol.PacketNumber(0xbeef))) - }) - - It("writes a 4 byte packet number", func() { - b := &bytes.Buffer{} - err := WriteVarIntPacketNumber(b, 0x12beef42, protocol.PacketNumberLen4) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(4)) - p, len, err := ReadVarIntPacketNumber(bytes.NewReader(b.Bytes())) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen4)) - Expect(p).To(Equal(protocol.PacketNumber(0x12beef42))) - }) - - It("only uses the least significant 30 bits when writing a 4 byte packet number", func() { - b := &bytes.Buffer{} - err := WriteVarIntPacketNumber(b, 0x1234deadbeef, protocol.PacketNumberLen4) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(4)) - p, len, err := ReadVarIntPacketNumber(bytes.NewReader(b.Bytes())) - Expect(err).ToNot(HaveOccurred()) - Expect(len).To(Equal(protocol.PacketNumberLen4)) - Expect(p).To(Equal(protocol.PacketNumber(0x1eadbeef))) - }) - - It("errors when encountering invalid packet number lengths", func() { - b := &bytes.Buffer{} - err := WriteVarIntPacketNumber(b, 0x1234deadbeef, 13) - Expect(err).To(MatchError("invalid packet number length: 13")) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/utils/varint_test.go b/vendor/lucas-clemente/quic-go/internal/utils/varint_test.go deleted file mode 100644 index b49774f02..000000000 --- a/vendor/lucas-clemente/quic-go/internal/utils/varint_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package utils - -import ( - "bytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Varint encoding / decoding", func() { - Context("decoding", func() { - It("reads a 1 byte number", func() { - b := bytes.NewReader([]byte{25}) // 00011001 - val, err := ReadVarInt(b) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint64(25))) - Expect(b.Len()).To(BeZero()) - }) - - It("reads a number that is encoded too long", func() { - b := bytes.NewReader([]byte{0x40, 0x25}) // first byte: 01000000 - val, err := ReadVarInt(b) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint64(37))) - Expect(b.Len()).To(BeZero()) - }) - - It("reads a 2 byte number", func() { - b := bytes.NewReader([]byte{0x7b, 0xbd}) // first byte: 01111011 - val, err := ReadVarInt(b) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint64(15293))) - Expect(b.Len()).To(BeZero()) - }) - - It("reads a 4 byte number", func() { - b := bytes.NewReader([]byte{0x9d, 0x7f, 0x3e, 0x7d}) // first byte: 10011011 - val, err := ReadVarInt(b) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint64(494878333))) - Expect(b.Len()).To(BeZero()) - }) - - It("reads an 8 byte number", func() { - b := bytes.NewReader([]byte{0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c}) // first byte: 10000010 - val, err := ReadVarInt(b) - Expect(err).ToNot(HaveOccurred()) - Expect(val).To(Equal(uint64(151288809941952652))) - Expect(b.Len()).To(BeZero()) - }) - }) - - Context("encoding", func() { - It("writes a 1 byte number", func() { - b := &bytes.Buffer{} - WriteVarInt(b, 37) - Expect(b.Bytes()).To(Equal([]byte{0x25})) - }) - - It("writes the maximum 1 byte number in 1 byte", func() { - b := &bytes.Buffer{} - WriteVarInt(b, maxVarInt1) - Expect(b.Bytes()).To(Equal([]byte{0x3f /* 00111111 */})) - }) - - It("writes the minimum 2 byte number in 2 bytes", func() { - b := &bytes.Buffer{} - WriteVarInt(b, maxVarInt1+1) - Expect(b.Bytes()).To(Equal([]byte{0x40, maxVarInt1 + 1})) - }) - - It("writes a 2 byte number", func() { - b := &bytes.Buffer{} - WriteVarInt(b, 15293) - Expect(b.Bytes()).To(Equal([]byte{0x7b, 0xbd})) - }) - - It("writes the maximum 2 byte number in 2 bytes", func() { - b := &bytes.Buffer{} - WriteVarInt(b, maxVarInt2) - Expect(b.Bytes()).To(Equal([]byte{0x7f /* 01111111 */, 0xff})) - }) - - It("writes the minimum 4 byte number in 4 bytes", func() { - b := &bytes.Buffer{} - WriteVarInt(b, maxVarInt2+1) - Expect(b.Len()).To(Equal(4)) - num, err := ReadVarInt(b) - Expect(err).ToNot(HaveOccurred()) - Expect(num).To(Equal(uint64(maxVarInt2 + 1))) - }) - - It("writes a 4 byte number", func() { - b := &bytes.Buffer{} - WriteVarInt(b, 494878333) - Expect(b.Bytes()).To(Equal([]byte{0x9d, 0x7f, 0x3e, 0x7d})) - }) - - It("writes the maximum 4 byte number in 4 bytes", func() { - b := &bytes.Buffer{} - WriteVarInt(b, maxVarInt4) - Expect(b.Bytes()).To(Equal([]byte{0xbf /* 10111111 */, 0xff, 0xff, 0xff})) - }) - - It("writes the minimum 8 byte number in 8 bytes", func() { - b := &bytes.Buffer{} - WriteVarInt(b, maxVarInt4+1) - Expect(b.Len()).To(Equal(8)) - num, err := ReadVarInt(b) - Expect(err).ToNot(HaveOccurred()) - Expect(num).To(Equal(uint64(maxVarInt4 + 1))) - }) - - It("writes an 8 byte number", func() { - b := &bytes.Buffer{} - WriteVarInt(b, 151288809941952652) - Expect(b.Bytes()).To(Equal([]byte{0xc2, 0x19, 0x7c, 0x5e, 0xff, 0x14, 0xe8, 0x8c})) - }) - - It("writes the maximum 8 byte number in 8 bytes", func() { - b := &bytes.Buffer{} - WriteVarInt(b, maxVarInt8) - Expect(b.Bytes()).To(Equal([]byte{0xff /* 11111111 */, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff})) - }) - - It("panics when given a too large number (> 62 bit)", func() { - b := &bytes.Buffer{} - Expect(func() { WriteVarInt(b, maxVarInt8+1) }).Should(Panic()) - }) - }) - - Context("determining the length needed for encoding", func() { - It("for numbers that need 1 byte", func() { - Expect(VarIntLen(0)).To(BeEquivalentTo(1)) - Expect(VarIntLen(maxVarInt1)).To(BeEquivalentTo(1)) - }) - - It("for numbers that need 2 bytes", func() { - Expect(VarIntLen(maxVarInt1 + 1)).To(BeEquivalentTo(2)) - Expect(VarIntLen(maxVarInt2)).To(BeEquivalentTo(2)) - }) - - It("for numbers that need 4 bytes", func() { - Expect(VarIntLen(maxVarInt2 + 1)).To(BeEquivalentTo(4)) - Expect(VarIntLen(maxVarInt4)).To(BeEquivalentTo(4)) - }) - - It("for numbers that need 8 bytes", func() { - Expect(VarIntLen(maxVarInt4 + 1)).To(BeEquivalentTo(8)) - Expect(VarIntLen(maxVarInt8)).To(BeEquivalentTo(8)) - }) - - It("panics when given a too large number (> 62 bit)", func() { - Expect(func() { VarIntLen(maxVarInt8 + 1) }).Should(Panic()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/ack_frame_legacy_test.go b/vendor/lucas-clemente/quic-go/internal/wire/ack_frame_legacy_test.go deleted file mode 100644 index 3be341a2f..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/ack_frame_legacy_test.go +++ /dev/null @@ -1,1045 +0,0 @@ -package wire - -import ( - "bytes" - "io" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ACK Frame (for gQUIC)", func() { - Context("when parsing", func() { - It("accepts a sample frame", func() { - b := bytes.NewReader([]byte{0x40, - 0x1c, // largest acked - 0x0, 0x0, // delay time - 0x1c, // block length - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x1c))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(1))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame that acks packet number 0", func() { - b := bytes.NewReader([]byte{0x40, - 0x0, // largest acked - 0x0, 0x0, // delay time - 0x1, // block length - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(0))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with 1 ACKed packet", func() { - b := bytes.NewReader([]byte{0x40, - 0x10, // largest acked - 0x0, 0x0, // delay time - 0x1, // block length - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x10))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(0x10))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame that acks multiple packets, starting with 0", func() { - b := bytes.NewReader([]byte{0x40, - 0x10, // largest acked - 0x0, 0x0, // delay time - 0x11, // block length - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x10))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(0))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with multiple timestamps", func() { - b := bytes.NewReader([]byte{0x40, - 0x10, // largest acked - 0x0, 0x0, // timestamp - 0x10, // block length - 0x4, // num timestamps - 0x1, 0x6b, 0x26, 0x4, 0x0, // 1st timestamp - 0x3, 0, 0, // 2nd timestamp - 0x2, 0, 0, // 3rd timestamp - 0x1, 0, 0, // 4th timestamp - }) - _, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(BeZero()) - }) - - It("errors when the ACK range is too large", func() { - // LargestAcked: 0x1c - // Length: 0x1d => LowestAcked would be -1 - b := bytes.NewReader([]byte{0x40, - 0x1c, // largest acked - 0x0, 0x0, // delay time - 0x1e, // block length - 0, - }) - _, err := parseAckFrame(b, versionBigEndian) - Expect(err).To(MatchError(errInvalidAckRanges)) - }) - - It("errors when the first ACK range is empty", func() { - b := bytes.NewReader([]byte{0x40, - 0x9, // largest acked - 0x0, 0x0, // delay time - 0x0, // block length - 0, - }) - _, err := parseAckFrame(b, versionBigEndian) - Expect(err).To(MatchError("invalid first ACK range")) - }) - - It("parses the delay time", func() { - b := bytes.NewReader([]byte{0x40, - 0x3, // largest acked - 0x0, 0x8e, // delay time - 0x3, // block length - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(3))) - Expect(frame.DelayTime).To(Equal(142 * time.Microsecond)) - }) - - It("errors on EOFs", func() { - data := []byte{0x60 ^ 0x4 ^ 0x1, - 0x9, 0x66, // largest acked - 0x23, 0x1, // delay time - 0x7, // num ACk blocks - 0x0, 0x7, // 1st block - 0xff, 0x0, 0x0, // 2nd block - 0xf5, 0x2, 0x8a, // 3rd block - 0xc8, 0x0, 0xe6, // 4th block - 0xff, 0x0, 0x0, // 5th block - 0xff, 0x0, 0x0, // 6th block - 0xff, 0x0, 0x0, // 7th block - 0x23, 0x0, 0x13, // 8th blocks - 0x2, // num timestamps - 0x1, 0x13, 0xae, 0xb, 0x0, // 1st timestamp - 0x0, 0x80, 0x5, // 2nd timestamp - } - _, err := parseAckFrame(bytes.NewReader(data), versionBigEndian) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseAckFrame(bytes.NewReader(data[0:i]), versionBigEndian) - Expect(err).To(MatchError(io.EOF)) - } - }) - - Context("largest acked length", func() { - It("parses a frame with a 2 byte packet number", func() { - b := bytes.NewReader([]byte{0x40 | 0x4, - 0x13, 0x37, // largest acked - 0x0, 0x0, // delay time - 0x9, // block length - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x1337))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(0x1337 - 0x9 + 1))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with a 4 byte packet number", func() { - b := bytes.NewReader([]byte{0x40 | 0x8, - 0xde, 0xca, 0xfb, 0xad, // largest acked - 0x0, 0x0, // timesatmp - 0x5, // block length - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0xdecafbad))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(0xdecafbad - 5 + 1))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with a 6 byte packet number", func() { - b := bytes.NewReader([]byte{0x4 | 0xc, - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, // largest acked - 0x0, 0x0, // delay time - 0x5, // block length - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0xdeadbeefcafe))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(0xdeadbeefcafe - 5 + 1))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - }) - - Context("ACK blocks", func() { - It("parses a frame with two ACK blocks", func() { - b := bytes.NewReader([]byte{0x60, - 0x18, // largest acked - 0x0, 0x0, // delay time - 0x1, // num ACK blocks - 0x3, // 1st block - 0x2, 0x10, // 2nd block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x18))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(2)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 0x18 - 0x3 + 1, Largest: 0x18})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: (0x18 - 0x3 + 1) - (0x2 + 1) - (0x10 - 1), Largest: (0x18 - 0x3 + 1) - (0x2 + 1)})) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(4))) - Expect(b.Len()).To(BeZero()) - }) - - It("rejects a frame with invalid ACK ranges", func() { - // like the test before, but increased the last ACK range, such that the First would be negative - b := bytes.NewReader([]byte{0x60, - 0x18, // largest acked - 0x0, 0x0, // delay time - 0x1, // num ACK blocks - 0x3, // 1st block - 0x2, 0x15, // 2nd block - 0, - }) - _, err := parseAckFrame(b, versionBigEndian) - Expect(err).To(MatchError(errInvalidAckRanges)) - }) - - It("rejects a frame that says it has ACK blocks in the typeByte, but doesn't have any", func() { - b := bytes.NewReader([]byte{0x60 ^ 0x3, - 0x4, // largest acked - 0x0, 0x0, // delay time - 0, // num ACK blocks - 0, - }) - _, err := parseAckFrame(b, versionBigEndian) - Expect(err).To(MatchError(errInvalidAckRanges)) - }) - - It("parses a frame with multiple single packets missing", func() { - b := bytes.NewReader([]byte{0x60, - 0x27, // largest acked - 0x0, 0x0, // delay time - 0x6, // num ACK blocks - 0x9, // 1st block - 0x1, 0x1, // 2nd block - 0x1, 0x1, // 3rd block - 0x1, 0x1, // 4th block - 0x1, 0x1, // 5th block - 0x1, 0x1, // 6th block - 0x1, 0x13, // 7th block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x27))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(7)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 31, Largest: 0x27})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: 29, Largest: 29})) - Expect(frame.AckRanges[2]).To(Equal(AckRange{Smallest: 27, Largest: 27})) - Expect(frame.AckRanges[3]).To(Equal(AckRange{Smallest: 25, Largest: 25})) - Expect(frame.AckRanges[4]).To(Equal(AckRange{Smallest: 23, Largest: 23})) - Expect(frame.AckRanges[5]).To(Equal(AckRange{Smallest: 21, Largest: 21})) - Expect(frame.AckRanges[6]).To(Equal(AckRange{Smallest: 1, Largest: 19})) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(1))) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with multiple longer ACK blocks", func() { - b := bytes.NewReader([]byte{0x60, - 0x52, // largest acked - 0xd1, 0x0, //delay time - 0x3, // num ACK blocks - 0x17, // 1st block - 0xa, 0x10, // 2nd block - 0x4, 0x8, // 3rd block - 0x2, 0x12, // 4th block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x52))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(4)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 60, Largest: 0x52})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: 34, Largest: 49})) - Expect(frame.AckRanges[2]).To(Equal(AckRange{Smallest: 22, Largest: 29})) - Expect(frame.AckRanges[3]).To(Equal(AckRange{Smallest: 2, Largest: 19})) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(2))) - Expect(b.Len()).To(BeZero()) - }) - - Context("more than 256 lost packets in a row", func() { - // 255 missing packets fit into a single ACK block - It("parses a frame with a range of 255 missing packets", func() { - b := bytes.NewReader([]byte{0x60 ^ 0x4, - 0x1, 0x15, // largest acked - 0x0, 0x0, // delay time - 0x1, // num ACK blocks - 0x3, // 1st block - 0xff, 0x13, // 2nd block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x115))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(2)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 20 + 255, Largest: 0x115})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: 1, Largest: 19})) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(1))) - Expect(b.Len()).To(BeZero()) - }) - - // 256 missing packets fit into two ACK blocks - It("parses a frame with a range of 256 missing packets", func() { - b := bytes.NewReader([]byte{0x60 ^ 0x4, - 0x1, 0x14, // largest acked - 0x0, 0x0, // delay time - 0x2, // num ACK blocks - 0x1, // 1st block - 0xff, 0x0, // 2nd block - 0x1, 0x13, // 3rd block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x114))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(2)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 20 + 256, Largest: 0x114})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: 1, Largest: 19})) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(1))) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with an incomplete range at the end", func() { - // this is a modified ACK frame that has 5 instead of originally 6 written ranges - // each gap is 300 packets and thus takes 2 ranges - // the last range is incomplete, and should be completely ignored - b := bytes.NewReader([]byte{0x60 ^ 0x4, - 0x3, 0x9b, // largest acked - 0x0, 0x0, // delay time - 0x5, // num ACK blocks, instead of 0x6 - 0x1, // 1st block - 0xff, 0x0, // 2nd block - 0x2d, 0x1, // 3rd block - 0xff, 0x0, // 4th block - 0x2d, 0x1, // 5th block - 0xff, 0x0, /*0x2d, 0x14,*/ // 6th block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x39b))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(3)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 20 + 3*301, Largest: 20 + 3*301})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: 20 + 2*301, Largest: 20 + 2*301})) - Expect(frame.AckRanges[2]).To(Equal(AckRange{Smallest: 20 + 1*301, Largest: 20 + 1*301})) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with one long range, spanning 2 blocks, of missing packets", func() { - // 280 missing packets - b := bytes.NewReader([]byte{0x60 ^ 0x4, - 0x1, 0x44, // largest acked - 0x0, 0x0, // delay time - 0x2, // num ACK blocks - 0x19, // 1st block - 0xff, 0x0, // 2nd block - 0x19, 0x13, // 3rd block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x144))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(2)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 300, Largest: 0x144})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: 1, Largest: 19})) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(1))) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with one long range, spanning multiple blocks, of missing packets", func() { - // 2345 missing packets - b := bytes.NewReader([]byte{0x60 ^ 0x4, - 0x9, 0x5b, // largest acked - 0x0, 0x0, // delay time - 0xa, // num ACK blocks - 0x1f, // 1st block - 0xff, 0x0, // 2nd block - 0xff, 0x0, // 3rd block - 0xff, 0x0, // 4th block - 0xff, 0x0, // 5th block - 0xff, 0x0, // 6th block - 0xff, 0x0, // 7th block - 0xff, 0x0, // 8th block - 0xff, 0x0, // 9th block - 0xff, 0x0, // 10th block - 0x32, 0x13, // 11th block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x95b))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(2)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 2365, Largest: 0x95b})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: 1, Largest: 19})) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(1))) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with multiple 2 byte long ranges of missing packets", func() { - b := bytes.NewReader([]byte{0x60 ^ 0x4 ^ 0x1, - 0x9, 0x66, // largest acked - 0x0, 0x0, // delay time - 0x7, // num ACK blocks - 0x0, 0x7, // 1st block - 0xff, 0x0, 0x0, // 2nd block - 0xf5, 0x2, 0x8a, // 3rd block - 0xc8, 0x0, 0xe6, // 4th block - 0xff, 0x0, 0x0, // 5th block - 0xff, 0x0, 0x0, // 6th block - 0xff, 0x0, 0x0, // 7th block - 0x23, 0x0, 0x13, // 8th block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0x966))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(4)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 2400, Largest: 0x966})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: 1250, Largest: 1899})) - Expect(frame.AckRanges[2]).To(Equal(AckRange{Smallest: 820, Largest: 1049})) - Expect(frame.AckRanges[3]).To(Equal(AckRange{Smallest: 1, Largest: 19})) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(1))) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with with a 4 byte ack block length", func() { - b := bytes.NewReader([]byte{0x60 ^ 0xc ^ 0x2, - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, // largest acked - 0x0, 0x0, // delay time - 0x1, // num ACK blocks - 0, 0, 0x13, 0x37, // 1st block - 0x20, 0x12, 0x34, 0x56, 0x78, // 2nd block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0xdeadbeefcafe))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(2)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 0xdeadbeefcafe - 0x1337 + 1, Largest: 0xdeadbeefcafe})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: (0xdeadbeefcafe - 0x1337 + 1) - (0x20 + 1) - (0x12345678 - 1), Largest: (0xdeadbeefcafe - 0x1337 + 1) - (0x20 + 1)})) - }) - - It("parses a frame with with a 6 byte ack block length", func() { - b := bytes.NewReader([]byte{0x60 ^ 0xc ^ 0x3, - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, // largest acked - 0x0, 0x0, // delay time - 0x1, // num ACk blocks - 0, 0, 0, 0, 0x13, 0x37, // 1st block - 0x20, 0x0, 0xab, 0x12, 0x34, 0x56, 0x78, // 2nd block - 0, - }) - frame, err := parseAckFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(0xdeadbeefcafe))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(HaveLen(2)) - Expect(frame.AckRanges[0]).To(Equal(AckRange{Smallest: 0xdeadbeefcafe - 0x1337 + 1, Largest: 0xdeadbeefcafe})) - Expect(frame.AckRanges[1]).To(Equal(AckRange{Smallest: (0xdeadbeefcafe - 0x1337 + 1) - (0x20 + 1) - (0xab12345678 - 1), Largest: (0xdeadbeefcafe - 0x1337 + 1) - (0x20 + 1)})) - }) - }) - }) - }) - - Context("when writing", func() { - var b *bytes.Buffer - - BeforeEach(func() { - b = &bytes.Buffer{} - }) - - Context("self-consistency", func() { - It("writes a simple ACK frame", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{{Smallest: 1, Largest: 1}}, - DelayTime: 876 * time.Microsecond, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(frame.DelayTime).To(Equal(frameOrig.DelayTime)) - Expect(r.Len()).To(BeZero()) - }) - - It("writes an ACK that also acks packet 0", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{{Smallest: 0, Largest: 1}}, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(r.Len()).To(BeZero()) - }) - - It("writes the correct block length in a simple ACK frame", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{{Smallest: 10, Largest: 20}}, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(r.Len()).To(BeZero()) - }) - - It("writes a simple ACK frame with a high packet number", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{{Smallest: 0xdeadbeefcafe, Largest: 0xdeadbeefcafe}}, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(r.Len()).To(BeZero()) - }) - - It("writes an ACK frame with one packet missing", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 25, Largest: 40}, - {Smallest: 0, Largest: 23}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - Expect(r.Len()).To(BeZero()) - }) - - It("writes an ACK frame with multiple missing packets", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 22, Largest: 25}, - {Smallest: 15, Largest: 18}, - {Smallest: 13, Largest: 13}, - {Smallest: 1, Largest: 10}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - Expect(r.Len()).To(BeZero()) - }) - - Context("longer gaps between ACK blocks", func() { - It("only writes one block for 254 lost packets", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 20 + 254, Largest: 300}, - {Smallest: 1, Largest: 19}, - }, - } - Expect(frameOrig.numWritableNackRanges()).To(Equal(uint64(2))) - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - }) - - It("only writes one block for 255 lost packets", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 20 + 255, Largest: 300}, - {Smallest: 1, Largest: 19}, - }, - } - Expect(frameOrig.numWritableNackRanges()).To(Equal(uint64(2))) - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - }) - - It("writes two blocks for 256 lost packets", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 20 + 256, Largest: 300}, - {Smallest: 1, Largest: 19}, - }, - } - Expect(frameOrig.numWritableNackRanges()).To(Equal(uint64(3))) - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - }) - - It("writes two blocks for 510 lost packets", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 20 + 510, Largest: 600}, - {Smallest: 1, Largest: 19}, - }, - } - Expect(frameOrig.numWritableNackRanges()).To(Equal(uint64(3))) - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - }) - - It("writes three blocks for 511 lost packets", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 20 + 511, Largest: 600}, - {Smallest: 1, Largest: 19}, - }, - } - Expect(frameOrig.numWritableNackRanges()).To(Equal(uint64(4))) - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - }) - - It("writes three blocks for 512 lost packets", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 20 + 512, Largest: 600}, - {Smallest: 1, Largest: 19}, - }, - } - Expect(frameOrig.numWritableNackRanges()).To(Equal(uint64(4))) - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - }) - - It("writes multiple blocks for a lot of lost packets", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 2900, Largest: 3000}, - {Smallest: 1, Largest: 19}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - }) - - It("writes multiple longer blocks for 256 lost packets", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 2900, Largest: 3600}, - {Smallest: 1000, Largest: 2500}, - {Smallest: 1, Largest: 19}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - }) - }) - - Context("largest acked length", func() { - It("writes a 1 largest acked", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{{Smallest: 1, Largest: 200}}, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x0))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(r.Len()).To(BeZero()) - }) - - It("writes a 2 byte largest acked", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{{Smallest: 1, Largest: 0x100}}, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x1))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(r.Len()).To(BeZero()) - }) - - It("writes a 4 byte largest acked", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{{Smallest: 1, Largest: 0x10000}}, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x2))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(r.Len()).To(BeZero()) - }) - - It("writes a 6 byte largest acked", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{{Smallest: 1, Largest: 0x100000000}}, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x3))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(r.Len()).To(BeZero()) - }) - }) - - Context("ack block length", func() { - It("writes a 1 byte ack block length, if all ACK blocks are short", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 5000, Largest: 5001}, - {Smallest: 250, Largest: 300}, - {Smallest: 1, Largest: 200}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x0))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - Expect(r.Len()).To(BeZero()) - }) - - It("writes a 2 byte ack block length, for a frame with one ACK block", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 9990, Largest: 10000}, - {Smallest: 1, Largest: 9988}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x1))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - Expect(r.Len()).To(BeZero()) - }) - - It("writes a 2 byte ack block length, for a frame with multiple ACK blocks", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 9990, Largest: 10000}, - {Smallest: 1, Largest: 256}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x1))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - Expect(r.Len()).To(BeZero()) - }) - - It("writes a 4 byte ack block length, for a frame with single ACK blocks", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 9990, Largest: 0xdeadbeef}, - {Smallest: 1, Largest: 9988}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x2))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - Expect(r.Len()).To(BeZero()) - }) - - It("writes a 4 byte ack block length, for a frame with multiple ACK blocks", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 9990, Largest: 0xdeadbeef}, - {Smallest: 1, Largest: 256}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x2))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - Expect(r.Len()).To(BeZero()) - }) - - It("writes a 6 byte ack block length, for a frame with a single ACK blocks", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 9990, Largest: 0xdeadbeefcafe}, - {Smallest: 1, Largest: 9988}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x3))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - Expect(r.Len()).To(BeZero()) - }) - - It("writes a 6 byte ack block length, for a frame with multiple ACK blocks", func() { - frameOrig := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 9990, Largest: 0xdeadbeefcafe}, - {Smallest: 1, Largest: 256}, - }, - } - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(byte(0x3))) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(frameOrig.LowestAcked())) - Expect(frame.AckRanges).To(Equal(frameOrig.AckRanges)) - Expect(r.Len()).To(BeZero()) - }) - }) - - Context("too many ACK blocks", func() { - It("skips the lowest ACK ranges, if there are more than 255 AckRanges", func() { - ackRanges := make([]AckRange, 300) - for i := 1; i <= 300; i++ { - ackRanges[300-i] = AckRange{Smallest: protocol.PacketNumber(3 * i), Largest: protocol.PacketNumber(3*i + 1)} - } - frameOrig := &AckFrame{AckRanges: ackRanges} - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(ackRanges[254].Smallest)) - Expect(frame.AckRanges).To(HaveLen(0xFF)) - Expect(frame.validateAckRanges()).To(BeTrue()) - }) - - It("skips the lowest ACK ranges, if the gaps are large", func() { - ackRanges := make([]AckRange, 100) - // every AckRange will take 4 written ACK ranges - for i := 1; i <= 100; i++ { - ackRanges[100-i] = AckRange{Smallest: protocol.PacketNumber(1000 * i), Largest: protocol.PacketNumber(1000*i + 1)} - } - frameOrig := &AckFrame{AckRanges: ackRanges} - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.LowestAcked()).To(Equal(ackRanges[255/4].Smallest)) - Expect(frame.validateAckRanges()).To(BeTrue()) - }) - - It("works with huge gaps", func() { - ackRanges := []AckRange{ - {Smallest: 2 * 255 * 200, Largest: 2*255*200 + 1}, - {Smallest: 1 * 255 * 200, Largest: 1*255*200 + 1}, - {Smallest: 1, Largest: 2}, - } - frameOrig := &AckFrame{AckRanges: ackRanges} - err := frameOrig.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - r := bytes.NewReader(b.Bytes()) - frame, err := parseAckFrame(r, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(frameOrig.LargestAcked())) - Expect(frame.AckRanges).To(HaveLen(2)) - Expect(frame.LowestAcked()).To(Equal(ackRanges[1].Smallest)) - Expect(frame.validateAckRanges()).To(BeTrue()) - }) - }) - }) - - Context("min length", func() { - It("has proper min length", func() { - f := &AckFrame{ - AckRanges: []AckRange{{Smallest: 1, Largest: 1}}, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionBigEndian)).To(Equal(protocol.ByteCount(b.Len()))) - }) - - It("has proper min length with a large LargestObserved", func() { - f := &AckFrame{ - AckRanges: []AckRange{{Smallest: 1, Largest: 0xdeadbeefcafe}}, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionBigEndian)).To(Equal(protocol.ByteCount(b.Len()))) - }) - - It("has the proper min length for an ACK with missing packets", func() { - f := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 1000, Largest: 2000}, - {Smallest: 50, Largest: 900}, - {Smallest: 10, Largest: 23}, - }, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionBigEndian)).To(Equal(protocol.ByteCount(b.Len()))) - }) - - It("has the proper min length for an ACK with long gaps of missing packets", func() { - f := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 1500, Largest: 2000}, - {Smallest: 290, Largest: 295}, - {Smallest: 1, Largest: 19}, - }, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionBigEndian)).To(Equal(protocol.ByteCount(b.Len()))) - }) - - It("has the proper min length for an ACK with a long ACK range", func() { - largestAcked := protocol.PacketNumber(2 + 0xFFFFFF) - f := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 1500, Largest: largestAcked}, - {Smallest: 290, Largest: 295}, - {Smallest: 1, Largest: 19}, - }, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionBigEndian)).To(Equal(protocol.ByteCount(b.Len()))) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/ack_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/ack_frame_test.go deleted file mode 100644 index 65c9e4ab1..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/ack_frame_test.go +++ /dev/null @@ -1,410 +0,0 @@ -package wire - -import ( - "bytes" - "io" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ACK Frame (for IETF QUIC)", func() { - Context("parsing", func() { - It("parses an ACK frame without any ranges", func() { - data := []byte{0xd} - data = append(data, encodeVarInt(100)...) // largest acked - data = append(data, encodeVarInt(0)...) // delay - data = append(data, encodeVarInt(0)...) // num blocks - data = append(data, encodeVarInt(10)...) // first ack block - b := bytes.NewReader(data) - frame, err := parseAckFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(100))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(90))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("parses an ACK frame that only acks a single packet", func() { - data := []byte{0xd} - data = append(data, encodeVarInt(55)...) // largest acked - data = append(data, encodeVarInt(0)...) // delay - data = append(data, encodeVarInt(0)...) // num blocks - data = append(data, encodeVarInt(0)...) // first ack block - b := bytes.NewReader(data) - frame, err := parseAckFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(55))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(55))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("accepts an ACK frame that acks all packets from 0 to largest", func() { - data := []byte{0xd} - data = append(data, encodeVarInt(20)...) // largest acked - data = append(data, encodeVarInt(0)...) // delay - data = append(data, encodeVarInt(0)...) // num blocks - data = append(data, encodeVarInt(20)...) // first ack block - b := bytes.NewReader(data) - frame, err := parseAckFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(20))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(0))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("rejects an ACK frame that has a first ACK block which is larger than LargestAcked", func() { - data := []byte{0xd} - data = append(data, encodeVarInt(20)...) // largest acked - data = append(data, encodeVarInt(0)...) // delay - data = append(data, encodeVarInt(0)...) // num blocks - data = append(data, encodeVarInt(21)...) // first ack block - b := bytes.NewReader(data) - _, err := parseAckFrame(b, versionIETFFrames) - Expect(err).To(MatchError("invalid first ACK range")) - }) - - It("parses an ACK frame that has a single block", func() { - data := []byte{0xd} - data = append(data, encodeVarInt(1000)...) // largest acked - data = append(data, encodeVarInt(0)...) // delay - data = append(data, encodeVarInt(1)...) // num blocks - data = append(data, encodeVarInt(100)...) // first ack block - data = append(data, encodeVarInt(98)...) // gap - data = append(data, encodeVarInt(50)...) // ack block - b := bytes.NewReader(data) - frame, err := parseAckFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(1000))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(750))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(Equal([]AckRange{ - {Largest: 1000, Smallest: 900}, - {Largest: 800, Smallest: 750}, - })) - Expect(b.Len()).To(BeZero()) - }) - - It("parses an ACK frame that has a multiple blocks", func() { - data := []byte{0xd} - data = append(data, encodeVarInt(100)...) // largest acked - data = append(data, encodeVarInt(0)...) // delay - data = append(data, encodeVarInt(2)...) // num blocks - data = append(data, encodeVarInt(0)...) // first ack block - data = append(data, encodeVarInt(0)...) // gap - data = append(data, encodeVarInt(0)...) // ack block - data = append(data, encodeVarInt(1)...) // gap - data = append(data, encodeVarInt(1)...) // ack block - b := bytes.NewReader(data) - frame, err := parseAckFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(100))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(94))) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(frame.AckRanges).To(Equal([]AckRange{ - {Largest: 100, Smallest: 100}, - {Largest: 98, Smallest: 98}, - {Largest: 95, Smallest: 94}, - })) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOF", func() { - data := []byte{0xd} - data = append(data, encodeVarInt(1000)...) // largest acked - data = append(data, encodeVarInt(0)...) // delay - data = append(data, encodeVarInt(1)...) // num blocks - data = append(data, encodeVarInt(100)...) // first ack block - data = append(data, encodeVarInt(98)...) // gap - data = append(data, encodeVarInt(50)...) // ack block - _, err := parseAckFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseAckFrame(bytes.NewReader(data[0:i]), versionIETFFrames) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("when writing", func() { - It("writes a simple frame", func() { - buf := &bytes.Buffer{} - f := &AckFrame{ - AckRanges: []AckRange{{Smallest: 100, Largest: 1337}}, - } - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0xd} - expected = append(expected, encodeVarInt(1337)...) // largest acked - expected = append(expected, 0) // delay - expected = append(expected, encodeVarInt(0)...) // num ranges - expected = append(expected, encodeVarInt(1337-100)...) - Expect(buf.Bytes()).To(Equal(expected)) - }) - - It("writes a frame that acks a single packet", func() { - buf := &bytes.Buffer{} - f := &AckFrame{ - AckRanges: []AckRange{{Smallest: 0xdeadbeef, Largest: 0xdeadbeef}}, - DelayTime: 18 * time.Millisecond, - } - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionIETFFrames)).To(BeEquivalentTo(buf.Len())) - b := bytes.NewReader(buf.Bytes()) - frame, err := parseAckFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(frame.DelayTime).To(Equal(f.DelayTime)) - Expect(b.Len()).To(BeZero()) - }) - - It("writes a frame that acks many packets", func() { - buf := &bytes.Buffer{} - f := &AckFrame{ - AckRanges: []AckRange{{Smallest: 0x1337, Largest: 0xdeadbeef}}, - } - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionIETFFrames)).To(BeEquivalentTo(buf.Len())) - b := bytes.NewReader(buf.Bytes()) - frame, err := parseAckFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("writes a frame with a a single gap", func() { - buf := &bytes.Buffer{} - f := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 400, Largest: 1000}, - {Smallest: 100, Largest: 200}, - }, - } - Expect(f.validateAckRanges()).To(BeTrue()) - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionIETFFrames)).To(BeEquivalentTo(buf.Len())) - b := bytes.NewReader(buf.Bytes()) - frame, err := parseAckFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(b.Len()).To(BeZero()) - }) - - It("writes a frame with multiple ranges", func() { - buf := &bytes.Buffer{} - f := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 10, Largest: 10}, - {Smallest: 8, Largest: 8}, - {Smallest: 5, Largest: 6}, - {Smallest: 1, Largest: 3}, - }, - } - Expect(f.validateAckRanges()).To(BeTrue()) - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionIETFFrames)).To(BeEquivalentTo(buf.Len())) - b := bytes.NewReader(buf.Bytes()) - frame, err := parseAckFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(b.Len()).To(BeZero()) - }) - - It("limits the maximum size of the ACK frame", func() { - buf := &bytes.Buffer{} - const numRanges = 1000 - ackRanges := make([]AckRange, numRanges) - for i := protocol.PacketNumber(1); i <= numRanges; i++ { - ackRanges[numRanges-i] = AckRange{Smallest: 2 * i, Largest: 2 * i} - } - f := &AckFrame{AckRanges: ackRanges} - Expect(f.validateAckRanges()).To(BeTrue()) - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionIETFFrames)).To(BeEquivalentTo(buf.Len())) - // make sure the ACK frame is *a little bit* smaller than the MaxAckFrameSize - Expect(buf.Len()).To(BeNumerically(">", protocol.MaxAckFrameSize-5)) - Expect(buf.Len()).To(BeNumerically("<=", protocol.MaxAckFrameSize)) - b := bytes.NewReader(buf.Bytes()) - frame, err := parseAckFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.HasMissingRanges()).To(BeTrue()) - Expect(b.Len()).To(BeZero()) - Expect(len(frame.AckRanges)).To(BeNumerically("<", numRanges)) // make sure we dropped some ranges - }) - }) - - Context("ACK range validator", func() { - It("rejects ACKs without ranges", func() { - Expect((&AckFrame{}).validateAckRanges()).To(BeFalse()) - }) - - It("accepts an ACK without NACK Ranges", func() { - ack := AckFrame{ - AckRanges: []AckRange{{Smallest: 1, Largest: 7}}, - } - Expect(ack.validateAckRanges()).To(BeTrue()) - }) - - It("rejects ACK ranges with Smallest greater than Largest", func() { - ack := AckFrame{ - AckRanges: []AckRange{ - {Smallest: 8, Largest: 10}, - {Smallest: 4, Largest: 3}, - }, - } - Expect(ack.validateAckRanges()).To(BeFalse()) - }) - - It("rejects ACK ranges in the wrong order", func() { - ack := AckFrame{ - AckRanges: []AckRange{ - {Smallest: 2, Largest: 2}, - {Smallest: 6, Largest: 7}, - }, - } - Expect(ack.validateAckRanges()).To(BeFalse()) - }) - - It("rejects with overlapping ACK ranges", func() { - ack := AckFrame{ - AckRanges: []AckRange{ - {Smallest: 5, Largest: 7}, - {Smallest: 2, Largest: 5}, - }, - } - Expect(ack.validateAckRanges()).To(BeFalse()) - }) - - It("rejects ACK ranges that are part of a larger ACK range", func() { - ack := AckFrame{ - AckRanges: []AckRange{ - {Smallest: 4, Largest: 7}, - {Smallest: 5, Largest: 6}, - }, - } - Expect(ack.validateAckRanges()).To(BeFalse()) - }) - - It("rejects with directly adjacent ACK ranges", func() { - ack := AckFrame{ - AckRanges: []AckRange{ - {Smallest: 5, Largest: 7}, - {Smallest: 2, Largest: 4}, - }, - } - Expect(ack.validateAckRanges()).To(BeFalse()) - }) - - It("accepts an ACK with one lost packet", func() { - ack := AckFrame{ - AckRanges: []AckRange{ - {Smallest: 5, Largest: 10}, - {Smallest: 1, Largest: 3}, - }, - } - Expect(ack.validateAckRanges()).To(BeTrue()) - }) - - It("accepts an ACK with multiple lost packets", func() { - ack := AckFrame{ - AckRanges: []AckRange{ - {Smallest: 15, Largest: 20}, - {Smallest: 10, Largest: 12}, - {Smallest: 1, Largest: 3}, - }, - } - Expect(ack.validateAckRanges()).To(BeTrue()) - }) - }) - - Context("check if ACK frame acks a certain packet", func() { - It("works with an ACK without any ranges", func() { - f := AckFrame{ - AckRanges: []AckRange{{Smallest: 5, Largest: 10}}, - } - Expect(f.AcksPacket(1)).To(BeFalse()) - Expect(f.AcksPacket(4)).To(BeFalse()) - Expect(f.AcksPacket(5)).To(BeTrue()) - Expect(f.AcksPacket(8)).To(BeTrue()) - Expect(f.AcksPacket(10)).To(BeTrue()) - Expect(f.AcksPacket(11)).To(BeFalse()) - Expect(f.AcksPacket(20)).To(BeFalse()) - }) - - It("works with an ACK with multiple ACK ranges", func() { - f := AckFrame{ - AckRanges: []AckRange{ - {Smallest: 15, Largest: 20}, - {Smallest: 5, Largest: 8}, - }, - } - Expect(f.AcksPacket(4)).To(BeFalse()) - Expect(f.AcksPacket(5)).To(BeTrue()) - Expect(f.AcksPacket(6)).To(BeTrue()) - Expect(f.AcksPacket(7)).To(BeTrue()) - Expect(f.AcksPacket(8)).To(BeTrue()) - Expect(f.AcksPacket(9)).To(BeFalse()) - Expect(f.AcksPacket(14)).To(BeFalse()) - Expect(f.AcksPacket(15)).To(BeTrue()) - Expect(f.AcksPacket(18)).To(BeTrue()) - Expect(f.AcksPacket(19)).To(BeTrue()) - Expect(f.AcksPacket(20)).To(BeTrue()) - Expect(f.AcksPacket(21)).To(BeFalse()) - }) - }) -}) - -var _ = Describe("ACK_ECN frame", func() { - Context("parsing", func() { - It("parses an ACK_ECN frame", func() { - data := []byte{0xd} - data = append(data, encodeVarInt(100)...) // largest acked - data = append(data, encodeVarInt(0)...) // delay - data = append(data, encodeVarInt(0x42)...) // ECT(0) - data = append(data, encodeVarInt(0x12345)...) // ECT(1) - data = append(data, encodeVarInt(0x12345678)...) // ECN-CE - data = append(data, encodeVarInt(0)...) // num blocks - data = append(data, encodeVarInt(10)...) // first ack block - b := bytes.NewReader(data) - frame, err := parseAckEcnFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LargestAcked()).To(Equal(protocol.PacketNumber(100))) - Expect(frame.LowestAcked()).To(Equal(protocol.PacketNumber(90))) - Expect(frame.HasMissingRanges()).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOF", func() { - data := []byte{0x1a} - data = append(data, encodeVarInt(1000)...) // largest acked - data = append(data, encodeVarInt(0)...) // delay - data = append(data, encodeVarInt(0x42)...) // ECT(0) - data = append(data, encodeVarInt(0x12345)...) // ECT(1) - data = append(data, encodeVarInt(0x12345678)...) // ECN-CE - data = append(data, encodeVarInt(1)...) // num blocks - data = append(data, encodeVarInt(100)...) // first ack block - data = append(data, encodeVarInt(98)...) // gap - data = append(data, encodeVarInt(50)...) // ack block - _, err := parseAckEcnFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseAckEcnFrame(bytes.NewReader(data[0:i]), versionIETFFrames) - Expect(err).To(MatchError(io.EOF)) - } - }) - - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/ack_range_test.go b/vendor/lucas-clemente/quic-go/internal/wire/ack_range_test.go deleted file mode 100644 index 84ef71b5e..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/ack_range_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package wire - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ACK range", func() { - It("returns the length", func() { - Expect(AckRange{Smallest: 10, Largest: 10}.Len()).To(BeEquivalentTo(1)) - Expect(AckRange{Smallest: 10, Largest: 13}.Len()).To(BeEquivalentTo(4)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/blocked_frame_legacy_test.go b/vendor/lucas-clemente/quic-go/internal/wire/blocked_frame_legacy_test.go deleted file mode 100644 index 6bd5abcf4..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/blocked_frame_legacy_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("legacy BLOCKED Frame", func() { - Context("when parsing", func() { - It("accepts sample frame for a stream", func() { - b := bytes.NewReader([]byte{0x5, 0xde, 0xad, 0xbe, 0xef}) - f, err := parseBlockedFrameLegacy(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f).To(BeAssignableToTypeOf(&StreamBlockedFrame{})) - frame := f.(*StreamBlockedFrame) - Expect(frame.StreamID).To(Equal(protocol.StreamID(0xdeadbeef))) - }) - - It("accepts sample frame for the connection", func() { - b := bytes.NewReader([]byte{0x5, 0x0, 0x0, 0x0, 0x0}) - f, err := parseBlockedFrameLegacy(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f).To(BeAssignableToTypeOf(&BlockedFrame{})) - }) - }) - - It("errors on EOFs", func() { - data := []byte{0x5, 0xef, 0xbe, 0xad, 0xde} - _, err := parseBlockedFrameLegacy(bytes.NewReader(data), protocol.VersionWhatever) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseBlockedFrameLegacy(bytes.NewReader(data[0:i]), protocol.VersionWhatever) - Expect(err).To(HaveOccurred()) - } - }) - - Context("when writing", func() { - It("writes a BLOCKED frame for a stream", func() { - b := &bytes.Buffer{} - frame := StreamBlockedFrame{StreamID: 0x1337} - frame.Write(b, versionBigEndian) - Expect(b.Bytes()).To(Equal([]byte{0x5, 0x0, 0x0, 0x13, 0x37})) - }) - - It("has the correct min length for a BLOCKED frame for a stream", func() { - frame := StreamBlockedFrame{StreamID: 3} - Expect(frame.Length(versionBigEndian)).To(Equal(protocol.ByteCount(5))) - }) - - It("writes a BLOCKED frame for the connection", func() { - b := &bytes.Buffer{} - frame := BlockedFrame{} - frame.Write(b, versionBigEndian) - Expect(b.Bytes()).To(Equal([]byte{0x5, 0x0, 0x0, 0x0, 0x0})) - }) - - It("has the correct min length for a BLOCKED frame for the connection", func() { - frame := BlockedFrame{} - Expect(frame.Length(versionBigEndian)).To(Equal(protocol.ByteCount(5))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/blocked_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/blocked_frame_test.go deleted file mode 100644 index ef67f4c3a..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/blocked_frame_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("BLOCKED frame", func() { - Context("when parsing", func() { - It("accepts sample frame", func() { - data := []byte{0x08} - data = append(data, encodeVarInt(0x12345678)...) - b := bytes.NewReader(data) - frame, err := parseBlockedFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.Offset).To(Equal(protocol.ByteCount(0x12345678))) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOFs", func() { - data := []byte{0x08} - data = append(data, encodeVarInt(0x12345678)...) - _, err := parseBlockedFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - for i := range data { - _, err := parseBlockedFrame(bytes.NewReader(data[:i]), versionIETFFrames) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("when writing", func() { - It("writes a sample frame", func() { - b := &bytes.Buffer{} - frame := BlockedFrame{Offset: 0xdeadbeef} - err := frame.Write(b, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x08} - expected = append(expected, encodeVarInt(0xdeadbeef)...) - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("has the correct min length", func() { - frame := BlockedFrame{Offset: 0x12345} - Expect(frame.Length(versionIETFFrames)).To(Equal(1 + utils.VarIntLen(0x12345))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/connection_close_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/connection_close_frame_test.go deleted file mode 100644 index c43095da4..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/connection_close_frame_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/qerr" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("CONNECTION_CLOSE Frame", func() { - Context("when parsing", func() { - Context("in varint encoding", func() { - It("accepts sample frame", func() { - data := []byte{0x2, 0x0, 0x19} - data = append(data, encodeVarInt(0x1b)...) // reason phrase length - data = append(data, []byte{ - 'N', 'o', ' ', 'r', 'e', 'c', 'e', 'n', 't', ' ', 'n', 'e', 't', 'w', 'o', 'r', 'k', ' ', 'a', 'c', 't', 'i', 'v', 'i', 't', 'y', '.', - }...) - b := bytes.NewReader(data) - frame, err := parseConnectionCloseFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.ErrorCode).To(Equal(qerr.ErrorCode(0x19))) - Expect(frame.ReasonPhrase).To(Equal("No recent network activity.")) - Expect(b.Len()).To(BeZero()) - }) - - It("rejects long reason phrases", func() { - data := []byte{0x2, 0xca, 0xfe} - data = append(data, encodeVarInt(0xffff)...) // reason phrase length - b := bytes.NewReader(data) - _, err := parseConnectionCloseFrame(b, versionIETFFrames) - Expect(err).To(MatchError(io.EOF)) - }) - - It("errors on EOFs", func() { - data := []byte{0x2, 0x0, 0x19} - data = append(data, encodeVarInt(0x1b)...) // reason phrase length - data = append(data, []byte{ - 'N', 'o', ' ', 'r', 'e', 'c', 'e', 'n', 't', ' ', 'n', 'e', 't', 'w', 'o', 'r', 'k', ' ', 'a', 'c', 't', 'i', 'v', 'i', 't', 'y', '.', - }...) - _, err := parseConnectionCloseFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseConnectionCloseFrame(bytes.NewReader(data[0:i]), versionIETFFrames) - Expect(err).To(HaveOccurred()) - } - }) - - It("parses a frame without a reason phrase", func() { - data := []byte{0x2, 0xca, 0xfe} - data = append(data, encodeVarInt(0)...) - b := bytes.NewReader(data) - frame, err := parseConnectionCloseFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.ReasonPhrase).To(BeEmpty()) - Expect(b.Len()).To(BeZero()) - }) - }) - - Context("in big endian", func() { - It("accepts sample frame", func() { - b := bytes.NewReader([]byte{0x2, - 0x0, 0x0, 0x0, 0x19, // error code - 0x0, 0x1b, // reason phrase length - 'N', 'o', ' ', 'r', 'e', 'c', 'e', 'n', 't', ' ', 'n', 'e', 't', 'w', 'o', 'r', 'k', ' ', 'a', 'c', 't', 'i', 'v', 'i', 't', 'y', '.', - }) - frame, err := parseConnectionCloseFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.ErrorCode).To(Equal(qerr.ErrorCode(0x19))) - Expect(frame.ReasonPhrase).To(Equal("No recent network activity.")) - Expect(b.Len()).To(BeZero()) - }) - - It("rejects long reason phrases", func() { - b := bytes.NewReader([]byte{0x2, - 0xad, 0xfb, 0xca, 0xde, // error code - 0xff, 0x0, // reason phrase length - }) - _, err := parseConnectionCloseFrame(b, versionBigEndian) - Expect(err).To(MatchError(io.EOF)) - }) - - It("errors on EOFs", func() { - data := []byte{0x40, - 0x19, 0x0, 0x0, 0x0, // error code - 0x0, 0x1b, // reason phrase length - 'N', 'o', ' ', 'r', 'e', 'c', 'e', 'n', 't', ' ', 'n', 'e', 't', 'w', 'o', 'r', 'k', ' ', 'a', 'c', 't', 'i', 'v', 'i', 't', 'y', '.', - } - _, err := parseConnectionCloseFrame(bytes.NewReader(data), versionBigEndian) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseConnectionCloseFrame(bytes.NewReader(data[0:i]), versionBigEndian) - Expect(err).To(HaveOccurred()) - } - }) - - It("parses a frame without a reason phrase", func() { - b := bytes.NewReader([]byte{0x2, - 0xad, 0xfb, 0xca, 0xde, // error code - 0x0, 0x0, // reason phrase length - }) - frame, err := parseConnectionCloseFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.ReasonPhrase).To(BeEmpty()) - Expect(b.Len()).To(BeZero()) - }) - }) - }) - - Context("when writing", func() { - Context("in varint encoding", func() { - It("writes a frame without a ReasonPhrase", func() { - b := &bytes.Buffer{} - frame := &ConnectionCloseFrame{ - ErrorCode: 0xbeef, - } - err := frame.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x2, 0xbe, 0xef} - expected = append(expected, encodeVarInt(0)...) - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("writes a frame with a ReasonPhrase", func() { - b := &bytes.Buffer{} - frame := &ConnectionCloseFrame{ - ErrorCode: 0xdead, - ReasonPhrase: "foobar", - } - err := frame.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x2, 0xde, 0xad} - expected = append(expected, encodeVarInt(6)...) - expected = append(expected, []byte{'f', 'o', 'o', 'b', 'a', 'r'}...) - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("has proper min length", func() { - b := &bytes.Buffer{} - f := &ConnectionCloseFrame{ - ErrorCode: 0xcafe, - ReasonPhrase: "foobar", - } - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionIETFFrames)).To(Equal(protocol.ByteCount(b.Len()))) - }) - }) - - Context("in big endian", func() { - It("writes a frame without a ReasonPhrase", func() { - b := &bytes.Buffer{} - frame := &ConnectionCloseFrame{ - ErrorCode: 0xdeadbeef, - } - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(1 + 2 + 4)) - Expect(b.Bytes()).To(Equal([]byte{0x2, - 0xde, 0xad, 0xbe, 0xef, // error code - 0x0, 0x0, // reason phrase length - })) - }) - - It("writes a frame with a ReasonPhrase", func() { - b := &bytes.Buffer{} - frame := &ConnectionCloseFrame{ - ErrorCode: 0xdeadbeef, - ReasonPhrase: "foobar", - } - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(1 + 2 + 4 + len(frame.ReasonPhrase))) - Expect(b.Bytes()).To(Equal([]byte{0x2, - 0xde, 0xad, 0xbe, 0xef, // error code - 0x0, 0x6, // reason phrase length - 'f', 'o', 'o', 'b', 'a', 'r', - })) - }) - - It("has proper min length", func() { - b := &bytes.Buffer{} - f := &ConnectionCloseFrame{ - ErrorCode: 0xcafe, - ReasonPhrase: "foobar", - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionBigEndian)).To(Equal(protocol.ByteCount(b.Len()))) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/frame_parser_test.go b/vendor/lucas-clemente/quic-go/internal/wire/frame_parser_test.go deleted file mode 100644 index ca89d5755..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/frame_parser_test.go +++ /dev/null @@ -1,359 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/qerr" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Frame parsing", func() { - var buf *bytes.Buffer - - BeforeEach(func() { - buf = &bytes.Buffer{} - }) - - It("returns nil if there's nothing more to read", func() { - f, err := ParseNextFrame(bytes.NewReader(nil), nil, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - Expect(f).To(BeNil()) - }) - - It("skips PADDING frames", func() { - buf.Write([]byte{0}) // PADDING frame - (&PingFrame{}).Write(buf, versionIETFFrames) - f, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(f).To(Equal(&PingFrame{})) - }) - - It("handles PADDING at the end", func() { - r := bytes.NewReader([]byte{0, 0, 0}) - f, err := ParseNextFrame(r, nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(f).To(BeNil()) - Expect(r.Len()).To(BeZero()) - }) - - Context("for gQUIC frames", func() { - It("unpacks RST_STREAM frames", func() { - f := &RstStreamFrame{ - StreamID: 0xdeadbeef, - ByteOffset: 0xdecafbad11223344, - ErrorCode: 0x1337, - } - err := f.Write(buf, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks CONNECTION_CLOSE frames", func() { - f := &ConnectionCloseFrame{ReasonPhrase: "foo"} - err := f.Write(buf, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks GOAWAY frames", func() { - f := &GoawayFrame{ - ErrorCode: 1, - LastGoodStream: 2, - ReasonPhrase: "foo", - } - err := f.Write(buf, 0) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks a stream-level WINDOW_UPDATE frame", func() { - f := &MaxStreamDataFrame{ - StreamID: 0xdeadbeef, - ByteOffset: 0xcafe000000001337, - } - buf := &bytes.Buffer{} - err := f.Write(buf, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks a connection-level WINDOW_UPDATE frame", func() { - f := &MaxDataFrame{ - ByteOffset: 0xcafe000000001337, - } - err := f.Write(buf, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks connection-level BLOCKED frames", func() { - f := &BlockedFrame{} - err := f.Write(buf, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks stream-level BLOCKED frames", func() { - f := &StreamBlockedFrame{StreamID: 0xdeadbeef} - err := f.Write(buf, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks STOP_WAITING frames", func() { - hdr := &Header{ - PacketNumber: 0x1338, - PacketNumberLen: protocol.PacketNumberLen4, - } - f := &StopWaitingFrame{ - LeastUnacked: 0x1337, - PacketNumber: hdr.PacketNumber, - PacketNumberLen: hdr.PacketNumberLen, - } - err := f.Write(buf, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), hdr, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(BeAssignableToTypeOf(f)) - Expect(frame.(*StopWaitingFrame).LeastUnacked).To(Equal(protocol.PacketNumber(0x1337))) - }) - - It("errors on STOP_WAITING frames in QUIC 44", func() { - Expect(protocol.Version44.UsesStopWaitingFrames()).To(BeFalse()) - hdr := &Header{ - PacketNumber: 0x1338, - PacketNumberLen: protocol.PacketNumberLen4, - } - f := &StopWaitingFrame{ - LeastUnacked: 0x1337, - PacketNumber: hdr.PacketNumber, - PacketNumberLen: hdr.PacketNumberLen, - } - err := f.Write(buf, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - _, err = ParseNextFrame(bytes.NewReader(buf.Bytes()), hdr, protocol.Version44) - Expect(err).To(MatchError("STOP_WAITING frames not supported by this QUIC version")) - }) - - It("unpacks PING frames", func() { - f := &PingFrame{} - err := f.Write(buf, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks ACK frames", func() { - f := &AckFrame{AckRanges: []AckRange{{Smallest: 1, Largest: 0x13}}} - err := f.Write(buf, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).ToNot(BeNil()) - Expect(frame).To(BeAssignableToTypeOf(f)) - Expect(frame.(*AckFrame).LargestAcked()).To(Equal(protocol.PacketNumber(0x13))) - }) - - It("errors on invalid type", func() { - _, err := ParseNextFrame(bytes.NewReader([]byte{0xf}), nil, versionBigEndian) - Expect(err).To(MatchError("InvalidFrameData: unknown type byte 0xf")) - }) - - It("errors on invalid frames", func() { - for b, e := range map[byte]qerr.ErrorCode{ - 0x80: qerr.InvalidStreamData, - 0x40: qerr.InvalidAckData, - 0x01: qerr.InvalidRstStreamData, - 0x02: qerr.InvalidConnectionCloseData, - 0x03: qerr.InvalidGoawayData, - 0x04: qerr.InvalidWindowUpdateData, - 0x05: qerr.InvalidBlockedData, - 0x06: qerr.InvalidStopWaitingData, - } { - _, err := ParseNextFrame(bytes.NewReader([]byte{b}), &Header{PacketNumberLen: 2}, versionBigEndian) - Expect(err).To(HaveOccurred()) - Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(e)) - } - }) - }) - - Context("for IETF draft frames", func() { - It("unpacks RST_STREAM frames", func() { - f := &RstStreamFrame{ - StreamID: 0xdeadbeef, - ByteOffset: 0xdecafbad1234, - ErrorCode: 0x1337, - } - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks CONNECTION_CLOSE frames", func() { - f := &ConnectionCloseFrame{ReasonPhrase: "foo"} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks MAX_DATA frames", func() { - f := &MaxDataFrame{ - ByteOffset: 0xcafe, - } - buf := &bytes.Buffer{} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks MAX_STREAM_DATA frames", func() { - f := &MaxStreamDataFrame{ - StreamID: 0xdeadbeef, - ByteOffset: 0xdecafbad, - } - buf := &bytes.Buffer{} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks MAX_STREAM_ID frames", func() { - f := &MaxStreamIDFrame{StreamID: 0x1337} - buf := &bytes.Buffer{} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks connection-level BLOCKED frames", func() { - f := &BlockedFrame{Offset: 0x1234} - buf := &bytes.Buffer{} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks stream-level BLOCKED frames", func() { - f := &StreamBlockedFrame{ - StreamID: 0xdeadbeef, - Offset: 0xdead, - } - buf := &bytes.Buffer{} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks STREAM_ID_BLOCKED frames", func() { - f := &StreamIDBlockedFrame{StreamID: 0x1234567} - buf := &bytes.Buffer{} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks STOP_SENDING frames", func() { - f := &StopSendingFrame{StreamID: 0x42} - buf := &bytes.Buffer{} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).To(Equal(f)) - }) - - It("unpacks ACK frames", func() { - f := &AckFrame{AckRanges: []AckRange{{Smallest: 1, Largest: 0x13}}} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).ToNot(BeNil()) - Expect(frame).To(BeAssignableToTypeOf(f)) - Expect(frame.(*AckFrame).LargestAcked()).To(Equal(protocol.PacketNumber(0x13))) - }) - - It("unpacks PATH_CHALLENGE frames", func() { - f := &PathChallengeFrame{Data: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).ToNot(BeNil()) - Expect(frame).To(BeAssignableToTypeOf(f)) - Expect(frame.(*PathChallengeFrame).Data).To(Equal([8]byte{1, 2, 3, 4, 5, 6, 7, 8})) - }) - - It("unpacks PATH_RESPONSE frames", func() { - f := &PathResponseFrame{Data: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}} - err := f.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - frame, err := ParseNextFrame(bytes.NewReader(buf.Bytes()), nil, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame).ToNot(BeNil()) - Expect(frame).To(BeAssignableToTypeOf(f)) - Expect(frame.(*PathResponseFrame).Data).To(Equal([8]byte{1, 2, 3, 4, 5, 6, 7, 8})) - }) - - It("errors on invalid type", func() { - _, err := ParseNextFrame(bytes.NewReader([]byte{0x42}), nil, versionIETFFrames) - Expect(err).To(MatchError("InvalidFrameData: unknown type byte 0x42")) - }) - - It("errors on invalid frames", func() { - for b, e := range map[byte]qerr.ErrorCode{ - 0x01: qerr.InvalidRstStreamData, - 0x02: qerr.InvalidConnectionCloseData, - 0x04: qerr.InvalidWindowUpdateData, - 0x05: qerr.InvalidWindowUpdateData, - 0x06: qerr.InvalidFrameData, - 0x08: qerr.InvalidBlockedData, - 0x09: qerr.InvalidBlockedData, - 0x0a: qerr.InvalidFrameData, - 0x0c: qerr.InvalidFrameData, - 0x0d: qerr.InvalidAckData, - 0x0e: qerr.InvalidFrameData, - 0x0f: qerr.InvalidFrameData, - 0x10: qerr.InvalidStreamData, - 0x1a: qerr.InvalidAckData, - } { - _, err := ParseNextFrame(bytes.NewReader([]byte{b}), nil, versionIETFFrames) - Expect(err).To(HaveOccurred()) - Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(e)) - } - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/goaway_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/goaway_frame_test.go deleted file mode 100644 index 611276491..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/goaway_frame_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/qerr" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("GoawayFrame", func() { - Context("when parsing", func() { - Context("in big endian", func() { - It("accepts sample frame", func() { - b := bytes.NewReader([]byte{0x3, - 0x0, 0x0, 0x13, 0x37, // error code - 0x0, 0x0, 0x12, 0x34, // last good stream id - 0x0, 0x3, // reason phrase length - 'f', 'o', 'o', - }) - frame, err := parseGoawayFrame(b, versionBigEndian) - Expect(frame).To(Equal(&GoawayFrame{ - ErrorCode: 0x1337, - LastGoodStream: 0x1234, - ReasonPhrase: "foo", - })) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOFs", func() { - data := []byte{0x3, - 0x0, 0x0, 0x0, 0x1, // error code - 0x0, 0x0, 0x0, 0x2, // last good stream id - 0x0, 0x3, // reason phrase length - 'f', 'o', 'o', - } - _, err := parseGoawayFrame(bytes.NewReader(data), versionBigEndian) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseGoawayFrame(bytes.NewReader(data[0:i]), versionBigEndian) - Expect(err).To(HaveOccurred()) - } - }) - }) - - It("rejects long reason phrases", func() { - b := bytes.NewReader([]byte{0x3, - 0x1, 0x0, 0x0, 0x0, // error code - 0x2, 0x0, 0x0, 0x0, // last good stream id - 0xff, 0xff, // reason phrase length - }) - _, err := parseGoawayFrame(b, protocol.VersionWhatever) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidGoawayData, "reason phrase too long"))) - }) - }) - - Context("when writing", func() { - Context("in big endian", func() { - It("writes a sample frame", func() { - b := &bytes.Buffer{} - frame := GoawayFrame{ - ErrorCode: 0x1337, - LastGoodStream: 2, - ReasonPhrase: "foo", - } - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()).To(Equal([]byte{0x3, - 0x0, 0x0, 0x13, 0x37, // reason code - 0x0, 0x0, 0x0, 0x2, // last good stream id - 0x0, 0x3, // reason phrase length - 'f', 'o', 'o', - })) - }) - }) - - It("has the correct min length", func() { - frame := GoawayFrame{ - ReasonPhrase: "foo", - } - Expect(frame.Length(0)).To(Equal(protocol.ByteCount(14))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/header_parser_test.go b/vendor/lucas-clemente/quic-go/internal/wire/header_parser_test.go deleted file mode 100644 index cf1266747..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/header_parser_test.go +++ /dev/null @@ -1,716 +0,0 @@ -package wire - -import ( - "bytes" - "encoding/binary" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/qerr" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Header Parsing", func() { - Context("IETF QUIC Header", func() { - appendPacketNumber := func(data []byte, pn protocol.PacketNumber, pnLen protocol.PacketNumberLen) []byte { - buf := &bytes.Buffer{} - utils.WriteVarIntPacketNumber(buf, pn, pnLen) - return append(data, buf.Bytes()...) - } - - Context("Version Negotiation Packets", func() { - It("parses", func() { - srcConnID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} - destConnID := protocol.ConnectionID{9, 8, 7, 6, 5, 4, 3, 2, 1} - versions := []protocol.VersionNumber{0x22334455, 0x33445566} - data, err := ComposeVersionNegotiation(destConnID, srcConnID, versions) - Expect(err).ToNot(HaveOccurred()) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.DestConnectionID).To(Equal(destConnID)) - Expect(iHdr.SrcConnectionID).To(Equal(srcConnID)) - Expect(iHdr.IsLongHeader).To(BeTrue()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.IsVersionNegotiation).To(BeTrue()) - Expect(hdr.Version).To(BeZero()) - Expect(hdr.DestConnectionID).To(Equal(destConnID)) - Expect(hdr.SrcConnectionID).To(Equal(srcConnID)) - for _, v := range versions { - Expect(hdr.SupportedVersions).To(ContainElement(v)) - } - }) - - It("errors if it contains versions of the wrong length", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - versions := []protocol.VersionNumber{0x22334455, 0x33445566} - data, err := ComposeVersionNegotiation(connID, connID, versions) - Expect(err).ToNot(HaveOccurred()) - b := bytes.NewReader(data[:len(data)-2]) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, versionIETFFrames) - Expect(err).To(MatchError(qerr.InvalidVersionNegotiationPacket)) - }) - - It("errors if the version list is empty", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - versions := []protocol.VersionNumber{0x22334455} - data, err := ComposeVersionNegotiation(connID, connID, versions) - Expect(err).ToNot(HaveOccurred()) - // remove 8 bytes (two versions), since ComposeVersionNegotiation also added a reserved version number - b := bytes.NewReader(data[:len(data)-8]) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, versionIETFFrames) - Expect(err).To(MatchError("InvalidVersionNegotiationPacket: empty version list")) - }) - }) - - Context("Long Headers", func() { - It("parses a Long Header", func() { - destConnID := protocol.ConnectionID{9, 8, 7, 6, 5, 4, 3, 2, 1} - srcConnID := protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef} - data := []byte{ - 0x80 ^ uint8(protocol.PacketTypeInitial), - 0x1, 0x2, 0x3, 0x4, // version number - 0x61, // connection ID lengths - } - data = append(data, destConnID...) - data = append(data, srcConnID...) - data = append(data, encodeVarInt(6)...) // token length - data = append(data, []byte("foobar")...) // token - data = append(data, encodeVarInt(0x1337)...) // payload length - // packet number - data = appendPacketNumber(data, 0xbeef, protocol.PacketNumberLen4) - - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeTrue()) - Expect(iHdr.DestConnectionID).To(Equal(destConnID)) - Expect(iHdr.SrcConnectionID).To(Equal(srcConnID)) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.Type).To(Equal(protocol.PacketTypeInitial)) - Expect(hdr.IsLongHeader).To(BeTrue()) - Expect(hdr.DestConnectionID).To(Equal(destConnID)) - Expect(hdr.SrcConnectionID).To(Equal(srcConnID)) - Expect(hdr.Token).To(Equal([]byte("foobar"))) - Expect(hdr.PayloadLen).To(Equal(protocol.ByteCount(0x1337))) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0xbeef))) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen4)) - Expect(hdr.Version).To(Equal(protocol.VersionNumber(0x1020304))) - Expect(hdr.IsVersionNegotiation).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a Long Header without a destination connection ID", func() { - data := []byte{ - 0x80 ^ uint8(protocol.PacketTypeInitial), - 0x1, 0x2, 0x3, 0x4, // version number - 0x01, // connection ID lengths - 0xde, 0xad, 0xbe, 0xef, // source connection ID - } - data = append(data, encodeVarInt(0x42)...) // payload length - data = append(data, []byte{0xde, 0xca, 0xfb, 0xad}...) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.SrcConnectionID).To(Equal(protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef})) - Expect(iHdr.DestConnectionID).To(BeEmpty()) - }) - - It("parses a Long Header without a source connection ID", func() { - data := []byte{ - 0x80 ^ uint8(protocol.PacketTypeInitial), - 0x1, 0x2, 0x3, 0x4, // version number - 0x70, // connection ID lengths - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // source connection ID - } - data = append(data, encodeVarInt(0x42)...) // payload length - data = append(data, []byte{0xde, 0xca, 0xfb, 0xad}...) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.SrcConnectionID).To(BeEmpty()) - Expect(iHdr.DestConnectionID).To(Equal(protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})) - }) - - It("parses a Long Header with a 2 byte packet number", func() { - data := []byte{ - 0x80 ^ uint8(protocol.PacketTypeInitial), - 0x1, 0x2, 0x3, 0x4, // version number - 0x0, // connection ID lengths - } - data = append(data, encodeVarInt(0)...) // token length - data = append(data, encodeVarInt(0x42)...) // payload length - data = appendPacketNumber(data, 0x123, protocol.PacketNumberLen2) - - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0x123))) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen2)) - }) - - It("parses a Retry packet", func() { - data := []byte{ - 0x80 ^ uint8(protocol.PacketTypeRetry), - 0x1, 0x2, 0x3, 0x4, // version number - 0x0, // connection ID lengths - 0x97, // Orig Destination Connection ID length - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // source connection ID - 'f', 'o', 'o', 'b', 'a', 'r', // token - } - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.Type).To(Equal(protocol.PacketTypeRetry)) - Expect(hdr.OrigDestConnectionID).To(Equal(protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})) - Expect(hdr.Token).To(Equal([]byte("foobar"))) - }) - - It("rejects packets sent with an unknown packet type", func() { - srcConnID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - buf := &bytes.Buffer{} - err := (&Header{ - IsLongHeader: true, - Type: 42, - SrcConnectionID: srcConnID, - Version: 0x10203040, - PacketNumber: 1, - PacketNumberLen: protocol.PacketNumberLen1, - }).Write(buf, protocol.PerspectiveClient, protocol.VersionTLS) - Expect(err).ToNot(HaveOccurred()) - b := bytes.NewReader(buf.Bytes()) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - _, err = iHdr.Parse(b, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).To(MatchError("InvalidPacketHeader: Received packet with invalid packet type: 42")) - }) - - It("errors if the token length is too large", func() { - data := []byte{ - 0x80 ^ uint8(protocol.PacketTypeInitial), - 0x1, 0x2, 0x3, 0x4, // version number - 0x0, // connection ID lengths - } - data = append(data, encodeVarInt(4)...) // token length: 4 bytes (1 byte too long) - data = append(data, encodeVarInt(0x42)...) // payload length, 1 byte - data = appendPacketNumber(data, 0x123, protocol.PacketNumberLen2) // 2 bytes - - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).To(MatchError(io.EOF)) - }) - - It("errors on EOF, when parsing the invariant header", func() { - data := []byte{ - 0x80 ^ uint8(protocol.PacketTypeInitial), - 0x1, 0x2, 0x3, 0x4, // version number - 0x55, // connection ID lengths - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37, // destination connection ID - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37, // source connection ID - } - for i := 0; i < len(data); i++ { - _, err := ParseInvariantHeader(bytes.NewReader(data[:i]), 0) - Expect(err).To(Equal(io.EOF)) - } - }) - - It("errors on EOF, when parsing the header", func() { - data := []byte{ - 0x80 ^ uint8(protocol.PacketTypeInitial), - 0x1, 0x2, 0x3, 0x4, // version number - 0x0, // connection ID lengths - } - iHdrLen := len(data) - data = append(data, encodeVarInt(0x1337)...) - data = appendPacketNumber(data, 0xdeadbeef, protocol.PacketNumberLen4) - for i := iHdrLen; i < len(data); i++ { - b := bytes.NewReader(data[:i]) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).To(Equal(io.EOF)) - } - }) - - It("errors on EOF, for a Retry packet", func() { - data := []byte{ - 0x80 ^ uint8(protocol.PacketTypeRetry), - 0x1, 0x2, 0x3, 0x4, // version number - 0x0, // connection ID lengths - } - iHdrLen := len(data) - data = append(data, []byte{ - 0x97, // Orig Destination Connection ID length - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // source connection ID - }...) - for i := iHdrLen; i < len(data); i++ { - b := bytes.NewReader(data[:i]) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).To(Equal(io.EOF)) - } - }) - }) - - Context("Short Headers", func() { - It("reads a Short Header with a 8 byte connection ID", func() { - connID := protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37} - data := append([]byte{0x30}, connID...) - data = appendPacketNumber(data, 0x42, protocol.PacketNumberLen1) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 8) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - Expect(iHdr.DestConnectionID).To(Equal(connID)) - hdr, err := iHdr.Parse(b, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.KeyPhase).To(Equal(0)) - Expect(hdr.DestConnectionID).To(Equal(connID)) - Expect(hdr.SrcConnectionID).To(BeEmpty()) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0x42))) - Expect(hdr.IsVersionNegotiation).To(BeFalse()) - Expect(b.Len()).To(BeZero()) - }) - - It("reads a Short Header with a 5 byte connection ID", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5} - data := append([]byte{0x30}, connID...) - data = appendPacketNumber(data, 0x42, protocol.PacketNumberLen1) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 5) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - Expect(iHdr.DestConnectionID).To(Equal(connID)) - hdr, err := iHdr.Parse(b, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.KeyPhase).To(Equal(0)) - Expect(hdr.DestConnectionID).To(Equal(connID)) - Expect(hdr.SrcConnectionID).To(BeEmpty()) - Expect(b.Len()).To(BeZero()) - }) - - It("reads the Key Phase Bit", func() { - data := []byte{ - 0x30 ^ 0x40, - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, // connection ID - } - data = appendPacketNumber(data, 11, protocol.PacketNumberLen1) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 6) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.IsLongHeader).To(BeFalse()) - Expect(hdr.KeyPhase).To(Equal(1)) - Expect(b.Len()).To(BeZero()) - }) - - It("reads a header with a 2 byte packet number", func() { - data := []byte{ - 0x30 ^ 0x40 ^ 0x1, - 0xde, 0xad, 0xbe, 0xef, // connection ID - } - data = appendPacketNumber(data, 0x1337, protocol.PacketNumberLen2) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 4) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.IsLongHeader).To(BeFalse()) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0x1337))) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen2)) - Expect(b.Len()).To(BeZero()) - }) - - It("reads a header with a 4 byte packet number", func() { - data := []byte{ - 0x30 ^ 0x40 ^ 0x2, - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x1, 0x2, 0x3, 0x4, // connection ID - } - data = appendPacketNumber(data, 0x99beef, protocol.PacketNumberLen4) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 10) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.IsLongHeader).To(BeFalse()) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0x99beef))) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen4)) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOF, when parsing the invariant header", func() { - data := []byte{ - 0x30 ^ 0x2, - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37, // connection ID - } - for i := 0; i < len(data); i++ { - _, err := ParseInvariantHeader(bytes.NewReader(data[:i]), 8) - Expect(err).To(Equal(io.EOF)) - } - }) - - It("errors on EOF, when parsing the invariant header", func() { - data := []byte{ - 0x30 ^ 0x2, - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, // connection ID - } - iHdrLen := len(data) - data = appendPacketNumber(data, 0xdeadbeef, protocol.PacketNumberLen4) - for i := iHdrLen; i < len(data); i++ { - b := bytes.NewReader(data[:i]) - iHdr, err := ParseInvariantHeader(b, 6) - Expect(err).ToNot(HaveOccurred()) - _, err = iHdr.Parse(b, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).To(Equal(io.EOF)) - } - }) - }) - }) - - Context("gQUIC 44", func() { - Context("Long Headers", func() { - It("parses a Long Header", func() { - destConnID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - srcConnID := protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1} - data := []byte{ - 0x80 ^ uint8(protocol.PacketTypeInitial), - 0x1, 0x2, 0x3, 0x4, // version - 0x55, // connection ID lengths - } - data = append(data, destConnID...) - data = append(data, srcConnID...) - data = append(data, []byte{0xde, 0xad, 0xbe, 0xef}...) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeTrue()) - Expect(iHdr.Version).To(Equal(protocol.VersionNumber(0x1020304))) - Expect(iHdr.DestConnectionID).To(Equal(destConnID)) - Expect(iHdr.SrcConnectionID).To(Equal(srcConnID)) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.IsPublicHeader).To(BeFalse()) - Expect(hdr.Type).To(Equal(protocol.PacketTypeInitial)) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen4)) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0xdeadbeef))) - }) - - It("parses a Long Header containing a Diversification Nonce", func() { - srcConnID := protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1} - divNonce := bytes.Repeat([]byte{'f'}, 32) - data := []byte{ - 0x80 ^ uint8(protocol.PacketType0RTT), - 0x1, 0x2, 0x3, 0x4, // version - 0x5, // connection ID lengths - } - data = append(data, srcConnID...) - data = append(data, []byte{0xde, 0xad, 0xbe, 0xef}...) - data = append(data, divNonce...) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeTrue()) - Expect(iHdr.Version).To(Equal(protocol.VersionNumber(0x1020304))) - Expect(iHdr.SrcConnectionID).To(Equal(srcConnID)) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.IsPublicHeader).To(BeFalse()) - Expect(hdr.Type).To(Equal(protocol.PacketType0RTT)) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen4)) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0xdeadbeef))) - Expect(hdr.DiversificationNonce).To(Equal(divNonce)) - }) - - It("errors on EOF, for Long Headers containing a Diversification Nonce", func() { - data := []byte{ - 0x80 ^ uint8(protocol.PacketType0RTT), - 0x1, 0x2, 0x3, 0x4, // version - 0x5, - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37, // connection ID - } - iHdrLen := len(data) - data = append(data, []byte{0xde, 0xca, 0xfb, 0xad}...) // packet number - data = append(data, bytes.Repeat([]byte{'d'}, 32)...) - for i := iHdrLen; i < len(data); i++ { - b := bytes.NewReader(data[:i]) - iHdr, err := ParseInvariantHeader(b, 8) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeTrue()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, protocol.Version44) - Expect(err).To(Equal(io.EOF)) - } - }) - }) - - Context("Short Headers", func() { - It("parses a Short Header with a 1 byte packet number", func() { - destConnID := protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1} - data := []byte{0x30} - data = append(data, destConnID...) - data = append(data, 0x42) // packet number - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 8) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - Expect(iHdr.DestConnectionID).To(Equal(destConnID)) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.IsPublicHeader).To(BeFalse()) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen1)) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0x42))) - }) - - It("parses a Short Header with a 2 byte packet number", func() { - data := []byte{0x30 ^ 0x1, 0xca, 0xfe} - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - Expect(iHdr.DestConnectionID.Len()).To(BeZero()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.IsPublicHeader).To(BeFalse()) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen2)) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0xcafe))) - }) - - It("parses a Short Header with a 4 byte packet number", func() { - data := []byte{0x30 ^ 0x2, 0xde, 0xad, 0xbe, 0xef} - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - Expect(iHdr.DestConnectionID.Len()).To(BeZero()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.IsPublicHeader).To(BeFalse()) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen4)) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0xdeadbeef))) - }) - - It("errors on an invalid packet number length flag", func() { - data := []byte{0x30 ^ 0x3, 0xde, 0xad, 0xbe, 0xef} - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - Expect(iHdr.DestConnectionID.Len()).To(BeZero()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, protocol.Version44) - Expect(err).To(MatchError(errInvalidPacketNumberLen)) - }) - - It("errors on EOF", func() { - data := []byte{0x30 ^ 0x2, 0xde, 0xad, 0xbe, 0xef} - iHdrLen := 1 - for i := iHdrLen; i < len(data); i++ { - b := bytes.NewReader(data[:i]) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, protocol.Version44) - Expect(err).To(Equal(io.EOF)) - } - }) - }) - }) - - Context("Public Header", func() { - It("accepts a sample client header", func() { - data := []byte{ - 0x9, - 0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6, - } - data = append(data, []byte{0xde, 0xad, 0xbe, 0xef}...) - data = append(data, 0x1) // packet number - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveClient, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.VersionFlag).To(BeTrue()) - Expect(hdr.IsVersionNegotiation).To(BeFalse()) - Expect(hdr.ResetFlag).To(BeFalse()) - connID := protocol.ConnectionID{0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6} - Expect(hdr.DestConnectionID).To(Equal(connID)) - Expect(hdr.SrcConnectionID).To(BeEmpty()) - Expect(hdr.Version).To(Equal(protocol.VersionNumber(0xdeadbeef))) - Expect(hdr.SupportedVersions).To(BeEmpty()) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(1))) - Expect(b.Len()).To(BeZero()) - }) - - It("accepts an omitted connection ID", func() { - b := bytes.NewReader([]byte{0x0, 0x1}) - iHdr, err := ParseInvariantHeader(b, 8) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - Expect(iHdr.DestConnectionID).To(BeEmpty()) - Expect(iHdr.SrcConnectionID).To(BeEmpty()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveClient, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(1))) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a PUBLIC_RESET packet", func() { - b := bytes.NewReader([]byte{0xa, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8}) - iHdr, err := ParseInvariantHeader(b, 4) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.ResetFlag).To(BeTrue()) - Expect(hdr.VersionFlag).To(BeFalse()) - Expect(hdr.IsVersionNegotiation).To(BeFalse()) - connID := protocol.ConnectionID{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8} - Expect(hdr.SrcConnectionID).To(BeEmpty()) - Expect(hdr.DestConnectionID).To(Equal(connID)) - }) - - It("reads a diversification nonce sent by the server", func() { - divNonce := []byte{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f} - Expect(divNonce).To(HaveLen(32)) - b := bytes.NewReader(append(append([]byte{0x0c, 0xf6, 0x19, 0x86, 0x66, 0x9b, 0x9f, 0xfa, 0x4c}, divNonce...), 0x37)) - iHdr, err := ParseInvariantHeader(b, 7) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.DestConnectionID).ToNot(BeEmpty()) - Expect(hdr.SrcConnectionID).To(BeEmpty()) - Expect(hdr.DiversificationNonce).To(Equal(divNonce)) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOF", func() { - data := []byte{ - 0x10 ^ 0x8 ^ 0x4, - 0xf6, 0x19, 0x86, 0x66, 0x9b, 0x9f, 0xfa, 0x4c, - } - iHdrLen := len(data) - data = append(data, bytes.Repeat([]byte{0}, 32)...) // add a diversification nonce - data = append(data, []byte{0x13, 37}...) // packet number - for i := iHdrLen; i < len(data); i++ { - b := bytes.NewReader(data[:i]) - iHdr, err := ParseInvariantHeader(b, 5) - Expect(err).ToNot(HaveOccurred()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).To(Equal(io.EOF)) - } - }) - - Context("version negotiation packets", func() { - appendVersion := func(data []byte, v protocol.VersionNumber) []byte { - data = append(data, []byte{0, 0, 0, 0}...) - binary.BigEndian.PutUint32(data[len(data)-4:], uint32(v)) - return data - } - - It("parses", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - versions := []protocol.VersionNumber{0x13, 0x37} - b := bytes.NewReader(ComposeGQUICVersionNegotiation(connID, versions)) - iHdr, err := ParseInvariantHeader(b, 6) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.DestConnectionID).To(Equal(connID)) - Expect(hdr.SrcConnectionID).To(BeEmpty()) - Expect(hdr.VersionFlag).To(BeTrue()) - Expect(hdr.Version).To(BeZero()) // unitialized - Expect(hdr.IsVersionNegotiation).To(BeTrue()) - // in addition to the versions, the supported versions might contain a reserved version number - for _, version := range versions { - Expect(hdr.SupportedVersions).To(ContainElement(version)) - } - Expect(b.Len()).To(BeZero()) - }) - - It("errors if it doesn't contain any versions", func() { - b := bytes.NewReader([]byte{0x9, 0xf6, 0x19, 0x86, 0x66, 0x9b, 0x9f, 0xfa, 0x4c}) - iHdr, err := ParseInvariantHeader(b, 4) - Expect(err).ToNot(HaveOccurred()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).To(MatchError("InvalidVersionNegotiationPacket: empty version list")) - }) - - It("reads version negotiation packets containing unsupported versions", func() { - data := []byte{0x9, 0xf6, 0x19, 0x86, 0x66, 0x9b, 0x9f, 0xfa, 0x4c} - data = appendVersion(data, 1) // unsupported version - data = appendVersion(data, protocol.SupportedVersions[0]) - data = appendVersion(data, 99) // unsupported version - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.VersionFlag).To(BeTrue()) - Expect(hdr.IsVersionNegotiation).To(BeTrue()) - Expect(hdr.SupportedVersions).To(Equal([]protocol.VersionNumber{1, protocol.SupportedVersions[0], 99})) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on invalid version tags", func() { - data := ComposeGQUICVersionNegotiation(protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, protocol.SupportedVersions) - data = append(data, []byte{0x13, 0x37}...) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - _, err = iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).To(MatchError(qerr.InvalidVersionNegotiationPacket)) - }) - }) - - Context("Packet Number lengths", func() { - It("accepts 1-byte packet numbers", func() { - b := bytes.NewReader([]byte{0x08, 0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6, 0xde}) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0xde))) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen1)) - Expect(b.Len()).To(BeZero()) - }) - - It("accepts 2-byte packet numbers", func() { - b := bytes.NewReader([]byte{0x18, 0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6, 0xde, 0xca}) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0xdeca))) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen2)) - Expect(b.Len()).To(BeZero()) - }) - - It("accepts 4-byte packet numbers", func() { - b := bytes.NewReader([]byte{0x28, 0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6, 0xad, 0xfb, 0xca, 0xde}) - iHdr, err := ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.PacketNumber).To(Equal(protocol.PacketNumber(0xadfbcade))) - Expect(hdr.PacketNumberLen).To(Equal(protocol.PacketNumberLen4)) - Expect(b.Len()).To(BeZero()) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/header_test.go b/vendor/lucas-clemente/quic-go/internal/wire/header_test.go deleted file mode 100644 index 9e7964436..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/header_test.go +++ /dev/null @@ -1,902 +0,0 @@ -package wire - -import ( - "bytes" - "log" - "os" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Header", func() { - const ( - versionPublicHeader = protocol.Version39 // a QUIC version that uses the Public Header format - versionIETFHeader = protocol.VersionTLS // a QUIC version that uses the IETF Header format - ) - - Context("Writing", func() { - var buf *bytes.Buffer - - BeforeEach(func() { - buf = &bytes.Buffer{} - }) - - Context("IETF Header", func() { - appendPacketNumber := func(data []byte, pn protocol.PacketNumber, pnLen protocol.PacketNumberLen) []byte { - buf := &bytes.Buffer{} - utils.WriteVarIntPacketNumber(buf, pn, pnLen) - return append(data, buf.Bytes()...) - } - - Context("Long Header", func() { - srcConnID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - - It("writes", func() { - err := (&Header{ - IsLongHeader: true, - Type: 0x5, - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe}, - SrcConnectionID: protocol.ConnectionID{0xde, 0xca, 0xfb, 0xad, 0x0, 0x0, 0x13, 0x37}, - PayloadLen: 0xcafe, - PacketNumber: 0xdecaf, - PacketNumberLen: protocol.PacketNumberLen4, - Version: 0x1020304, - }).Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{ - 0x80 ^ 0x5, - 0x1, 0x2, 0x3, 0x4, // version number - 0x35, // connection ID lengths - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, // dest connection ID - 0xde, 0xca, 0xfb, 0xad, 0x0, 0x0, 0x13, 0x37, // source connection ID - } - expected = append(expected, encodeVarInt(0xcafe)...) // payload length - expected = appendPacketNumber(expected, 0xdecaf, protocol.PacketNumberLen4) - Expect(buf.Bytes()).To(Equal(expected)) - }) - - It("refuses to write a header with a too short connection ID", func() { - err := (&Header{ - IsLongHeader: true, - Type: 0x5, - SrcConnectionID: srcConnID, - DestConnectionID: protocol.ConnectionID{1, 2, 3}, // connection IDs must be at least 4 bytes long - PacketNumber: 0xdecafbad, - PacketNumberLen: protocol.PacketNumberLen4, - Version: 0x1020304, - }).Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).To(MatchError("invalid connection ID length: 3 bytes")) - }) - - It("refuses to write a header with a too long connection ID", func() { - err := (&Header{ - IsLongHeader: true, - Type: 0x5, - SrcConnectionID: srcConnID, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}, // connection IDs must be at most 18 bytes long - PacketNumber: 0xdecafbad, - PacketNumberLen: protocol.PacketNumberLen4, - Version: 0x1020304, - }).Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).To(MatchError("invalid connection ID length: 19 bytes")) - }) - - It("writes a header with an 18 byte connection ID", func() { - err := (&Header{ - IsLongHeader: true, - Type: 0x5, - SrcConnectionID: srcConnID, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}, // connection IDs must be at most 18 bytes long - PacketNumber: 0xdecafbad, - PacketNumberLen: protocol.PacketNumberLen4, - Version: 0x1020304, - }).Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(ContainSubstring(string([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}))) - }) - - It("writes an Initial containing a token", func() { - token := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.") - err := (&Header{ - IsLongHeader: true, - Type: protocol.PacketTypeInitial, - Token: token, - PacketNumber: 0xdecafbad, - PacketNumberLen: protocol.PacketNumberLen4, - Version: 0x1020304, - }).Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - expectedSubstring := append(encodeVarInt(uint64(len(token))), token...) - Expect(buf.Bytes()).To(ContainSubstring(string(expectedSubstring))) - }) - - It("writes a Retry packet", func() { - token := []byte("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.") - err := (&Header{ - IsLongHeader: true, - Type: protocol.PacketTypeRetry, - Token: token, - OrigDestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8, 9}, - Version: 0x1020304, - }).Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()[:6]).To(Equal([]byte{ - 0x80 ^ uint8(protocol.PacketTypeRetry), - 0x1, 0x2, 0x3, 0x4, // version number - 0x0, // connection ID lengths)) - })) - Expect(buf.Bytes()[6] & 0xf).To(Equal(uint8(6))) - Expect(buf.Bytes()[7 : 7+9]).To(Equal([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9})) // Orig Dest Connection ID - Expect(buf.Bytes()[7+9:]).To(Equal(token)) - }) - - It("refuses to write a Retry packet with an invalid Orig Destination Connection ID length", func() { - err := (&Header{ - IsLongHeader: true, - Type: protocol.PacketTypeRetry, - Token: []byte("foobar"), - OrigDestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}, // connection IDs must be at most 18 bytes long - Version: 0x1020304, - }).Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).To(MatchError("invalid connection ID length: 19 bytes")) - }) - }) - - Context("short header", func() { - It("writes a header with connection ID", func() { - err := (&Header{ - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37}, - PacketNumberLen: protocol.PacketNumberLen1, - PacketNumber: 0x42, - }).Write(buf, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(Equal([]byte{ - 0x30, - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37, // connection ID - 0x42, // packet number - })) - }) - - It("writes a header without connection ID", func() { - err := (&Header{ - PacketNumberLen: protocol.PacketNumberLen1, - PacketNumber: 0x42, - }).Write(buf, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(Equal([]byte{ - 0x30, - 0x42, // packet number - })) - }) - - It("writes a header with a 2 byte packet number", func() { - err := (&Header{ - PacketNumberLen: protocol.PacketNumberLen2, - PacketNumber: 0x765, - }).Write(buf, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x30} - expected = appendPacketNumber(expected, 0x765, protocol.PacketNumberLen2) - Expect(buf.Bytes()).To(Equal(expected)) - }) - - It("writes a header with a 4 byte packet number", func() { - err := (&Header{ - PacketNumberLen: protocol.PacketNumberLen4, - PacketNumber: 0x123456, - }).Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x30} - expected = appendPacketNumber(expected, 0x123456, protocol.PacketNumberLen4) - Expect(buf.Bytes()).To(Equal(expected)) - }) - - It("errors when given an invalid packet number length", func() { - err := (&Header{ - PacketNumberLen: 3, - PacketNumber: 0xdecafbad, - }).Write(buf, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).To(MatchError("invalid packet number length: 3")) - }) - - It("writes the Key Phase Bit", func() { - err := (&Header{ - KeyPhase: 1, - PacketNumberLen: protocol.PacketNumberLen1, - PacketNumber: 0x42, - }).Write(buf, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(Equal([]byte{ - 0x30 | 0x40, - 0x42, // packet number - })) - }) - }) - }) - - Context("gQUIC 44", func() { - Context("Long Header", func() { - It("writes", func() { - err := (&Header{ - IsLongHeader: true, - Type: protocol.PacketTypeInitial, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - Version: 0xdeadbeef, - PacketNumberLen: protocol.PacketNumberLen4, - PacketNumber: 0xdecafbad, - }).Write(buf, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{ - 0x80 ^ uint8(protocol.PacketTypeInitial), - 0xde, 0xad, 0xbe, 0xef, // version - 0x50, // connection ID lengths - 1, 2, 3, 4, 5, 6, 7, 8, // connection ID - 0xde, 0xca, 0xfb, 0xad, // packet number - } - Expect(buf.Bytes()).To(Equal(expected)) - }) - - It("writes a 0-RTT packet with a Diversification Nonce", func() { - divNonce := bytes.Repeat([]byte{'c'}, 32) - err := (&Header{ - IsLongHeader: true, - Type: protocol.PacketType0RTT, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - Version: 0xdeadbeef, - PacketNumberLen: protocol.PacketNumberLen4, - PacketNumber: 0xdecafbad, - DiversificationNonce: divNonce, - }).Write(buf, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{ - 0x80 ^ uint8(protocol.PacketType0RTT), - 0xde, 0xad, 0xbe, 0xef, // version - 0x50, // connection ID lengths - 1, 2, 3, 4, 5, 6, 7, 8, // connection ID - 0xde, 0xca, 0xfb, 0xad, // packet number - } - expected = append(expected, divNonce...) - Expect(buf.Bytes()).To(Equal(expected)) - }) - - It("refuses to write a 0-RTT packet with a wrong length Diversification Nonce", func() { - divNonce := bytes.Repeat([]byte{'c'}, 31) - err := (&Header{ - IsLongHeader: true, - Type: protocol.PacketType0RTT, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - Version: 0xdeadbeef, - PacketNumberLen: protocol.PacketNumberLen4, - PacketNumber: 0xdecafbad, - DiversificationNonce: divNonce, - }).Write(buf, protocol.PerspectiveServer, protocol.Version44) - Expect(err).To(MatchError("invalid diversification nonce length")) - }) - }) - - Context("Short Header", func() { - It("writes a Short Header with a 1 byte packet number", func() { - err := (&Header{ - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - PacketNumberLen: protocol.PacketNumberLen1, - PacketNumber: 0x42, - }).Write(buf, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{ - 0x30, - 1, 2, 3, 4, 5, 6, 7, 8, // connection ID - 0x42, // packet number - } - Expect(buf.Bytes()).To(Equal(expected)) - }) - - It("writes a Short Header with a 2 byte packet number", func() { - err := (&Header{ - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - PacketNumberLen: protocol.PacketNumberLen2, - PacketNumber: 0xcafe, - }).Write(buf, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{ - 0x30 ^ 0x1, - 1, 2, 3, 4, 5, 6, 7, 8, // connection ID - 0xca, 0xfe, // packet number - } - Expect(buf.Bytes()).To(Equal(expected)) - }) - - It("writes a Short Header with a 4 byte packet number", func() { - err := (&Header{ - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - PacketNumberLen: protocol.PacketNumberLen4, - PacketNumber: 0xdeadbeef, - }).Write(buf, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{ - 0x30 ^ 0x2, - 1, 2, 3, 4, 5, 6, 7, 8, // connection ID - 0xde, 0xad, 0xbe, 0xef, // packet number - } - Expect(buf.Bytes()).To(Equal(expected)) - }) - }) - }) - - Context("Public Header", func() { - connID := protocol.ConnectionID{0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6} - - It("writes a sample header as a server", func() { - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 2, - PacketNumberLen: protocol.PacketNumberLen4, - } - err := hdr.Write(buf, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(Equal([]byte{ - 0x28, - 0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6, - 0, 0, 0, 2, - })) - }) - - It("writes a sample header as a client", func() { - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 0x1337, - PacketNumberLen: protocol.PacketNumberLen2, - } - err := hdr.Write(buf, protocol.PerspectiveClient, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(Equal([]byte{ - 0x18, 0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6, - 0x13, 0x37, - })) - }) - - It("refuses to write a Public Header with a source connection ID", func() { - hdr := Header{ - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - SrcConnectionID: protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1}, - PacketNumber: 0x1337, - PacketNumberLen: protocol.PacketNumberLen4, - } - err := hdr.Write(buf, protocol.PerspectiveClient, versionPublicHeader) - Expect(err).To(MatchError("PublicHeader: SrcConnectionID must not be set")) - }) - - It("refuses to write a Public Header if the connection ID has the wrong length", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7} - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 2, - PacketNumberLen: protocol.PacketNumberLen2, - } - err := hdr.Write(buf, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).To(MatchError("PublicHeader: wrong length for Connection ID: 7 (expected 8)")) - }) - - It("refuses to write a Public Header if the PacketNumberLen is not set", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 2, - } - err := hdr.Write(buf, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).To(MatchError("PublicHeader: PacketNumberLen not set")) - }) - - It("omits the connection ID", func() { - hdr := Header{ - PacketNumberLen: protocol.PacketNumberLen1, - PacketNumber: 1, - } - err := hdr.Write(buf, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(Equal([]byte{0x0, 0x1})) - }) - - It("writes diversification nonces", func() { - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 0x42, - PacketNumberLen: protocol.PacketNumberLen1, - DiversificationNonce: bytes.Repeat([]byte{1}, 32), - } - err := hdr.Write(buf, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(Equal([]byte{ - 0xc, - 0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 0x42, - })) - }) - - It("writes packets with Version Flag, as a client", func() { - hdr := Header{ - VersionFlag: true, - Version: 0x11223344, - DestConnectionID: connID, - PacketNumber: 0x42, - PacketNumberLen: protocol.PacketNumberLen1, - } - err := hdr.Write(buf, protocol.PerspectiveClient, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - // must be the first assertion - Expect(buf.Len()).To(Equal(1 + 8 + 4 + 1)) // 1 FlagByte + 8 ConnectionID + 4 version number + 1 PacketNumber - firstByte, _ := buf.ReadByte() - Expect(firstByte & 0x01).To(Equal(uint8(1))) - Expect(firstByte & 0x30).To(Equal(uint8(0x0))) - Expect(buf.Bytes()[8:12]).To(Equal([]byte{0x11, 0x22, 0x33, 0x44})) - Expect(buf.Bytes()[12:13]).To(Equal([]byte{0x42})) - }) - - Context("packet number length", func() { - It("doesn't write a header if the packet number length is not set", func() { - b := &bytes.Buffer{} - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 0xDECAFBAD, - } - err := hdr.Write(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).To(MatchError("PublicHeader: PacketNumberLen not set")) - }) - - It("writes a header with a 1-byte packet number", func() { - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 0xdecafbad, - PacketNumberLen: protocol.PacketNumberLen1, - } - err := hdr.Write(buf, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(Equal([]byte{ - 0x8, - 0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6, - 0xad, - })) - }) - - It("writes a header with a 2-byte packet number", func() { - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 0xdecafbad, - PacketNumberLen: protocol.PacketNumberLen2, - } - err := hdr.Write(buf, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(Equal([]byte{ - 0x18, - 0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6, - 0xfb, 0xad, - })) - }) - - It("writes a header with a 4-byte packet number", func() { - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 0x13decafbad, - PacketNumberLen: protocol.PacketNumberLen4, - } - err := hdr.Write(buf, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Bytes()).To(Equal([]byte{ - 0x28, - 0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6, - 0xde, 0xca, 0xfb, 0xad, - })) - }) - - It("refuses to write a header with a 6-byte packet number", func() { - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 0xbe1337decafbad, - PacketNumberLen: protocol.PacketNumberLen6, - } - err := hdr.writePublicHeader(buf, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).To(MatchError(errInvalidPacketNumberLen)) - }) - }) - }) - }) - - Context("getting the length", func() { - var buf *bytes.Buffer - - BeforeEach(func() { - buf = &bytes.Buffer{} - }) - - Context("IETF QUIC", func() { - It("has the right length for the Long Header, for a short payload length", func() { - h := &Header{ - IsLongHeader: true, - PayloadLen: 1, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - SrcConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - PacketNumberLen: protocol.PacketNumberLen1, - } - expectedLen := 1 /* type byte */ + 4 /* version */ + 1 /* conn ID len */ + 8 /* dest conn id */ + 8 /* src conn id */ + 1 /* short payload len */ + 1 /* packet number */ - Expect(h.GetLength(versionIETFHeader)).To(BeEquivalentTo(expectedLen)) - err := h.Write(buf, protocol.PerspectiveClient, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(expectedLen)) - }) - - It("has the right length for the Long Header, for a long payload length", func() { - h := &Header{ - IsLongHeader: true, - PayloadLen: 1500, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - SrcConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - PacketNumberLen: protocol.PacketNumberLen2, - } - expectedLen := 1 /* type byte */ + 4 /* version */ + 1 /* conn ID len */ + 8 /* dest conn id */ + 8 /* src conn id */ + 2 /* long payload len */ + 2 /* packet number */ - Expect(h.GetLength(versionIETFHeader)).To(BeEquivalentTo(expectedLen)) - err := h.Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(expectedLen)) - }) - - It("has the right length for an Initial not containing a Token", func() { - h := &Header{ - Type: protocol.PacketTypeInitial, - IsLongHeader: true, - PayloadLen: 1500, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - SrcConnectionID: protocol.ConnectionID{1, 2, 3, 4}, - PacketNumberLen: protocol.PacketNumberLen2, - } - expectedLen := 1 /* type byte */ + 4 /* version */ + 1 /* conn ID len */ + 8 /* dest conn id */ + 4 /* src conn id */ + 1 /* token length */ + 2 /* long payload len */ + 2 /* packet number */ - Expect(h.GetLength(versionIETFHeader)).To(BeEquivalentTo(expectedLen)) - err := h.Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(expectedLen)) - }) - - It("has the right length for an Initial containing a Token", func() { - h := &Header{ - Type: protocol.PacketTypeInitial, - IsLongHeader: true, - PayloadLen: 1500, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - SrcConnectionID: protocol.ConnectionID{1, 2, 3, 4}, - PacketNumberLen: protocol.PacketNumberLen2, - Token: []byte("foo"), - } - expectedLen := 1 /* type byte */ + 4 /* version */ + 1 /* conn ID len */ + 8 /* dest conn id */ + 4 /* src conn id */ + 1 /* token length */ + 3 /* token */ + 2 /* long payload len */ + 2 /* packet number */ - Expect(h.GetLength(versionIETFHeader)).To(BeEquivalentTo(expectedLen)) - err := h.Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(expectedLen)) - }) - - It("has the right length for a Short Header containing a connection ID", func() { - h := &Header{ - PacketNumberLen: protocol.PacketNumberLen1, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - } - Expect(h.GetLength(versionIETFHeader)).To(Equal(protocol.ByteCount(1 + 8 + 1))) - err := h.Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(10)) - }) - - It("has the right length for a short header without a connection ID", func() { - h := &Header{PacketNumberLen: protocol.PacketNumberLen1} - Expect(h.GetLength(versionIETFHeader)).To(Equal(protocol.ByteCount(1 + 1))) - err := h.Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(2)) - }) - - It("has the right length for a short header with a 2 byte packet number", func() { - h := &Header{PacketNumberLen: protocol.PacketNumberLen2} - Expect(h.GetLength(versionIETFHeader)).To(Equal(protocol.ByteCount(1 + 2))) - err := h.Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(3)) - }) - - It("has the right length for a short header with a 5 byte packet number", func() { - h := &Header{PacketNumberLen: protocol.PacketNumberLen4} - Expect(h.GetLength(versionIETFHeader)).To(Equal(protocol.ByteCount(1 + 4))) - err := h.Write(buf, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(5)) - }) - - It("errors when given an invalid packet number length", func() { - h := &Header{PacketNumberLen: 5} - _, err := h.GetLength(versionIETFHeader) - Expect(err).To(MatchError("invalid packet number length: 5")) - }) - }) - - Context("gQUIC 44", func() { - It("has the right length for the Long Header", func() { - h := &Header{ - IsLongHeader: true, - Type: protocol.PacketTypeInitial, - PayloadLen: 1, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - PacketNumberLen: protocol.PacketNumberLen4, - } - expectedLen := 1 /* type byte */ + 4 /* version */ + 1 /* conn ID len */ + 8 /* dest conn id */ + 4 /* packet number */ - Expect(h.GetLength(protocol.Version44)).To(BeEquivalentTo(expectedLen)) - err := h.Write(buf, protocol.PerspectiveClient, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(expectedLen)) - }) - - It("has the right length for the Long Header containing a Diversification Nonce", func() { - h := &Header{ - IsLongHeader: true, - Type: protocol.PacketType0RTT, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - PacketNumberLen: protocol.PacketNumberLen4, - DiversificationNonce: bytes.Repeat([]byte{'d'}, 32), - } - expectedLen := 1 /* type byte */ + 4 /* version */ + 1 /* conn ID len */ + 8 /* dest conn id */ + 4 /* packet number */ + 32 /* div nonce */ - Expect(h.GetLength(protocol.Version44)).To(BeEquivalentTo(expectedLen)) - err := h.Write(buf, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(expectedLen)) - }) - - It("has the right length for a Short Header", func() { - h := &Header{ - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - PacketNumberLen: protocol.PacketNumberLen2, - } - expectedLen := 1 /*type byte*/ + 8 /* conn ID */ + 2 /* packet number */ - Expect(h.GetLength(protocol.Version44)).To(BeEquivalentTo(expectedLen)) - err := h.Write(buf, protocol.PerspectiveServer, protocol.Version44) - Expect(err).ToNot(HaveOccurred()) - Expect(buf.Len()).To(Equal(expectedLen)) - }) - }) - - Context("Public Header", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - - It("errors when PacketNumberLen is not set", func() { - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 0xdecafbad, - } - _, err := hdr.GetLength(versionPublicHeader) - Expect(err).To(MatchError(errPacketNumberLenNotSet)) - }) - - It("gets the length of a packet with longest packet number length and connectionID", func() { - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 0xdecafbad, - PacketNumberLen: protocol.PacketNumberLen4, - } - length, err := hdr.GetLength(versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(length).To(Equal(protocol.ByteCount(1 + 8 + 4))) // 1 byte public flag, 8 bytes connectionID, and packet number - }) - - It("gets the lengths of a packet sent by the client with the VersionFlag set", func() { - hdr := Header{ - PacketNumber: 0xdecafbad, - PacketNumberLen: protocol.PacketNumberLen4, - VersionFlag: true, - Version: versionPublicHeader, - } - length, err := hdr.GetLength(versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(length).To(Equal(protocol.ByteCount(1 + 4 + 4))) // 1 byte public flag, 4 version number, and packet number - }) - - It("gets the length of a packet with longest packet number length and omitted connectionID", func() { - hdr := Header{ - PacketNumber: 0xDECAFBAD, - PacketNumberLen: protocol.PacketNumberLen4, - } - length, err := hdr.GetLength(versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(length).To(Equal(protocol.ByteCount(1 + 4))) // 1 byte public flag, and packet number - }) - - It("gets the length of a packet 2 byte packet number length ", func() { - hdr := Header{ - DestConnectionID: connID, - PacketNumber: 0xDECAFBAD, - PacketNumberLen: protocol.PacketNumberLen2, - } - length, err := hdr.GetLength(versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(length).To(Equal(protocol.ByteCount(1 + 8 + 2))) // 1 byte public flag, 8 byte connectionID, and packet number - }) - - It("works with diversification nonce", func() { - hdr := Header{ - DiversificationNonce: []byte("foo"), - PacketNumberLen: protocol.PacketNumberLen1, - } - length, err := hdr.GetLength(versionPublicHeader) - Expect(err).NotTo(HaveOccurred()) - Expect(length).To(Equal(protocol.ByteCount(1 + 3 + 1))) // 1 byte public flag, 3 byte DiversificationNonce, 1 byte PacketNumber - }) - }) - }) - - Context("Logging", func() { - var ( - buf *bytes.Buffer - logger utils.Logger - ) - - BeforeEach(func() { - buf = &bytes.Buffer{} - logger = utils.DefaultLogger - logger.SetLogLevel(utils.LogLevelDebug) - log.SetOutput(buf) - }) - - AfterEach(func() { - log.SetOutput(os.Stdout) - }) - - Context("IETF QUIC Header", func() { - It("logs version negotiation packets", func() { - destConnID := protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37} - srcConnID := protocol.ConnectionID{0xde, 0xca, 0xfb, 0xad, 0x013, 0x37, 0x13, 0x37} - data, err := ComposeVersionNegotiation(destConnID, srcConnID, []protocol.VersionNumber{0x12345678, 0x87654321}) - Expect(err).ToNot(HaveOccurred()) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 4) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - hdr.Log(logger) - Expect(buf.String()).To(ContainSubstring("VersionNegotiationPacket{DestConnectionID: 0xdeadbeefcafe1337, SrcConnectionID: 0xdecafbad13371337")) - Expect(buf.String()).To(ContainSubstring("0x12345678")) - Expect(buf.String()).To(ContainSubstring("0x87654321")) - }) - - It("logs Long Headers", func() { - (&Header{ - IsLongHeader: true, - Type: protocol.PacketTypeHandshake, - PacketNumber: 0x1337, - PacketNumberLen: protocol.PacketNumberLen2, - PayloadLen: 54321, - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37}, - SrcConnectionID: protocol.ConnectionID{0xde, 0xca, 0xfb, 0xad, 0x013, 0x37, 0x13, 0x37}, - Version: 0xfeed, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("Long Header{Type: Handshake, DestConnectionID: 0xdeadbeefcafe1337, SrcConnectionID: 0xdecafbad13371337, PacketNumber: 0x1337, PacketNumberLen: 2, PayloadLen: 54321, Version: 0xfeed}")) - }) - - It("logs Initial Packets with a Token", func() { - (&Header{ - IsLongHeader: true, - Type: protocol.PacketTypeInitial, - Token: []byte{0xde, 0xad, 0xbe, 0xef}, - PacketNumber: 0x42, - PacketNumberLen: protocol.PacketNumberLen2, - PayloadLen: 100, - DestConnectionID: protocol.ConnectionID{0xca, 0xfe, 0x13, 0x37}, - SrcConnectionID: protocol.ConnectionID{0xde, 0xca, 0xfb, 0xad}, - Version: 0xfeed, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("Long Header{Type: Initial, DestConnectionID: 0xcafe1337, SrcConnectionID: 0xdecafbad, Token: 0xdeadbeef, PacketNumber: 0x42, PacketNumberLen: 2, PayloadLen: 100, Version: 0xfeed}")) - }) - - It("logs Initial Packets without a Token", func() { - (&Header{ - IsLongHeader: true, - Type: protocol.PacketTypeInitial, - PacketNumber: 0x42, - PacketNumberLen: protocol.PacketNumberLen2, - PayloadLen: 100, - DestConnectionID: protocol.ConnectionID{0xca, 0xfe, 0x13, 0x37}, - SrcConnectionID: protocol.ConnectionID{0xde, 0xca, 0xfb, 0xad}, - Version: 0xfeed, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("Long Header{Type: Initial, DestConnectionID: 0xcafe1337, SrcConnectionID: 0xdecafbad, Token: (empty), PacketNumber: 0x42, PacketNumberLen: 2, PayloadLen: 100, Version: 0xfeed}")) - }) - - It("logs Initial Packets without a Token", func() { - (&Header{ - IsLongHeader: true, - Type: protocol.PacketTypeRetry, - DestConnectionID: protocol.ConnectionID{0xca, 0xfe, 0x13, 0x37}, - SrcConnectionID: protocol.ConnectionID{0xde, 0xca, 0xfb, 0xad}, - OrigDestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef}, - Token: []byte{0x12, 0x34, 0x56}, - Version: 0xfeed, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("Long Header{Type: Retry, DestConnectionID: 0xcafe1337, SrcConnectionID: 0xdecafbad, Token: 0x123456, OrigDestConnectionID: 0xdeadbeef, Version: 0xfeed}")) - }) - - It("logs Short Headers containing a connection ID", func() { - (&Header{ - KeyPhase: 1, - PacketNumber: 0x1337, - PacketNumberLen: 4, - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37}, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("Short Header{DestConnectionID: 0xdeadbeefcafe1337, PacketNumber: 0x1337, PacketNumberLen: 4, KeyPhase: 1}")) - }) - }) - - Context("gQUIC 44", func() { - It("logs Long Headers", func() { - (&Header{ - IsLongHeader: true, - Type: protocol.PacketTypeHandshake, - PacketNumber: 0x1337, - PacketNumberLen: protocol.PacketNumberLen4, - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37}, - SrcConnectionID: protocol.ConnectionID{0xde, 0xca, 0xfb, 0xad, 0x013, 0x37, 0x13, 0x37}, - Version: protocol.Version44, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("Long Header{Type: Handshake, DestConnectionID: 0xdeadbeefcafe1337, SrcConnectionID: 0xdecafbad13371337, PacketNumber: 0x1337, PacketNumberLen: 4, Version: gQUIC 44}")) - }) - - It("logs a Long Header with a Diversification Nonce", func() { - (&Header{ - IsLongHeader: true, - Type: protocol.PacketType0RTT, - PacketNumber: 0x1337, - PacketNumberLen: protocol.PacketNumberLen4, - SrcConnectionID: protocol.ConnectionID{0xde, 0xca, 0xfb, 0xad, 0x013, 0x37, 0x13, 0x37}, - DiversificationNonce: []byte{0xde, 0xad, 0xbe, 0xef}, - Version: protocol.Version44, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("Long Header{Type: 0-RTT Protected, DestConnectionID: (empty), SrcConnectionID: 0xdecafbad13371337, PacketNumber: 0x1337, PacketNumberLen: 4, Diversification Nonce: 0xdeadbeef, Version: gQUIC 44}")) - }) - }) - - Context("Public Header", func() { - It("logs a Public Header containing a connection ID", func() { - (&Header{ - IsPublicHeader: true, - DestConnectionID: protocol.ConnectionID{0x13, 0x37, 0, 0, 0xde, 0xca, 0xfb, 0xad}, - PacketNumber: 0x1337, - PacketNumberLen: 6, - Version: protocol.Version39, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("Public Header{ConnectionID: 0x13370000decafbad, PacketNumber: 0x1337, PacketNumberLen: 6, Version: gQUIC 39")) - }) - - It("logs a Public Header with omitted connection ID", func() { - (&Header{ - IsPublicHeader: true, - PacketNumber: 0x1337, - PacketNumberLen: 6, - Version: protocol.Version39, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("Public Header{ConnectionID: (empty)")) - }) - - It("logs a Public Header without a version", func() { - (&Header{ - IsPublicHeader: true, - PacketNumber: 0x1337, - PacketNumberLen: 6, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("Version: (unset)")) - }) - - It("logs diversification nonces", func() { - (&Header{ - IsPublicHeader: true, - DestConnectionID: []byte{0x13, 0x13, 0, 0, 0xde, 0xca, 0xfb, 0xad}, - DiversificationNonce: []byte{0xba, 0xdf, 0x00, 0x0d}, - }).Log(logger) - Expect(buf.String()).To(ContainSubstring("DiversificationNonce: []byte{0xba, 0xdf, 0x0, 0xd}")) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/log_test.go b/vendor/lucas-clemente/quic-go/internal/wire/log_test.go deleted file mode 100644 index 4b1078f85..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/log_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package wire - -import ( - "bytes" - "log" - "os" - "time" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Frame logging", func() { - var ( - buf *bytes.Buffer - logger utils.Logger - ) - - BeforeEach(func() { - buf = &bytes.Buffer{} - logger = utils.DefaultLogger - logger.SetLogLevel(utils.LogLevelDebug) - log.SetOutput(buf) - }) - - AfterEach(func() { - log.SetOutput(os.Stdout) - }) - - It("doesn't log when debug is disabled", func() { - logger.SetLogLevel(utils.LogLevelInfo) - LogFrame(logger, &RstStreamFrame{}, true) - Expect(buf.Len()).To(BeZero()) - }) - - It("logs sent frames", func() { - LogFrame(logger, &RstStreamFrame{}, true) - Expect(buf.Bytes()).To(ContainSubstring("\t-> &wire.RstStreamFrame{StreamID:0x0, ErrorCode:0x0, ByteOffset:0x0}\n")) - }) - - It("logs received frames", func() { - LogFrame(logger, &RstStreamFrame{}, false) - Expect(buf.Bytes()).To(ContainSubstring("\t<- &wire.RstStreamFrame{StreamID:0x0, ErrorCode:0x0, ByteOffset:0x0}\n")) - }) - - It("logs stream frames", func() { - frame := &StreamFrame{ - StreamID: 42, - Offset: 0x1337, - Data: bytes.Repeat([]byte{'f'}, 0x100), - } - LogFrame(logger, frame, false) - Expect(buf.Bytes()).To(ContainSubstring("\t<- &wire.StreamFrame{StreamID: 42, FinBit: false, Offset: 0x1337, Data length: 0x100, Offset + Data length: 0x1437}\n")) - }) - - It("logs ACK frames without missing packets", func() { - frame := &AckFrame{ - AckRanges: []AckRange{{Smallest: 0x42, Largest: 0x1337}}, - DelayTime: 1 * time.Millisecond, - } - LogFrame(logger, frame, false) - Expect(buf.String()).To(ContainSubstring("\t<- &wire.AckFrame{LargestAcked: 0x1337, LowestAcked: 0x42, DelayTime: 1ms}\n")) - }) - - It("logs ACK frames with missing packets", func() { - frame := &AckFrame{ - AckRanges: []AckRange{ - {Smallest: 0x5, Largest: 0x8}, - {Smallest: 0x2, Largest: 0x3}, - }, - DelayTime: 12 * time.Millisecond, - } - LogFrame(logger, frame, false) - Expect(buf.String()).To(ContainSubstring("\t<- &wire.AckFrame{LargestAcked: 0x8, LowestAcked: 0x2, AckRanges: {{Largest: 0x8, Smallest: 0x5}, {Largest: 0x3, Smallest: 0x2}}, DelayTime: 12ms}\n")) - }) - - It("logs incoming StopWaiting frames", func() { - frame := &StopWaitingFrame{ - LeastUnacked: 0x1337, - } - LogFrame(logger, frame, false) - Expect(buf.Bytes()).To(ContainSubstring("\t<- &wire.StopWaitingFrame{LeastUnacked: 0x1337}\n")) - }) - - It("logs outgoing StopWaiting frames", func() { - frame := &StopWaitingFrame{ - LeastUnacked: 0x1337, - PacketNumberLen: protocol.PacketNumberLen4, - } - LogFrame(logger, frame, true) - Expect(buf.Bytes()).To(ContainSubstring("\t-> &wire.StopWaitingFrame{LeastUnacked: 0x1337, PacketNumberLen: 0x4}\n")) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/max_data_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/max_data_frame_test.go deleted file mode 100644 index a56d26165..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/max_data_frame_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("MAX_DATA frame", func() { - Context("when parsing", func() { - It("accepts sample frame", func() { - data := []byte{0x4} - data = append(data, encodeVarInt(0xdecafbad123456)...) // byte offset - b := bytes.NewReader(data) - frame, err := parseMaxDataFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.ByteOffset).To(Equal(protocol.ByteCount(0xdecafbad123456))) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOFs", func() { - data := []byte{0x4} - data = append(data, encodeVarInt(0xdecafbad1234567)...) // byte offset - _, err := parseMaxDataFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseMaxDataFrame(bytes.NewReader(data[0:i]), versionIETFFrames) - Expect(err).To(HaveOccurred()) - } - }) - }) - - Context("writing", func() { - It("has proper min length", func() { - f := &MaxDataFrame{ - ByteOffset: 0xdeadbeef, - } - Expect(f.Length(versionIETFFrames)).To(Equal(1 + utils.VarIntLen(0xdeadbeef))) - }) - - It("writes a MAX_DATA frame", func() { - b := &bytes.Buffer{} - f := &MaxDataFrame{ - ByteOffset: 0xdeadbeefcafe, - } - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x4} - expected = append(expected, encodeVarInt(0xdeadbeefcafe)...) - Expect(b.Bytes()).To(Equal(expected)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/max_stream_data_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/max_stream_data_frame_test.go deleted file mode 100644 index 06f7c2456..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/max_stream_data_frame_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("MAX_STREAM_DATA frame", func() { - Context("parsing", func() { - It("accepts sample frame", func() { - data := []byte{0x5} - data = append(data, encodeVarInt(0xdeadbeef)...) // Stream ID - data = append(data, encodeVarInt(0x12345678)...) // Offset - b := bytes.NewReader(data) - frame, err := parseMaxStreamDataFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(0xdeadbeef))) - Expect(frame.ByteOffset).To(Equal(protocol.ByteCount(0x12345678))) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOFs", func() { - data := []byte{0x5} - data = append(data, encodeVarInt(0xdeadbeef)...) // Stream ID - data = append(data, encodeVarInt(0x12345678)...) // Offset - _, err := parseMaxStreamDataFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseMaxStreamDataFrame(bytes.NewReader(data[0:i]), versionIETFFrames) - Expect(err).To(HaveOccurred()) - } - }) - }) - - Context("writing", func() { - It("has proper min length", func() { - f := &MaxStreamDataFrame{ - StreamID: 0x1337, - ByteOffset: 0xdeadbeef, - } - Expect(f.Length(protocol.VersionWhatever)).To(Equal(1 + utils.VarIntLen(uint64(f.StreamID)) + utils.VarIntLen(uint64(f.ByteOffset)))) - }) - - It("writes a sample frame", func() { - b := &bytes.Buffer{} - f := &MaxStreamDataFrame{ - StreamID: 0xdecafbad, - ByteOffset: 0xdeadbeefcafe42, - } - expected := []byte{0x5} - expected = append(expected, encodeVarInt(0xdecafbad)...) - expected = append(expected, encodeVarInt(0xdeadbeefcafe42)...) - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()).To(Equal(expected)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/max_stream_id_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/max_stream_id_frame_test.go deleted file mode 100644 index 66a27e7ba..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/max_stream_id_frame_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("MAX_STREAM_ID frame", func() { - Context("parsing", func() { - It("accepts sample frame", func() { - data := []byte{0x6} - data = append(data, encodeVarInt(0xdecafbad)...) - b := bytes.NewReader(data) - f, err := parseMaxStreamIDFrame(b, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - Expect(f.StreamID).To(Equal(protocol.StreamID(0xdecafbad))) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOFs", func() { - data := []byte{0x06} - data = append(data, encodeVarInt(0xdeadbeefcafe13)...) - _, err := parseMaxStreamIDFrame(bytes.NewReader(data), protocol.VersionWhatever) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseMaxStreamIDFrame(bytes.NewReader(data[0:i]), protocol.VersionWhatever) - Expect(err).To(HaveOccurred()) - } - }) - }) - - Context("writing", func() { - It("writes a sample frame", func() { - b := &bytes.Buffer{} - frame := MaxStreamIDFrame{StreamID: 0x12345678} - frame.Write(b, protocol.VersionWhatever) - expected := []byte{0x6} - expected = append(expected, encodeVarInt(0x12345678)...) - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("has the correct min length", func() { - frame := MaxStreamIDFrame{StreamID: 0x1337} - Expect(frame.Length(protocol.VersionWhatever)).To(Equal(1 + utils.VarIntLen(0x1337))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/path_challenge_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/path_challenge_frame_test.go deleted file mode 100644 index bbfc71093..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/path_challenge_frame_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("PATH_CHALLENGE frame", func() { - Context("when parsing", func() { - It("accepts sample frame", func() { - b := bytes.NewReader([]byte{0x0e, 1, 2, 3, 4, 5, 6, 7, 8}) - f, err := parsePathChallengeFrame(b, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(BeZero()) - Expect(f.Data).To(Equal([8]byte{1, 2, 3, 4, 5, 6, 7, 8})) - }) - - It("errors on EOFs", func() { - data := []byte{0x0e, 1, 2, 3, 4, 5, 6, 7, 8} - _, err := parsePathChallengeFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parsePathChallengeFrame(bytes.NewReader(data[0:i]), versionIETFFrames) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("when writing", func() { - It("writes a sample frame", func() { - b := &bytes.Buffer{} - frame := PathChallengeFrame{Data: [8]byte{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37}} - err := frame.Write(b, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()).To(Equal([]byte{0x0e, 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37})) - }) - - It("has the correct min length", func() { - frame := PathChallengeFrame{} - Expect(frame.Length(protocol.VersionWhatever)).To(Equal(protocol.ByteCount(9))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/path_response_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/path_response_frame_test.go deleted file mode 100644 index 14e45bed8..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/path_response_frame_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("PATH_RESPONSE frame", func() { - Context("when parsing", func() { - It("accepts sample frame", func() { - b := bytes.NewReader([]byte{0x0f, 1, 2, 3, 4, 5, 6, 7, 8}) - f, err := parsePathResponseFrame(b, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(BeZero()) - Expect(f.Data).To(Equal([8]byte{1, 2, 3, 4, 5, 6, 7, 8})) - }) - - It("errors on EOFs", func() { - data := []byte{0x0f, 1, 2, 3, 4, 5, 6, 7, 8} - _, err := parsePathResponseFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parsePathResponseFrame(bytes.NewReader(data[0:i]), versionIETFFrames) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("when writing", func() { - It("writes a sample frame", func() { - b := &bytes.Buffer{} - frame := PathResponseFrame{Data: [8]byte{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37}} - err := frame.Write(b, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()).To(Equal([]byte{0x0f, 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37})) - }) - - It("has the correct min length", func() { - frame := PathResponseFrame{} - Expect(frame.Length(protocol.VersionWhatever)).To(Equal(protocol.ByteCount(9))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/ping_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/ping_frame_test.go deleted file mode 100644 index 54c7c6c16..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/ping_frame_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("PingFrame", func() { - Context("when parsing", func() { - It("accepts sample frame", func() { - b := bytes.NewReader([]byte{0x07}) - _, err := parsePingFrame(b, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOFs", func() { - _, err := parsePingFrame(bytes.NewReader(nil), protocol.VersionWhatever) - Expect(err).To(HaveOccurred()) - }) - }) - - Context("when writing", func() { - It("writes a sample frame", func() { - b := &bytes.Buffer{} - frame := PingFrame{} - frame.Write(b, protocol.VersionWhatever) - Expect(b.Bytes()).To(Equal([]byte{0x07})) - }) - - It("has the correct min length", func() { - frame := PingFrame{} - Expect(frame.Length(0)).To(Equal(protocol.ByteCount(1))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/public_reset_test.go b/vendor/lucas-clemente/quic-go/internal/wire/public_reset_test.go deleted file mode 100644 index 45347df6f..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/public_reset_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/handshake" - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("public reset", func() { - Context("writing", func() { - It("writes public reset packets", func() { - Expect(WritePublicReset(protocol.ConnectionID{0, 0, 0, 0, 0xde, 0xad, 0xbe, 0xef}, 0x8badf00d, 0xdecafbad)).To(Equal([]byte{ - 0x0a, - 0x0, 0x0, 0x0, 0x0, 0xde, 0xad, 0xbe, 0xef, - 'P', 'R', 'S', 'T', - 0x02, 0x00, 0x00, 0x00, - 'R', 'N', 'O', 'N', - 0x08, 0x00, 0x00, 0x00, - 'R', 'S', 'E', 'Q', - 0x10, 0x00, 0x00, 0x00, - 0xad, 0xfb, 0xca, 0xde, 0x0, 0x0, 0x0, 0x0, - 0x0d, 0xf0, 0xad, 0x8b, 0x0, 0x0, 0x0, 0x0, - })) - }) - }) - - Context("parsing", func() { - var b *bytes.Buffer - - BeforeEach(func() { - b = &bytes.Buffer{} - }) - - It("parses a public reset", func() { - packet := WritePublicReset(protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, 0x8badf00d, 0xdecafbad) - pr, err := ParsePublicReset(bytes.NewReader(packet[9:])) // 1 byte Public Flag, 8 bytes connection ID - Expect(err).ToNot(HaveOccurred()) - Expect(pr.Nonce).To(Equal(uint64(0xdecafbad))) - Expect(pr.RejectedPacketNumber).To(Equal(protocol.PacketNumber(0x8badf00d))) - }) - - It("rejects packets that it can't parse", func() { - _, err := ParsePublicReset(bytes.NewReader([]byte{})) - Expect(err).To(MatchError(io.EOF)) - }) - - It("rejects packets with the wrong tag", func() { - handshake.HandshakeMessage{Tag: handshake.TagREJ, Data: nil}.Write(b) - _, err := ParsePublicReset(bytes.NewReader(b.Bytes())) - Expect(err).To(MatchError("wrong public reset tag")) - }) - - It("rejects packets missing the nonce", func() { - data := map[handshake.Tag][]byte{ - handshake.TagRSEQ: {0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37}, - } - handshake.HandshakeMessage{Tag: handshake.TagPRST, Data: data}.Write(b) - _, err := ParsePublicReset(bytes.NewReader(b.Bytes())) - Expect(err).To(MatchError("RNON missing")) - }) - - It("rejects packets with a wrong length nonce", func() { - data := map[handshake.Tag][]byte{ - handshake.TagRSEQ: {0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37}, - handshake.TagRNON: {0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13}, - } - handshake.HandshakeMessage{Tag: handshake.TagPRST, Data: data}.Write(b) - _, err := ParsePublicReset(bytes.NewReader(b.Bytes())) - Expect(err).To(MatchError("invalid RNON tag")) - }) - - It("accepts packets missing the rejected packet number", func() { - data := map[handshake.Tag][]byte{ - handshake.TagRNON: {0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37}, - } - handshake.HandshakeMessage{Tag: handshake.TagPRST, Data: data}.Write(b) - pr, err := ParsePublicReset(bytes.NewReader(b.Bytes())) - Expect(err).ToNot(HaveOccurred()) - Expect(pr.Nonce).To(Equal(uint64(0x3713fecaefbeadde))) - }) - - It("rejects packets with a wrong length rejected packet number", func() { - data := map[handshake.Tag][]byte{ - handshake.TagRSEQ: {0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13}, - handshake.TagRNON: {0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37}, - } - handshake.HandshakeMessage{Tag: handshake.TagPRST, Data: data}.Write(b) - _, err := ParsePublicReset(bytes.NewReader(b.Bytes())) - Expect(err).To(MatchError("invalid RSEQ tag")) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/rst_stream_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/rst_stream_frame_test.go deleted file mode 100644 index f39be0f7b..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/rst_stream_frame_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("RST_STREAM frame", func() { - Context("when parsing", func() { - Context("in varint encoding", func() { - It("accepts sample frame", func() { - data := []byte{0x1} - data = append(data, encodeVarInt(0xdeadbeef)...) // stream ID - data = append(data, []byte{0x13, 0x37}...) // error code - data = append(data, encodeVarInt(0x987654321)...) // byte offset - b := bytes.NewReader(data) - frame, err := parseRstStreamFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(0xdeadbeef))) - Expect(frame.ByteOffset).To(Equal(protocol.ByteCount(0x987654321))) - Expect(frame.ErrorCode).To(Equal(protocol.ApplicationErrorCode(0x1337))) - }) - - It("errors on EOFs", func() { - data := []byte{0x1} - data = append(data, encodeVarInt(0xdeadbeef)...) // stream ID - data = append(data, []byte{0x13, 0x37}...) // error code - data = append(data, encodeVarInt(0x987654321)...) // byte offset - _, err := parseRstStreamFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseRstStreamFrame(bytes.NewReader(data[0:i]), versionIETFFrames) - Expect(err).To(HaveOccurred()) - } - }) - }) - - Context("in big endian", func() { - It("accepts sample frame", func() { - b := bytes.NewReader([]byte{0x1, - 0xde, 0xad, 0xbe, 0xef, // stream id - 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, // byte offset - 0x0, 0x0, 0xca, 0xfe, // error code - }) - frame, err := parseRstStreamFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(0xdeadbeef))) - Expect(frame.ByteOffset).To(Equal(protocol.ByteCount(0x8877665544332211))) - Expect(frame.ErrorCode).To(Equal(protocol.ApplicationErrorCode(0xcafe))) - }) - - It("errors on EOFs", func() { - data := []byte{0x1, - 0xef, 0xbe, 0xad, 0xde, 0x44, // stream id - 0x33, 0x22, 0x11, 0xad, 0xfb, 0xca, 0xde, 0x34, // byte offset - 0x12, 0x37, 0x13, // error code - } - _, err := parseRstStreamFrame(bytes.NewReader(data), versionBigEndian) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseRstStreamFrame(bytes.NewReader(data[0:i]), versionBigEndian) - Expect(err).To(HaveOccurred()) - } - }) - }) - }) - - Context("when writing", func() { - Context("in varint encoding", func() { - It("writes a sample frame", func() { - frame := RstStreamFrame{ - StreamID: 0x1337, - ByteOffset: 0x11223344decafbad, - ErrorCode: 0xcafe, - } - b := &bytes.Buffer{} - err := frame.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x1} - expected = append(expected, encodeVarInt(0x1337)...) - expected = append(expected, []byte{0xca, 0xfe}...) - expected = append(expected, encodeVarInt(0x11223344decafbad)...) - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("has the correct min length", func() { - rst := RstStreamFrame{ - StreamID: 0x1337, - ByteOffset: 0x1234567, - ErrorCode: 0xde, - } - expectedLen := 1 + utils.VarIntLen(0x1337) + utils.VarIntLen(0x1234567) + 2 - Expect(rst.Length(versionIETFFrames)).To(Equal(expectedLen)) - }) - }) - - Context("in big endian", func() { - It("writes a sample frame", func() { - frame := RstStreamFrame{ - StreamID: 0x1337, - ByteOffset: 0x11223344decafbad, - ErrorCode: 0xcafe, - } - b := &bytes.Buffer{} - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()).To(Equal([]byte{0x01, - 0x0, 0x0, 0x13, 0x37, // stream id - 0x11, 0x22, 0x33, 0x44, 0xde, 0xca, 0xfb, 0xad, // byte offset - 0x0, 0x0, 0xca, 0xfe, // error code - })) - }) - - It("has the correct min length", func() { - rst := RstStreamFrame{ - StreamID: 0x1337, - ByteOffset: 0x1000, - ErrorCode: 0xde, - } - Expect(rst.Length(versionBigEndian)).To(Equal(protocol.ByteCount(17))) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/stop_sending_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/stop_sending_frame_test.go deleted file mode 100644 index 2f93487ac..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/stop_sending_frame_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("STOP_SENDING frame", func() { - Context("when parsing", func() { - It("parses a sample frame", func() { - data := []byte{0x0c} - data = append(data, encodeVarInt(0xdecafbad)...) // stream ID - data = append(data, []byte{0x13, 0x37}...) // error code - b := bytes.NewReader(data) - frame, err := parseStopSendingFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(0xdecafbad))) - Expect(frame.ErrorCode).To(Equal(protocol.ApplicationErrorCode(0x1337))) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOFs", func() { - data := []byte{0x0c} - data = append(data, encodeVarInt(0xdecafbad)...) // stream ID - data = append(data, []byte{0x13, 0x37}...) // error code - _, err := parseStopSendingFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseStopSendingFrame(bytes.NewReader(data[:i]), versionIETFFrames) - Expect(err).To(HaveOccurred()) - } - }) - }) - - Context("when writing", func() { - It("writes", func() { - frame := &StopSendingFrame{ - StreamID: 0xdeadbeefcafe, - ErrorCode: 0x10, - } - buf := &bytes.Buffer{} - err := frame.Write(buf, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x0c} - expected = append(expected, encodeVarInt(0xdeadbeefcafe)...) - expected = append(expected, []byte{0x0, 0x10}...) - Expect(buf.Bytes()).To(Equal(expected)) - }) - - It("has the correct min length", func() { - frame := &StopSendingFrame{ - StreamID: 0xdeadbeef, - ErrorCode: 0x10, - } - Expect(frame.Length(versionIETFFrames)).To(Equal(1 + 2 + utils.VarIntLen(0xdeadbeef))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/stop_waiting_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/stop_waiting_frame_test.go deleted file mode 100644 index 7452f06da..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/stop_waiting_frame_test.go +++ /dev/null @@ -1,208 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("StopWaitingFrame", func() { - Context("when parsing", func() { - Context("in big endian", func() { - It("accepts sample frame", func() { - b := bytes.NewReader([]byte{0x06, 0x12, 0x34}) - frame, err := parseStopWaitingFrame(b, 0x1337, 2, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LeastUnacked).To(Equal(protocol.PacketNumber(0x1337 - 0x1234))) - Expect(b.Len()).To(BeZero()) - }) - }) - - It("rejects frames that would have a negative LeastUnacked value", func() { - b := bytes.NewReader([]byte{0x06, 0xD}) - _, err := parseStopWaitingFrame(b, 10, 1, protocol.VersionWhatever) - Expect(err).To(HaveOccurred()) - Expect(b.Len()).To(BeZero()) - }) - - It("parses a frame with 0 as LeastUnacked", func() { - b := bytes.NewReader([]byte{0x6, 0x8}) - frame, err := parseStopWaitingFrame(b, 8, 1, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.LeastUnacked).To(Equal(protocol.PacketNumber(0))) - Expect(b.Len()).To(BeZero()) - }) - - It("rejects frames that underflow LeastUnacked", func() { - b := bytes.NewReader([]byte{0x6, 0x9}) - _, err := parseStopWaitingFrame(b, 8, 1, protocol.VersionWhatever) - Expect(err).To(MatchError("invalid LeastUnackedDelta")) - }) - - It("errors on EOFs", func() { - data := []byte{0x06, 0x03} - _, err := parseStopWaitingFrame(bytes.NewReader(data), 5, 1, protocol.VersionWhatever) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseStopWaitingFrame(bytes.NewReader(data[0:i]), 5, 1, protocol.VersionWhatever) - Expect(err).To(HaveOccurred()) - } - }) - }) - - Context("when writing", func() { - It("writes a sample frame", func() { - b := &bytes.Buffer{} - frame := &StopWaitingFrame{ - LeastUnacked: 10, - PacketNumber: 13, - PacketNumberLen: protocol.PacketNumberLen6, - } - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0]).To(Equal(uint8(0x06))) - Expect(b.Bytes()[1:7]).To(Equal([]byte{0, 0, 0, 0, 0, 3})) - }) - - It("writes a frame for LeastUnacked = 0", func() { - b := &bytes.Buffer{} - frame := &StopWaitingFrame{ - LeastUnacked: 0, - PacketNumber: 8, - PacketNumberLen: protocol.PacketNumberLen1, - } - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()).To(Equal([]byte{0x6, 0x8})) - }) - - It("errors when PacketNumber was not set", func() { - b := &bytes.Buffer{} - frame := &StopWaitingFrame{ - LeastUnacked: 10, - PacketNumberLen: protocol.PacketNumberLen1, - } - err := frame.Write(b, versionBigEndian) - Expect(err).To(MatchError(errPacketNumberNotSet)) - }) - - It("errors when PacketNumberLen was not set", func() { - b := &bytes.Buffer{} - frame := &StopWaitingFrame{ - LeastUnacked: 10, - PacketNumber: 13, - } - err := frame.Write(b, versionBigEndian) - Expect(err).To(MatchError(errPacketNumberLenNotSet)) - }) - - It("errors when the LeastUnackedDelta would be negative", func() { - b := &bytes.Buffer{} - frame := &StopWaitingFrame{ - LeastUnacked: 10, - PacketNumber: 5, - PacketNumberLen: protocol.PacketNumberLen1, - } - err := frame.Write(b, versionBigEndian) - Expect(err).To(MatchError(errLeastUnackedHigherThanPacketNumber)) - }) - - It("refuses to write for IETF QUIC", func() { - b := &bytes.Buffer{} - frame := &StopWaitingFrame{ - LeastUnacked: 10, - PacketNumber: 13, - PacketNumberLen: protocol.PacketNumberLen6, - } - err := frame.Write(b, versionIETFFrames) - Expect(err).To(MatchError("STOP_WAITING not defined in IETF QUIC")) - }) - - Context("LeastUnackedDelta length", func() { - Context("in big endian", func() { - It("writes a 1-byte LeastUnackedDelta", func() { - b := &bytes.Buffer{} - frame := &StopWaitingFrame{ - LeastUnacked: 10, - PacketNumber: 13, - PacketNumberLen: protocol.PacketNumberLen1, - } - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(2)) - Expect(b.Bytes()[1]).To(Equal(uint8(3))) - }) - - It("writes a 2-byte LeastUnackedDelta", func() { - b := &bytes.Buffer{} - frame := &StopWaitingFrame{ - LeastUnacked: 0x10, - PacketNumber: 0x1300, - PacketNumberLen: protocol.PacketNumberLen2, - } - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(3)) - Expect(b.Bytes()[1:3]).To(Equal([]byte{0x12, 0xf0})) - }) - - It("writes a 4-byte LeastUnackedDelta", func() { - b := &bytes.Buffer{} - frame := &StopWaitingFrame{ - LeastUnacked: 0x1000, - PacketNumber: 0x12345678, - PacketNumberLen: protocol.PacketNumberLen4, - } - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(5)) - Expect(b.Bytes()[1:5]).To(Equal([]byte{0x12, 0x34, 0x46, 0x78})) - }) - - It("writes a 6-byte LeastUnackedDelta, for a delta that fits into 6 bytes", func() { - b := &bytes.Buffer{} - frame := &StopWaitingFrame{ - LeastUnacked: 0x10, - PacketNumber: 0x123456789abc, - PacketNumberLen: protocol.PacketNumberLen6, - } - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(7)) - Expect(b.Bytes()[1:7]).To(Equal([]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc - 0x10})) - }) - }) - }) - }) - - Context("Length", func() { - It("calculates the right length", func() { - for _, length := range []protocol.PacketNumberLen{protocol.PacketNumberLen1, protocol.PacketNumberLen2, protocol.PacketNumberLen4, protocol.PacketNumberLen6} { - frame := &StopWaitingFrame{ - LeastUnacked: 10, - PacketNumberLen: length, - } - Expect(frame.Length(protocol.VersionWhatever)).To(Equal(protocol.ByteCount(length + 1))) - } - }) - }) - - Context("self consistency", func() { - It("reads a STOP_WAITING frame that it wrote", func() { - packetNumber := protocol.PacketNumber(13) - frame := &StopWaitingFrame{ - LeastUnacked: 10, - PacketNumber: packetNumber, - PacketNumberLen: protocol.PacketNumberLen4, - } - b := &bytes.Buffer{} - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - readframe, err := parseStopWaitingFrame(bytes.NewReader(b.Bytes()), packetNumber, protocol.PacketNumberLen4, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(readframe.LeastUnacked).To(Equal(frame.LeastUnacked)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/stream_blocked_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/stream_blocked_frame_test.go deleted file mode 100644 index d72f4bda5..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/stream_blocked_frame_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("STREAM_BLOCKED frame", func() { - Context("parsing", func() { - It("accepts sample frame", func() { - data := []byte{0x9} - data = append(data, encodeVarInt(0xdeadbeef)...) // stream ID - data = append(data, encodeVarInt(0xdecafbad)...) // offset - b := bytes.NewReader(data) - frame, err := parseStreamBlockedFrame(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(0xdeadbeef))) - Expect(frame.Offset).To(Equal(protocol.ByteCount(0xdecafbad))) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOFs", func() { - data := []byte{0x9} - data = append(data, encodeVarInt(0xdeadbeef)...) - data = append(data, encodeVarInt(0xc0010ff)...) - _, err := parseStreamBlockedFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseStreamBlockedFrame(bytes.NewReader(data[0:i]), versionIETFFrames) - Expect(err).To(HaveOccurred()) - } - }) - }) - - Context("writing", func() { - It("has proper min length", func() { - f := &StreamBlockedFrame{ - StreamID: 0x1337, - Offset: 0xdeadbeef, - } - Expect(f.Length(0)).To(Equal(1 + utils.VarIntLen(0x1337) + utils.VarIntLen(0xdeadbeef))) - }) - - It("writes a sample frame", func() { - b := &bytes.Buffer{} - f := &StreamBlockedFrame{ - StreamID: 0xdecafbad, - Offset: 0x1337, - } - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x9} - expected = append(expected, encodeVarInt(uint64(f.StreamID))...) - expected = append(expected, encodeVarInt(uint64(f.Offset))...) - Expect(b.Bytes()).To(Equal(expected)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/stream_frame_legacy_test.go b/vendor/lucas-clemente/quic-go/internal/wire/stream_frame_legacy_test.go deleted file mode 100644 index 7927e92aa..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/stream_frame_legacy_test.go +++ /dev/null @@ -1,515 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/qerr" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("STREAM frame (for gQUIC)", func() { - Context("when parsing", func() { - It("accepts a sample frame", func() { - // a STREAM frame, plus 3 additional bytes, not belonging to this frame - b := bytes.NewReader([]byte{0x80 ^ 0x20, - 0x1, // stream id - 0x0, 0x6, // data length - 'f', 'o', 'o', 'b', 'a', 'r', - 'f', 'o', 'o', // additional bytes - }) - frame, err := parseStreamFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.FinBit).To(BeFalse()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(1))) - Expect(frame.Offset).To(BeZero()) - Expect(frame.DataLenPresent).To(BeTrue()) - Expect(frame.Data).To(Equal([]byte("foobar"))) - Expect(b.Len()).To(Equal(3)) - }) - - It("accepts frames with offsets", func() { - b := bytes.NewReader([]byte{0x80 ^ 0x20 /* 2 byte offset */ ^ 0x4, - 0x1, // stream id - 0x0, 0x42, // offset - 0x0, 0x6, // data length - 'f', 'o', 'o', 'b', 'a', 'r', - }) - frame, err := parseStreamFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.FinBit).To(BeFalse()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(1))) - Expect(frame.Offset).To(Equal(protocol.ByteCount(0x42))) - Expect(frame.DataLenPresent).To(BeTrue()) - Expect(frame.Data).To(Equal([]byte("foobar"))) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOFs", func() { - data := []byte{0x80 ^ 0x20 ^ 0x4, - 0x1, // stream id - 0x0, 0x2a, // offset - 0x0, 0x6, // data length, - 'f', 'o', 'o', 'b', 'a', 'r', - } - _, err := parseStreamFrame(bytes.NewReader(data), versionBigEndian) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseStreamFrame(bytes.NewReader(data[0:i]), versionBigEndian) - Expect(err).To(HaveOccurred()) - } - }) - - It("accepts frame without data length", func() { - b := bytes.NewReader([]byte{0x80, - 0x1, // stream id - 'f', 'o', 'o', 'b', 'a', 'r', - }) - frame, err := parseStreamFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.FinBit).To(BeFalse()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(1))) - Expect(frame.Offset).To(BeZero()) - Expect(frame.DataLenPresent).To(BeFalse()) - Expect(frame.Data).To(Equal([]byte("foobar"))) - Expect(b.Len()).To(BeZero()) - }) - - It("accepts an empty frame with FinBit set, with data length set", func() { - // the STREAM frame, plus 3 additional bytes, not belonging to this frame - b := bytes.NewReader([]byte{0x80 ^ 0x40 ^ 0x20, - 0x1, // stream id - 0, 0, // data length - 'f', 'o', 'o', // additional bytes - }) - frame, err := parseStreamFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.FinBit).To(BeTrue()) - Expect(frame.DataLenPresent).To(BeTrue()) - Expect(frame.Data).To(BeEmpty()) - Expect(b.Len()).To(Equal(3)) - }) - - It("accepts an empty frame with the FinBit set", func() { - b := bytes.NewReader([]byte{0x80 ^ 0x40, - 0x1, // stream id - 'f', 'o', 'o', 'b', 'a', 'r', - }) - frame, err := parseStreamFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.FinBit).To(BeTrue()) - Expect(frame.DataLenPresent).To(BeFalse()) - Expect(frame.Data).To(Equal([]byte("foobar"))) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on empty stream frames that don't have the FinBit set", func() { - b := bytes.NewReader([]byte{0x80 ^ 0x20, - 0x1, // stream id - 0, 0, // data length - }) - _, err := parseStreamFrame(b, versionBigEndian) - Expect(err).To(MatchError(qerr.EmptyStreamFrameNoFin)) - }) - - It("rejects frames to too large dataLen", func() { - b := bytes.NewReader([]byte{0xa0, 0x1, 0xff, 0xff}) - _, err := parseStreamFrame(b, versionBigEndian) - Expect(err).To(MatchError(io.EOF)) - }) - - It("rejects frames that overflow the offset", func() { - // Offset + len(Data) overflows MaxByteCount - f := &StreamFrame{ - StreamID: 1, - Offset: protocol.MaxByteCount, - Data: []byte{'f'}, - } - b := &bytes.Buffer{} - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - _, err = parseStreamFrame(bytes.NewReader(b.Bytes()), versionBigEndian) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidStreamData, "data overflows maximum offset"))) - }) - }) - - Context("when writing", func() { - Context("in big endian", func() { - It("writes sample frame", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - DataLenPresent: true, - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()).To(Equal([]byte{0x80 ^ 0x20, - 0x1, // stream id - 0x0, 0x6, // data length - 'f', 'o', 'o', 'b', 'a', 'r', - })) - }) - }) - - It("sets the FinBit", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - FinBit: true, - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x40).To(Equal(byte(0x40))) - }) - - It("errors when length is zero and FIN is not set", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 1, - }).Write(b, versionBigEndian) - Expect(err).To(MatchError("StreamFrame: attempting to write empty frame without FIN")) - }) - - It("has proper min length for a short StreamID and a short offset", func() { - b := &bytes.Buffer{} - f := &StreamFrame{ - StreamID: 1, - Data: []byte{}, - Offset: 0, - FinBit: true, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(0)).To(Equal(protocol.ByteCount(b.Len()))) - }) - - It("has proper min length for a long StreamID and a big offset", func() { - b := &bytes.Buffer{} - f := &StreamFrame{ - StreamID: 0xdecafbad, - Data: []byte{}, - Offset: 0xdeadbeefcafe, - FinBit: true, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f.Length(versionBigEndian)).To(Equal(protocol.ByteCount(b.Len()))) - }) - - Context("data length field", func() { - It("writes the data length", func() { - dataLen := 0x1337 - b := &bytes.Buffer{} - f := &StreamFrame{ - StreamID: 1, - Data: bytes.Repeat([]byte{'f'}, dataLen), - DataLenPresent: true, - Offset: 0, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x20).To(Equal(uint8(0x20))) - frame, err := parseStreamFrame(bytes.NewReader(b.Bytes()), versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.DataLenPresent).To(BeTrue()) - Expect(frame.DataLen()).To(Equal(protocol.ByteCount(dataLen))) - }) - }) - - It("omits the data length field", func() { - dataLen := 0x1337 - b := &bytes.Buffer{} - f := &StreamFrame{ - StreamID: 1, - Data: bytes.Repeat([]byte{'f'}, dataLen), - DataLenPresent: false, - Offset: 0, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x20).To(Equal(uint8(0))) - Expect(b.Bytes()[1 : b.Len()-dataLen]).ToNot(ContainSubstring(string([]byte{0x37, 0x13}))) - length := f.Length(versionBigEndian) - f.DataLenPresent = true - lengthWithoutDataLen := f.Length(versionBigEndian) - Expect(length).To(Equal(lengthWithoutDataLen - 2)) - }) - - It("calculates the correct min-length", func() { - f := &StreamFrame{ - StreamID: 0xcafe, - Data: []byte("foobar"), - DataLenPresent: false, - Offset: 0xdeadbeef, - } - lengthWithoutDataLen := f.Length(versionBigEndian) - f.DataLenPresent = true - Expect(f.Length(versionBigEndian)).To(Equal(lengthWithoutDataLen + 2)) - }) - - Context("offset lengths", func() { - It("does not write an offset if the offset is 0", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - Offset: 0, - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x1c).To(Equal(uint8(0x0))) - }) - - It("writes a 2-byte offset if the offset is larger than 0", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - Offset: 0x1337, - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x1c).To(Equal(uint8(0x1 << 2))) - Expect(b.Bytes()[2:4]).To(Equal([]byte{0x13, 0x37})) - }) - - It("writes a 3-byte offset if the offset", func() { - b := &bytes.Buffer{} - (&StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - Offset: 0x13cafe, - }).Write(b, versionBigEndian) - Expect(b.Bytes()[0] & 0x1c).To(Equal(uint8(0x2 << 2))) - Expect(b.Bytes()[2:5]).To(Equal([]byte{0x13, 0xca, 0xfe})) - }) - - It("writes a 4-byte offset if the offset", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - Offset: 0xdeadbeef, - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x1c).To(Equal(uint8(0x3 << 2))) - Expect(b.Bytes()[2:6]).To(Equal([]byte{0xde, 0xad, 0xbe, 0xef})) - }) - - It("writes a 5-byte offset if the offset", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - Offset: 0x13deadbeef, - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x1c).To(Equal(uint8(0x4 << 2))) - Expect(b.Bytes()[2:7]).To(Equal([]byte{0x13, 0xde, 0xad, 0xbe, 0xef})) - }) - - It("writes a 6-byte offset if the offset", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - Offset: 0xdeadbeefcafe, - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x1c).To(Equal(uint8(0x5 << 2))) - Expect(b.Bytes()[2:8]).To(Equal([]byte{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe})) - }) - - It("writes a 7-byte offset if the offset", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - Offset: 0x13deadbeefcafe, - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x1c).To(Equal(uint8(0x6 << 2))) - Expect(b.Bytes()[2:9]).To(Equal([]byte{0x13, 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe})) - }) - - It("writes a 8-byte offset if the offset", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - Offset: 0x1337deadbeefcafe, - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x1c).To(Equal(uint8(0x7 << 2))) - Expect(b.Bytes()[2:10]).To(Equal([]byte{0x13, 0x37, 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe})) - }) - }) - - Context("lengths of StreamIDs", func() { - It("writes a 1 byte StreamID", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 13, - Data: []byte("foobar"), - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(uint8(0x0))) - Expect(b.Bytes()[1]).To(Equal(uint8(13))) - }) - - It("writes a 2 byte StreamID", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 0xcafe, - Data: []byte("foobar"), - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(uint8(0x1))) - Expect(b.Bytes()[1:3]).To(Equal([]byte{0xca, 0xfe})) - }) - - It("writes a 3 byte StreamID", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 0x13beef, - Data: []byte("foobar"), - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(uint8(0x2))) - Expect(b.Bytes()[1:4]).To(Equal([]byte{0x13, 0xbe, 0xef})) - }) - - It("writes a 4 byte StreamID", func() { - b := &bytes.Buffer{} - err := (&StreamFrame{ - StreamID: 0xdecafbad, - Data: []byte("foobar"), - }).Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(uint8(0x3))) - Expect(b.Bytes()[1:5]).To(Equal([]byte{0xde, 0xca, 0xfb, 0xad})) - }) - - It("writes a multiple byte StreamID, after the Stream length was already determined by MinLenght()", func() { - b := &bytes.Buffer{} - frame := &StreamFrame{ - StreamID: 0xdecafbad, - Data: []byte("foobar"), - } - err := frame.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()[0] & 0x3).To(Equal(uint8(0x3))) - Expect(b.Bytes()[1:5]).To(Equal([]byte{0xde, 0xca, 0xfb, 0xad})) - }) - }) - }) - - Context("shortening of StreamIDs", func() { - It("determines the length of a 1 byte StreamID", func() { - f := &StreamFrame{StreamID: 0xFF} - Expect(f.calculateStreamIDLength()).To(Equal(uint8(1))) - }) - - It("determines the length of a 2 byte StreamID", func() { - f := &StreamFrame{StreamID: 0xFFFF} - Expect(f.calculateStreamIDLength()).To(Equal(uint8(2))) - }) - - It("determines the length of a 3 byte StreamID", func() { - f := &StreamFrame{StreamID: 0xFFFFFF} - Expect(f.calculateStreamIDLength()).To(Equal(uint8(3))) - }) - - It("determines the length of a 4 byte StreamID", func() { - f := &StreamFrame{StreamID: 0xFFFFFFFF} - Expect(f.calculateStreamIDLength()).To(Equal(uint8(4))) - }) - }) - - Context("shortening of Offsets", func() { - It("determines length 0 of offset 0", func() { - f := &StreamFrame{Offset: 0} - Expect(f.getOffsetLength()).To(Equal(protocol.ByteCount(0))) - }) - - It("determines the length of a 2 byte offset", func() { - f := &StreamFrame{Offset: 0xFFFF} - Expect(f.getOffsetLength()).To(Equal(protocol.ByteCount(2))) - }) - - It("determines the length of a 2 byte offset, even if it would fit into 1 byte", func() { - f := &StreamFrame{Offset: 0x1} - Expect(f.getOffsetLength()).To(Equal(protocol.ByteCount(2))) - }) - - It("determines the length of a 3 byte offset", func() { - f := &StreamFrame{Offset: 0xFFFFFF} - Expect(f.getOffsetLength()).To(Equal(protocol.ByteCount(3))) - }) - - It("determines the length of a 4 byte offset", func() { - f := &StreamFrame{Offset: 0xFFFFFFFF} - Expect(f.getOffsetLength()).To(Equal(protocol.ByteCount(4))) - }) - - It("determines the length of a 5 byte offset", func() { - f := &StreamFrame{Offset: 0xFFFFFFFFFF} - Expect(f.getOffsetLength()).To(Equal(protocol.ByteCount(5))) - }) - - It("determines the length of a 6 byte offset", func() { - f := &StreamFrame{Offset: 0xFFFFFFFFFFFF} - Expect(f.getOffsetLength()).To(Equal(protocol.ByteCount(6))) - }) - - It("determines the length of a 7 byte offset", func() { - f := &StreamFrame{Offset: 0xFFFFFFFFFFFFFF} - Expect(f.getOffsetLength()).To(Equal(protocol.ByteCount(7))) - }) - - It("determines the length of an 8 byte offset", func() { - f := &StreamFrame{Offset: 0xFFFFFFFFFFFFFFFF} - Expect(f.getOffsetLength()).To(Equal(protocol.ByteCount(8))) - }) - }) - - Context("DataLen", func() { - It("determines the length of the data", func() { - frame := StreamFrame{ - Data: []byte("foobar"), - } - Expect(frame.DataLen()).To(Equal(protocol.ByteCount(6))) - }) - }) - - Context("max data length", func() { - It("always returns a data length such that the resulting frame has the right size", func() { - const maxSize = 3000 - - data := make([]byte, maxSize) - f := &StreamFrame{ - StreamID: 0x1337, - Offset: 0xdeadbeef, - DataLenPresent: true, - } - b := &bytes.Buffer{} - for i := 1; i < 3000; i++ { - b.Reset() - f.Data = nil - maxDataLen := f.MaxDataLen(protocol.ByteCount(i), versionBigEndian) - if maxDataLen == 0 { // 0 means that no valid STREAM frame can be written - // check that writing a minimal size STREAM frame (i.e. with 1 byte data) is actually larger than the desired size - f.Data = []byte{0} - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(BeNumerically(">", i)) - continue - } - f.Data = data[:int(maxDataLen)] - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(i)) - } - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/stream_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/stream_frame_test.go deleted file mode 100644 index e8d4c3ed0..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/stream_frame_test.go +++ /dev/null @@ -1,396 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/qerr" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("STREAM frame (for IETF QUIC)", func() { - Context("when parsing", func() { - It("parses a frame with OFF bit", func() { - data := []byte{0x10 ^ 0x4} - data = append(data, encodeVarInt(0x12345)...) // stream ID - data = append(data, encodeVarInt(0xdecafbad)...) // offset - data = append(data, []byte("foobar")...) - r := bytes.NewReader(data) - frame, err := parseStreamFrame(r, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(0x12345))) - Expect(frame.Data).To(Equal([]byte("foobar"))) - Expect(frame.FinBit).To(BeFalse()) - Expect(frame.Offset).To(Equal(protocol.ByteCount(0xdecafbad))) - Expect(r.Len()).To(BeZero()) - }) - - It("respects the LEN when parsing the frame", func() { - data := []byte{0x10 ^ 0x2} - data = append(data, encodeVarInt(0x12345)...) // stream ID - data = append(data, encodeVarInt(4)...) // data length - data = append(data, []byte("foobar")...) - r := bytes.NewReader(data) - frame, err := parseStreamFrame(r, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(0x12345))) - Expect(frame.Data).To(Equal([]byte("foob"))) - Expect(frame.FinBit).To(BeFalse()) - Expect(frame.Offset).To(BeZero()) - Expect(r.Len()).To(Equal(2)) - }) - - It("parses a frame with FIN bit", func() { - data := []byte{0x10 ^ 0x1} - data = append(data, encodeVarInt(9)...) // stream ID - data = append(data, []byte("foobar")...) - r := bytes.NewReader(data) - frame, err := parseStreamFrame(r, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(9))) - Expect(frame.Data).To(Equal([]byte("foobar"))) - Expect(frame.FinBit).To(BeTrue()) - Expect(frame.Offset).To(BeZero()) - Expect(r.Len()).To(BeZero()) - }) - - It("allows empty frames", func() { - data := []byte{0x10 ^ 0x4} - data = append(data, encodeVarInt(0x1337)...) // stream ID - data = append(data, encodeVarInt(0x12345)...) // offset - r := bytes.NewReader(data) - f, err := parseStreamFrame(r, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(f.StreamID).To(Equal(protocol.StreamID(0x1337))) - Expect(f.Offset).To(Equal(protocol.ByteCount(0x12345))) - Expect(f.Data).To(BeEmpty()) - Expect(f.FinBit).To(BeFalse()) - }) - - It("rejects frames that overflow the maximum offset", func() { - data := []byte{0x10 ^ 0x4} - data = append(data, encodeVarInt(0x12345)...) // stream ID - data = append(data, encodeVarInt(uint64(protocol.MaxByteCount-5))...) // offset - data = append(data, []byte("foobar")...) - r := bytes.NewReader(data) - _, err := parseStreamFrame(r, versionIETFFrames) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidStreamData, "data overflows maximum offset"))) - }) - - It("errors on EOFs", func() { - data := []byte{0x10 ^ 0x4 ^ 0x2} - data = append(data, encodeVarInt(0x12345)...) // stream ID - data = append(data, encodeVarInt(0xdecafbad)...) // offset - data = append(data, encodeVarInt(6)...) // data length - data = append(data, []byte("foobar")...) - _, err := parseStreamFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseStreamFrame(bytes.NewReader(data[0:i]), versionIETFFrames) - Expect(err).To(HaveOccurred()) - } - }) - }) - - Context("when writing", func() { - It("writes a frame without offset", func() { - f := &StreamFrame{ - StreamID: 0x1337, - Data: []byte("foobar"), - } - b := &bytes.Buffer{} - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x10} - expected = append(expected, encodeVarInt(0x1337)...) // stream ID - expected = append(expected, []byte("foobar")...) - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("writes a frame with offset", func() { - f := &StreamFrame{ - StreamID: 0x1337, - Offset: 0x123456, - Data: []byte("foobar"), - } - b := &bytes.Buffer{} - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x10 ^ 0x4} - expected = append(expected, encodeVarInt(0x1337)...) // stream ID - expected = append(expected, encodeVarInt(0x123456)...) // offset - expected = append(expected, []byte("foobar")...) - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("writes a frame with FIN bit", func() { - f := &StreamFrame{ - StreamID: 0x1337, - Offset: 0x123456, - FinBit: true, - } - b := &bytes.Buffer{} - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x10 ^ 0x4 ^ 0x1} - expected = append(expected, encodeVarInt(0x1337)...) // stream ID - expected = append(expected, encodeVarInt(0x123456)...) // offset - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("writes a frame with data length", func() { - f := &StreamFrame{ - StreamID: 0x1337, - Data: []byte("foobar"), - DataLenPresent: true, - } - b := &bytes.Buffer{} - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x10 ^ 0x2} - expected = append(expected, encodeVarInt(0x1337)...) // stream ID - expected = append(expected, encodeVarInt(6)...) // data length - expected = append(expected, []byte("foobar")...) - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("writes a frame with data length and offset", func() { - f := &StreamFrame{ - StreamID: 0x1337, - Data: []byte("foobar"), - DataLenPresent: true, - Offset: 0x123456, - } - b := &bytes.Buffer{} - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0x10 ^ 0x4 ^ 0x2} - expected = append(expected, encodeVarInt(0x1337)...) // stream ID - expected = append(expected, encodeVarInt(0x123456)...) // offset - expected = append(expected, encodeVarInt(6)...) // data length - expected = append(expected, []byte("foobar")...) - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("refuses to write an empty frame without FIN", func() { - f := &StreamFrame{ - StreamID: 0x42, - Offset: 0x1337, - } - b := &bytes.Buffer{} - err := f.Write(b, versionIETFFrames) - Expect(err).To(MatchError("StreamFrame: attempting to write empty frame without FIN")) - }) - }) - - Context("length", func() { - It("has the right length for a frame without offset and data length", func() { - f := &StreamFrame{ - StreamID: 0x1337, - Data: []byte("foobar"), - } - Expect(f.Length(versionIETFFrames)).To(Equal(1 + utils.VarIntLen(0x1337) + 6)) - }) - - It("has the right length for a frame with offset", func() { - f := &StreamFrame{ - StreamID: 0x1337, - Offset: 0x42, - Data: []byte("foobar"), - } - Expect(f.Length(versionIETFFrames)).To(Equal(1 + utils.VarIntLen(0x1337) + utils.VarIntLen(0x42) + 6)) - }) - - It("has the right length for a frame with data length", func() { - f := &StreamFrame{ - StreamID: 0x1337, - Offset: 0x1234567, - DataLenPresent: true, - Data: []byte("foobar"), - } - Expect(f.Length(versionIETFFrames)).To(Equal(1 + utils.VarIntLen(0x1337) + utils.VarIntLen(0x1234567) + utils.VarIntLen(6) + 6)) - }) - }) - - Context("max data length", func() { - const maxSize = 3000 - - It("always returns a data length such that the resulting frame has the right size, if data length is not present", func() { - data := make([]byte, maxSize) - f := &StreamFrame{ - StreamID: 0x1337, - Offset: 0xdeadbeef, - } - b := &bytes.Buffer{} - for i := 1; i < 3000; i++ { - b.Reset() - f.Data = nil - maxDataLen := f.MaxDataLen(protocol.ByteCount(i), versionIETFFrames) - if maxDataLen == 0 { // 0 means that no valid STREAM frame can be written - // check that writing a minimal size STREAM frame (i.e. with 1 byte data) is actually larger than the desired size - f.Data = []byte{0} - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(BeNumerically(">", i)) - continue - } - f.Data = data[:int(maxDataLen)] - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(Equal(i)) - } - }) - - It("always returns a data length such that the resulting frame has the right size, if data length is present", func() { - data := make([]byte, maxSize) - f := &StreamFrame{ - StreamID: 0x1337, - Offset: 0xdeadbeef, - DataLenPresent: true, - } - b := &bytes.Buffer{} - var frameOneByteTooSmallCounter int - for i := 1; i < 3000; i++ { - b.Reset() - f.Data = nil - maxDataLen := f.MaxDataLen(protocol.ByteCount(i), versionIETFFrames) - if maxDataLen == 0 { // 0 means that no valid STREAM frame can be written - // check that writing a minimal size STREAM frame (i.e. with 1 byte data) is actually larger than the desired size - f.Data = []byte{0} - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Len()).To(BeNumerically(">", i)) - continue - } - f.Data = data[:int(maxDataLen)] - err := f.Write(b, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - // There's *one* pathological case, where a data length of x can be encoded into 1 byte - // but a data lengths of x+1 needs 2 bytes - // In that case, it's impossible to create a STREAM frame of the desired size - if b.Len() == i-1 { - frameOneByteTooSmallCounter++ - continue - } - Expect(b.Len()).To(Equal(i)) - } - Expect(frameOneByteTooSmallCounter).To(Equal(1)) - }) - }) - - Context("splitting", func() { - for _, v := range []protocol.VersionNumber{versionBigEndian, versionIETFFrames} { - version := v - - It("doesn't split if the frame is short enough", func() { - f := &StreamFrame{ - StreamID: 0x1337, - DataLenPresent: true, - Offset: 0xdeadbeef, - Data: make([]byte, 100), - } - newFrame, err := f.MaybeSplitOffFrame(f.Length(version), version) - Expect(err).ToNot(HaveOccurred()) - Expect(newFrame).To(BeNil()) - newFrame, err = f.MaybeSplitOffFrame(f.Length(version)-1, version) - Expect(err).ToNot(HaveOccurred()) - Expect(newFrame).ToNot(BeNil()) - }) - - It("keeps the data len", func() { - f := &StreamFrame{ - StreamID: 0x1337, - DataLenPresent: true, - Data: make([]byte, 100), - } - newFrame, err := f.MaybeSplitOffFrame(66, version) - Expect(err).ToNot(HaveOccurred()) - Expect(newFrame).ToNot(BeNil()) - Expect(f.DataLenPresent).To(BeTrue()) - Expect(newFrame.DataLenPresent).To(BeTrue()) - }) - - It("adjusts the offset", func() { - f := &StreamFrame{ - StreamID: 0x1337, - Offset: 0x100, - Data: []byte("foobar"), - } - newFrame, err := f.MaybeSplitOffFrame(f.Length(version)-3, version) - Expect(err).ToNot(HaveOccurred()) - Expect(newFrame).ToNot(BeNil()) - Expect(newFrame.Offset).To(Equal(protocol.ByteCount(0x100))) - Expect(newFrame.Data).To(Equal([]byte("foo"))) - Expect(f.Offset).To(Equal(protocol.ByteCount(0x100 + 3))) - Expect(f.Data).To(Equal([]byte("bar"))) - }) - - It("preserves the FIN bit", func() { - f := &StreamFrame{ - StreamID: 0x1337, - FinBit: true, - Offset: 0xdeadbeef, - Data: make([]byte, 100), - } - newFrame, err := f.MaybeSplitOffFrame(50, version) - Expect(err).ToNot(HaveOccurred()) - Expect(newFrame).ToNot(BeNil()) - Expect(newFrame.Offset).To(BeNumerically("<", f.Offset)) - Expect(f.FinBit).To(BeTrue()) - Expect(newFrame.FinBit).To(BeFalse()) - }) - - It("produces frames of the correct length, without data len", func() { - const size = 1000 - f := &StreamFrame{ - StreamID: 0xdecafbad, - Offset: 0x1234, - Data: []byte{0}, - } - minFrameSize := f.Length(version) - for i := protocol.ByteCount(0); i < minFrameSize; i++ { - _, err := f.MaybeSplitOffFrame(i, version) - Expect(err).To(HaveOccurred()) - } - for i := minFrameSize; i < size; i++ { - f.Data = make([]byte, size) - newFrame, err := f.MaybeSplitOffFrame(i, version) - Expect(err).ToNot(HaveOccurred()) - Expect(newFrame.Length(version)).To(Equal(i)) - } - }) - } - - It("produces frames of the correct length, with data len", func() { - const size = 1000 - f := &StreamFrame{ - StreamID: 0xdecafbad, - Offset: 0x1234, - DataLenPresent: true, - Data: []byte{0}, - } - minFrameSize := f.Length(versionIETFFrames) - for i := protocol.ByteCount(0); i < minFrameSize; i++ { - _, err := f.MaybeSplitOffFrame(i, versionIETFFrames) - Expect(err).To(HaveOccurred()) - } - var frameOneByteTooSmallCounter int - for i := minFrameSize; i < size; i++ { - f.Data = make([]byte, size) - newFrame, err := f.MaybeSplitOffFrame(i, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - // There's *one* pathological case, where a data length of x can be encoded into 1 byte - // but a data lengths of x+1 needs 2 bytes - // In that case, it's impossible to create a STREAM frame of the desired size - if newFrame.Length(versionIETFFrames) == i-1 { - frameOneByteTooSmallCounter++ - continue - } - Expect(newFrame.Length(versionIETFFrames)).To(Equal(i)) - } - Expect(frameOneByteTooSmallCounter).To(Equal(1)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/stream_id_blocked_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/stream_id_blocked_frame_test.go deleted file mode 100644 index 7fb1cfb15..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/stream_id_blocked_frame_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package wire - -import ( - "bytes" - "io" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("STREAM_ID_BLOCKED frame", func() { - Context("parsing", func() { - It("accepts sample frame", func() { - expected := []byte{0xa} - expected = append(expected, encodeVarInt(0xdecafbad)...) - b := bytes.NewReader(expected) - frame, err := parseStreamIDBlockedFrame(b, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - Expect(frame.StreamID).To(Equal(protocol.StreamID(0xdecafbad))) - Expect(b.Len()).To(BeZero()) - }) - - It("errors on EOFs", func() { - data := []byte{0xa} - data = append(data, encodeVarInt(0x12345678)...) - _, err := parseStreamIDBlockedFrame(bytes.NewReader(data), versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - for i := range data { - _, err := parseStreamIDBlockedFrame(bytes.NewReader(data[:i]), versionIETFFrames) - Expect(err).To(MatchError(io.EOF)) - } - }) - }) - - Context("writing", func() { - It("writes a sample frame", func() { - b := &bytes.Buffer{} - frame := StreamIDBlockedFrame{StreamID: 0xdeadbeefcafe} - err := frame.Write(b, protocol.VersionWhatever) - Expect(err).ToNot(HaveOccurred()) - expected := []byte{0xa} - expected = append(expected, encodeVarInt(0xdeadbeefcafe)...) - Expect(b.Bytes()).To(Equal(expected)) - }) - - It("has the correct min length", func() { - frame := StreamIDBlockedFrame{StreamID: 0x123456} - Expect(frame.Length(0)).To(Equal(protocol.ByteCount(1) + utils.VarIntLen(0x123456))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/version_negotiation_test.go b/vendor/lucas-clemente/quic-go/internal/wire/version_negotiation_test.go deleted file mode 100644 index 0d53142a7..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/version_negotiation_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Version Negotiation Packets", func() { - It("writes for gQUIC", func() { - connID := protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37} - versions := []protocol.VersionNumber{1001, 1003} - data := ComposeGQUICVersionNegotiation(connID, versions) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 4) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionPublicHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.VersionFlag).To(BeTrue()) - Expect(hdr.DestConnectionID).To(Equal(connID)) - Expect(hdr.SrcConnectionID).To(BeEmpty()) - Expect(hdr.SupportedVersions).To(Equal(versions)) - }) - - It("writes in IETF draft style", func() { - srcConnID := protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37} - destConnID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - versions := []protocol.VersionNumber{1001, 1003} - data, err := ComposeVersionNegotiation(destConnID, srcConnID, versions) - Expect(err).ToNot(HaveOccurred()) - Expect(data[0] & 0x80).ToNot(BeZero()) - b := bytes.NewReader(data) - iHdr, err := ParseInvariantHeader(b, 4) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, versionIETFHeader) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.IsVersionNegotiation).To(BeTrue()) - Expect(hdr.DestConnectionID).To(Equal(destConnID)) - Expect(hdr.SrcConnectionID).To(Equal(srcConnID)) - Expect(hdr.Version).To(BeZero()) - // the supported versions should include one reserved version number - Expect(hdr.SupportedVersions).To(HaveLen(len(versions) + 1)) - for _, version := range versions { - Expect(hdr.SupportedVersions).To(ContainElement(version)) - } - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/window_update_frame_test.go b/vendor/lucas-clemente/quic-go/internal/wire/window_update_frame_test.go deleted file mode 100644 index cc1c08194..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/window_update_frame_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("WINDOW_UPDATE frame", func() { - Context("parsing", func() { - Context("in big endian", func() { - It("parses a stream-level WINDOW_UPDATE", func() { - b := bytes.NewReader([]byte{0x4, - 0xde, 0xad, 0xbe, 0xef, // stream id - 0xde, 0xca, 0xfb, 0xad, 0x11, 0x22, 0x33, 0x44, // byte offset - }) - f, err := parseWindowUpdateFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f).To(BeAssignableToTypeOf(&MaxStreamDataFrame{})) - frame := f.(*MaxStreamDataFrame) - Expect(frame.ByteOffset).To(Equal(protocol.ByteCount(0xdecafbad11223344))) - Expect(frame.StreamID).To(Equal(protocol.StreamID(0xdeadbeef))) - }) - - It("parses a connection-level WINDOW_UPDATE", func() { - b := bytes.NewReader([]byte{0x4, - 0x0, 0x0, 0x0, 0x0, // stream id - 0xde, 0xca, 0xfb, 0xad, 0x11, 0x22, 0x33, 0x44, // byte offset - }) - f, err := parseWindowUpdateFrame(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(f).To(BeAssignableToTypeOf(&MaxDataFrame{})) - frame := f.(*MaxDataFrame) - Expect(frame.ByteOffset).To(Equal(protocol.ByteCount(0xdecafbad11223344))) - }) - - It("errors on EOFs", func() { - data := []byte{0x4, - 0xef, 0xbe, 0xad, 0xde, // stream id - 0x44, 0x33, 0x22, 0x11, 0xad, 0xfb, 0xca, 0xde, // byte offset - } - _, err := parseWindowUpdateFrame(bytes.NewReader(data), versionBigEndian) - Expect(err).NotTo(HaveOccurred()) - for i := range data { - _, err := parseWindowUpdateFrame(bytes.NewReader(data[0:i]), versionBigEndian) - Expect(err).To(HaveOccurred()) - } - }) - }) - }) - - Context("writing", func() { - It("has the proper min length for the stream-level WINDOW_UPDATE frame", func() { - f := &MaxDataFrame{ - ByteOffset: 0xdeadbeef, - } - Expect(f.Length(versionBigEndian)).To(Equal(protocol.ByteCount(1 + 4 + 8))) - }) - - It("has the proper min length for the connection-level WINDOW_UPDATE frame", func() { - f := &MaxDataFrame{ - ByteOffset: 0xdeadbeef, - } - Expect(f.Length(versionBigEndian)).To(Equal(protocol.ByteCount(1 + 4 + 8))) - }) - - Context("in big endian", func() { - It("writes a stream-level WINDOW_UPDATE frame", func() { - b := &bytes.Buffer{} - f := &MaxStreamDataFrame{ - StreamID: 0xdecafbad, - ByteOffset: 0xdeadbeefcafe1337, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()).To(Equal([]byte{0x4, - 0xde, 0xca, 0xfb, 0xad, // stream ID 0 - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37, // byte offset - })) - }) - - It("writes a connection-level WINDOW_UPDATE frame", func() { - b := &bytes.Buffer{} - f := &MaxDataFrame{ - ByteOffset: 0xdeadbeefcafe1337, - } - err := f.Write(b, versionBigEndian) - Expect(err).ToNot(HaveOccurred()) - Expect(b.Bytes()).To(Equal([]byte{0x4, - 0x0, 0x0, 0x0, 0x0, // stream ID 0 - 0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0x13, 0x37, // byte offset - })) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/internal/wire/wire_suite_test.go b/vendor/lucas-clemente/quic-go/internal/wire/wire_suite_test.go deleted file mode 100644 index 7eda79187..000000000 --- a/vendor/lucas-clemente/quic-go/internal/wire/wire_suite_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package wire - -import ( - "bytes" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestWire(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Wire Suite") -} - -const ( - // a QUIC version that uses big endian encoding - versionBigEndian = protocol.Version39 - // a QUIC version that uses the IETF frame types - versionIETFFrames = protocol.VersionTLS - // a QUIC version that uses the gQUIC Public Header - versionPublicHeader = protocol.Version43 - // a QUIC version that the IETF QUIC Header - versionIETFHeader = protocol.VersionTLS -) - -func encodeVarInt(i uint64) []byte { - b := &bytes.Buffer{} - utils.WriteVarInt(b, i) - return b.Bytes() -} - -var _ = BeforeSuite(func() { - Expect(versionBigEndian.UsesIETFFrameFormat()).To(BeFalse()) - Expect(versionIETFFrames.UsesIETFFrameFormat()).To(BeTrue()) -}) diff --git a/vendor/lucas-clemente/quic-go/mint_utils_test.go b/vendor/lucas-clemente/quic-go/mint_utils_test.go deleted file mode 100644 index 39b17c5e8..000000000 --- a/vendor/lucas-clemente/quic-go/mint_utils_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package quic - -import ( - "crypto/tls" - "crypto/x509" - "errors" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Mint Utils", func() { - Context("generating a mint.Config", func() { - It("sets non-blocking mode", func() { - mintConf, err := tlsToMintConfig(nil, protocol.PerspectiveClient) - Expect(err).ToNot(HaveOccurred()) - Expect(mintConf.NonBlocking).To(BeTrue()) - }) - - It("sets the certificate chain", func() { - tlsConf := testdata.GetTLSConfig() - mintConf, err := tlsToMintConfig(tlsConf, protocol.PerspectiveClient) - Expect(err).ToNot(HaveOccurred()) - Expect(mintConf.Certificates).ToNot(BeEmpty()) - Expect(mintConf.Certificates).To(HaveLen(len(tlsConf.Certificates))) - }) - - It("copies values from the tls.Config", func() { - verifyErr := errors.New("test err") - certPool := &x509.CertPool{} - tlsConf := &tls.Config{ - RootCAs: certPool, - ServerName: "www.example.com", - InsecureSkipVerify: true, - VerifyPeerCertificate: func(_ [][]byte, _ [][]*x509.Certificate) error { - return verifyErr - }, - } - mintConf, err := tlsToMintConfig(tlsConf, protocol.PerspectiveClient) - Expect(err).ToNot(HaveOccurred()) - Expect(mintConf.RootCAs).To(Equal(certPool)) - Expect(mintConf.ServerName).To(Equal("www.example.com")) - Expect(mintConf.InsecureSkipVerify).To(BeTrue()) - Expect(mintConf.VerifyPeerCertificate(nil, nil)).To(MatchError(verifyErr)) - }) - - It("requires client authentication", func() { - mintConf, err := tlsToMintConfig(nil, protocol.PerspectiveClient) - Expect(err).ToNot(HaveOccurred()) - Expect(mintConf.RequireClientAuth).To(BeFalse()) - conf := &tls.Config{ClientAuth: tls.RequireAnyClientCert} - mintConf, err = tlsToMintConfig(conf, protocol.PerspectiveClient) - Expect(err).ToNot(HaveOccurred()) - Expect(mintConf.RequireClientAuth).To(BeTrue()) - }) - - It("rejects unsupported client auth types", func() { - conf := &tls.Config{ClientAuth: tls.RequireAndVerifyClientCert} - _, err := tlsToMintConfig(conf, protocol.PerspectiveClient) - Expect(err).To(MatchError("mint currently only support ClientAuthType RequireAnyClientCert")) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/mock_crypto_stream_test.go b/vendor/lucas-clemente/quic-go/mock_crypto_stream_test.go deleted file mode 100644 index 68e47c1d2..000000000 --- a/vendor/lucas-clemente/quic-go/mock_crypto_stream_test.go +++ /dev/null @@ -1,141 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: CryptoStream) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" - wire "github.com/lucas-clemente/quic-go/internal/wire" -) - -// MockCryptoStream is a mock of CryptoStream interface -type MockCryptoStream struct { - ctrl *gomock.Controller - recorder *MockCryptoStreamMockRecorder -} - -// MockCryptoStreamMockRecorder is the mock recorder for MockCryptoStream -type MockCryptoStreamMockRecorder struct { - mock *MockCryptoStream -} - -// NewMockCryptoStream creates a new mock instance -func NewMockCryptoStream(ctrl *gomock.Controller) *MockCryptoStream { - mock := &MockCryptoStream{ctrl: ctrl} - mock.recorder = &MockCryptoStreamMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockCryptoStream) EXPECT() *MockCryptoStreamMockRecorder { - return m.recorder -} - -// Read mocks base method -func (m *MockCryptoStream) Read(arg0 []byte) (int, error) { - ret := m.ctrl.Call(m, "Read", arg0) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Read indicates an expected call of Read -func (mr *MockCryptoStreamMockRecorder) Read(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockCryptoStream)(nil).Read), arg0) -} - -// StreamID mocks base method -func (m *MockCryptoStream) StreamID() protocol.StreamID { - ret := m.ctrl.Call(m, "StreamID") - ret0, _ := ret[0].(protocol.StreamID) - return ret0 -} - -// StreamID indicates an expected call of StreamID -func (mr *MockCryptoStreamMockRecorder) StreamID() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StreamID", reflect.TypeOf((*MockCryptoStream)(nil).StreamID)) -} - -// Write mocks base method -func (m *MockCryptoStream) Write(arg0 []byte) (int, error) { - ret := m.ctrl.Call(m, "Write", arg0) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Write indicates an expected call of Write -func (mr *MockCryptoStreamMockRecorder) Write(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockCryptoStream)(nil).Write), arg0) -} - -// closeForShutdown mocks base method -func (m *MockCryptoStream) closeForShutdown(arg0 error) { - m.ctrl.Call(m, "closeForShutdown", arg0) -} - -// closeForShutdown indicates an expected call of closeForShutdown -func (mr *MockCryptoStreamMockRecorder) closeForShutdown(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "closeForShutdown", reflect.TypeOf((*MockCryptoStream)(nil).closeForShutdown), arg0) -} - -// getWindowUpdate mocks base method -func (m *MockCryptoStream) getWindowUpdate() protocol.ByteCount { - ret := m.ctrl.Call(m, "getWindowUpdate") - ret0, _ := ret[0].(protocol.ByteCount) - return ret0 -} - -// getWindowUpdate indicates an expected call of getWindowUpdate -func (mr *MockCryptoStreamMockRecorder) getWindowUpdate() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "getWindowUpdate", reflect.TypeOf((*MockCryptoStream)(nil).getWindowUpdate)) -} - -// handleMaxStreamDataFrame mocks base method -func (m *MockCryptoStream) handleMaxStreamDataFrame(arg0 *wire.MaxStreamDataFrame) { - m.ctrl.Call(m, "handleMaxStreamDataFrame", arg0) -} - -// handleMaxStreamDataFrame indicates an expected call of handleMaxStreamDataFrame -func (mr *MockCryptoStreamMockRecorder) handleMaxStreamDataFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handleMaxStreamDataFrame", reflect.TypeOf((*MockCryptoStream)(nil).handleMaxStreamDataFrame), arg0) -} - -// handleStreamFrame mocks base method -func (m *MockCryptoStream) handleStreamFrame(arg0 *wire.StreamFrame) error { - ret := m.ctrl.Call(m, "handleStreamFrame", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// handleStreamFrame indicates an expected call of handleStreamFrame -func (mr *MockCryptoStreamMockRecorder) handleStreamFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handleStreamFrame", reflect.TypeOf((*MockCryptoStream)(nil).handleStreamFrame), arg0) -} - -// popStreamFrame mocks base method -func (m *MockCryptoStream) popStreamFrame(arg0 protocol.ByteCount) (*wire.StreamFrame, bool) { - ret := m.ctrl.Call(m, "popStreamFrame", arg0) - ret0, _ := ret[0].(*wire.StreamFrame) - ret1, _ := ret[1].(bool) - return ret0, ret1 -} - -// popStreamFrame indicates an expected call of popStreamFrame -func (mr *MockCryptoStreamMockRecorder) popStreamFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "popStreamFrame", reflect.TypeOf((*MockCryptoStream)(nil).popStreamFrame), arg0) -} - -// setReadOffset mocks base method -func (m *MockCryptoStream) setReadOffset(arg0 protocol.ByteCount) { - m.ctrl.Call(m, "setReadOffset", arg0) -} - -// setReadOffset indicates an expected call of setReadOffset -func (mr *MockCryptoStreamMockRecorder) setReadOffset(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "setReadOffset", reflect.TypeOf((*MockCryptoStream)(nil).setReadOffset), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_gquic_aead_test.go b/vendor/lucas-clemente/quic-go/mock_gquic_aead_test.go deleted file mode 100644 index c8ac324be..000000000 --- a/vendor/lucas-clemente/quic-go/mock_gquic_aead_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: GQUICAEAD) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// MockGQUICAEAD is a mock of GQUICAEAD interface -type MockGQUICAEAD struct { - ctrl *gomock.Controller - recorder *MockGQUICAEADMockRecorder -} - -// MockGQUICAEADMockRecorder is the mock recorder for MockGQUICAEAD -type MockGQUICAEADMockRecorder struct { - mock *MockGQUICAEAD -} - -// NewMockGQUICAEAD creates a new mock instance -func NewMockGQUICAEAD(ctrl *gomock.Controller) *MockGQUICAEAD { - mock := &MockGQUICAEAD{ctrl: ctrl} - mock.recorder = &MockGQUICAEADMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockGQUICAEAD) EXPECT() *MockGQUICAEADMockRecorder { - return m.recorder -} - -// Open mocks base method -func (m *MockGQUICAEAD) Open(arg0, arg1 []byte, arg2 protocol.PacketNumber, arg3 []byte) ([]byte, protocol.EncryptionLevel, error) { - ret := m.ctrl.Call(m, "Open", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(protocol.EncryptionLevel) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// Open indicates an expected call of Open -func (mr *MockGQUICAEADMockRecorder) Open(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Open", reflect.TypeOf((*MockGQUICAEAD)(nil).Open), arg0, arg1, arg2, arg3) -} diff --git a/vendor/lucas-clemente/quic-go/mock_multiplexer_test.go b/vendor/lucas-clemente/quic-go/mock_multiplexer_test.go deleted file mode 100644 index 2c1ac30df..000000000 --- a/vendor/lucas-clemente/quic-go/mock_multiplexer_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: Multiplexer) - -// Package quic is a generated GoMock package. -package quic - -import ( - net "net" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" -) - -// MockMultiplexer is a mock of Multiplexer interface -type MockMultiplexer struct { - ctrl *gomock.Controller - recorder *MockMultiplexerMockRecorder -} - -// MockMultiplexerMockRecorder is the mock recorder for MockMultiplexer -type MockMultiplexerMockRecorder struct { - mock *MockMultiplexer -} - -// NewMockMultiplexer creates a new mock instance -func NewMockMultiplexer(ctrl *gomock.Controller) *MockMultiplexer { - mock := &MockMultiplexer{ctrl: ctrl} - mock.recorder = &MockMultiplexerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockMultiplexer) EXPECT() *MockMultiplexerMockRecorder { - return m.recorder -} - -// AddConn mocks base method -func (m *MockMultiplexer) AddConn(arg0 net.PacketConn, arg1 int) (packetHandlerManager, error) { - ret := m.ctrl.Call(m, "AddConn", arg0, arg1) - ret0, _ := ret[0].(packetHandlerManager) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AddConn indicates an expected call of AddConn -func (mr *MockMultiplexerMockRecorder) AddConn(arg0, arg1 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddConn", reflect.TypeOf((*MockMultiplexer)(nil).AddConn), arg0, arg1) -} diff --git a/vendor/lucas-clemente/quic-go/mock_packet_handler_manager_test.go b/vendor/lucas-clemente/quic-go/mock_packet_handler_manager_test.go deleted file mode 100644 index fef4eb847..000000000 --- a/vendor/lucas-clemente/quic-go/mock_packet_handler_manager_test.go +++ /dev/null @@ -1,75 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: PacketHandlerManager) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// MockPacketHandlerManager is a mock of PacketHandlerManager interface -type MockPacketHandlerManager struct { - ctrl *gomock.Controller - recorder *MockPacketHandlerManagerMockRecorder -} - -// MockPacketHandlerManagerMockRecorder is the mock recorder for MockPacketHandlerManager -type MockPacketHandlerManagerMockRecorder struct { - mock *MockPacketHandlerManager -} - -// NewMockPacketHandlerManager creates a new mock instance -func NewMockPacketHandlerManager(ctrl *gomock.Controller) *MockPacketHandlerManager { - mock := &MockPacketHandlerManager{ctrl: ctrl} - mock.recorder = &MockPacketHandlerManagerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockPacketHandlerManager) EXPECT() *MockPacketHandlerManagerMockRecorder { - return m.recorder -} - -// Add mocks base method -func (m *MockPacketHandlerManager) Add(arg0 protocol.ConnectionID, arg1 packetHandler) { - m.ctrl.Call(m, "Add", arg0, arg1) -} - -// Add indicates an expected call of Add -func (mr *MockPacketHandlerManagerMockRecorder) Add(arg0, arg1 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockPacketHandlerManager)(nil).Add), arg0, arg1) -} - -// CloseServer mocks base method -func (m *MockPacketHandlerManager) CloseServer() { - m.ctrl.Call(m, "CloseServer") -} - -// CloseServer indicates an expected call of CloseServer -func (mr *MockPacketHandlerManagerMockRecorder) CloseServer() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloseServer", reflect.TypeOf((*MockPacketHandlerManager)(nil).CloseServer)) -} - -// Remove mocks base method -func (m *MockPacketHandlerManager) Remove(arg0 protocol.ConnectionID) { - m.ctrl.Call(m, "Remove", arg0) -} - -// Remove indicates an expected call of Remove -func (mr *MockPacketHandlerManagerMockRecorder) Remove(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockPacketHandlerManager)(nil).Remove), arg0) -} - -// SetServer mocks base method -func (m *MockPacketHandlerManager) SetServer(arg0 unknownPacketHandler) { - m.ctrl.Call(m, "SetServer", arg0) -} - -// SetServer indicates an expected call of SetServer -func (mr *MockPacketHandlerManagerMockRecorder) SetServer(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetServer", reflect.TypeOf((*MockPacketHandlerManager)(nil).SetServer), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_packet_handler_test.go b/vendor/lucas-clemente/quic-go/mock_packet_handler_test.go deleted file mode 100644 index dfa884a9f..000000000 --- a/vendor/lucas-clemente/quic-go/mock_packet_handler_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: PacketHandler) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// MockPacketHandler is a mock of PacketHandler interface -type MockPacketHandler struct { - ctrl *gomock.Controller - recorder *MockPacketHandlerMockRecorder -} - -// MockPacketHandlerMockRecorder is the mock recorder for MockPacketHandler -type MockPacketHandlerMockRecorder struct { - mock *MockPacketHandler -} - -// NewMockPacketHandler creates a new mock instance -func NewMockPacketHandler(ctrl *gomock.Controller) *MockPacketHandler { - mock := &MockPacketHandler{ctrl: ctrl} - mock.recorder = &MockPacketHandlerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockPacketHandler) EXPECT() *MockPacketHandlerMockRecorder { - return m.recorder -} - -// Close mocks base method -func (m *MockPacketHandler) Close() error { - ret := m.ctrl.Call(m, "Close") - ret0, _ := ret[0].(error) - return ret0 -} - -// Close indicates an expected call of Close -func (mr *MockPacketHandlerMockRecorder) Close() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockPacketHandler)(nil).Close)) -} - -// GetPerspective mocks base method -func (m *MockPacketHandler) GetPerspective() protocol.Perspective { - ret := m.ctrl.Call(m, "GetPerspective") - ret0, _ := ret[0].(protocol.Perspective) - return ret0 -} - -// GetPerspective indicates an expected call of GetPerspective -func (mr *MockPacketHandlerMockRecorder) GetPerspective() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPerspective", reflect.TypeOf((*MockPacketHandler)(nil).GetPerspective)) -} - -// GetVersion mocks base method -func (m *MockPacketHandler) GetVersion() protocol.VersionNumber { - ret := m.ctrl.Call(m, "GetVersion") - ret0, _ := ret[0].(protocol.VersionNumber) - return ret0 -} - -// GetVersion indicates an expected call of GetVersion -func (mr *MockPacketHandlerMockRecorder) GetVersion() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVersion", reflect.TypeOf((*MockPacketHandler)(nil).GetVersion)) -} - -// destroy mocks base method -func (m *MockPacketHandler) destroy(arg0 error) { - m.ctrl.Call(m, "destroy", arg0) -} - -// destroy indicates an expected call of destroy -func (mr *MockPacketHandlerMockRecorder) destroy(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "destroy", reflect.TypeOf((*MockPacketHandler)(nil).destroy), arg0) -} - -// handlePacket mocks base method -func (m *MockPacketHandler) handlePacket(arg0 *receivedPacket) { - m.ctrl.Call(m, "handlePacket", arg0) -} - -// handlePacket indicates an expected call of handlePacket -func (mr *MockPacketHandlerMockRecorder) handlePacket(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handlePacket", reflect.TypeOf((*MockPacketHandler)(nil).handlePacket), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_quic_aead_test.go b/vendor/lucas-clemente/quic-go/mock_quic_aead_test.go deleted file mode 100644 index 63a2a5a7b..000000000 --- a/vendor/lucas-clemente/quic-go/mock_quic_aead_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: QuicAEAD) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// MockQuicAEAD is a mock of QuicAEAD interface -type MockQuicAEAD struct { - ctrl *gomock.Controller - recorder *MockQuicAEADMockRecorder -} - -// MockQuicAEADMockRecorder is the mock recorder for MockQuicAEAD -type MockQuicAEADMockRecorder struct { - mock *MockQuicAEAD -} - -// NewMockQuicAEAD creates a new mock instance -func NewMockQuicAEAD(ctrl *gomock.Controller) *MockQuicAEAD { - mock := &MockQuicAEAD{ctrl: ctrl} - mock.recorder = &MockQuicAEADMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockQuicAEAD) EXPECT() *MockQuicAEADMockRecorder { - return m.recorder -} - -// Open1RTT mocks base method -func (m *MockQuicAEAD) Open1RTT(arg0, arg1 []byte, arg2 protocol.PacketNumber, arg3 []byte) ([]byte, error) { - ret := m.ctrl.Call(m, "Open1RTT", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Open1RTT indicates an expected call of Open1RTT -func (mr *MockQuicAEADMockRecorder) Open1RTT(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Open1RTT", reflect.TypeOf((*MockQuicAEAD)(nil).Open1RTT), arg0, arg1, arg2, arg3) -} - -// OpenHandshake mocks base method -func (m *MockQuicAEAD) OpenHandshake(arg0, arg1 []byte, arg2 protocol.PacketNumber, arg3 []byte) ([]byte, error) { - ret := m.ctrl.Call(m, "OpenHandshake", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OpenHandshake indicates an expected call of OpenHandshake -func (mr *MockQuicAEADMockRecorder) OpenHandshake(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenHandshake", reflect.TypeOf((*MockQuicAEAD)(nil).OpenHandshake), arg0, arg1, arg2, arg3) -} diff --git a/vendor/lucas-clemente/quic-go/mock_quic_session_test.go b/vendor/lucas-clemente/quic-go/mock_quic_session_test.go deleted file mode 100644 index d67d1fa3c..000000000 --- a/vendor/lucas-clemente/quic-go/mock_quic_session_test.go +++ /dev/null @@ -1,242 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: QuicSession) - -// Package quic is a generated GoMock package. -package quic - -import ( - context "context" - net "net" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - handshake "github.com/lucas-clemente/quic-go/internal/handshake" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// MockQuicSession is a mock of QuicSession interface -type MockQuicSession struct { - ctrl *gomock.Controller - recorder *MockQuicSessionMockRecorder -} - -// MockQuicSessionMockRecorder is the mock recorder for MockQuicSession -type MockQuicSessionMockRecorder struct { - mock *MockQuicSession -} - -// NewMockQuicSession creates a new mock instance -func NewMockQuicSession(ctrl *gomock.Controller) *MockQuicSession { - mock := &MockQuicSession{ctrl: ctrl} - mock.recorder = &MockQuicSessionMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockQuicSession) EXPECT() *MockQuicSessionMockRecorder { - return m.recorder -} - -// AcceptStream mocks base method -func (m *MockQuicSession) AcceptStream() (Stream, error) { - ret := m.ctrl.Call(m, "AcceptStream") - ret0, _ := ret[0].(Stream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AcceptStream indicates an expected call of AcceptStream -func (mr *MockQuicSessionMockRecorder) AcceptStream() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AcceptStream", reflect.TypeOf((*MockQuicSession)(nil).AcceptStream)) -} - -// AcceptUniStream mocks base method -func (m *MockQuicSession) AcceptUniStream() (ReceiveStream, error) { - ret := m.ctrl.Call(m, "AcceptUniStream") - ret0, _ := ret[0].(ReceiveStream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AcceptUniStream indicates an expected call of AcceptUniStream -func (mr *MockQuicSessionMockRecorder) AcceptUniStream() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AcceptUniStream", reflect.TypeOf((*MockQuicSession)(nil).AcceptUniStream)) -} - -// Close mocks base method -func (m *MockQuicSession) Close() error { - ret := m.ctrl.Call(m, "Close") - ret0, _ := ret[0].(error) - return ret0 -} - -// Close indicates an expected call of Close -func (mr *MockQuicSessionMockRecorder) Close() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockQuicSession)(nil).Close)) -} - -// CloseWithError mocks base method -func (m *MockQuicSession) CloseWithError(arg0 protocol.ApplicationErrorCode, arg1 error) error { - ret := m.ctrl.Call(m, "CloseWithError", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// CloseWithError indicates an expected call of CloseWithError -func (mr *MockQuicSessionMockRecorder) CloseWithError(arg0, arg1 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloseWithError", reflect.TypeOf((*MockQuicSession)(nil).CloseWithError), arg0, arg1) -} - -// ConnectionState mocks base method -func (m *MockQuicSession) ConnectionState() handshake.ConnectionState { - ret := m.ctrl.Call(m, "ConnectionState") - ret0, _ := ret[0].(handshake.ConnectionState) - return ret0 -} - -// ConnectionState indicates an expected call of ConnectionState -func (mr *MockQuicSessionMockRecorder) ConnectionState() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConnectionState", reflect.TypeOf((*MockQuicSession)(nil).ConnectionState)) -} - -// Context mocks base method -func (m *MockQuicSession) Context() context.Context { - ret := m.ctrl.Call(m, "Context") - ret0, _ := ret[0].(context.Context) - return ret0 -} - -// Context indicates an expected call of Context -func (mr *MockQuicSessionMockRecorder) Context() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Context", reflect.TypeOf((*MockQuicSession)(nil).Context)) -} - -// GetVersion mocks base method -func (m *MockQuicSession) GetVersion() protocol.VersionNumber { - ret := m.ctrl.Call(m, "GetVersion") - ret0, _ := ret[0].(protocol.VersionNumber) - return ret0 -} - -// GetVersion indicates an expected call of GetVersion -func (mr *MockQuicSessionMockRecorder) GetVersion() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetVersion", reflect.TypeOf((*MockQuicSession)(nil).GetVersion)) -} - -// LocalAddr mocks base method -func (m *MockQuicSession) LocalAddr() net.Addr { - ret := m.ctrl.Call(m, "LocalAddr") - ret0, _ := ret[0].(net.Addr) - return ret0 -} - -// LocalAddr indicates an expected call of LocalAddr -func (mr *MockQuicSessionMockRecorder) LocalAddr() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LocalAddr", reflect.TypeOf((*MockQuicSession)(nil).LocalAddr)) -} - -// OpenStream mocks base method -func (m *MockQuicSession) OpenStream() (Stream, error) { - ret := m.ctrl.Call(m, "OpenStream") - ret0, _ := ret[0].(Stream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OpenStream indicates an expected call of OpenStream -func (mr *MockQuicSessionMockRecorder) OpenStream() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenStream", reflect.TypeOf((*MockQuicSession)(nil).OpenStream)) -} - -// OpenStreamSync mocks base method -func (m *MockQuicSession) OpenStreamSync() (Stream, error) { - ret := m.ctrl.Call(m, "OpenStreamSync") - ret0, _ := ret[0].(Stream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OpenStreamSync indicates an expected call of OpenStreamSync -func (mr *MockQuicSessionMockRecorder) OpenStreamSync() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenStreamSync", reflect.TypeOf((*MockQuicSession)(nil).OpenStreamSync)) -} - -// OpenUniStream mocks base method -func (m *MockQuicSession) OpenUniStream() (SendStream, error) { - ret := m.ctrl.Call(m, "OpenUniStream") - ret0, _ := ret[0].(SendStream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OpenUniStream indicates an expected call of OpenUniStream -func (mr *MockQuicSessionMockRecorder) OpenUniStream() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenUniStream", reflect.TypeOf((*MockQuicSession)(nil).OpenUniStream)) -} - -// OpenUniStreamSync mocks base method -func (m *MockQuicSession) OpenUniStreamSync() (SendStream, error) { - ret := m.ctrl.Call(m, "OpenUniStreamSync") - ret0, _ := ret[0].(SendStream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OpenUniStreamSync indicates an expected call of OpenUniStreamSync -func (mr *MockQuicSessionMockRecorder) OpenUniStreamSync() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenUniStreamSync", reflect.TypeOf((*MockQuicSession)(nil).OpenUniStreamSync)) -} - -// RemoteAddr mocks base method -func (m *MockQuicSession) RemoteAddr() net.Addr { - ret := m.ctrl.Call(m, "RemoteAddr") - ret0, _ := ret[0].(net.Addr) - return ret0 -} - -// RemoteAddr indicates an expected call of RemoteAddr -func (mr *MockQuicSessionMockRecorder) RemoteAddr() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoteAddr", reflect.TypeOf((*MockQuicSession)(nil).RemoteAddr)) -} - -// closeRemote mocks base method -func (m *MockQuicSession) closeRemote(arg0 error) { - m.ctrl.Call(m, "closeRemote", arg0) -} - -// closeRemote indicates an expected call of closeRemote -func (mr *MockQuicSessionMockRecorder) closeRemote(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "closeRemote", reflect.TypeOf((*MockQuicSession)(nil).closeRemote), arg0) -} - -// destroy mocks base method -func (m *MockQuicSession) destroy(arg0 error) { - m.ctrl.Call(m, "destroy", arg0) -} - -// destroy indicates an expected call of destroy -func (mr *MockQuicSessionMockRecorder) destroy(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "destroy", reflect.TypeOf((*MockQuicSession)(nil).destroy), arg0) -} - -// handlePacket mocks base method -func (m *MockQuicSession) handlePacket(arg0 *receivedPacket) { - m.ctrl.Call(m, "handlePacket", arg0) -} - -// handlePacket indicates an expected call of handlePacket -func (mr *MockQuicSessionMockRecorder) handlePacket(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handlePacket", reflect.TypeOf((*MockQuicSession)(nil).handlePacket), arg0) -} - -// run mocks base method -func (m *MockQuicSession) run() error { - ret := m.ctrl.Call(m, "run") - ret0, _ := ret[0].(error) - return ret0 -} - -// run indicates an expected call of run -func (mr *MockQuicSessionMockRecorder) run() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "run", reflect.TypeOf((*MockQuicSession)(nil).run)) -} diff --git a/vendor/lucas-clemente/quic-go/mock_receive_stream_internal_test.go b/vendor/lucas-clemente/quic-go/mock_receive_stream_internal_test.go deleted file mode 100644 index c41bfa7e3..000000000 --- a/vendor/lucas-clemente/quic-go/mock_receive_stream_internal_test.go +++ /dev/null @@ -1,132 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: ReceiveStreamI) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - time "time" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" - wire "github.com/lucas-clemente/quic-go/internal/wire" -) - -// MockReceiveStreamI is a mock of ReceiveStreamI interface -type MockReceiveStreamI struct { - ctrl *gomock.Controller - recorder *MockReceiveStreamIMockRecorder -} - -// MockReceiveStreamIMockRecorder is the mock recorder for MockReceiveStreamI -type MockReceiveStreamIMockRecorder struct { - mock *MockReceiveStreamI -} - -// NewMockReceiveStreamI creates a new mock instance -func NewMockReceiveStreamI(ctrl *gomock.Controller) *MockReceiveStreamI { - mock := &MockReceiveStreamI{ctrl: ctrl} - mock.recorder = &MockReceiveStreamIMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockReceiveStreamI) EXPECT() *MockReceiveStreamIMockRecorder { - return m.recorder -} - -// CancelRead mocks base method -func (m *MockReceiveStreamI) CancelRead(arg0 protocol.ApplicationErrorCode) error { - ret := m.ctrl.Call(m, "CancelRead", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// CancelRead indicates an expected call of CancelRead -func (mr *MockReceiveStreamIMockRecorder) CancelRead(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CancelRead", reflect.TypeOf((*MockReceiveStreamI)(nil).CancelRead), arg0) -} - -// Read mocks base method -func (m *MockReceiveStreamI) Read(arg0 []byte) (int, error) { - ret := m.ctrl.Call(m, "Read", arg0) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Read indicates an expected call of Read -func (mr *MockReceiveStreamIMockRecorder) Read(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockReceiveStreamI)(nil).Read), arg0) -} - -// SetReadDeadline mocks base method -func (m *MockReceiveStreamI) SetReadDeadline(arg0 time.Time) error { - ret := m.ctrl.Call(m, "SetReadDeadline", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// SetReadDeadline indicates an expected call of SetReadDeadline -func (mr *MockReceiveStreamIMockRecorder) SetReadDeadline(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetReadDeadline", reflect.TypeOf((*MockReceiveStreamI)(nil).SetReadDeadline), arg0) -} - -// StreamID mocks base method -func (m *MockReceiveStreamI) StreamID() protocol.StreamID { - ret := m.ctrl.Call(m, "StreamID") - ret0, _ := ret[0].(protocol.StreamID) - return ret0 -} - -// StreamID indicates an expected call of StreamID -func (mr *MockReceiveStreamIMockRecorder) StreamID() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StreamID", reflect.TypeOf((*MockReceiveStreamI)(nil).StreamID)) -} - -// closeForShutdown mocks base method -func (m *MockReceiveStreamI) closeForShutdown(arg0 error) { - m.ctrl.Call(m, "closeForShutdown", arg0) -} - -// closeForShutdown indicates an expected call of closeForShutdown -func (mr *MockReceiveStreamIMockRecorder) closeForShutdown(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "closeForShutdown", reflect.TypeOf((*MockReceiveStreamI)(nil).closeForShutdown), arg0) -} - -// getWindowUpdate mocks base method -func (m *MockReceiveStreamI) getWindowUpdate() protocol.ByteCount { - ret := m.ctrl.Call(m, "getWindowUpdate") - ret0, _ := ret[0].(protocol.ByteCount) - return ret0 -} - -// getWindowUpdate indicates an expected call of getWindowUpdate -func (mr *MockReceiveStreamIMockRecorder) getWindowUpdate() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "getWindowUpdate", reflect.TypeOf((*MockReceiveStreamI)(nil).getWindowUpdate)) -} - -// handleRstStreamFrame mocks base method -func (m *MockReceiveStreamI) handleRstStreamFrame(arg0 *wire.RstStreamFrame) error { - ret := m.ctrl.Call(m, "handleRstStreamFrame", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// handleRstStreamFrame indicates an expected call of handleRstStreamFrame -func (mr *MockReceiveStreamIMockRecorder) handleRstStreamFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handleRstStreamFrame", reflect.TypeOf((*MockReceiveStreamI)(nil).handleRstStreamFrame), arg0) -} - -// handleStreamFrame mocks base method -func (m *MockReceiveStreamI) handleStreamFrame(arg0 *wire.StreamFrame) error { - ret := m.ctrl.Call(m, "handleStreamFrame", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// handleStreamFrame indicates an expected call of handleStreamFrame -func (mr *MockReceiveStreamIMockRecorder) handleStreamFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handleStreamFrame", reflect.TypeOf((*MockReceiveStreamI)(nil).handleStreamFrame), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_send_stream_internal_test.go b/vendor/lucas-clemente/quic-go/mock_send_stream_internal_test.go deleted file mode 100644 index f1e68a0f9..000000000 --- a/vendor/lucas-clemente/quic-go/mock_send_stream_internal_test.go +++ /dev/null @@ -1,154 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: SendStreamI) - -// Package quic is a generated GoMock package. -package quic - -import ( - context "context" - reflect "reflect" - time "time" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" - wire "github.com/lucas-clemente/quic-go/internal/wire" -) - -// MockSendStreamI is a mock of SendStreamI interface -type MockSendStreamI struct { - ctrl *gomock.Controller - recorder *MockSendStreamIMockRecorder -} - -// MockSendStreamIMockRecorder is the mock recorder for MockSendStreamI -type MockSendStreamIMockRecorder struct { - mock *MockSendStreamI -} - -// NewMockSendStreamI creates a new mock instance -func NewMockSendStreamI(ctrl *gomock.Controller) *MockSendStreamI { - mock := &MockSendStreamI{ctrl: ctrl} - mock.recorder = &MockSendStreamIMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockSendStreamI) EXPECT() *MockSendStreamIMockRecorder { - return m.recorder -} - -// CancelWrite mocks base method -func (m *MockSendStreamI) CancelWrite(arg0 protocol.ApplicationErrorCode) error { - ret := m.ctrl.Call(m, "CancelWrite", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// CancelWrite indicates an expected call of CancelWrite -func (mr *MockSendStreamIMockRecorder) CancelWrite(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CancelWrite", reflect.TypeOf((*MockSendStreamI)(nil).CancelWrite), arg0) -} - -// Close mocks base method -func (m *MockSendStreamI) Close() error { - ret := m.ctrl.Call(m, "Close") - ret0, _ := ret[0].(error) - return ret0 -} - -// Close indicates an expected call of Close -func (mr *MockSendStreamIMockRecorder) Close() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockSendStreamI)(nil).Close)) -} - -// Context mocks base method -func (m *MockSendStreamI) Context() context.Context { - ret := m.ctrl.Call(m, "Context") - ret0, _ := ret[0].(context.Context) - return ret0 -} - -// Context indicates an expected call of Context -func (mr *MockSendStreamIMockRecorder) Context() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Context", reflect.TypeOf((*MockSendStreamI)(nil).Context)) -} - -// SetWriteDeadline mocks base method -func (m *MockSendStreamI) SetWriteDeadline(arg0 time.Time) error { - ret := m.ctrl.Call(m, "SetWriteDeadline", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// SetWriteDeadline indicates an expected call of SetWriteDeadline -func (mr *MockSendStreamIMockRecorder) SetWriteDeadline(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetWriteDeadline", reflect.TypeOf((*MockSendStreamI)(nil).SetWriteDeadline), arg0) -} - -// StreamID mocks base method -func (m *MockSendStreamI) StreamID() protocol.StreamID { - ret := m.ctrl.Call(m, "StreamID") - ret0, _ := ret[0].(protocol.StreamID) - return ret0 -} - -// StreamID indicates an expected call of StreamID -func (mr *MockSendStreamIMockRecorder) StreamID() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StreamID", reflect.TypeOf((*MockSendStreamI)(nil).StreamID)) -} - -// Write mocks base method -func (m *MockSendStreamI) Write(arg0 []byte) (int, error) { - ret := m.ctrl.Call(m, "Write", arg0) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Write indicates an expected call of Write -func (mr *MockSendStreamIMockRecorder) Write(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockSendStreamI)(nil).Write), arg0) -} - -// closeForShutdown mocks base method -func (m *MockSendStreamI) closeForShutdown(arg0 error) { - m.ctrl.Call(m, "closeForShutdown", arg0) -} - -// closeForShutdown indicates an expected call of closeForShutdown -func (mr *MockSendStreamIMockRecorder) closeForShutdown(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "closeForShutdown", reflect.TypeOf((*MockSendStreamI)(nil).closeForShutdown), arg0) -} - -// handleMaxStreamDataFrame mocks base method -func (m *MockSendStreamI) handleMaxStreamDataFrame(arg0 *wire.MaxStreamDataFrame) { - m.ctrl.Call(m, "handleMaxStreamDataFrame", arg0) -} - -// handleMaxStreamDataFrame indicates an expected call of handleMaxStreamDataFrame -func (mr *MockSendStreamIMockRecorder) handleMaxStreamDataFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handleMaxStreamDataFrame", reflect.TypeOf((*MockSendStreamI)(nil).handleMaxStreamDataFrame), arg0) -} - -// handleStopSendingFrame mocks base method -func (m *MockSendStreamI) handleStopSendingFrame(arg0 *wire.StopSendingFrame) { - m.ctrl.Call(m, "handleStopSendingFrame", arg0) -} - -// handleStopSendingFrame indicates an expected call of handleStopSendingFrame -func (mr *MockSendStreamIMockRecorder) handleStopSendingFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handleStopSendingFrame", reflect.TypeOf((*MockSendStreamI)(nil).handleStopSendingFrame), arg0) -} - -// popStreamFrame mocks base method -func (m *MockSendStreamI) popStreamFrame(arg0 protocol.ByteCount) (*wire.StreamFrame, bool) { - ret := m.ctrl.Call(m, "popStreamFrame", arg0) - ret0, _ := ret[0].(*wire.StreamFrame) - ret1, _ := ret[1].(bool) - return ret0, ret1 -} - -// popStreamFrame indicates an expected call of popStreamFrame -func (mr *MockSendStreamIMockRecorder) popStreamFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "popStreamFrame", reflect.TypeOf((*MockSendStreamI)(nil).popStreamFrame), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_session_runner_test.go b/vendor/lucas-clemente/quic-go/mock_session_runner_test.go deleted file mode 100644 index 4ef433ce8..000000000 --- a/vendor/lucas-clemente/quic-go/mock_session_runner_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: SessionRunner) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// MockSessionRunner is a mock of SessionRunner interface -type MockSessionRunner struct { - ctrl *gomock.Controller - recorder *MockSessionRunnerMockRecorder -} - -// MockSessionRunnerMockRecorder is the mock recorder for MockSessionRunner -type MockSessionRunnerMockRecorder struct { - mock *MockSessionRunner -} - -// NewMockSessionRunner creates a new mock instance -func NewMockSessionRunner(ctrl *gomock.Controller) *MockSessionRunner { - mock := &MockSessionRunner{ctrl: ctrl} - mock.recorder = &MockSessionRunnerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockSessionRunner) EXPECT() *MockSessionRunnerMockRecorder { - return m.recorder -} - -// onHandshakeComplete mocks base method -func (m *MockSessionRunner) onHandshakeComplete(arg0 Session) { - m.ctrl.Call(m, "onHandshakeComplete", arg0) -} - -// onHandshakeComplete indicates an expected call of onHandshakeComplete -func (mr *MockSessionRunnerMockRecorder) onHandshakeComplete(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "onHandshakeComplete", reflect.TypeOf((*MockSessionRunner)(nil).onHandshakeComplete), arg0) -} - -// removeConnectionID mocks base method -func (m *MockSessionRunner) removeConnectionID(arg0 protocol.ConnectionID) { - m.ctrl.Call(m, "removeConnectionID", arg0) -} - -// removeConnectionID indicates an expected call of removeConnectionID -func (mr *MockSessionRunnerMockRecorder) removeConnectionID(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "removeConnectionID", reflect.TypeOf((*MockSessionRunner)(nil).removeConnectionID), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_stream_frame_source_test.go b/vendor/lucas-clemente/quic-go/mock_stream_frame_source_test.go deleted file mode 100644 index 9b3658052..000000000 --- a/vendor/lucas-clemente/quic-go/mock_stream_frame_source_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: StreamFrameSource) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" - wire "github.com/lucas-clemente/quic-go/internal/wire" -) - -// MockStreamFrameSource is a mock of StreamFrameSource interface -type MockStreamFrameSource struct { - ctrl *gomock.Controller - recorder *MockStreamFrameSourceMockRecorder -} - -// MockStreamFrameSourceMockRecorder is the mock recorder for MockStreamFrameSource -type MockStreamFrameSourceMockRecorder struct { - mock *MockStreamFrameSource -} - -// NewMockStreamFrameSource creates a new mock instance -func NewMockStreamFrameSource(ctrl *gomock.Controller) *MockStreamFrameSource { - mock := &MockStreamFrameSource{ctrl: ctrl} - mock.recorder = &MockStreamFrameSourceMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockStreamFrameSource) EXPECT() *MockStreamFrameSourceMockRecorder { - return m.recorder -} - -// HasCryptoStreamData mocks base method -func (m *MockStreamFrameSource) HasCryptoStreamData() bool { - ret := m.ctrl.Call(m, "HasCryptoStreamData") - ret0, _ := ret[0].(bool) - return ret0 -} - -// HasCryptoStreamData indicates an expected call of HasCryptoStreamData -func (mr *MockStreamFrameSourceMockRecorder) HasCryptoStreamData() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasCryptoStreamData", reflect.TypeOf((*MockStreamFrameSource)(nil).HasCryptoStreamData)) -} - -// PopCryptoStreamFrame mocks base method -func (m *MockStreamFrameSource) PopCryptoStreamFrame(arg0 protocol.ByteCount) *wire.StreamFrame { - ret := m.ctrl.Call(m, "PopCryptoStreamFrame", arg0) - ret0, _ := ret[0].(*wire.StreamFrame) - return ret0 -} - -// PopCryptoStreamFrame indicates an expected call of PopCryptoStreamFrame -func (mr *MockStreamFrameSourceMockRecorder) PopCryptoStreamFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PopCryptoStreamFrame", reflect.TypeOf((*MockStreamFrameSource)(nil).PopCryptoStreamFrame), arg0) -} - -// PopStreamFrames mocks base method -func (m *MockStreamFrameSource) PopStreamFrames(arg0 protocol.ByteCount) []*wire.StreamFrame { - ret := m.ctrl.Call(m, "PopStreamFrames", arg0) - ret0, _ := ret[0].([]*wire.StreamFrame) - return ret0 -} - -// PopStreamFrames indicates an expected call of PopStreamFrames -func (mr *MockStreamFrameSourceMockRecorder) PopStreamFrames(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PopStreamFrames", reflect.TypeOf((*MockStreamFrameSource)(nil).PopStreamFrames), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_stream_getter_test.go b/vendor/lucas-clemente/quic-go/mock_stream_getter_test.go deleted file mode 100644 index 8dfa2d865..000000000 --- a/vendor/lucas-clemente/quic-go/mock_stream_getter_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: StreamGetter) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" -) - -// MockStreamGetter is a mock of StreamGetter interface -type MockStreamGetter struct { - ctrl *gomock.Controller - recorder *MockStreamGetterMockRecorder -} - -// MockStreamGetterMockRecorder is the mock recorder for MockStreamGetter -type MockStreamGetterMockRecorder struct { - mock *MockStreamGetter -} - -// NewMockStreamGetter creates a new mock instance -func NewMockStreamGetter(ctrl *gomock.Controller) *MockStreamGetter { - mock := &MockStreamGetter{ctrl: ctrl} - mock.recorder = &MockStreamGetterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockStreamGetter) EXPECT() *MockStreamGetterMockRecorder { - return m.recorder -} - -// GetOrOpenReceiveStream mocks base method -func (m *MockStreamGetter) GetOrOpenReceiveStream(arg0 protocol.StreamID) (receiveStreamI, error) { - ret := m.ctrl.Call(m, "GetOrOpenReceiveStream", arg0) - ret0, _ := ret[0].(receiveStreamI) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetOrOpenReceiveStream indicates an expected call of GetOrOpenReceiveStream -func (mr *MockStreamGetterMockRecorder) GetOrOpenReceiveStream(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrOpenReceiveStream", reflect.TypeOf((*MockStreamGetter)(nil).GetOrOpenReceiveStream), arg0) -} - -// GetOrOpenSendStream mocks base method -func (m *MockStreamGetter) GetOrOpenSendStream(arg0 protocol.StreamID) (sendStreamI, error) { - ret := m.ctrl.Call(m, "GetOrOpenSendStream", arg0) - ret0, _ := ret[0].(sendStreamI) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetOrOpenSendStream indicates an expected call of GetOrOpenSendStream -func (mr *MockStreamGetterMockRecorder) GetOrOpenSendStream(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrOpenSendStream", reflect.TypeOf((*MockStreamGetter)(nil).GetOrOpenSendStream), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_stream_internal_test.go b/vendor/lucas-clemente/quic-go/mock_stream_internal_test.go deleted file mode 100644 index 6cbc8a971..000000000 --- a/vendor/lucas-clemente/quic-go/mock_stream_internal_test.go +++ /dev/null @@ -1,239 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: StreamI) - -// Package quic is a generated GoMock package. -package quic - -import ( - context "context" - reflect "reflect" - time "time" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" - wire "github.com/lucas-clemente/quic-go/internal/wire" -) - -// MockStreamI is a mock of StreamI interface -type MockStreamI struct { - ctrl *gomock.Controller - recorder *MockStreamIMockRecorder -} - -// MockStreamIMockRecorder is the mock recorder for MockStreamI -type MockStreamIMockRecorder struct { - mock *MockStreamI -} - -// NewMockStreamI creates a new mock instance -func NewMockStreamI(ctrl *gomock.Controller) *MockStreamI { - mock := &MockStreamI{ctrl: ctrl} - mock.recorder = &MockStreamIMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockStreamI) EXPECT() *MockStreamIMockRecorder { - return m.recorder -} - -// CancelRead mocks base method -func (m *MockStreamI) CancelRead(arg0 protocol.ApplicationErrorCode) error { - ret := m.ctrl.Call(m, "CancelRead", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// CancelRead indicates an expected call of CancelRead -func (mr *MockStreamIMockRecorder) CancelRead(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CancelRead", reflect.TypeOf((*MockStreamI)(nil).CancelRead), arg0) -} - -// CancelWrite mocks base method -func (m *MockStreamI) CancelWrite(arg0 protocol.ApplicationErrorCode) error { - ret := m.ctrl.Call(m, "CancelWrite", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// CancelWrite indicates an expected call of CancelWrite -func (mr *MockStreamIMockRecorder) CancelWrite(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CancelWrite", reflect.TypeOf((*MockStreamI)(nil).CancelWrite), arg0) -} - -// Close mocks base method -func (m *MockStreamI) Close() error { - ret := m.ctrl.Call(m, "Close") - ret0, _ := ret[0].(error) - return ret0 -} - -// Close indicates an expected call of Close -func (mr *MockStreamIMockRecorder) Close() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockStreamI)(nil).Close)) -} - -// Context mocks base method -func (m *MockStreamI) Context() context.Context { - ret := m.ctrl.Call(m, "Context") - ret0, _ := ret[0].(context.Context) - return ret0 -} - -// Context indicates an expected call of Context -func (mr *MockStreamIMockRecorder) Context() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Context", reflect.TypeOf((*MockStreamI)(nil).Context)) -} - -// Read mocks base method -func (m *MockStreamI) Read(arg0 []byte) (int, error) { - ret := m.ctrl.Call(m, "Read", arg0) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Read indicates an expected call of Read -func (mr *MockStreamIMockRecorder) Read(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockStreamI)(nil).Read), arg0) -} - -// SetDeadline mocks base method -func (m *MockStreamI) SetDeadline(arg0 time.Time) error { - ret := m.ctrl.Call(m, "SetDeadline", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// SetDeadline indicates an expected call of SetDeadline -func (mr *MockStreamIMockRecorder) SetDeadline(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDeadline", reflect.TypeOf((*MockStreamI)(nil).SetDeadline), arg0) -} - -// SetReadDeadline mocks base method -func (m *MockStreamI) SetReadDeadline(arg0 time.Time) error { - ret := m.ctrl.Call(m, "SetReadDeadline", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// SetReadDeadline indicates an expected call of SetReadDeadline -func (mr *MockStreamIMockRecorder) SetReadDeadline(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetReadDeadline", reflect.TypeOf((*MockStreamI)(nil).SetReadDeadline), arg0) -} - -// SetWriteDeadline mocks base method -func (m *MockStreamI) SetWriteDeadline(arg0 time.Time) error { - ret := m.ctrl.Call(m, "SetWriteDeadline", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// SetWriteDeadline indicates an expected call of SetWriteDeadline -func (mr *MockStreamIMockRecorder) SetWriteDeadline(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetWriteDeadline", reflect.TypeOf((*MockStreamI)(nil).SetWriteDeadline), arg0) -} - -// StreamID mocks base method -func (m *MockStreamI) StreamID() protocol.StreamID { - ret := m.ctrl.Call(m, "StreamID") - ret0, _ := ret[0].(protocol.StreamID) - return ret0 -} - -// StreamID indicates an expected call of StreamID -func (mr *MockStreamIMockRecorder) StreamID() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StreamID", reflect.TypeOf((*MockStreamI)(nil).StreamID)) -} - -// Write mocks base method -func (m *MockStreamI) Write(arg0 []byte) (int, error) { - ret := m.ctrl.Call(m, "Write", arg0) - ret0, _ := ret[0].(int) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Write indicates an expected call of Write -func (mr *MockStreamIMockRecorder) Write(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockStreamI)(nil).Write), arg0) -} - -// closeForShutdown mocks base method -func (m *MockStreamI) closeForShutdown(arg0 error) { - m.ctrl.Call(m, "closeForShutdown", arg0) -} - -// closeForShutdown indicates an expected call of closeForShutdown -func (mr *MockStreamIMockRecorder) closeForShutdown(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "closeForShutdown", reflect.TypeOf((*MockStreamI)(nil).closeForShutdown), arg0) -} - -// getWindowUpdate mocks base method -func (m *MockStreamI) getWindowUpdate() protocol.ByteCount { - ret := m.ctrl.Call(m, "getWindowUpdate") - ret0, _ := ret[0].(protocol.ByteCount) - return ret0 -} - -// getWindowUpdate indicates an expected call of getWindowUpdate -func (mr *MockStreamIMockRecorder) getWindowUpdate() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "getWindowUpdate", reflect.TypeOf((*MockStreamI)(nil).getWindowUpdate)) -} - -// handleMaxStreamDataFrame mocks base method -func (m *MockStreamI) handleMaxStreamDataFrame(arg0 *wire.MaxStreamDataFrame) { - m.ctrl.Call(m, "handleMaxStreamDataFrame", arg0) -} - -// handleMaxStreamDataFrame indicates an expected call of handleMaxStreamDataFrame -func (mr *MockStreamIMockRecorder) handleMaxStreamDataFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handleMaxStreamDataFrame", reflect.TypeOf((*MockStreamI)(nil).handleMaxStreamDataFrame), arg0) -} - -// handleRstStreamFrame mocks base method -func (m *MockStreamI) handleRstStreamFrame(arg0 *wire.RstStreamFrame) error { - ret := m.ctrl.Call(m, "handleRstStreamFrame", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// handleRstStreamFrame indicates an expected call of handleRstStreamFrame -func (mr *MockStreamIMockRecorder) handleRstStreamFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handleRstStreamFrame", reflect.TypeOf((*MockStreamI)(nil).handleRstStreamFrame), arg0) -} - -// handleStopSendingFrame mocks base method -func (m *MockStreamI) handleStopSendingFrame(arg0 *wire.StopSendingFrame) { - m.ctrl.Call(m, "handleStopSendingFrame", arg0) -} - -// handleStopSendingFrame indicates an expected call of handleStopSendingFrame -func (mr *MockStreamIMockRecorder) handleStopSendingFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handleStopSendingFrame", reflect.TypeOf((*MockStreamI)(nil).handleStopSendingFrame), arg0) -} - -// handleStreamFrame mocks base method -func (m *MockStreamI) handleStreamFrame(arg0 *wire.StreamFrame) error { - ret := m.ctrl.Call(m, "handleStreamFrame", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// handleStreamFrame indicates an expected call of handleStreamFrame -func (mr *MockStreamIMockRecorder) handleStreamFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handleStreamFrame", reflect.TypeOf((*MockStreamI)(nil).handleStreamFrame), arg0) -} - -// popStreamFrame mocks base method -func (m *MockStreamI) popStreamFrame(arg0 protocol.ByteCount) (*wire.StreamFrame, bool) { - ret := m.ctrl.Call(m, "popStreamFrame", arg0) - ret0, _ := ret[0].(*wire.StreamFrame) - ret1, _ := ret[1].(bool) - return ret0, ret1 -} - -// popStreamFrame indicates an expected call of popStreamFrame -func (mr *MockStreamIMockRecorder) popStreamFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "popStreamFrame", reflect.TypeOf((*MockStreamI)(nil).popStreamFrame), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_stream_manager_test.go b/vendor/lucas-clemente/quic-go/mock_stream_manager_test.go deleted file mode 100644 index 0fdd72623..000000000 --- a/vendor/lucas-clemente/quic-go/mock_stream_manager_test.go +++ /dev/null @@ -1,185 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: StreamManager) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - handshake "github.com/lucas-clemente/quic-go/internal/handshake" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" - wire "github.com/lucas-clemente/quic-go/internal/wire" -) - -// MockStreamManager is a mock of StreamManager interface -type MockStreamManager struct { - ctrl *gomock.Controller - recorder *MockStreamManagerMockRecorder -} - -// MockStreamManagerMockRecorder is the mock recorder for MockStreamManager -type MockStreamManagerMockRecorder struct { - mock *MockStreamManager -} - -// NewMockStreamManager creates a new mock instance -func NewMockStreamManager(ctrl *gomock.Controller) *MockStreamManager { - mock := &MockStreamManager{ctrl: ctrl} - mock.recorder = &MockStreamManagerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockStreamManager) EXPECT() *MockStreamManagerMockRecorder { - return m.recorder -} - -// AcceptStream mocks base method -func (m *MockStreamManager) AcceptStream() (Stream, error) { - ret := m.ctrl.Call(m, "AcceptStream") - ret0, _ := ret[0].(Stream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AcceptStream indicates an expected call of AcceptStream -func (mr *MockStreamManagerMockRecorder) AcceptStream() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AcceptStream", reflect.TypeOf((*MockStreamManager)(nil).AcceptStream)) -} - -// AcceptUniStream mocks base method -func (m *MockStreamManager) AcceptUniStream() (ReceiveStream, error) { - ret := m.ctrl.Call(m, "AcceptUniStream") - ret0, _ := ret[0].(ReceiveStream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AcceptUniStream indicates an expected call of AcceptUniStream -func (mr *MockStreamManagerMockRecorder) AcceptUniStream() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AcceptUniStream", reflect.TypeOf((*MockStreamManager)(nil).AcceptUniStream)) -} - -// CloseWithError mocks base method -func (m *MockStreamManager) CloseWithError(arg0 error) { - m.ctrl.Call(m, "CloseWithError", arg0) -} - -// CloseWithError indicates an expected call of CloseWithError -func (mr *MockStreamManagerMockRecorder) CloseWithError(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloseWithError", reflect.TypeOf((*MockStreamManager)(nil).CloseWithError), arg0) -} - -// DeleteStream mocks base method -func (m *MockStreamManager) DeleteStream(arg0 protocol.StreamID) error { - ret := m.ctrl.Call(m, "DeleteStream", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// DeleteStream indicates an expected call of DeleteStream -func (mr *MockStreamManagerMockRecorder) DeleteStream(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteStream", reflect.TypeOf((*MockStreamManager)(nil).DeleteStream), arg0) -} - -// GetOrOpenReceiveStream mocks base method -func (m *MockStreamManager) GetOrOpenReceiveStream(arg0 protocol.StreamID) (receiveStreamI, error) { - ret := m.ctrl.Call(m, "GetOrOpenReceiveStream", arg0) - ret0, _ := ret[0].(receiveStreamI) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetOrOpenReceiveStream indicates an expected call of GetOrOpenReceiveStream -func (mr *MockStreamManagerMockRecorder) GetOrOpenReceiveStream(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrOpenReceiveStream", reflect.TypeOf((*MockStreamManager)(nil).GetOrOpenReceiveStream), arg0) -} - -// GetOrOpenSendStream mocks base method -func (m *MockStreamManager) GetOrOpenSendStream(arg0 protocol.StreamID) (sendStreamI, error) { - ret := m.ctrl.Call(m, "GetOrOpenSendStream", arg0) - ret0, _ := ret[0].(sendStreamI) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetOrOpenSendStream indicates an expected call of GetOrOpenSendStream -func (mr *MockStreamManagerMockRecorder) GetOrOpenSendStream(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOrOpenSendStream", reflect.TypeOf((*MockStreamManager)(nil).GetOrOpenSendStream), arg0) -} - -// HandleMaxStreamIDFrame mocks base method -func (m *MockStreamManager) HandleMaxStreamIDFrame(arg0 *wire.MaxStreamIDFrame) error { - ret := m.ctrl.Call(m, "HandleMaxStreamIDFrame", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// HandleMaxStreamIDFrame indicates an expected call of HandleMaxStreamIDFrame -func (mr *MockStreamManagerMockRecorder) HandleMaxStreamIDFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleMaxStreamIDFrame", reflect.TypeOf((*MockStreamManager)(nil).HandleMaxStreamIDFrame), arg0) -} - -// OpenStream mocks base method -func (m *MockStreamManager) OpenStream() (Stream, error) { - ret := m.ctrl.Call(m, "OpenStream") - ret0, _ := ret[0].(Stream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OpenStream indicates an expected call of OpenStream -func (mr *MockStreamManagerMockRecorder) OpenStream() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenStream", reflect.TypeOf((*MockStreamManager)(nil).OpenStream)) -} - -// OpenStreamSync mocks base method -func (m *MockStreamManager) OpenStreamSync() (Stream, error) { - ret := m.ctrl.Call(m, "OpenStreamSync") - ret0, _ := ret[0].(Stream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OpenStreamSync indicates an expected call of OpenStreamSync -func (mr *MockStreamManagerMockRecorder) OpenStreamSync() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenStreamSync", reflect.TypeOf((*MockStreamManager)(nil).OpenStreamSync)) -} - -// OpenUniStream mocks base method -func (m *MockStreamManager) OpenUniStream() (SendStream, error) { - ret := m.ctrl.Call(m, "OpenUniStream") - ret0, _ := ret[0].(SendStream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OpenUniStream indicates an expected call of OpenUniStream -func (mr *MockStreamManagerMockRecorder) OpenUniStream() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenUniStream", reflect.TypeOf((*MockStreamManager)(nil).OpenUniStream)) -} - -// OpenUniStreamSync mocks base method -func (m *MockStreamManager) OpenUniStreamSync() (SendStream, error) { - ret := m.ctrl.Call(m, "OpenUniStreamSync") - ret0, _ := ret[0].(SendStream) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// OpenUniStreamSync indicates an expected call of OpenUniStreamSync -func (mr *MockStreamManagerMockRecorder) OpenUniStreamSync() *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OpenUniStreamSync", reflect.TypeOf((*MockStreamManager)(nil).OpenUniStreamSync)) -} - -// UpdateLimits mocks base method -func (m *MockStreamManager) UpdateLimits(arg0 *handshake.TransportParameters) { - m.ctrl.Call(m, "UpdateLimits", arg0) -} - -// UpdateLimits indicates an expected call of UpdateLimits -func (mr *MockStreamManagerMockRecorder) UpdateLimits(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateLimits", reflect.TypeOf((*MockStreamManager)(nil).UpdateLimits), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_stream_sender_test.go b/vendor/lucas-clemente/quic-go/mock_stream_sender_test.go deleted file mode 100644 index d6f090a1f..000000000 --- a/vendor/lucas-clemente/quic-go/mock_stream_sender_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: StreamSender) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - protocol "github.com/lucas-clemente/quic-go/internal/protocol" - wire "github.com/lucas-clemente/quic-go/internal/wire" -) - -// MockStreamSender is a mock of StreamSender interface -type MockStreamSender struct { - ctrl *gomock.Controller - recorder *MockStreamSenderMockRecorder -} - -// MockStreamSenderMockRecorder is the mock recorder for MockStreamSender -type MockStreamSenderMockRecorder struct { - mock *MockStreamSender -} - -// NewMockStreamSender creates a new mock instance -func NewMockStreamSender(ctrl *gomock.Controller) *MockStreamSender { - mock := &MockStreamSender{ctrl: ctrl} - mock.recorder = &MockStreamSenderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockStreamSender) EXPECT() *MockStreamSenderMockRecorder { - return m.recorder -} - -// onHasStreamData mocks base method -func (m *MockStreamSender) onHasStreamData(arg0 protocol.StreamID) { - m.ctrl.Call(m, "onHasStreamData", arg0) -} - -// onHasStreamData indicates an expected call of onHasStreamData -func (mr *MockStreamSenderMockRecorder) onHasStreamData(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "onHasStreamData", reflect.TypeOf((*MockStreamSender)(nil).onHasStreamData), arg0) -} - -// onStreamCompleted mocks base method -func (m *MockStreamSender) onStreamCompleted(arg0 protocol.StreamID) { - m.ctrl.Call(m, "onStreamCompleted", arg0) -} - -// onStreamCompleted indicates an expected call of onStreamCompleted -func (mr *MockStreamSenderMockRecorder) onStreamCompleted(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "onStreamCompleted", reflect.TypeOf((*MockStreamSender)(nil).onStreamCompleted), arg0) -} - -// queueControlFrame mocks base method -func (m *MockStreamSender) queueControlFrame(arg0 wire.Frame) { - m.ctrl.Call(m, "queueControlFrame", arg0) -} - -// queueControlFrame indicates an expected call of queueControlFrame -func (mr *MockStreamSenderMockRecorder) queueControlFrame(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "queueControlFrame", reflect.TypeOf((*MockStreamSender)(nil).queueControlFrame), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_unknown_packet_handler_test.go b/vendor/lucas-clemente/quic-go/mock_unknown_packet_handler_test.go deleted file mode 100644 index 65f2978ac..000000000 --- a/vendor/lucas-clemente/quic-go/mock_unknown_packet_handler_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: UnknownPacketHandler) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" -) - -// MockUnknownPacketHandler is a mock of UnknownPacketHandler interface -type MockUnknownPacketHandler struct { - ctrl *gomock.Controller - recorder *MockUnknownPacketHandlerMockRecorder -} - -// MockUnknownPacketHandlerMockRecorder is the mock recorder for MockUnknownPacketHandler -type MockUnknownPacketHandlerMockRecorder struct { - mock *MockUnknownPacketHandler -} - -// NewMockUnknownPacketHandler creates a new mock instance -func NewMockUnknownPacketHandler(ctrl *gomock.Controller) *MockUnknownPacketHandler { - mock := &MockUnknownPacketHandler{ctrl: ctrl} - mock.recorder = &MockUnknownPacketHandlerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockUnknownPacketHandler) EXPECT() *MockUnknownPacketHandlerMockRecorder { - return m.recorder -} - -// closeWithError mocks base method -func (m *MockUnknownPacketHandler) closeWithError(arg0 error) error { - ret := m.ctrl.Call(m, "closeWithError", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// closeWithError indicates an expected call of closeWithError -func (mr *MockUnknownPacketHandlerMockRecorder) closeWithError(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "closeWithError", reflect.TypeOf((*MockUnknownPacketHandler)(nil).closeWithError), arg0) -} - -// handlePacket mocks base method -func (m *MockUnknownPacketHandler) handlePacket(arg0 *receivedPacket) { - m.ctrl.Call(m, "handlePacket", arg0) -} - -// handlePacket indicates an expected call of handlePacket -func (mr *MockUnknownPacketHandlerMockRecorder) handlePacket(arg0 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "handlePacket", reflect.TypeOf((*MockUnknownPacketHandler)(nil).handlePacket), arg0) -} diff --git a/vendor/lucas-clemente/quic-go/mock_unpacker_test.go b/vendor/lucas-clemente/quic-go/mock_unpacker_test.go deleted file mode 100644 index 6bf3cc692..000000000 --- a/vendor/lucas-clemente/quic-go/mock_unpacker_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/lucas-clemente/quic-go (interfaces: Unpacker) - -// Package quic is a generated GoMock package. -package quic - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - wire "github.com/lucas-clemente/quic-go/internal/wire" -) - -// MockUnpacker is a mock of Unpacker interface -type MockUnpacker struct { - ctrl *gomock.Controller - recorder *MockUnpackerMockRecorder -} - -// MockUnpackerMockRecorder is the mock recorder for MockUnpacker -type MockUnpackerMockRecorder struct { - mock *MockUnpacker -} - -// NewMockUnpacker creates a new mock instance -func NewMockUnpacker(ctrl *gomock.Controller) *MockUnpacker { - mock := &MockUnpacker{ctrl: ctrl} - mock.recorder = &MockUnpackerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockUnpacker) EXPECT() *MockUnpackerMockRecorder { - return m.recorder -} - -// Unpack mocks base method -func (m *MockUnpacker) Unpack(arg0 []byte, arg1 *wire.Header, arg2 []byte) (*unpackedPacket, error) { - ret := m.ctrl.Call(m, "Unpack", arg0, arg1, arg2) - ret0, _ := ret[0].(*unpackedPacket) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Unpack indicates an expected call of Unpack -func (mr *MockUnpackerMockRecorder) Unpack(arg0, arg1, arg2 interface{}) *gomock.Call { - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unpack", reflect.TypeOf((*MockUnpacker)(nil).Unpack), arg0, arg1, arg2) -} diff --git a/vendor/lucas-clemente/quic-go/multiplexer_test.go b/vendor/lucas-clemente/quic-go/multiplexer_test.go deleted file mode 100644 index f50f227fd..000000000 --- a/vendor/lucas-clemente/quic-go/multiplexer_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package quic - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Client Multiplexer", func() { - It("adds a new packet conn ", func() { - conn := newMockPacketConn() - _, err := getMultiplexer().AddConn(conn, 8) - Expect(err).ToNot(HaveOccurred()) - }) - - It("errors when adding an existing conn with a different connection ID length", func() { - conn := newMockPacketConn() - _, err := getMultiplexer().AddConn(conn, 5) - Expect(err).ToNot(HaveOccurred()) - _, err = getMultiplexer().AddConn(conn, 6) - Expect(err).To(MatchError("cannot use 6 byte connection IDs on a connection that is already using 5 byte connction IDs")) - }) - -}) diff --git a/vendor/lucas-clemente/quic-go/packet_handler_map_test.go b/vendor/lucas-clemente/quic-go/packet_handler_map_test.go deleted file mode 100644 index 4986081ff..000000000 --- a/vendor/lucas-clemente/quic-go/packet_handler_map_test.go +++ /dev/null @@ -1,206 +0,0 @@ -package quic - -import ( - "bytes" - "errors" - "time" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Packet Handler Map", func() { - var ( - handler *packetHandlerMap - conn *mockPacketConn - ) - - getPacket := func(connID protocol.ConnectionID) []byte { - buf := &bytes.Buffer{} - err := (&wire.Header{ - DestConnectionID: connID, - PacketNumberLen: protocol.PacketNumberLen1, - }).Write(buf, protocol.PerspectiveServer, versionGQUICFrames) - Expect(err).ToNot(HaveOccurred()) - return buf.Bytes() - } - - BeforeEach(func() { - conn = newMockPacketConn() - handler = newPacketHandlerMap(conn, 5, utils.DefaultLogger).(*packetHandlerMap) - }) - - It("closes", func() { - testErr := errors.New("test error ") - sess1 := NewMockPacketHandler(mockCtrl) - sess1.EXPECT().destroy(testErr) - sess2 := NewMockPacketHandler(mockCtrl) - sess2.EXPECT().destroy(testErr) - handler.Add(protocol.ConnectionID{1, 1, 1, 1}, sess1) - handler.Add(protocol.ConnectionID{2, 2, 2, 2}, sess2) - handler.close(testErr) - }) - - Context("handling packets", func() { - It("handles packets for different packet handlers on the same packet conn", func() { - connID1 := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - connID2 := protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1} - packetHandler1 := NewMockPacketHandler(mockCtrl) - packetHandler2 := NewMockPacketHandler(mockCtrl) - handledPacket1 := make(chan struct{}) - handledPacket2 := make(chan struct{}) - packetHandler1.EXPECT().handlePacket(gomock.Any()).Do(func(p *receivedPacket) { - Expect(p.header.DestConnectionID).To(Equal(connID1)) - close(handledPacket1) - }) - packetHandler1.EXPECT().GetVersion() - packetHandler1.EXPECT().GetPerspective().Return(protocol.PerspectiveClient) - packetHandler2.EXPECT().handlePacket(gomock.Any()).Do(func(p *receivedPacket) { - Expect(p.header.DestConnectionID).To(Equal(connID2)) - close(handledPacket2) - }) - packetHandler2.EXPECT().GetVersion() - packetHandler2.EXPECT().GetPerspective().Return(protocol.PerspectiveClient) - handler.Add(connID1, packetHandler1) - handler.Add(connID2, packetHandler2) - - conn.dataToRead <- getPacket(connID1) - conn.dataToRead <- getPacket(connID2) - Eventually(handledPacket1).Should(BeClosed()) - Eventually(handledPacket2).Should(BeClosed()) - - // makes the listen go routine return - packetHandler1.EXPECT().destroy(gomock.Any()).AnyTimes() - packetHandler2.EXPECT().destroy(gomock.Any()).AnyTimes() - close(conn.dataToRead) - }) - - It("drops unparseable packets", func() { - err := handler.handlePacket(nil, []byte("invalid")) - Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("error parsing invariant header:")) - }) - - It("deletes nil session entries after a wait time", func() { - handler.deleteClosedSessionsAfter = 10 * time.Millisecond - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - handler.Add(connID, NewMockPacketHandler(mockCtrl)) - handler.Remove(connID) - Eventually(func() error { - return handler.handlePacket(nil, getPacket(connID)) - }).Should(MatchError("received a packet with an unexpected connection ID 0x0102030405060708")) - }) - - It("ignores packets arriving late for closed sessions", func() { - handler.deleteClosedSessionsAfter = time.Hour - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - handler.Add(connID, NewMockPacketHandler(mockCtrl)) - handler.Remove(connID) - err := handler.handlePacket(nil, getPacket(connID)) - Expect(err).ToNot(HaveOccurred()) - }) - - It("drops packets for unknown receivers", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - err := handler.handlePacket(nil, getPacket(connID)) - Expect(err).To(MatchError("received a packet with an unexpected connection ID 0x0102030405060708")) - }) - - It("errors on packets that are smaller than the Payload Length in the packet header", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - packetHandler := NewMockPacketHandler(mockCtrl) - packetHandler.EXPECT().GetVersion().Return(versionIETFFrames) - packetHandler.EXPECT().GetPerspective().Return(protocol.PerspectiveClient) - handler.Add(connID, packetHandler) - hdr := &wire.Header{ - IsLongHeader: true, - Type: protocol.PacketTypeHandshake, - PayloadLen: 1000, - DestConnectionID: connID, - PacketNumberLen: protocol.PacketNumberLen1, - Version: versionIETFFrames, - } - buf := &bytes.Buffer{} - Expect(hdr.Write(buf, protocol.PerspectiveServer, versionIETFFrames)).To(Succeed()) - buf.Write(bytes.Repeat([]byte{0}, 500)) - - err := handler.handlePacket(nil, buf.Bytes()) - Expect(err).To(MatchError("packet payload (500 bytes) is smaller than the expected payload length (1000 bytes)")) - }) - - It("cuts packets at the Payload Length", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - packetHandler := NewMockPacketHandler(mockCtrl) - packetHandler.EXPECT().GetVersion().Return(versionIETFFrames) - packetHandler.EXPECT().GetPerspective().Return(protocol.PerspectiveClient) - handler.Add(connID, packetHandler) - packetHandler.EXPECT().handlePacket(gomock.Any()).Do(func(p *receivedPacket) { - Expect(p.data).To(HaveLen(456)) - }) - - hdr := &wire.Header{ - IsLongHeader: true, - Type: protocol.PacketTypeHandshake, - PayloadLen: 456, - DestConnectionID: connID, - PacketNumberLen: protocol.PacketNumberLen1, - Version: versionIETFFrames, - } - buf := &bytes.Buffer{} - Expect(hdr.Write(buf, protocol.PerspectiveServer, versionIETFFrames)).To(Succeed()) - buf.Write(bytes.Repeat([]byte{0}, 500)) - err := handler.handlePacket(nil, buf.Bytes()) - Expect(err).ToNot(HaveOccurred()) - }) - - It("closes the packet handlers when reading from the conn fails", func() { - done := make(chan struct{}) - packetHandler := NewMockPacketHandler(mockCtrl) - packetHandler.EXPECT().destroy(gomock.Any()).Do(func(e error) { - Expect(e).To(HaveOccurred()) - close(done) - }) - handler.Add(protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, packetHandler) - conn.Close() - Eventually(done).Should(BeClosed()) - }) - }) - - Context("running a server", func() { - It("adds a server", func() { - connID := protocol.ConnectionID{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88} - p := getPacket(connID) - server := NewMockUnknownPacketHandler(mockCtrl) - server.EXPECT().handlePacket(gomock.Any()).Do(func(p *receivedPacket) { - Expect(p.header.DestConnectionID).To(Equal(connID)) - }) - handler.SetServer(server) - Expect(handler.handlePacket(nil, p)).To(Succeed()) - }) - - It("closes all server sessions", func() { - clientSess := NewMockPacketHandler(mockCtrl) - clientSess.EXPECT().GetPerspective().Return(protocol.PerspectiveClient) - serverSess := NewMockPacketHandler(mockCtrl) - serverSess.EXPECT().GetPerspective().Return(protocol.PerspectiveServer) - serverSess.EXPECT().Close() - - handler.Add(protocol.ConnectionID{1, 1, 1, 1}, clientSess) - handler.Add(protocol.ConnectionID{2, 2, 2, 2}, serverSess) - handler.CloseServer() - }) - - It("stops handling packets with unknown connection IDs after the server is closed", func() { - connID := protocol.ConnectionID{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88} - p := getPacket(connID) - server := NewMockUnknownPacketHandler(mockCtrl) - handler.SetServer(server) - handler.CloseServer() - Expect(handler.handlePacket(nil, p)).To(MatchError("received a packet with an unexpected connection ID 0x1122334455667788")) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/packet_number_generator_test.go b/vendor/lucas-clemente/quic-go/packet_number_generator_test.go deleted file mode 100644 index ece74a961..000000000 --- a/vendor/lucas-clemente/quic-go/packet_number_generator_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package quic - -import ( - "math" - - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Packet Number Generator", func() { - var png packetNumberGenerator - - BeforeEach(func() { - png = *newPacketNumberGenerator(1, 100) - }) - - It("can be initialized to return any first packet number", func() { - png = *newPacketNumberGenerator(12345, 100) - Expect(png.Pop()).To(Equal(protocol.PacketNumber(12345))) - }) - - It("gets 1 as the first packet number", func() { - num := png.Pop() - Expect(num).To(Equal(protocol.PacketNumber(1))) - }) - - It("allows peeking", func() { - png.nextToSkip = 1000 - Expect(png.Peek()).To(Equal(protocol.PacketNumber(1))) - Expect(png.Peek()).To(Equal(protocol.PacketNumber(1))) - num := png.Pop() - Expect(num).To(Equal(protocol.PacketNumber(1))) - Expect(png.Peek()).To(Equal(protocol.PacketNumber(2))) - Expect(png.Peek()).To(Equal(protocol.PacketNumber(2))) - }) - - It("skips a packet number", func() { - png.nextToSkip = 2 - num := png.Pop() - Expect(num).To(Equal(protocol.PacketNumber(1))) - Expect(png.Peek()).To(Equal(protocol.PacketNumber(3))) - num = png.Pop() - Expect(num).To(Equal(protocol.PacketNumber(3))) - }) - - It("generates a new packet number to skip", func() { - png.next = 100 - png.averagePeriod = 100 - - rep := 5000 - var sum protocol.PacketNumber - - for i := 0; i < rep; i++ { - png.generateNewSkip() - Expect(png.nextToSkip).ToNot(Equal(protocol.PacketNumber(101))) - sum += png.nextToSkip - } - - average := sum / protocol.PacketNumber(rep) - Expect(average).To(BeNumerically("==", protocol.PacketNumber(200), 4)) - }) - - It("uses random numbers", func() { - var smallest uint16 = math.MaxUint16 - var largest uint16 - var sum uint64 - - rep := 10000 - - for i := 0; i < rep; i++ { - num, err := png.getRandomNumber() - Expect(err).ToNot(HaveOccurred()) - sum += uint64(num) - if num > largest { - largest = num - } - if num < smallest { - smallest = num - } - } - - Expect(smallest).To(BeNumerically("<", 300)) - Expect(largest).To(BeNumerically(">", math.MaxUint16-300)) - Expect(sum / uint64(rep)).To(BeNumerically("==", uint64(math.MaxUint16/2), 1000)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/packet_packer_test.go b/vendor/lucas-clemente/quic-go/packet_packer_test.go deleted file mode 100644 index ae40aa2e2..000000000 --- a/vendor/lucas-clemente/quic-go/packet_packer_test.go +++ /dev/null @@ -1,1079 +0,0 @@ -package quic - -import ( - "bytes" - "net" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/ackhandler" - "github.com/lucas-clemente/quic-go/internal/handshake" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type mockSealer struct{} - -func (s *mockSealer) Seal(dst, src []byte, packetNumber protocol.PacketNumber, associatedData []byte) []byte { - return append(src, bytes.Repeat([]byte{0}, 12)...) -} - -func (s *mockSealer) Overhead() int { return 12 } - -var _ handshake.Sealer = &mockSealer{} - -type mockCryptoSetup struct { - handleErr error - encLevelSeal protocol.EncryptionLevel - encLevelSealCrypto protocol.EncryptionLevel - divNonce []byte -} - -var _ handshake.CryptoSetup = &mockCryptoSetup{} - -func (m *mockCryptoSetup) HandleCryptoStream() error { - return m.handleErr -} -func (m *mockCryptoSetup) Open(dst, src []byte, packetNumber protocol.PacketNumber, associatedData []byte) ([]byte, protocol.EncryptionLevel, error) { - return nil, protocol.EncryptionUnspecified, nil -} -func (m *mockCryptoSetup) GetSealer() (protocol.EncryptionLevel, handshake.Sealer) { - return m.encLevelSeal, &mockSealer{} -} -func (m *mockCryptoSetup) GetSealerForCryptoStream() (protocol.EncryptionLevel, handshake.Sealer) { - return m.encLevelSealCrypto, &mockSealer{} -} -func (m *mockCryptoSetup) GetSealerWithEncryptionLevel(protocol.EncryptionLevel) (handshake.Sealer, error) { - return &mockSealer{}, nil -} -func (m *mockCryptoSetup) SetDiversificationNonce(divNonce []byte) error { - m.divNonce = divNonce - return nil -} -func (m *mockCryptoSetup) ConnectionState() ConnectionState { panic("not implemented") } - -var _ = Describe("Packet packer", func() { - const maxPacketSize protocol.ByteCount = 1357 - var ( - packer *packetPacker - publicHeaderLen protocol.ByteCount - maxFrameSize protocol.ByteCount - mockStreamFramer *MockStreamFrameSource - divNonce []byte - token []byte - ) - - checkPayloadLen := func(data []byte) { - r := bytes.NewReader(data) - iHdr, err := wire.ParseInvariantHeader(r, 0) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(r, protocol.PerspectiveServer, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - ExpectWithOffset(0, hdr.PayloadLen).To(BeEquivalentTo(r.Len())) - } - - BeforeEach(func() { - version := versionGQUICFrames - mockSender := NewMockStreamSender(mockCtrl) - mockSender.EXPECT().onHasStreamData(gomock.Any()).AnyTimes() - mockStreamFramer = NewMockStreamFrameSource(mockCtrl) - divNonce = bytes.Repeat([]byte{'e'}, 32) - token = []byte("initial token") - - packer = newPacketPacker( - protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - 1, - func(protocol.PacketNumber) protocol.PacketNumberLen { return protocol.PacketNumberLen2 }, - &net.TCPAddr{}, - token, // token - divNonce, - &mockCryptoSetup{encLevelSeal: protocol.EncryptionForwardSecure}, - mockStreamFramer, - protocol.PerspectiveServer, - version, - ) - publicHeaderLen = 1 + 8 + 2 // 1 flag byte, 8 connection ID, 2 packet number - maxFrameSize = maxPacketSize - protocol.ByteCount((&mockSealer{}).Overhead()) - publicHeaderLen - packer.hasSentPacket = true - packer.version = version - packer.maxPacketSize = maxPacketSize - }) - - Context("determining the maximum packet size", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - - It("uses the minimum initial size, if it can't determine if the remote address is IPv4 or IPv6", func() { - remoteAddr := &net.TCPAddr{} - packer = newPacketPacker(connID, connID, 1, nil, remoteAddr, nil, nil, nil, nil, protocol.PerspectiveServer, protocol.VersionWhatever) - Expect(packer.maxPacketSize).To(BeEquivalentTo(protocol.MinInitialPacketSize)) - }) - - It("uses the maximum IPv4 packet size, if the remote address is IPv4", func() { - remoteAddr := &net.UDPAddr{IP: net.IPv4(11, 12, 13, 14), Port: 1337} - packer = newPacketPacker(connID, connID, 1, nil, remoteAddr, nil, nil, nil, nil, protocol.PerspectiveServer, protocol.VersionWhatever) - Expect(packer.maxPacketSize).To(BeEquivalentTo(protocol.MaxPacketSizeIPv4)) - }) - - It("uses the maximum IPv6 packet size, if the remote address is IPv6", func() { - ip := net.ParseIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334") - remoteAddr := &net.UDPAddr{IP: ip, Port: 1337} - packer = newPacketPacker(connID, connID, 1, nil, remoteAddr, nil, nil, nil, nil, protocol.PerspectiveServer, protocol.VersionWhatever) - Expect(packer.maxPacketSize).To(BeEquivalentTo(protocol.MaxPacketSizeIPv6)) - }) - }) - - It("returns nil when no packet is queued", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - p, err := packer.PackPacket() - Expect(p).To(BeNil()) - Expect(err).ToNot(HaveOccurred()) - }) - - It("packs single packets", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - f := &wire.StreamFrame{ - StreamID: 5, - Data: []byte{0xDE, 0xCA, 0xFB, 0xAD}, - } - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).Return([]*wire.StreamFrame{f}) - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).ToNot(BeNil()) - b := &bytes.Buffer{} - f.Write(b, packer.version) - Expect(p.frames).To(Equal([]wire.Frame{f})) - Expect(p.raw).To(ContainSubstring(b.String())) - }) - - It("stores the encryption level a packet was sealed with", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).Return([]*wire.StreamFrame{{ - StreamID: 5, - Data: []byte("foobar"), - }}) - packer.cryptoSetup.(*mockCryptoSetup).encLevelSeal = protocol.EncryptionForwardSecure - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.encryptionLevel).To(Equal(protocol.EncryptionForwardSecure)) - }) - - Context("generating a packet header", func() { - const ( - versionPublicHeader = protocol.Version39 // a QUIC version that uses the Public Header format - versionIETFHeader = protocol.VersionTLS // a QUIC version that uses the IETF Header format - ) - - Context("Public Header (for gQUIC)", func() { - BeforeEach(func() { - packer.version = versionPublicHeader - }) - - It("doesn't set the source connection ID", func() { - ph := packer.getHeader(protocol.EncryptionForwardSecure) - Expect(ph.SrcConnectionID).To(BeEmpty()) - }) - - It("it omits the connection ID for forward-secure packets", func() { - packer.version = protocol.Version43 - ph := packer.getHeader(protocol.EncryptionForwardSecure) - Expect(ph.DestConnectionID.Len()).ToNot(BeZero()) - packer.SetOmitConnectionID() - ph = packer.getHeader(protocol.EncryptionForwardSecure) - Expect(ph.DestConnectionID.Len()).To(BeZero()) - }) - - It("doesn't omit the connection ID for non-forward-secure packets", func() { - packer.SetOmitConnectionID() - ph := packer.getHeader(protocol.EncryptionSecure) - Expect(ph.DestConnectionID.Len()).ToNot(BeZero()) - }) - - It("adds the Version Flag to the Public Header before the crypto handshake is finished", func() { - packer.perspective = protocol.PerspectiveClient - ph := packer.getHeader(protocol.EncryptionSecure) - Expect(ph.VersionFlag).To(BeTrue()) - }) - - It("doesn't add the Version Flag to the Public Header for forward-secure packets", func() { - packer.perspective = protocol.PerspectiveClient - ph := packer.getHeader(protocol.EncryptionForwardSecure) - Expect(ph.VersionFlag).To(BeFalse()) - }) - - Context("diversificaton nonces", func() { - It("doesn't include a div nonce, when sending a packet with initial encryption", func() { - ph := packer.getHeader(protocol.EncryptionUnencrypted) - Expect(ph.DiversificationNonce).To(BeEmpty()) - }) - - It("includes a div nonce, when sending a packet with secure encryption", func() { - ph := packer.getHeader(protocol.EncryptionSecure) - Expect(ph.DiversificationNonce).To(Equal(divNonce)) - }) - - It("doesn't include a div nonce, when sending a packet with forward-secure encryption", func() { - ph := packer.getHeader(protocol.EncryptionForwardSecure) - Expect(ph.DiversificationNonce).To(BeEmpty()) - }) - - It("doesn't send a div nonce as a client", func() { - packer.perspective = protocol.PerspectiveClient - ph := packer.getHeader(protocol.EncryptionSecure) - Expect(ph.DiversificationNonce).To(BeEmpty()) - }) - }) - }) - - Context("Header (for gQUIC 44)", func() { - BeforeEach(func() { - packer.version = protocol.Version44 - }) - - It("sends an Initial packet as the first packets, for the client", func() { - packer.perspective = protocol.PerspectiveClient - packer.hasSentPacket = false - h := packer.getHeader(protocol.EncryptionUnencrypted) - Expect(h.IsLongHeader).To(BeTrue()) - Expect(h.Type).To(Equal(protocol.PacketTypeInitial)) - Expect(h.Version).To(Equal(protocol.Version44)) - Expect(h.DestConnectionID).To(Equal(packer.destConnID)) - Expect(h.SrcConnectionID).To(Equal(packer.srcConnID)) - Expect(h.PacketNumberLen).To(Equal(protocol.PacketNumberLen4)) - }) - - It("sends a Handshake for non-forward-secure packets, for the server", func() { - packer.perspective = protocol.PerspectiveServer - h := packer.getHeader(protocol.EncryptionUnencrypted) - Expect(h.IsLongHeader).To(BeTrue()) - Expect(h.Type).To(Equal(protocol.PacketTypeHandshake)) - Expect(h.Version).To(Equal(protocol.Version44)) - Expect(h.DestConnectionID).To(Equal(packer.destConnID)) - Expect(h.SrcConnectionID).To(Equal(packer.srcConnID)) - Expect(h.PacketNumberLen).To(Equal(protocol.PacketNumberLen4)) - }) - - It("sets the Diversification Nonce for secure packets", func() { - packer.perspective = protocol.PerspectiveServer - Expect(divNonce).ToNot(BeEmpty()) - h := packer.getHeader(protocol.EncryptionSecure) - Expect(h.IsLongHeader).To(BeTrue()) - Expect(h.Version).To(Equal(protocol.Version44)) - Expect(h.Type).To(Equal(protocol.PacketType0RTT)) - Expect(h.DiversificationNonce).To(Equal(divNonce)) - }) - - It("uses the Short Header for forward-secure packets", func() { - h := packer.getHeader(protocol.EncryptionForwardSecure) - Expect(h.IsLongHeader).To(BeFalse()) - Expect(h.IsPublicHeader).To(BeFalse()) - Expect(h.DestConnectionID).To(Equal(packer.destConnID)) - }) - }) - - Context("Header (for IETF draft QUIC)", func() { - BeforeEach(func() { - packer.version = versionIETFHeader - }) - - It("uses the Long Header format for non-forward-secure packets", func() { - h := packer.getHeader(protocol.EncryptionSecure) - Expect(h.IsLongHeader).To(BeTrue()) - Expect(h.Version).To(Equal(versionIETFHeader)) - }) - - It("sets source and destination connection ID", func() { - srcConnID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - destConnID := protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1} - packer.srcConnID = srcConnID - packer.destConnID = destConnID - h := packer.getHeader(protocol.EncryptionSecure) - Expect(h.SrcConnectionID).To(Equal(srcConnID)) - Expect(h.DestConnectionID).To(Equal(destConnID)) - }) - - It("changes the destination connection ID", func() { - srcConnID := protocol.ConnectionID{1, 1, 1, 1, 1, 1, 1, 1} - packer.srcConnID = srcConnID - dest1 := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - dest2 := protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1} - packer.ChangeDestConnectionID(dest1) - h := packer.getHeader(protocol.EncryptionUnencrypted) - Expect(h.SrcConnectionID).To(Equal(srcConnID)) - Expect(h.DestConnectionID).To(Equal(dest1)) - packer.ChangeDestConnectionID(dest2) - h = packer.getHeader(protocol.EncryptionUnencrypted) - Expect(h.SrcConnectionID).To(Equal(srcConnID)) - Expect(h.DestConnectionID).To(Equal(dest2)) - }) - - It("uses the Short Header format for forward-secure packets", func() { - h := packer.getHeader(protocol.EncryptionForwardSecure) - Expect(h.IsLongHeader).To(BeFalse()) - Expect(h.PacketNumberLen).To(BeNumerically(">", 0)) - }) - }) - }) - - It("sets the payload length for packets containing crypto data", func() { - packer.version = versionIETFFrames - f := &wire.StreamFrame{ - StreamID: packer.version.CryptoStreamID(), - Offset: 0x1337, - Data: []byte("foobar"), - } - mockStreamFramer.EXPECT().HasCryptoStreamData().Return(true) - mockStreamFramer.EXPECT().PopCryptoStreamFrame(gomock.Any()).Return(f) - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - checkPayloadLen(p.raw) - }) - - It("packs a CONNECTION_CLOSE", func() { - ccf := wire.ConnectionCloseFrame{ - ErrorCode: 0x1337, - ReasonPhrase: "foobar", - } - p, err := packer.PackConnectionClose(&ccf) - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(HaveLen(1)) - Expect(p.frames[0]).To(Equal(&ccf)) - }) - - It("doesn't send any other frames when sending a CONNECTION_CLOSE", func() { - // expect no mockStreamFramer.PopStreamFrames - ccf := &wire.ConnectionCloseFrame{ - ErrorCode: 0x1337, - ReasonPhrase: "foobar", - } - packer.controlFrames = []wire.Frame{&wire.MaxStreamDataFrame{StreamID: 37}} - p, err := packer.PackConnectionClose(ccf) - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(Equal([]wire.Frame{ccf})) - }) - - It("packs only control frames", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - packer.QueueControlFrame(&wire.RstStreamFrame{}) - packer.QueueControlFrame(&wire.MaxDataFrame{}) - p, err := packer.PackPacket() - Expect(p).ToNot(BeNil()) - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(HaveLen(2)) - Expect(p.raw).NotTo(BeEmpty()) - }) - - It("increases the packet number", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData().Times(2) - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).Times(2) - packer.QueueControlFrame(&wire.RstStreamFrame{}) - p1, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p1).ToNot(BeNil()) - packer.QueueControlFrame(&wire.RstStreamFrame{}) - p2, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p2).ToNot(BeNil()) - Expect(p2.header.PacketNumber).To(BeNumerically(">", p1.header.PacketNumber)) - }) - - It("packs a STOP_WAITING frame first", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - packer.packetNumberGenerator.next = 15 - swf := &wire.StopWaitingFrame{LeastUnacked: 10} - packer.QueueControlFrame(&wire.RstStreamFrame{}) - packer.QueueControlFrame(swf) - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).ToNot(BeNil()) - Expect(p.frames).To(HaveLen(2)) - Expect(p.frames[0]).To(Equal(swf)) - }) - - It("sets the LeastUnackedDelta length of a STOP_WAITING frame", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - packer.packetNumberGenerator.next = 0x1337 - swf := &wire.StopWaitingFrame{LeastUnacked: 0x1337 - 0x100} - packer.QueueControlFrame(&wire.RstStreamFrame{}) - packer.QueueControlFrame(swf) - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames[0].(*wire.StopWaitingFrame).PacketNumberLen).To(Equal(protocol.PacketNumberLen2)) - }) - - It("does not pack a packet containing only a STOP_WAITING frame", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - swf := &wire.StopWaitingFrame{LeastUnacked: 10} - packer.QueueControlFrame(swf) - p, err := packer.PackPacket() - Expect(p).To(BeNil()) - Expect(err).ToNot(HaveOccurred()) - }) - - It("packs a packet if it has queued control frames, but no new control frames", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - packer.controlFrames = []wire.Frame{&wire.BlockedFrame{}} - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).ToNot(BeNil()) - }) - - It("refuses to send a packet that doesn't contain crypto stream data, if it has never sent a packet before", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - packer.hasSentPacket = false - packer.controlFrames = []wire.Frame{&wire.BlockedFrame{}} - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).To(BeNil()) - }) - - It("packs many control frames into 1 packets", func() { - f := &wire.AckFrame{AckRanges: []wire.AckRange{{Largest: 1, Smallest: 1}}} - b := &bytes.Buffer{} - err := f.Write(b, packer.version) - Expect(err).ToNot(HaveOccurred()) - maxFramesPerPacket := int(maxFrameSize) / b.Len() - var controlFrames []wire.Frame - for i := 0; i < maxFramesPerPacket; i++ { - controlFrames = append(controlFrames, f) - } - packer.controlFrames = controlFrames - payloadFrames, err := packer.composeNextPacket(maxFrameSize, false) - Expect(err).ToNot(HaveOccurred()) - Expect(payloadFrames).To(HaveLen(maxFramesPerPacket)) - payloadFrames, err = packer.composeNextPacket(maxFrameSize, false) - Expect(err).ToNot(HaveOccurred()) - Expect(payloadFrames).To(BeEmpty()) - }) - - It("packs a lot of control frames into 2 packets if they don't fit into one", func() { - blockedFrame := &wire.BlockedFrame{} - maxFramesPerPacket := int(maxFrameSize) / int(blockedFrame.Length(packer.version)) - var controlFrames []wire.Frame - for i := 0; i < maxFramesPerPacket+10; i++ { - controlFrames = append(controlFrames, blockedFrame) - } - packer.controlFrames = controlFrames - payloadFrames, err := packer.composeNextPacket(maxFrameSize, false) - Expect(err).ToNot(HaveOccurred()) - Expect(payloadFrames).To(HaveLen(maxFramesPerPacket)) - payloadFrames, err = packer.composeNextPacket(maxFrameSize, false) - Expect(err).ToNot(HaveOccurred()) - Expect(payloadFrames).To(HaveLen(10)) - }) - - It("only increases the packet number when there is an actual packet to send", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData().Times(2) - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - packer.packetNumberGenerator.nextToSkip = 1000 - p, err := packer.PackPacket() - Expect(p).To(BeNil()) - Expect(err).ToNot(HaveOccurred()) - Expect(packer.packetNumberGenerator.Peek()).To(Equal(protocol.PacketNumber(1))) - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).Return([]*wire.StreamFrame{{ - StreamID: 5, - Data: []byte{0xDE, 0xCA, 0xFB, 0xAD}, - }}) - p, err = packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).ToNot(BeNil()) - Expect(p.header.PacketNumber).To(Equal(protocol.PacketNumber(1))) - Expect(packer.packetNumberGenerator.Peek()).To(Equal(protocol.PacketNumber(2))) - }) - - Context("making ACK packets retransmittable", func() { - sendMaxNumNonRetransmittableAcks := func() { - mockStreamFramer.EXPECT().HasCryptoStreamData().Times(protocol.MaxNonRetransmittableAcks) - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).Times(protocol.MaxNonRetransmittableAcks) - for i := 0; i < protocol.MaxNonRetransmittableAcks; i++ { - packer.QueueControlFrame(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}}) - p, err := packer.PackPacket() - Expect(p).ToNot(BeNil()) - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(HaveLen(1)) - } - } - - It("adds a PING frame when it's supposed to send a retransmittable packet", func() { - sendMaxNumNonRetransmittableAcks() - mockStreamFramer.EXPECT().HasCryptoStreamData().Times(2) - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).Times(2) - packer.QueueControlFrame(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}}) - p, err := packer.PackPacket() - Expect(p).ToNot(BeNil()) - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(ContainElement(&wire.PingFrame{})) - // make sure the next packet doesn't contain another PING - packer.QueueControlFrame(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 2, Largest: 2}}}) - p, err = packer.PackPacket() - Expect(p).ToNot(BeNil()) - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(HaveLen(1)) - }) - - It("waits until there's something to send before adding a PING frame", func() { - sendMaxNumNonRetransmittableAcks() - mockStreamFramer.EXPECT().HasCryptoStreamData().Times(2) - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).Times(2) - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).To(BeNil()) - packer.QueueControlFrame(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}}) - p, err = packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(HaveLen(2)) - Expect(p.frames).To(ContainElement(&wire.PingFrame{})) - }) - - It("doesn't send a PING if it already sent another retransmittable frame", func() { - sendMaxNumNonRetransmittableAcks() - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - packer.QueueControlFrame(&wire.MaxDataFrame{}) - packer.QueueControlFrame(&wire.StopWaitingFrame{}) - p, err := packer.PackPacket() - Expect(p).ToNot(BeNil()) - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(HaveLen(2)) - Expect(p.frames).ToNot(ContainElement(&wire.PingFrame{})) - }) - }) - - Context("STREAM frame handling", func() { - It("does not splits a STREAM frame with maximum size, for gQUIC frames", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData().Times(2) - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).DoAndReturn(func(maxSize protocol.ByteCount) []*wire.StreamFrame { - f := &wire.StreamFrame{ - Offset: 1, - StreamID: 5, - DataLenPresent: true, - } - f.Data = bytes.Repeat([]byte{'f'}, int(maxSize-f.Length(packer.version))) - return []*wire.StreamFrame{f} - }) - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(HaveLen(1)) - Expect(p.raw).To(HaveLen(int(maxPacketSize))) - Expect(p.frames[0].(*wire.StreamFrame).DataLenPresent).To(BeFalse()) - p, err = packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).To(BeNil()) - }) - - It("does not splits a STREAM frame with maximum size, for IETF draft style frame", func() { - packer.version = versionIETFFrames - mockStreamFramer.EXPECT().HasCryptoStreamData().Times(2) - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).DoAndReturn(func(maxSize protocol.ByteCount) []*wire.StreamFrame { - f := &wire.StreamFrame{ - Offset: 1, - StreamID: 5, - DataLenPresent: true, - } - f.Data = bytes.Repeat([]byte{'f'}, int(maxSize-f.Length(packer.version))) - return []*wire.StreamFrame{f} - }) - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(HaveLen(1)) - Expect(p.raw).To(HaveLen(int(maxPacketSize))) - Expect(p.frames[0].(*wire.StreamFrame).DataLenPresent).To(BeFalse()) - p, err = packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).To(BeNil()) - }) - - It("packs multiple small STREAM frames into single packet", func() { - f1 := &wire.StreamFrame{ - StreamID: 5, - Data: []byte("frame 1"), - DataLenPresent: true, - } - f2 := &wire.StreamFrame{ - StreamID: 5, - Data: []byte("frame 2"), - DataLenPresent: true, - } - f3 := &wire.StreamFrame{ - StreamID: 3, - Data: []byte("frame 3"), - DataLenPresent: true, - } - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).Return([]*wire.StreamFrame{f1, f2, f3}) - p, err := packer.PackPacket() - Expect(p).ToNot(BeNil()) - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(HaveLen(3)) - Expect(p.frames[0].(*wire.StreamFrame).Data).To(Equal([]byte("frame 1"))) - Expect(p.frames[1].(*wire.StreamFrame).Data).To(Equal([]byte("frame 2"))) - Expect(p.frames[2].(*wire.StreamFrame).Data).To(Equal([]byte("frame 3"))) - Expect(p.frames[0].(*wire.StreamFrame).DataLenPresent).To(BeTrue()) - Expect(p.frames[1].(*wire.StreamFrame).DataLenPresent).To(BeTrue()) - Expect(p.frames[2].(*wire.StreamFrame).DataLenPresent).To(BeFalse()) - }) - - It("refuses to send unencrypted stream data on a data stream", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - // don't expect a call to mockStreamFramer.PopStreamFrames - packer.cryptoSetup.(*mockCryptoSetup).encLevelSeal = protocol.EncryptionUnencrypted - p, err := packer.PackPacket() - Expect(err).NotTo(HaveOccurred()) - Expect(p).To(BeNil()) - }) - - It("sends non forward-secure data as the client", func() { - f := &wire.StreamFrame{ - StreamID: 5, - Data: []byte("foobar"), - } - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).Return([]*wire.StreamFrame{f}) - packer.perspective = protocol.PerspectiveClient - packer.cryptoSetup.(*mockCryptoSetup).encLevelSeal = protocol.EncryptionSecure - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.encryptionLevel).To(Equal(protocol.EncryptionSecure)) - Expect(p.frames).To(Equal([]wire.Frame{f})) - }) - - It("does not send non forward-secure data as the server", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - // don't expect a call to mockStreamFramer.PopStreamFrames - packer.cryptoSetup.(*mockCryptoSetup).encLevelSeal = protocol.EncryptionSecure - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p).To(BeNil()) - }) - - It("packs a maximum size crypto packet", func() { - var f *wire.StreamFrame - packer.version = versionIETFFrames - mockStreamFramer.EXPECT().HasCryptoStreamData().Return(true) - mockStreamFramer.EXPECT().PopCryptoStreamFrame(gomock.Any()).DoAndReturn(func(size protocol.ByteCount) *wire.StreamFrame { - f = &wire.StreamFrame{ - StreamID: packer.version.CryptoStreamID(), - Offset: 0x1337, - } - f.Data = bytes.Repeat([]byte{'f'}, int(size-f.Length(packer.version))) - return f - }) - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(HaveLen(1)) - expectedPacketLen := packer.maxPacketSize - protocol.NonForwardSecurePacketSizeReduction - Expect(p.raw).To(HaveLen(int(expectedPacketLen))) - Expect(p.header.IsLongHeader).To(BeTrue()) - checkPayloadLen(p.raw) - }) - - It("sends unencrypted stream data on the crypto stream", func() { - f := &wire.StreamFrame{ - StreamID: packer.version.CryptoStreamID(), - Data: []byte("foobar"), - } - mockStreamFramer.EXPECT().HasCryptoStreamData().Return(true) - mockStreamFramer.EXPECT().PopCryptoStreamFrame(gomock.Any()).Return(f) - packer.cryptoSetup.(*mockCryptoSetup).encLevelSealCrypto = protocol.EncryptionUnencrypted - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(Equal([]wire.Frame{f})) - Expect(p.encryptionLevel).To(Equal(protocol.EncryptionUnencrypted)) - }) - - It("sends encrypted stream data on the crypto stream", func() { - f := &wire.StreamFrame{ - StreamID: packer.version.CryptoStreamID(), - Data: []byte("foobar"), - } - mockStreamFramer.EXPECT().HasCryptoStreamData().Return(true) - mockStreamFramer.EXPECT().PopCryptoStreamFrame(gomock.Any()).Return(f) - packer.cryptoSetup.(*mockCryptoSetup).encLevelSealCrypto = protocol.EncryptionSecure - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(Equal([]wire.Frame{f})) - Expect(p.encryptionLevel).To(Equal(protocol.EncryptionSecure)) - }) - - It("does not pack STREAM frames if not allowed", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - // don't expect a call to mockStreamFramer.PopStreamFrames - packer.cryptoSetup.(*mockCryptoSetup).encLevelSeal = protocol.EncryptionUnencrypted - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Largest: 10, Smallest: 1}}} - packer.QueueControlFrame(ack) - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.frames).To(Equal([]wire.Frame{ack})) - }) - }) - - It("packs a single ACK", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Largest: 42, Smallest: 1}}} - packer.QueueControlFrame(ack) - p, err := packer.PackPacket() - Expect(err).NotTo(HaveOccurred()) - Expect(p).ToNot(BeNil()) - Expect(p.frames[0]).To(Equal(ack)) - }) - - It("does not return nil if we only have a single ACK but request it to be sent", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()) - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 1}}} - packer.QueueControlFrame(ack) - p, err := packer.PackPacket() - Expect(err).NotTo(HaveOccurred()) - Expect(p).ToNot(BeNil()) - }) - - Context("retransmitting of handshake packets", func() { - swf := &wire.StopWaitingFrame{LeastUnacked: 1} - sf := &wire.StreamFrame{ - StreamID: 1, - Data: []byte("foobar"), - } - - BeforeEach(func() { - packer.QueueControlFrame(swf) - }) - - It("packs a retransmission for a packet sent with no encryption", func() { - packet := &ackhandler.Packet{ - PacketType: protocol.PacketTypeHandshake, - EncryptionLevel: protocol.EncryptionUnencrypted, - Frames: []wire.Frame{sf}, - } - p, err := packer.PackRetransmission(packet) - Expect(err).ToNot(HaveOccurred()) - Expect(p).To(HaveLen(1)) - Expect(p[0].header.Type).To(Equal(protocol.PacketTypeHandshake)) - Expect(p[0].frames).To(Equal([]wire.Frame{swf, sf})) - Expect(p[0].encryptionLevel).To(Equal(protocol.EncryptionUnencrypted)) - }) - - It("doesn't add a STOP_WAITING frame for IETF QUIC", func() { - packer.version = versionIETFFrames - packet := &ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionUnencrypted, - Frames: []wire.Frame{sf}, - } - p, err := packer.PackRetransmission(packet) - Expect(err).ToNot(HaveOccurred()) - Expect(p).To(HaveLen(1)) - Expect(p[0].frames).To(Equal([]wire.Frame{sf})) - Expect(p[0].encryptionLevel).To(Equal(protocol.EncryptionUnencrypted)) - }) - - It("packs a retransmission for a packet sent with initial encryption", func() { - packet := &ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionSecure, - Frames: []wire.Frame{sf}, - } - p, err := packer.PackRetransmission(packet) - Expect(err).ToNot(HaveOccurred()) - Expect(p).To(HaveLen(1)) - Expect(p[0].frames).To(Equal([]wire.Frame{swf, sf})) - Expect(p[0].encryptionLevel).To(Equal(protocol.EncryptionSecure)) - // a packet sent by the server with initial encryption contains the SHLO - // it needs to have a diversification nonce - Expect(p[0].raw).To(ContainSubstring(string(divNonce))) - }) - - It("includes the diversification nonce on packets sent with initial encryption", func() { - packet := &ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionSecure, - Frames: []wire.Frame{sf}, - } - p, err := packer.PackRetransmission(packet) - Expect(err).ToNot(HaveOccurred()) - Expect(p).To(HaveLen(1)) - Expect(p[0].encryptionLevel).To(Equal(protocol.EncryptionSecure)) - }) - - // this should never happen, since non forward-secure packets are limited to a size smaller than MaxPacketSize, such that it is always possible to retransmit them without splitting the StreamFrame - // (note that the retransmitted packet needs to have enough space for the StopWaitingFrame) - It("refuses to send a packet larger than MaxPacketSize", func() { - packet := &ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionSecure, - Frames: []wire.Frame{ - &wire.StreamFrame{ - StreamID: 1, - Data: bytes.Repeat([]byte{'f'}, int(maxPacketSize-5)), - }, - }, - } - _, err := packer.PackRetransmission(packet) - Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("PacketPacker BUG: packet too large")) - }) - - It("pads Initial packets to the required minimum packet size", func() { - f := &wire.StreamFrame{ - StreamID: packer.version.CryptoStreamID(), - Data: []byte("foobar"), - } - mockStreamFramer.EXPECT().HasCryptoStreamData().Return(true) - mockStreamFramer.EXPECT().PopCryptoStreamFrame(gomock.Any()).Return(f) - packer.version = protocol.VersionTLS - packer.hasSentPacket = false - packer.perspective = protocol.PerspectiveClient - packer.cryptoSetup.(*mockCryptoSetup).encLevelSealCrypto = protocol.EncryptionUnencrypted - packet, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(packet.header.Token).To(Equal(token)) - Expect(packet.raw).To(HaveLen(protocol.MinInitialPacketSize)) - Expect(packet.frames).To(HaveLen(1)) - sf := packet.frames[0].(*wire.StreamFrame) - Expect(sf.Data).To(Equal([]byte("foobar"))) - Expect(sf.DataLenPresent).To(BeTrue()) - }) - - It("set the correct payload length for an Initial packet", func() { - mockStreamFramer.EXPECT().HasCryptoStreamData().Return(true) - mockStreamFramer.EXPECT().PopCryptoStreamFrame(gomock.Any()).Return(&wire.StreamFrame{ - StreamID: packer.version.CryptoStreamID(), - Data: []byte("foobar"), - }) - packer.version = protocol.VersionTLS - packer.hasSentPacket = false - packer.perspective = protocol.PerspectiveClient - packer.cryptoSetup.(*mockCryptoSetup).encLevelSealCrypto = protocol.EncryptionUnencrypted - packet, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - checkPayloadLen(packet.raw) - }) - - It("packs a retransmission for an Initial packet", func() { - packer.version = versionIETFFrames - packer.perspective = protocol.PerspectiveClient - packet := &ackhandler.Packet{ - PacketType: protocol.PacketTypeInitial, - EncryptionLevel: protocol.EncryptionUnencrypted, - Frames: []wire.Frame{sf}, - } - p, err := packer.PackRetransmission(packet) - Expect(err).ToNot(HaveOccurred()) - Expect(p).To(HaveLen(1)) - Expect(p[0].frames).To(Equal([]wire.Frame{sf})) - Expect(p[0].encryptionLevel).To(Equal(protocol.EncryptionUnencrypted)) - Expect(p[0].header.Type).To(Equal(protocol.PacketTypeInitial)) - Expect(p[0].header.Token).To(Equal(token)) - }) - - It("refuses to retransmit packets without a STOP_WAITING Frame", func() { - packer.stopWaiting = nil - _, err := packer.PackRetransmission(&ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionSecure, - }) - Expect(err).To(MatchError("PacketPacker BUG: Handshake retransmissions must contain a STOP_WAITING frame")) - }) - }) - - Context("retransmission of forward-secure packets", func() { - BeforeEach(func() { - packer.packetNumberGenerator.next = 15 - packer.stopWaiting = &wire.StopWaitingFrame{LeastUnacked: 7} - }) - - It("retransmits a small packet", func() { - frames := []wire.Frame{ - &wire.MaxDataFrame{ByteOffset: 0x1234}, - &wire.StreamFrame{StreamID: 42, Data: []byte("foobar")}, - } - packets, err := packer.PackRetransmission(&ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionForwardSecure, - Frames: frames, - }) - Expect(err).ToNot(HaveOccurred()) - Expect(packets).To(HaveLen(1)) - p := packets[0] - Expect(p.encryptionLevel).To(Equal(protocol.EncryptionForwardSecure)) - Expect(p.frames).To(HaveLen(3)) - Expect(p.frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{})) - Expect(p.frames[0].(*wire.StopWaitingFrame).LeastUnacked).To(Equal(protocol.PacketNumber(7))) - Expect(p.frames[0].(*wire.StopWaitingFrame).PacketNumber).To(Equal(p.header.PacketNumber)) - Expect(p.frames[0].(*wire.StopWaitingFrame).PacketNumberLen).To(Equal(p.header.PacketNumberLen)) - Expect(p.frames[1:]).To(Equal(frames)) - }) - - It("refuses to retransmit packets without a STOP_WAITING Frame", func() { - packer.stopWaiting = nil - _, err := packer.PackRetransmission(&ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionForwardSecure, - Frames: []wire.Frame{&wire.MaxDataFrame{ByteOffset: 0x1234}}, - }) - Expect(err).To(MatchError("PacketPacker BUG: Handshake retransmissions must contain a STOP_WAITING frame")) - }) - - It("packs two packets for retransmission if the original packet contained many control frames", func() { - var frames []wire.Frame - var totalLen protocol.ByteCount - // pack a bunch of control frames, such that the packet is way bigger than a single packet - for i := 0; totalLen < maxPacketSize*3/2; i++ { - f := &wire.MaxStreamDataFrame{StreamID: protocol.StreamID(i), ByteOffset: protocol.ByteCount(i)} - frames = append(frames, f) - totalLen += f.Length(packer.version) - } - packets, err := packer.PackRetransmission(&ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionForwardSecure, - Frames: frames, - }) - Expect(err).ToNot(HaveOccurred()) - Expect(packets).To(HaveLen(2)) - Expect(len(packets[0].frames) + len(packets[1].frames)).To(Equal(len(frames) + 2)) // all frames, plus 2 STOP_WAITING frames - Expect(packets[0].frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{})) - Expect(packets[1].frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{})) - Expect(packets[0].frames[1:]).To(Equal(frames[:len(packets[0].frames)-1])) - Expect(packets[1].frames[1:]).To(Equal(frames[len(packets[0].frames)-1:])) - // check that the first packet was filled up as far as possible: - // if the first frame (after the STOP_WAITING) was packed into the first packet, it would have overflown the MaxPacketSize - Expect(len(packets[0].raw) + int(packets[1].frames[1].Length(packer.version))).To(BeNumerically(">", maxPacketSize)) - }) - - It("splits a STREAM frame that doesn't fit", func() { - packets, err := packer.PackRetransmission(&ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionForwardSecure, - Frames: []wire.Frame{&wire.StreamFrame{ - StreamID: 42, - Offset: 1337, - Data: bytes.Repeat([]byte{'a'}, int(maxPacketSize)*3/2), - }}, - }) - Expect(err).ToNot(HaveOccurred()) - Expect(packets).To(HaveLen(2)) - Expect(packets[0].frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{})) - Expect(packets[1].frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{})) - Expect(packets[0].frames[1]).To(BeAssignableToTypeOf(&wire.StreamFrame{})) - Expect(packets[1].frames[1]).To(BeAssignableToTypeOf(&wire.StreamFrame{})) - sf1 := packets[0].frames[1].(*wire.StreamFrame) - sf2 := packets[1].frames[1].(*wire.StreamFrame) - Expect(sf1.StreamID).To(Equal(protocol.StreamID(42))) - Expect(sf1.Offset).To(Equal(protocol.ByteCount(1337))) - Expect(sf1.DataLenPresent).To(BeFalse()) - Expect(sf2.StreamID).To(Equal(protocol.StreamID(42))) - Expect(sf2.Offset).To(Equal(protocol.ByteCount(1337) + sf1.DataLen())) - Expect(sf2.DataLenPresent).To(BeFalse()) - Expect(sf1.DataLen() + sf2.DataLen()).To(Equal(maxPacketSize * 3 / 2)) - Expect(packets[0].raw).To(HaveLen(int(maxPacketSize))) - }) - - It("packs two packets for retransmission if the original packet contained many STREAM frames", func() { - var frames []wire.Frame - var totalLen protocol.ByteCount - // pack a bunch of control frames, such that the packet is way bigger than a single packet - for i := 0; totalLen < maxPacketSize*3/2; i++ { - f := &wire.StreamFrame{ - StreamID: protocol.StreamID(i), - Data: []byte("foobar"), - DataLenPresent: true, - } - frames = append(frames, f) - totalLen += f.Length(packer.version) - } - packets, err := packer.PackRetransmission(&ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionForwardSecure, - Frames: frames, - }) - Expect(err).ToNot(HaveOccurred()) - Expect(packets).To(HaveLen(2)) - Expect(len(packets[0].frames) + len(packets[1].frames)).To(Equal(len(frames) + 2)) // all frames, plus 2 STOP_WAITING frames - Expect(packets[0].frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{})) - Expect(packets[1].frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{})) - Expect(packets[0].frames[1:]).To(Equal(frames[:len(packets[0].frames)-1])) - Expect(packets[1].frames[1:]).To(Equal(frames[len(packets[0].frames)-1:])) - // check that the first packet was filled up as far as possible: - // if the first frame (after the STOP_WAITING) was packed into the first packet, it would have overflown the MaxPacketSize - Expect(len(packets[0].raw) + int(packets[1].frames[1].Length(packer.version))).To(BeNumerically(">", maxPacketSize-protocol.MinStreamFrameSize)) - }) - - It("correctly sets the DataLenPresent on STREAM frames", func() { - frames := []wire.Frame{ - &wire.StreamFrame{StreamID: 4, Data: []byte("foobar"), DataLenPresent: true}, - &wire.StreamFrame{StreamID: 5, Data: []byte("barfoo")}, - } - packets, err := packer.PackRetransmission(&ackhandler.Packet{ - EncryptionLevel: protocol.EncryptionForwardSecure, - Frames: frames, - }) - Expect(err).ToNot(HaveOccurred()) - Expect(packets).To(HaveLen(1)) - p := packets[0] - Expect(p.frames).To(HaveLen(3)) - Expect(p.frames[1]).To(BeAssignableToTypeOf(&wire.StreamFrame{})) - Expect(p.frames[2]).To(BeAssignableToTypeOf(&wire.StreamFrame{})) - sf1 := p.frames[1].(*wire.StreamFrame) - sf2 := p.frames[2].(*wire.StreamFrame) - Expect(sf1.StreamID).To(Equal(protocol.StreamID(4))) - Expect(sf1.DataLenPresent).To(BeTrue()) - Expect(sf2.StreamID).To(Equal(protocol.StreamID(5))) - Expect(sf2.DataLenPresent).To(BeFalse()) - }) - }) - - Context("packing ACK packets", func() { - It("packs ACK packets", func() { - packer.QueueControlFrame(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}) - p, err := packer.PackAckPacket() - Expect(err).NotTo(HaveOccurred()) - Expect(p.frames).To(HaveLen(1)) - Expect(p.frames[0]).To(BeAssignableToTypeOf(&wire.AckFrame{})) - ack := p.frames[0].(*wire.AckFrame) - Expect(ack.LargestAcked()).To(Equal(protocol.PacketNumber(10))) - }) - - It("packs ACK packets with STOP_WAITING frames", func() { - packer.QueueControlFrame(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 10}}}) - packer.QueueControlFrame(&wire.StopWaitingFrame{}) - p, err := packer.PackAckPacket() - Expect(err).NotTo(HaveOccurred()) - Expect(p.frames).To(HaveLen(2)) - Expect(p.frames[0]).To(BeAssignableToTypeOf(&wire.AckFrame{})) - Expect(p.frames[1]).To(Equal(&wire.StopWaitingFrame{PacketNumber: 1, PacketNumberLen: 2})) - }) - }) - - Context("max packet size", func() { - It("sets the maximum packet size", func() { - for i := 0; i < 10*int(maxPacketSize); i++ { - packer.QueueControlFrame(&wire.PingFrame{}) - } - mockStreamFramer.EXPECT().HasCryptoStreamData().AnyTimes() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).AnyTimes() - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.raw).To(HaveLen(int(maxPacketSize))) - // now reduce the maxPacketSize - packer.SetMaxPacketSize(maxPacketSize - 10) - p, err = packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.raw).To(HaveLen(int(maxPacketSize) - 10)) - }) - - It("doesn't increase the max packet size", func() { - for i := 0; i < 10*int(maxPacketSize); i++ { - packer.QueueControlFrame(&wire.PingFrame{}) - } - mockStreamFramer.EXPECT().HasCryptoStreamData().AnyTimes() - mockStreamFramer.EXPECT().PopStreamFrames(gomock.Any()).AnyTimes() - p, err := packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.raw).To(HaveLen(int(maxPacketSize))) - // now try to increase the maxPacketSize - packer.SetMaxPacketSize(maxPacketSize + 10) - p, err = packer.PackPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(p.raw).To(HaveLen(int(maxPacketSize))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/packet_unpacker_test.go b/vendor/lucas-clemente/quic-go/packet_unpacker_test.go deleted file mode 100644 index 1ed5b8408..000000000 --- a/vendor/lucas-clemente/quic-go/packet_unpacker_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package quic - -import ( - "bytes" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - "github.com/lucas-clemente/quic-go/qerr" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Packet Unpacker (for gQUIC)", func() { - var ( - unpacker *packetUnpackerGQUIC - hdr *wire.Header - aead *MockGQUICAEAD - ) - - BeforeEach(func() { - aead = NewMockGQUICAEAD(mockCtrl) - hdr = &wire.Header{ - PacketNumber: 10, - PacketNumberLen: 1, - Raw: []byte{0x04, 0x4c, 0x01}, - } - unpacker = newPacketUnpackerGQUIC(aead, versionGQUICFrames).(*packetUnpackerGQUIC) - }) - - It("errors if the packet doesn't contain any payload", func() { - data := []byte("foobar") - aead.EXPECT().Open(gomock.Any(), []byte("foobar"), hdr.PacketNumber, hdr.Raw).Return([]byte{}, protocol.EncryptionForwardSecure, nil) - _, err := unpacker.Unpack(hdr.Raw, hdr, data) - Expect(err).To(MatchError(qerr.MissingPayload)) - }) - - It("saves the encryption level", func() { - aead.EXPECT().Open(gomock.Any(), gomock.Any(), hdr.PacketNumber, hdr.Raw).Return([]byte{0}, protocol.EncryptionSecure, nil) - packet, err := unpacker.Unpack(hdr.Raw, hdr, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(packet.encryptionLevel).To(Equal(protocol.EncryptionSecure)) - }) - - It("unpacks the frames", func() { - buf := &bytes.Buffer{} - (&wire.PingFrame{}).Write(buf, versionGQUICFrames) - (&wire.BlockedFrame{}).Write(buf, versionGQUICFrames) - aead.EXPECT().Open(gomock.Any(), gomock.Any(), hdr.PacketNumber, hdr.Raw).Return(buf.Bytes(), protocol.EncryptionForwardSecure, nil) - packet, err := unpacker.Unpack(hdr.Raw, hdr, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(packet.frames).To(Equal([]wire.Frame{&wire.PingFrame{}, &wire.BlockedFrame{}})) - }) -}) - -var _ = Describe("Packet Unpacker (for IETF QUIC)", func() { - var ( - unpacker *packetUnpacker - hdr *wire.Header - aead *MockQuicAEAD - ) - - BeforeEach(func() { - aead = NewMockQuicAEAD(mockCtrl) - hdr = &wire.Header{ - PacketNumber: 10, - PacketNumberLen: 1, - Raw: []byte{0x04, 0x4c, 0x01}, - } - unpacker = newPacketUnpacker(aead, versionIETFFrames).(*packetUnpacker) - }) - - It("errors if the packet doesn't contain any payload", func() { - data := []byte("foobar") - aead.EXPECT().Open1RTT(gomock.Any(), []byte("foobar"), hdr.PacketNumber, hdr.Raw).Return([]byte{}, nil) - _, err := unpacker.Unpack(hdr.Raw, hdr, data) - Expect(err).To(MatchError(qerr.MissingPayload)) - }) - - It("opens handshake packets", func() { - hdr.IsLongHeader = true - aead.EXPECT().OpenHandshake(gomock.Any(), gomock.Any(), hdr.PacketNumber, hdr.Raw).Return([]byte{0}, nil) - packet, err := unpacker.Unpack(hdr.Raw, hdr, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(packet.encryptionLevel).To(Equal(protocol.EncryptionUnencrypted)) - }) - - It("unpacks the frames", func() { - buf := &bytes.Buffer{} - (&wire.PingFrame{}).Write(buf, versionIETFFrames) - (&wire.BlockedFrame{}).Write(buf, versionIETFFrames) - aead.EXPECT().Open1RTT(gomock.Any(), gomock.Any(), hdr.PacketNumber, hdr.Raw).Return(buf.Bytes(), nil) - packet, err := unpacker.Unpack(hdr.Raw, hdr, nil) - Expect(err).ToNot(HaveOccurred()) - Expect(packet.frames).To(Equal([]wire.Frame{&wire.PingFrame{}, &wire.BlockedFrame{}})) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/qerr/errorcodes_test.go b/vendor/lucas-clemente/quic-go/qerr/errorcodes_test.go deleted file mode 100644 index f8cde2246..000000000 --- a/vendor/lucas-clemente/quic-go/qerr/errorcodes_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package qerr - -import ( - "go/ast" - "go/parser" - "go/token" - "path" - "runtime" - "strconv" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("error codes", func() { - // If this test breaks, you should run `go generate ./...` - It("has a string representation for every error code", func() { - // We parse the error code file, extract all constants, and verify that - // each of them has a string version. Go FTW! - _, thisfile, _, ok := runtime.Caller(0) - if !ok { - panic("Failed to get current frame") - } - filename := path.Join(path.Dir(thisfile), "error_codes.go") - fileAst, err := parser.ParseFile(token.NewFileSet(), filename, nil, 0) - Expect(err).NotTo(HaveOccurred()) - constSpecs := fileAst.Decls[0].(*ast.GenDecl).Specs - Expect(len(constSpecs)).To(BeNumerically(">", 4)) // at time of writing - for _, c := range constSpecs { - name := c.(*ast.ValueSpec).Names[0].Name - valString := c.(*ast.ValueSpec).Values[0].(*ast.BasicLit).Value - val, err := strconv.Atoi(valString) - Expect(err).NotTo(HaveOccurred()) - Expect(ErrorCode(val).String()).To(Equal(name)) - } - Expect(ErrorCode(0).String()).To(Equal("ErrorCode(0)")) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/qerr/errors_suite_test.go b/vendor/lucas-clemente/quic-go/qerr/errors_suite_test.go deleted file mode 100644 index 749cdedcf..000000000 --- a/vendor/lucas-clemente/quic-go/qerr/errors_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package qerr - -import ( - "testing" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -func TestErrorcodes(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Errors Suite") -} diff --git a/vendor/lucas-clemente/quic-go/qerr/quic_error_test.go b/vendor/lucas-clemente/quic-go/qerr/quic_error_test.go deleted file mode 100644 index 58d48feb3..000000000 --- a/vendor/lucas-clemente/quic-go/qerr/quic_error_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package qerr - -import ( - "io" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Quic error", func() { - Context("QuicError", func() { - It("has a string representation", func() { - err := Error(DecryptionFailure, "foobar") - Expect(err.Error()).To(Equal("DecryptionFailure: foobar")) - }) - }) - - Context("ErrorCode", func() { - It("works as error", func() { - var err error = DecryptionFailure - Expect(err).To(MatchError("DecryptionFailure")) - }) - }) - - Context("TimeoutError", func() { - It("works as timeout error", func() { - err := Error(HandshakeTimeout, "handshake timeout") - Expect(err.Timeout()).Should(BeTrue()) - }) - }) - - Context("ToQuicError", func() { - It("leaves QuicError unchanged", func() { - err := Error(DecryptionFailure, "foo") - Expect(ToQuicError(err)).To(Equal(err)) - }) - - It("wraps ErrorCode properly", func() { - var err error = DecryptionFailure - Expect(ToQuicError(err)).To(Equal(Error(DecryptionFailure, ""))) - }) - - It("changes default errors to InternalError", func() { - Expect(ToQuicError(io.EOF)).To(Equal(Error(InternalError, "EOF"))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/quic_suite_test.go b/vendor/lucas-clemente/quic-go/quic_suite_test.go deleted file mode 100644 index fefe277f9..000000000 --- a/vendor/lucas-clemente/quic-go/quic_suite_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package quic - -import ( - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/protocol" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestQuicGo(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "QUIC Suite") -} - -const ( - versionGQUICFrames = protocol.Version39 - versionIETFFrames = protocol.VersionTLS -) - -var mockCtrl *gomock.Controller - -var _ = BeforeSuite(func() { - Expect(versionGQUICFrames.CryptoStreamID()).To(Equal(protocol.StreamID(1))) - Expect(versionGQUICFrames.UsesIETFFrameFormat()).To(BeFalse()) - Expect(versionIETFFrames.CryptoStreamID()).To(Equal(protocol.StreamID(0))) - Expect(versionIETFFrames.UsesIETFFrameFormat()).To(BeTrue()) -}) - -var _ = BeforeEach(func() { - mockCtrl = gomock.NewController(GinkgoT()) -}) - -var _ = AfterEach(func() { - mockCtrl.Finish() -}) diff --git a/vendor/lucas-clemente/quic-go/receive_stream_test.go b/vendor/lucas-clemente/quic-go/receive_stream_test.go deleted file mode 100644 index 1b3f5c35b..000000000 --- a/vendor/lucas-clemente/quic-go/receive_stream_test.go +++ /dev/null @@ -1,630 +0,0 @@ -package quic - -import ( - "errors" - "io" - "runtime" - "time" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/mocks" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" -) - -var _ = Describe("Receive Stream", func() { - const streamID protocol.StreamID = 1337 - - var ( - str *receiveStream - strWithTimeout io.Reader // str wrapped with gbytes.TimeoutReader - mockFC *mocks.MockStreamFlowController - mockSender *MockStreamSender - ) - - BeforeEach(func() { - mockSender = NewMockStreamSender(mockCtrl) - mockFC = mocks.NewMockStreamFlowController(mockCtrl) - str = newReceiveStream(streamID, mockSender, mockFC, versionIETFFrames) - - timeout := scaleDuration(250 * time.Millisecond) - strWithTimeout = gbytes.TimeoutReader(str, timeout) - }) - - It("gets stream id", func() { - Expect(str.StreamID()).To(Equal(protocol.StreamID(1337))) - }) - - Context("reading", func() { - It("reads a single STREAM frame", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(4), false) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(4)) - mockFC.EXPECT().MaybeQueueWindowUpdate() - frame := wire.StreamFrame{ - Offset: 0, - Data: []byte{0xDE, 0xAD, 0xBE, 0xEF}, - } - err := str.handleStreamFrame(&frame) - Expect(err).ToNot(HaveOccurred()) - b := make([]byte, 4) - n, err := strWithTimeout.Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(4)) - Expect(b).To(Equal([]byte{0xDE, 0xAD, 0xBE, 0xEF})) - }) - - It("reads a single STREAM frame in multiple goes", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(4), false) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)) - mockFC.EXPECT().MaybeQueueWindowUpdate().Times(2) - frame := wire.StreamFrame{ - Offset: 0, - Data: []byte{0xDE, 0xAD, 0xBE, 0xEF}, - } - err := str.handleStreamFrame(&frame) - Expect(err).ToNot(HaveOccurred()) - b := make([]byte, 2) - n, err := strWithTimeout.Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(2)) - Expect(b).To(Equal([]byte{0xDE, 0xAD})) - n, err = strWithTimeout.Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(2)) - Expect(b).To(Equal([]byte{0xBE, 0xEF})) - }) - - It("reads all data available", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(2), false) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(4), false) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)).Times(2) - mockFC.EXPECT().MaybeQueueWindowUpdate().Times(2) - frame1 := wire.StreamFrame{ - Offset: 0, - Data: []byte{0xDE, 0xAD}, - } - frame2 := wire.StreamFrame{ - Offset: 2, - Data: []byte{0xBE, 0xEF}, - } - err := str.handleStreamFrame(&frame1) - Expect(err).ToNot(HaveOccurred()) - err = str.handleStreamFrame(&frame2) - Expect(err).ToNot(HaveOccurred()) - b := make([]byte, 6) - n, err := strWithTimeout.Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(4)) - Expect(b).To(Equal([]byte{0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x00})) - }) - - It("assembles multiple STREAM frames", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(2), false) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(4), false) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)).Times(2) - mockFC.EXPECT().MaybeQueueWindowUpdate().Times(2) - frame1 := wire.StreamFrame{ - Offset: 0, - Data: []byte{0xDE, 0xAD}, - } - frame2 := wire.StreamFrame{ - Offset: 2, - Data: []byte{0xBE, 0xEF}, - } - err := str.handleStreamFrame(&frame1) - Expect(err).ToNot(HaveOccurred()) - err = str.handleStreamFrame(&frame2) - Expect(err).ToNot(HaveOccurred()) - b := make([]byte, 4) - n, err := strWithTimeout.Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(4)) - Expect(b).To(Equal([]byte{0xDE, 0xAD, 0xBE, 0xEF})) - }) - - It("waits until data is available", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(2), false) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)) - mockFC.EXPECT().MaybeQueueWindowUpdate() - go func() { - defer GinkgoRecover() - frame := wire.StreamFrame{Data: []byte{0xDE, 0xAD}} - time.Sleep(10 * time.Millisecond) - err := str.handleStreamFrame(&frame) - Expect(err).ToNot(HaveOccurred()) - }() - b := make([]byte, 2) - n, err := strWithTimeout.Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(2)) - }) - - It("handles STREAM frames in wrong order", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(2), false) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(4), false) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)).Times(2) - mockFC.EXPECT().MaybeQueueWindowUpdate().Times(2) - frame1 := wire.StreamFrame{ - Offset: 2, - Data: []byte{0xBE, 0xEF}, - } - frame2 := wire.StreamFrame{ - Offset: 0, - Data: []byte{0xDE, 0xAD}, - } - err := str.handleStreamFrame(&frame1) - Expect(err).ToNot(HaveOccurred()) - err = str.handleStreamFrame(&frame2) - Expect(err).ToNot(HaveOccurred()) - b := make([]byte, 4) - n, err := strWithTimeout.Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(4)) - Expect(b).To(Equal([]byte{0xDE, 0xAD, 0xBE, 0xEF})) - }) - - It("ignores duplicate STREAM frames", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(2), false) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(2), false) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(4), false) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)).Times(2) - mockFC.EXPECT().MaybeQueueWindowUpdate().Times(2) - frame1 := wire.StreamFrame{ - Offset: 0, - Data: []byte{0xDE, 0xAD}, - } - frame2 := wire.StreamFrame{ - Offset: 0, - Data: []byte{0x13, 0x37}, - } - frame3 := wire.StreamFrame{ - Offset: 2, - Data: []byte{0xBE, 0xEF}, - } - err := str.handleStreamFrame(&frame1) - Expect(err).ToNot(HaveOccurred()) - err = str.handleStreamFrame(&frame2) - Expect(err).ToNot(HaveOccurred()) - err = str.handleStreamFrame(&frame3) - Expect(err).ToNot(HaveOccurred()) - b := make([]byte, 4) - n, err := strWithTimeout.Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(4)) - Expect(b).To(Equal([]byte{0xDE, 0xAD, 0xBE, 0xEF})) - }) - - It("doesn't rejects a STREAM frames with an overlapping data range", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(4), false) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(6), false) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(4)) - mockFC.EXPECT().MaybeQueueWindowUpdate().Times(2) - frame1 := wire.StreamFrame{ - Offset: 0, - Data: []byte("foob"), - } - frame2 := wire.StreamFrame{ - Offset: 2, - Data: []byte("obar"), - } - err := str.handleStreamFrame(&frame1) - Expect(err).ToNot(HaveOccurred()) - err = str.handleStreamFrame(&frame2) - Expect(err).ToNot(HaveOccurred()) - b := make([]byte, 6) - n, err := strWithTimeout.Read(b) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(6)) - Expect(b).To(Equal([]byte("foobar"))) - }) - - Context("deadlines", func() { - It("the deadline error has the right net.Error properties", func() { - Expect(errDeadline.Temporary()).To(BeTrue()) - Expect(errDeadline.Timeout()).To(BeTrue()) - Expect(errDeadline).To(MatchError("deadline exceeded")) - }) - - It("returns an error when Read is called after the deadline", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(6), false).AnyTimes() - f := &wire.StreamFrame{Data: []byte("foobar")} - err := str.handleStreamFrame(f) - Expect(err).ToNot(HaveOccurred()) - str.SetReadDeadline(time.Now().Add(-time.Second)) - b := make([]byte, 6) - n, err := strWithTimeout.Read(b) - Expect(err).To(MatchError(errDeadline)) - Expect(n).To(BeZero()) - }) - - It("unblocks after the deadline", func() { - deadline := time.Now().Add(scaleDuration(50 * time.Millisecond)) - str.SetReadDeadline(deadline) - b := make([]byte, 6) - n, err := strWithTimeout.Read(b) - Expect(err).To(MatchError(errDeadline)) - Expect(n).To(BeZero()) - Expect(time.Now()).To(BeTemporally("~", deadline, scaleDuration(10*time.Millisecond))) - }) - - It("doesn't unblock if the deadline is changed before the first one expires", func() { - deadline1 := time.Now().Add(scaleDuration(50 * time.Millisecond)) - deadline2 := time.Now().Add(scaleDuration(100 * time.Millisecond)) - str.SetReadDeadline(deadline1) - go func() { - defer GinkgoRecover() - time.Sleep(scaleDuration(20 * time.Millisecond)) - str.SetReadDeadline(deadline2) - // make sure that this was actually execute before the deadline expires - Expect(time.Now()).To(BeTemporally("<", deadline1)) - }() - runtime.Gosched() - b := make([]byte, 10) - n, err := strWithTimeout.Read(b) - Expect(err).To(MatchError(errDeadline)) - Expect(n).To(BeZero()) - Expect(time.Now()).To(BeTemporally("~", deadline2, scaleDuration(20*time.Millisecond))) - }) - - It("unblocks earlier, when a new deadline is set", func() { - deadline1 := time.Now().Add(scaleDuration(200 * time.Millisecond)) - deadline2 := time.Now().Add(scaleDuration(50 * time.Millisecond)) - go func() { - defer GinkgoRecover() - time.Sleep(scaleDuration(10 * time.Millisecond)) - str.SetReadDeadline(deadline2) - // make sure that this was actually execute before the deadline expires - Expect(time.Now()).To(BeTemporally("<", deadline2)) - }() - str.SetReadDeadline(deadline1) - runtime.Gosched() - b := make([]byte, 10) - _, err := strWithTimeout.Read(b) - Expect(err).To(MatchError(errDeadline)) - Expect(time.Now()).To(BeTemporally("~", deadline2, scaleDuration(25*time.Millisecond))) - }) - }) - - Context("closing", func() { - Context("with FIN bit", func() { - It("returns EOFs", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(4), true) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(4)) - mockFC.EXPECT().MaybeQueueWindowUpdate() - str.handleStreamFrame(&wire.StreamFrame{ - Offset: 0, - Data: []byte{0xDE, 0xAD, 0xBE, 0xEF}, - FinBit: true, - }) - mockSender.EXPECT().onStreamCompleted(streamID) - b := make([]byte, 4) - n, err := strWithTimeout.Read(b) - Expect(err).To(MatchError(io.EOF)) - Expect(n).To(Equal(4)) - Expect(b).To(Equal([]byte{0xDE, 0xAD, 0xBE, 0xEF})) - n, err = strWithTimeout.Read(b) - Expect(n).To(BeZero()) - Expect(err).To(MatchError(io.EOF)) - }) - - It("handles out-of-order frames", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(2), false) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(4), true) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)).Times(2) - mockFC.EXPECT().MaybeQueueWindowUpdate().Times(2) - frame1 := wire.StreamFrame{ - Offset: 2, - Data: []byte{0xBE, 0xEF}, - FinBit: true, - } - frame2 := wire.StreamFrame{ - Offset: 0, - Data: []byte{0xDE, 0xAD}, - } - err := str.handleStreamFrame(&frame1) - Expect(err).ToNot(HaveOccurred()) - err = str.handleStreamFrame(&frame2) - Expect(err).ToNot(HaveOccurred()) - mockSender.EXPECT().onStreamCompleted(streamID) - b := make([]byte, 4) - n, err := strWithTimeout.Read(b) - Expect(err).To(MatchError(io.EOF)) - Expect(n).To(Equal(4)) - Expect(b).To(Equal([]byte{0xDE, 0xAD, 0xBE, 0xEF})) - n, err = strWithTimeout.Read(b) - Expect(n).To(BeZero()) - Expect(err).To(MatchError(io.EOF)) - }) - - It("returns EOFs with partial read", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(2), true) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)) - mockFC.EXPECT().MaybeQueueWindowUpdate() - err := str.handleStreamFrame(&wire.StreamFrame{ - Offset: 0, - Data: []byte{0xde, 0xad}, - FinBit: true, - }) - Expect(err).ToNot(HaveOccurred()) - mockSender.EXPECT().onStreamCompleted(streamID) - b := make([]byte, 4) - n, err := strWithTimeout.Read(b) - Expect(err).To(MatchError(io.EOF)) - Expect(n).To(Equal(2)) - Expect(b[:n]).To(Equal([]byte{0xde, 0xad})) - }) - - It("handles immediate FINs", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(0), true) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(0)) - mockFC.EXPECT().MaybeQueueWindowUpdate() - err := str.handleStreamFrame(&wire.StreamFrame{ - Offset: 0, - FinBit: true, - }) - Expect(err).ToNot(HaveOccurred()) - mockSender.EXPECT().onStreamCompleted(streamID) - b := make([]byte, 4) - n, err := strWithTimeout.Read(b) - Expect(n).To(BeZero()) - Expect(err).To(MatchError(io.EOF)) - }) - }) - - It("closes when CloseRemote is called", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(0), true) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(0)) - mockFC.EXPECT().MaybeQueueWindowUpdate() - str.CloseRemote(0) - mockSender.EXPECT().onStreamCompleted(streamID) - b := make([]byte, 8) - n, err := strWithTimeout.Read(b) - Expect(n).To(BeZero()) - Expect(err).To(MatchError(io.EOF)) - }) - }) - - Context("closing for shutdown", func() { - testErr := errors.New("test error") - - It("immediately returns all reads", func() { - done := make(chan struct{}) - b := make([]byte, 4) - go func() { - defer GinkgoRecover() - n, err := strWithTimeout.Read(b) - Expect(n).To(BeZero()) - Expect(err).To(MatchError(testErr)) - close(done) - }() - Consistently(done).ShouldNot(BeClosed()) - str.closeForShutdown(testErr) - Eventually(done).Should(BeClosed()) - }) - - It("errors for all following reads", func() { - str.closeForShutdown(testErr) - b := make([]byte, 1) - n, err := strWithTimeout.Read(b) - Expect(n).To(BeZero()) - Expect(err).To(MatchError(testErr)) - }) - }) - }) - - Context("stream cancelations", func() { - Context("canceling read", func() { - It("unblocks Read", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := strWithTimeout.Read([]byte{0}) - Expect(err).To(MatchError("Read on stream 1337 canceled with error code 1234")) - close(done) - }() - Consistently(done).ShouldNot(BeClosed()) - err := str.CancelRead(1234) - Expect(err).ToNot(HaveOccurred()) - Eventually(done).Should(BeClosed()) - }) - - It("doesn't allow further calls to Read", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - err := str.CancelRead(1234) - Expect(err).ToNot(HaveOccurred()) - _, err = strWithTimeout.Read([]byte{0}) - Expect(err).To(MatchError("Read on stream 1337 canceled with error code 1234")) - }) - - It("does nothing when CancelRead is called twice", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - err := str.CancelRead(1234) - Expect(err).ToNot(HaveOccurred()) - err = str.CancelRead(2345) - Expect(err).ToNot(HaveOccurred()) - _, err = strWithTimeout.Read([]byte{0}) - Expect(err).To(MatchError("Read on stream 1337 canceled with error code 1234")) - }) - - It("doesn't send a RST_STREAM frame, if the FIN was already read", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(6), true) - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(6)) - mockFC.EXPECT().MaybeQueueWindowUpdate() - // no calls to mockSender.queueControlFrame - err := str.handleStreamFrame(&wire.StreamFrame{ - StreamID: streamID, - Data: []byte("foobar"), - FinBit: true, - }) - Expect(err).ToNot(HaveOccurred()) - mockSender.EXPECT().onStreamCompleted(streamID) - _, err = strWithTimeout.Read(make([]byte, 100)) - Expect(err).To(MatchError(io.EOF)) - err = str.CancelRead(1234) - Expect(err).ToNot(HaveOccurred()) - }) - - It("queues a STOP_SENDING frame, for IETF QUIC", func() { - str.version = versionIETFFrames - mockSender.EXPECT().queueControlFrame(&wire.StopSendingFrame{ - StreamID: streamID, - ErrorCode: 1234, - }) - err := str.CancelRead(1234) - Expect(err).ToNot(HaveOccurred()) - }) - - It("doesn't queue a STOP_SENDING frame, for gQUIC", func() { - str.version = versionGQUICFrames - // no calls to mockSender.queueControlFrame - err := str.CancelRead(1234) - Expect(err).ToNot(HaveOccurred()) - }) - }) - - Context("receiving RST_STREAM frames", func() { - rst := &wire.RstStreamFrame{ - StreamID: streamID, - ByteOffset: 42, - ErrorCode: 1234, - } - - It("unblocks Read", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(42), true) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := strWithTimeout.Read([]byte{0}) - Expect(err).To(MatchError("Stream 1337 was reset with error code 1234")) - Expect(err).To(BeAssignableToTypeOf(streamCanceledError{})) - Expect(err.(streamCanceledError).Canceled()).To(BeTrue()) - Expect(err.(streamCanceledError).ErrorCode()).To(Equal(protocol.ApplicationErrorCode(1234))) - close(done) - }() - Consistently(done).ShouldNot(BeClosed()) - mockSender.EXPECT().onStreamCompleted(streamID) - str.handleRstStreamFrame(rst) - Eventually(done).Should(BeClosed()) - }) - - It("doesn't allow further calls to Read", func() { - mockSender.EXPECT().onStreamCompleted(streamID) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(42), true) - err := str.handleRstStreamFrame(rst) - Expect(err).ToNot(HaveOccurred()) - _, err = strWithTimeout.Read([]byte{0}) - Expect(err).To(MatchError("Stream 1337 was reset with error code 1234")) - Expect(err).To(BeAssignableToTypeOf(streamCanceledError{})) - Expect(err.(streamCanceledError).Canceled()).To(BeTrue()) - Expect(err.(streamCanceledError).ErrorCode()).To(Equal(protocol.ApplicationErrorCode(1234))) - }) - - It("errors when receiving a RST_STREAM with an inconsistent offset", func() { - testErr := errors.New("already received a different final offset before") - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(42), true).Return(testErr) - err := str.handleRstStreamFrame(rst) - Expect(err).To(MatchError(testErr)) - }) - - It("ignores duplicate RST_STREAM frames", func() { - mockSender.EXPECT().onStreamCompleted(streamID) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(42), true).Times(2) - err := str.handleRstStreamFrame(rst) - Expect(err).ToNot(HaveOccurred()) - err = str.handleRstStreamFrame(rst) - Expect(err).ToNot(HaveOccurred()) - }) - - It("doesn't do anyting when it was closed for shutdown", func() { - str.closeForShutdown(nil) - err := str.handleRstStreamFrame(rst) - Expect(err).ToNot(HaveOccurred()) - }) - - Context("for gQUIC", func() { - BeforeEach(func() { - str.version = versionGQUICFrames - }) - - It("unblocks Read when receiving a RST_STREAM frame with non-zero error code", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(42), true) - readReturned := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := strWithTimeout.Read([]byte{0}) - Expect(err).To(MatchError("Stream 1337 was reset with error code 1234")) - Expect(err).To(BeAssignableToTypeOf(streamCanceledError{})) - Expect(err.(streamCanceledError).Canceled()).To(BeTrue()) - Expect(err.(streamCanceledError).ErrorCode()).To(Equal(protocol.ApplicationErrorCode(1234))) - close(readReturned) - }() - Consistently(readReturned).ShouldNot(BeClosed()) - mockSender.EXPECT().onStreamCompleted(streamID) - err := str.handleRstStreamFrame(rst) - Expect(err).ToNot(HaveOccurred()) - Eventually(readReturned).Should(BeClosed()) - }) - - It("continues reading until the end when receiving a RST_STREAM frame with error code 0", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(6), true).Times(2) - gomock.InOrder( - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(4)), - mockFC.EXPECT().AddBytesRead(protocol.ByteCount(2)), - mockSender.EXPECT().onStreamCompleted(streamID), - ) - mockFC.EXPECT().MaybeQueueWindowUpdate().Times(2) - readReturned := make(chan struct{}) - go func() { - defer GinkgoRecover() - n, err := strWithTimeout.Read(make([]byte, 4)) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(4)) - n, err = strWithTimeout.Read(make([]byte, 4)) - Expect(err).To(MatchError(io.EOF)) - Expect(n).To(Equal(2)) - close(readReturned) - }() - Consistently(readReturned).ShouldNot(BeClosed()) - err := str.handleStreamFrame(&wire.StreamFrame{ - StreamID: streamID, - Data: []byte("foobar"), - FinBit: true, - }) - Expect(err).ToNot(HaveOccurred()) - err = str.handleRstStreamFrame(&wire.RstStreamFrame{ - StreamID: streamID, - ByteOffset: 6, - ErrorCode: 0, - }) - Expect(err).ToNot(HaveOccurred()) - Eventually(readReturned).Should(BeClosed()) - }) - }) - }) - }) - - Context("flow control", func() { - It("errors when a STREAM frame causes a flow control violation", func() { - testErr := errors.New("flow control violation") - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(8), false).Return(testErr) - frame := wire.StreamFrame{ - Offset: 2, - Data: []byte("foobar"), - } - err := str.handleStreamFrame(&frame) - Expect(err).To(MatchError(testErr)) - }) - - It("gets a window update", func() { - mockFC.EXPECT().GetWindowUpdate().Return(protocol.ByteCount(0x100)) - Expect(str.getWindowUpdate()).To(Equal(protocol.ByteCount(0x100))) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/send_stream_test.go b/vendor/lucas-clemente/quic-go/send_stream_test.go deleted file mode 100644 index 76aabda11..000000000 --- a/vendor/lucas-clemente/quic-go/send_stream_test.go +++ /dev/null @@ -1,599 +0,0 @@ -package quic - -import ( - "bytes" - "errors" - "io" - "runtime" - "time" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/mocks" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" -) - -var _ = Describe("Send Stream", func() { - const streamID protocol.StreamID = 1337 - - var ( - str *sendStream - strWithTimeout io.Writer // str wrapped with gbytes.TimeoutWriter - mockFC *mocks.MockStreamFlowController - mockSender *MockStreamSender - ) - - BeforeEach(func() { - mockSender = NewMockStreamSender(mockCtrl) - mockFC = mocks.NewMockStreamFlowController(mockCtrl) - str = newSendStream(streamID, mockSender, mockFC, protocol.VersionWhatever) - - timeout := scaleDuration(250 * time.Millisecond) - strWithTimeout = gbytes.TimeoutWriter(str, timeout) - }) - - waitForWrite := func() { - EventuallyWithOffset(0, func() []byte { - str.mutex.Lock() - data := str.dataForWriting - str.mutex.Unlock() - return data - }).ShouldNot(BeEmpty()) - } - - It("gets stream id", func() { - Expect(str.StreamID()).To(Equal(protocol.StreamID(1337))) - }) - - Context("writing", func() { - It("writes and gets all data at once", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockFC.EXPECT().SendWindowSize().Return(protocol.ByteCount(9999)) - mockFC.EXPECT().AddBytesSent(protocol.ByteCount(6)) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - n, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(6)) - close(done) - }() - waitForWrite() - f, _ := str.popStreamFrame(1000) - Expect(f.Data).To(Equal([]byte("foobar"))) - Expect(f.FinBit).To(BeFalse()) - Expect(f.Offset).To(BeZero()) - Expect(f.DataLenPresent).To(BeTrue()) - Expect(str.writeOffset).To(Equal(protocol.ByteCount(6))) - Expect(str.dataForWriting).To(BeNil()) - Eventually(done).Should(BeClosed()) - }) - - It("writes and gets data in two turns", func() { - mockSender.EXPECT().onHasStreamData(streamID) - frameHeaderLen := protocol.ByteCount(4) - mockFC.EXPECT().SendWindowSize().Return(protocol.ByteCount(9999)).Times(2) - mockFC.EXPECT().AddBytesSent(gomock.Any() /* protocol.ByteCount(3)*/).Times(2) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - n, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(6)) - close(done) - }() - waitForWrite() - f, _ := str.popStreamFrame(3 + frameHeaderLen) - Expect(f.Data).To(Equal([]byte("foo"))) - Expect(f.FinBit).To(BeFalse()) - Expect(f.Offset).To(BeZero()) - Expect(f.DataLenPresent).To(BeTrue()) - f, _ = str.popStreamFrame(100) - Expect(f.Data).To(Equal([]byte("bar"))) - Expect(f.FinBit).To(BeFalse()) - Expect(f.Offset).To(Equal(protocol.ByteCount(3))) - Expect(f.DataLenPresent).To(BeTrue()) - Expect(str.popStreamFrame(1000)).To(BeNil()) - Eventually(done).Should(BeClosed()) - }) - - It("popStreamFrame returns nil if no data is available", func() { - frame, hasMoreData := str.popStreamFrame(1000) - Expect(frame).To(BeNil()) - Expect(hasMoreData).To(BeFalse()) - }) - - It("says if it has more data for writing", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockFC.EXPECT().SendWindowSize().Return(protocol.ByteCount(9999)).Times(2) - mockFC.EXPECT().AddBytesSent(gomock.Any()).Times(2) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - n, err := strWithTimeout.Write(bytes.Repeat([]byte{0}, 100)) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(100)) - close(done) - }() - waitForWrite() - frame, hasMoreData := str.popStreamFrame(50) - Expect(frame).ToNot(BeNil()) - Expect(hasMoreData).To(BeTrue()) - frame, hasMoreData = str.popStreamFrame(1000) - Expect(frame).ToNot(BeNil()) - Expect(hasMoreData).To(BeFalse()) - frame, _ = str.popStreamFrame(1000) - Expect(frame).To(BeNil()) - Eventually(done).Should(BeClosed()) - }) - - It("copies the slice while writing", func() { - mockSender.EXPECT().onHasStreamData(streamID) - frameHeaderSize := protocol.ByteCount(4) - mockFC.EXPECT().SendWindowSize().Return(protocol.ByteCount(9999)).Times(2) - mockFC.EXPECT().AddBytesSent(protocol.ByteCount(1)) - mockFC.EXPECT().AddBytesSent(protocol.ByteCount(2)) - s := []byte("foo") - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - n, err := strWithTimeout.Write(s) - Expect(err).ToNot(HaveOccurred()) - Expect(n).To(Equal(3)) - close(done) - }() - waitForWrite() - frame, _ := str.popStreamFrame(frameHeaderSize + 1) - Expect(frame.Data).To(Equal([]byte("f"))) - s[1] = 'e' - f, _ := str.popStreamFrame(100) - Expect(f).ToNot(BeNil()) - Expect(f.Data).To(Equal([]byte("oo"))) - Eventually(done).Should(BeClosed()) - }) - - It("returns when given a nil input", func() { - n, err := strWithTimeout.Write(nil) - Expect(n).To(BeZero()) - Expect(err).ToNot(HaveOccurred()) - }) - - It("returns when given an empty slice", func() { - n, err := strWithTimeout.Write([]byte("")) - Expect(n).To(BeZero()) - Expect(err).ToNot(HaveOccurred()) - }) - - It("cancels the context when Close is called", func() { - mockSender.EXPECT().onHasStreamData(streamID) - Expect(str.Context().Done()).ToNot(BeClosed()) - str.Close() - Expect(str.Context().Done()).To(BeClosed()) - }) - - Context("flow control blocking", func() { - It("queues a BLOCKED frame if the stream is flow control blocked", func() { - mockFC.EXPECT().SendWindowSize().Return(protocol.ByteCount(0)) - mockFC.EXPECT().IsNewlyBlocked().Return(true, protocol.ByteCount(12)) - mockSender.EXPECT().queueControlFrame(&wire.StreamBlockedFrame{ - StreamID: streamID, - Offset: 12, - }) - mockSender.EXPECT().onHasStreamData(streamID) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := str.Write([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - waitForWrite() - f, hasMoreData := str.popStreamFrame(1000) - Expect(f).To(BeNil()) - Expect(hasMoreData).To(BeFalse()) - // make the Write go routine return - str.closeForShutdown(nil) - Eventually(done).Should(BeClosed()) - }) - - It("says that it doesn't have any more data, when it is flow control blocked", func() { - frameHeaderSize := protocol.ByteCount(4) - mockSender.EXPECT().onHasStreamData(streamID) - - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := str.Write([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - waitForWrite() - - // first pop a STREAM frame of the maximum size allowed by flow control - mockFC.EXPECT().SendWindowSize().Return(protocol.ByteCount(3)) - mockFC.EXPECT().AddBytesSent(protocol.ByteCount(3)) - f, hasMoreData := str.popStreamFrame(frameHeaderSize + 3) - Expect(f).ToNot(BeNil()) - Expect(hasMoreData).To(BeTrue()) - - // try to pop again, this time noticing that we're blocked - mockFC.EXPECT().SendWindowSize() - // don't use offset 3 here, to make sure the BLOCKED frame contains the number returned by the flow controller - mockFC.EXPECT().IsNewlyBlocked().Return(true, protocol.ByteCount(10)) - mockSender.EXPECT().queueControlFrame(&wire.StreamBlockedFrame{ - StreamID: streamID, - Offset: 10, - }) - f, hasMoreData = str.popStreamFrame(1000) - Expect(f).To(BeNil()) - Expect(hasMoreData).To(BeFalse()) - // make the Write go routine return - str.closeForShutdown(nil) - Eventually(done).Should(BeClosed()) - }) - }) - - Context("deadlines", func() { - It("returns an error when Write is called after the deadline", func() { - str.SetWriteDeadline(time.Now().Add(-time.Second)) - n, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).To(MatchError(errDeadline)) - Expect(n).To(BeZero()) - }) - - It("unblocks after the deadline", func() { - mockSender.EXPECT().onHasStreamData(streamID) - deadline := time.Now().Add(scaleDuration(50 * time.Millisecond)) - str.SetWriteDeadline(deadline) - n, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).To(MatchError(errDeadline)) - Expect(n).To(BeZero()) - Expect(time.Now()).To(BeTemporally("~", deadline, scaleDuration(20*time.Millisecond))) - }) - - It("returns the number of bytes written, when the deadline expires", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockFC.EXPECT().SendWindowSize().Return(protocol.ByteCount(10000)).AnyTimes() - mockFC.EXPECT().AddBytesSent(gomock.Any()) - deadline := time.Now().Add(scaleDuration(50 * time.Millisecond)) - str.SetWriteDeadline(deadline) - var n int - writeReturned := make(chan struct{}) - go func() { - defer GinkgoRecover() - var err error - n, err = strWithTimeout.Write(bytes.Repeat([]byte{0}, 100)) - Expect(err).To(MatchError(errDeadline)) - Expect(time.Now()).To(BeTemporally("~", deadline, scaleDuration(20*time.Millisecond))) - close(writeReturned) - }() - waitForWrite() - frame, hasMoreData := str.popStreamFrame(50) - Expect(frame).ToNot(BeNil()) - Expect(hasMoreData).To(BeTrue()) - Eventually(writeReturned, scaleDuration(80*time.Millisecond)).Should(BeClosed()) - Expect(n).To(BeEquivalentTo(frame.DataLen())) - }) - - It("doesn't pop any data after the deadline expired", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockFC.EXPECT().SendWindowSize().Return(protocol.ByteCount(10000)).AnyTimes() - mockFC.EXPECT().AddBytesSent(gomock.Any()) - deadline := time.Now().Add(scaleDuration(50 * time.Millisecond)) - str.SetWriteDeadline(deadline) - writeReturned := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := strWithTimeout.Write(bytes.Repeat([]byte{0}, 100)) - Expect(err).To(MatchError(errDeadline)) - close(writeReturned) - }() - waitForWrite() - frame, hasMoreData := str.popStreamFrame(50) - Expect(frame).ToNot(BeNil()) - Expect(hasMoreData).To(BeTrue()) - Eventually(writeReturned, scaleDuration(80*time.Millisecond)).Should(BeClosed()) - frame, hasMoreData = str.popStreamFrame(50) - Expect(frame).To(BeNil()) - Expect(hasMoreData).To(BeFalse()) - }) - - It("doesn't unblock if the deadline is changed before the first one expires", func() { - mockSender.EXPECT().onHasStreamData(streamID) - deadline1 := time.Now().Add(scaleDuration(50 * time.Millisecond)) - deadline2 := time.Now().Add(scaleDuration(100 * time.Millisecond)) - str.SetWriteDeadline(deadline1) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - time.Sleep(scaleDuration(20 * time.Millisecond)) - str.SetWriteDeadline(deadline2) - // make sure that this was actually execute before the deadline expires - Expect(time.Now()).To(BeTemporally("<", deadline1)) - close(done) - }() - runtime.Gosched() - n, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).To(MatchError(errDeadline)) - Expect(n).To(BeZero()) - Expect(time.Now()).To(BeTemporally("~", deadline2, scaleDuration(20*time.Millisecond))) - Eventually(done).Should(BeClosed()) - }) - - It("unblocks earlier, when a new deadline is set", func() { - mockSender.EXPECT().onHasStreamData(streamID) - deadline1 := time.Now().Add(scaleDuration(200 * time.Millisecond)) - deadline2 := time.Now().Add(scaleDuration(50 * time.Millisecond)) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - time.Sleep(scaleDuration(10 * time.Millisecond)) - str.SetWriteDeadline(deadline2) - // make sure that this was actually execute before the deadline expires - Expect(time.Now()).To(BeTemporally("<", deadline2)) - close(done) - }() - str.SetWriteDeadline(deadline1) - runtime.Gosched() - _, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).To(MatchError(errDeadline)) - Expect(time.Now()).To(BeTemporally("~", deadline2, scaleDuration(20*time.Millisecond))) - Eventually(done).Should(BeClosed()) - }) - }) - - Context("closing", func() { - It("doesn't allow writes after it has been closed", func() { - mockSender.EXPECT().onHasStreamData(streamID) - str.Close() - _, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).To(MatchError("write on closed stream 1337")) - }) - - It("allows FIN", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockSender.EXPECT().onStreamCompleted(streamID) - str.Close() - f, hasMoreData := str.popStreamFrame(1000) - Expect(f).ToNot(BeNil()) - Expect(f.Data).To(BeEmpty()) - Expect(f.FinBit).To(BeTrue()) - Expect(hasMoreData).To(BeFalse()) - }) - - It("doesn't send a FIN when there's still data", func() { - mockSender.EXPECT().onHasStreamData(streamID) - frameHeaderLen := protocol.ByteCount(4) - mockFC.EXPECT().SendWindowSize().Return(protocol.ByteCount(9999)).Times(2) - mockFC.EXPECT().AddBytesSent(gomock.Any()).Times(2) - str.dataForWriting = []byte("foobar") - Expect(str.Close()).To(Succeed()) - f, _ := str.popStreamFrame(3 + frameHeaderLen) - Expect(f).ToNot(BeNil()) - Expect(f.Data).To(Equal([]byte("foo"))) - Expect(f.FinBit).To(BeFalse()) - mockSender.EXPECT().onStreamCompleted(streamID) - f, _ = str.popStreamFrame(100) - Expect(f.Data).To(Equal([]byte("bar"))) - Expect(f.FinBit).To(BeTrue()) - }) - - It("doesn't allow FIN after it is closed for shutdown", func() { - str.closeForShutdown(errors.New("test")) - f, hasMoreData := str.popStreamFrame(1000) - Expect(f).To(BeNil()) - Expect(hasMoreData).To(BeFalse()) - }) - - It("doesn't allow FIN twice", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockSender.EXPECT().onStreamCompleted(streamID) - str.Close() - f, _ := str.popStreamFrame(1000) - Expect(f).ToNot(BeNil()) - Expect(f.Data).To(BeEmpty()) - Expect(f.FinBit).To(BeTrue()) - f, hasMoreData := str.popStreamFrame(1000) - Expect(f).To(BeNil()) - Expect(hasMoreData).To(BeFalse()) - }) - }) - - Context("closing for shutdown", func() { - testErr := errors.New("test") - - It("returns errors when the stream is cancelled", func() { - str.closeForShutdown(testErr) - n, err := strWithTimeout.Write([]byte("foo")) - Expect(n).To(BeZero()) - Expect(err).To(MatchError(testErr)) - }) - - It("doesn't get data for writing if an error occurred", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockFC.EXPECT().SendWindowSize().Return(protocol.ByteCount(9999)) - mockFC.EXPECT().AddBytesSent(gomock.Any()) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := strWithTimeout.Write(bytes.Repeat([]byte{0}, 500)) - Expect(err).To(MatchError(testErr)) - close(done) - }() - waitForWrite() - frame, hasMoreData := str.popStreamFrame(50) // get a STREAM frame containing some data, but not all - Expect(frame).ToNot(BeNil()) - Expect(hasMoreData).To(BeTrue()) - str.closeForShutdown(testErr) - frame, hasMoreData = str.popStreamFrame(1000) - Expect(frame).To(BeNil()) - Expect(hasMoreData).To(BeFalse()) - Eventually(done).Should(BeClosed()) - }) - - It("cancels the context", func() { - Expect(str.Context().Done()).ToNot(BeClosed()) - str.closeForShutdown(testErr) - Expect(str.Context().Done()).To(BeClosed()) - }) - }) - }) - - Context("handling MAX_STREAM_DATA frames", func() { - It("informs the flow controller", func() { - mockFC.EXPECT().UpdateSendWindow(protocol.ByteCount(0x1337)) - str.handleMaxStreamDataFrame(&wire.MaxStreamDataFrame{ - StreamID: streamID, - ByteOffset: 0x1337, - }) - }) - - It("says when it has data for sending", func() { - mockFC.EXPECT().UpdateSendWindow(gomock.Any()) - mockSender.EXPECT().onHasStreamData(streamID).Times(2) // once for Write, once for the MAX_STREAM_DATA frame - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := str.Write([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - waitForWrite() - str.handleMaxStreamDataFrame(&wire.MaxStreamDataFrame{ - StreamID: streamID, - ByteOffset: 42, - }) - // make sure the Write go routine returns - str.closeForShutdown(nil) - Eventually(done).Should(BeClosed()) - }) - }) - - Context("stream cancelations", func() { - Context("canceling writing", func() { - It("queues a RST_STREAM frame", func() { - mockSender.EXPECT().queueControlFrame(&wire.RstStreamFrame{ - StreamID: streamID, - ByteOffset: 1234, - ErrorCode: 9876, - }) - mockSender.EXPECT().onStreamCompleted(streamID) - str.writeOffset = 1234 - err := str.CancelWrite(9876) - Expect(err).ToNot(HaveOccurred()) - }) - - It("unblocks Write", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockSender.EXPECT().onStreamCompleted(streamID) - mockSender.EXPECT().queueControlFrame(gomock.Any()) - mockFC.EXPECT().SendWindowSize().Return(protocol.MaxByteCount) - mockFC.EXPECT().AddBytesSent(gomock.Any()) - writeReturned := make(chan struct{}) - var n int - go func() { - defer GinkgoRecover() - var err error - n, err = strWithTimeout.Write(bytes.Repeat([]byte{0}, 100)) - Expect(err).To(MatchError("Write on stream 1337 canceled with error code 1234")) - close(writeReturned) - }() - waitForWrite() - frame, _ := str.popStreamFrame(50) - Expect(frame).ToNot(BeNil()) - err := str.CancelWrite(1234) - Expect(err).ToNot(HaveOccurred()) - Eventually(writeReturned).Should(BeClosed()) - Expect(n).To(BeEquivalentTo(frame.DataLen())) - }) - - It("cancels the context", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - mockSender.EXPECT().onStreamCompleted(streamID) - Expect(str.Context().Done()).ToNot(BeClosed()) - str.CancelWrite(1234) - Expect(str.Context().Done()).To(BeClosed()) - }) - - It("doesn't allow further calls to Write", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - mockSender.EXPECT().onStreamCompleted(streamID) - err := str.CancelWrite(1234) - Expect(err).ToNot(HaveOccurred()) - _, err = strWithTimeout.Write([]byte("foobar")) - Expect(err).To(MatchError("Write on stream 1337 canceled with error code 1234")) - }) - - It("only cancels once", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - mockSender.EXPECT().onStreamCompleted(streamID) - err := str.CancelWrite(1234) - Expect(err).ToNot(HaveOccurred()) - err = str.CancelWrite(4321) - Expect(err).ToNot(HaveOccurred()) - }) - - It("doesn't cancel when the stream was already closed", func() { - mockSender.EXPECT().onHasStreamData(streamID) - err := str.Close() - Expect(err).ToNot(HaveOccurred()) - err = str.CancelWrite(123) - Expect(err).To(MatchError("CancelWrite for closed stream 1337")) - }) - }) - - Context("receiving STOP_SENDING frames", func() { - It("queues a RST_STREAM frames with error code Stopping", func() { - mockSender.EXPECT().queueControlFrame(&wire.RstStreamFrame{ - StreamID: streamID, - ErrorCode: errorCodeStopping, - }) - mockSender.EXPECT().onStreamCompleted(streamID) - str.handleStopSendingFrame(&wire.StopSendingFrame{ - StreamID: streamID, - ErrorCode: 101, - }) - }) - - It("unblocks Write", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockSender.EXPECT().queueControlFrame(gomock.Any()) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := str.Write([]byte("foobar")) - Expect(err).To(MatchError("Stream 1337 was reset with error code 123")) - Expect(err).To(BeAssignableToTypeOf(streamCanceledError{})) - Expect(err.(streamCanceledError).Canceled()).To(BeTrue()) - Expect(err.(streamCanceledError).ErrorCode()).To(Equal(protocol.ApplicationErrorCode(123))) - close(done) - }() - waitForWrite() - mockSender.EXPECT().onStreamCompleted(streamID) - str.handleStopSendingFrame(&wire.StopSendingFrame{ - StreamID: streamID, - ErrorCode: 123, - }) - Eventually(done).Should(BeClosed()) - }) - - It("doesn't allow further calls to Write", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - mockSender.EXPECT().onStreamCompleted(streamID) - str.handleStopSendingFrame(&wire.StopSendingFrame{ - StreamID: streamID, - ErrorCode: 123, - }) - _, err := str.Write([]byte("foobar")) - Expect(err).To(MatchError("Stream 1337 was reset with error code 123")) - Expect(err).To(BeAssignableToTypeOf(streamCanceledError{})) - Expect(err.(streamCanceledError).Canceled()).To(BeTrue()) - Expect(err.(streamCanceledError).ErrorCode()).To(Equal(protocol.ApplicationErrorCode(123))) - }) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/server_session_test.go b/vendor/lucas-clemente/quic-go/server_session_test.go deleted file mode 100644 index 4486d7e41..000000000 --- a/vendor/lucas-clemente/quic-go/server_session_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package quic - -import ( - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Server Session", func() { - var ( - qsess *MockQuicSession - sess *serverSession - ) - - BeforeEach(func() { - qsess = NewMockQuicSession(mockCtrl) - sess = newServerSession(qsess, &Config{}, utils.DefaultLogger).(*serverSession) - }) - - It("handles packets", func() { - p := &receivedPacket{ - header: &wire.Header{DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5}}, - } - qsess.EXPECT().handlePacket(p) - sess.handlePacket(p) - }) - - It("ignores Public Resets", func() { - p := &receivedPacket{ - header: &wire.Header{ - ResetFlag: true, - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef}, - }, - } - err := sess.handlePacketImpl(p) - Expect(err).To(MatchError("Received unexpected Public Reset for connection 0xdeadbeef")) - }) - - It("ignores delayed packets with mismatching versions, for gQUIC", func() { - qsess.EXPECT().GetVersion().Return(protocol.VersionNumber(100)) - // don't EXPECT any calls to handlePacket() - p := &receivedPacket{ - header: &wire.Header{ - VersionFlag: true, - Version: protocol.VersionNumber(123), - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef}, - }, - } - err := sess.handlePacketImpl(p) - Expect(err).ToNot(HaveOccurred()) - }) - - It("ignores delayed packets with mismatching versions, for IETF QUIC", func() { - qsess.EXPECT().GetVersion().Return(protocol.VersionNumber(100)) - // don't EXPECT any calls to handlePacket() - p := &receivedPacket{ - header: &wire.Header{ - IsLongHeader: true, - Version: protocol.VersionNumber(123), - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef}, - }, - } - err := sess.handlePacketImpl(p) - Expect(err).ToNot(HaveOccurred()) - }) - - It("ignores packets with the wrong Long Header type", func() { - qsess.EXPECT().GetVersion().Return(protocol.VersionNumber(100)) - p := &receivedPacket{ - header: &wire.Header{ - IsLongHeader: true, - Type: protocol.PacketTypeRetry, - Version: protocol.VersionNumber(100), - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef}, - }, - } - err := sess.handlePacketImpl(p) - Expect(err).To(MatchError("Received unsupported packet type: Retry")) - }) - - It("passes on Handshake packets", func() { - p := &receivedPacket{ - header: &wire.Header{ - IsLongHeader: true, - Type: protocol.PacketTypeHandshake, - Version: protocol.VersionNumber(100), - DestConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef}, - }, - } - qsess.EXPECT().GetVersion().Return(protocol.VersionNumber(100)) - qsess.EXPECT().handlePacket(p) - Expect(sess.handlePacketImpl(p)).To(Succeed()) - }) - - It("has the right perspective", func() { - Expect(sess.GetPerspective()).To(Equal(protocol.PerspectiveServer)) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/server_test.go b/vendor/lucas-clemente/quic-go/server_test.go deleted file mode 100644 index 387ec665a..000000000 --- a/vendor/lucas-clemente/quic-go/server_test.go +++ /dev/null @@ -1,519 +0,0 @@ -package quic - -import ( - "bytes" - "crypto/tls" - "errors" - "net" - "reflect" - "time" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/handshake" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type mockSession struct { - *MockQuicSession - - connID protocol.ConnectionID - runner sessionRunner -} - -func (s *mockSession) GetPerspective() protocol.Perspective { panic("not implemented") } - -var _ = Describe("Server", func() { - var ( - conn *mockPacketConn - config *Config - udpAddr = &net.UDPAddr{IP: net.IPv4(192, 168, 100, 200), Port: 1337} - ) - - BeforeEach(func() { - conn = newMockPacketConn() - conn.addr = &net.UDPAddr{} - config = &Config{Versions: protocol.SupportedVersions} - }) - - Context("quic.Config", func() { - It("setups with the right values", func() { - config := &Config{ - HandshakeTimeout: 1337 * time.Minute, - IdleTimeout: 42 * time.Hour, - RequestConnectionIDOmission: true, - MaxIncomingStreams: 1234, - MaxIncomingUniStreams: 4321, - ConnectionIDLength: 12, - Versions: []protocol.VersionNumber{VersionGQUIC43}, - } - c := populateServerConfig(config) - Expect(c.HandshakeTimeout).To(Equal(1337 * time.Minute)) - Expect(c.IdleTimeout).To(Equal(42 * time.Hour)) - Expect(c.RequestConnectionIDOmission).To(BeFalse()) - Expect(c.MaxIncomingStreams).To(Equal(1234)) - Expect(c.MaxIncomingUniStreams).To(Equal(4321)) - Expect(c.ConnectionIDLength).To(Equal(12)) - Expect(c.Versions).To(Equal([]protocol.VersionNumber{VersionGQUIC43})) - }) - - It("uses 8 byte connection IDs if gQUIC 44 is supported", func() { - config := &Config{ - Versions: []protocol.VersionNumber{protocol.Version43, protocol.Version44}, - ConnectionIDLength: 13, - } - c := populateServerConfig(config) - Expect(c.Versions).To(Equal([]protocol.VersionNumber{protocol.Version43, protocol.Version44})) - Expect(c.ConnectionIDLength).To(Equal(8)) - }) - - It("uses 4 byte connection IDs by default, if gQUIC 44 is not supported", func() { - config := &Config{ - Versions: []protocol.VersionNumber{protocol.Version39}, - } - c := populateServerConfig(config) - Expect(c.ConnectionIDLength).To(Equal(protocol.DefaultConnectionIDLength)) - }) - - It("disables bidirectional streams", func() { - config := &Config{ - MaxIncomingStreams: -1, - MaxIncomingUniStreams: 4321, - } - c := populateServerConfig(config) - Expect(c.MaxIncomingStreams).To(BeZero()) - Expect(c.MaxIncomingUniStreams).To(Equal(4321)) - }) - - It("disables unidirectional streams", func() { - config := &Config{ - MaxIncomingStreams: 1234, - MaxIncomingUniStreams: -1, - } - c := populateServerConfig(config) - Expect(c.MaxIncomingStreams).To(Equal(1234)) - Expect(c.MaxIncomingUniStreams).To(BeZero()) - }) - }) - - Context("with mock session", func() { - var ( - serv *server - firstPacket *receivedPacket - connID = protocol.ConnectionID{0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6} - sessions = make([]*MockQuicSession, 0) - sessionHandler *MockPacketHandlerManager - ) - - BeforeEach(func() { - sessionHandler = NewMockPacketHandlerManager(mockCtrl) - newMockSession := func( - _ connection, - runner sessionRunner, - _ protocol.VersionNumber, - connID protocol.ConnectionID, - _ protocol.ConnectionID, - _ *handshake.ServerConfig, - _ *tls.Config, - _ *Config, - _ utils.Logger, - ) (quicSession, error) { - ExpectWithOffset(0, sessions).ToNot(BeEmpty()) - s := &mockSession{MockQuicSession: sessions[0]} - s.connID = connID - s.runner = runner - sessions = sessions[1:] - return s, nil - } - serv = &server{ - sessionHandler: sessionHandler, - newSession: newMockSession, - conn: conn, - config: config, - sessionQueue: make(chan Session, 5), - errorChan: make(chan struct{}), - logger: utils.DefaultLogger, - } - serv.setup() - b := &bytes.Buffer{} - utils.BigEndian.WriteUint32(b, uint32(protocol.SupportedVersions[0])) - firstPacket = &receivedPacket{ - header: &wire.Header{ - VersionFlag: true, - Version: serv.config.Versions[0], - DestConnectionID: protocol.ConnectionID{0x4c, 0xfa, 0x9f, 0x9b, 0x66, 0x86, 0x19, 0xf6}, - PacketNumber: 1, - }, - data: bytes.Repeat([]byte{0}, protocol.MinClientHelloSize), - rcvTime: time.Now(), - } - }) - - AfterEach(func() { - Expect(sessions).To(BeEmpty()) - }) - - It("returns the address", func() { - conn.addr = &net.UDPAddr{ - IP: net.IPv4(192, 168, 13, 37), - Port: 1234, - } - Expect(serv.Addr().String()).To(Equal("192.168.13.37:1234")) - }) - - It("creates new sessions", func() { - s := NewMockQuicSession(mockCtrl) - s.EXPECT().handlePacket(gomock.Any()) - run := make(chan struct{}) - s.EXPECT().run().Do(func() { close(run) }) - sessions = append(sessions, s) - - sessionHandler.EXPECT().Add(connID, gomock.Any()).Do(func(cid protocol.ConnectionID, _ packetHandler) { - Expect(cid).To(Equal(connID)) - }) - Expect(serv.handlePacketImpl(firstPacket)).To(Succeed()) - Eventually(run).Should(BeClosed()) - }) - - It("accepts new TLS sessions", func() { - connID := protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8} - sess := NewMockQuicSession(mockCtrl) - err := serv.setupTLS() - Expect(err).ToNot(HaveOccurred()) - added := make(chan struct{}) - sessionHandler.EXPECT().Add(connID, gomock.Any()).Do(func(_ protocol.ConnectionID, ph packetHandler) { - Expect(ph.GetPerspective()).To(Equal(protocol.PerspectiveServer)) - close(added) - }) - serv.serverTLS.sessionChan <- tlsSession{ - connID: connID, - sess: sess, - } - Eventually(added).Should(BeClosed()) - }) - - It("accepts a session once the connection it is forward secure", func() { - s := NewMockQuicSession(mockCtrl) - s.EXPECT().handlePacket(gomock.Any()) - run := make(chan struct{}) - s.EXPECT().run().Do(func() { close(run) }) - sessions = append(sessions, s) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := serv.Accept() - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - sessionHandler.EXPECT().Add(connID, gomock.Any()).Do(func(_ protocol.ConnectionID, sess packetHandler) { - Consistently(done).ShouldNot(BeClosed()) - sess.(*serverSession).quicSession.(*mockSession).runner.onHandshakeComplete(sess.(Session)) - }) - err := serv.handlePacketImpl(firstPacket) - Expect(err).ToNot(HaveOccurred()) - Eventually(done).Should(BeClosed()) - Eventually(run).Should(BeClosed()) - }) - - It("doesn't accept sessions that error during the handshake", func() { - run := make(chan error, 1) - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().handlePacket(gomock.Any()) - sess.EXPECT().run().DoAndReturn(func() error { return <-run }) - sessions = append(sessions, sess) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - serv.Accept() - close(done) - }() - sessionHandler.EXPECT().Add(connID, gomock.Any()).Do(func(protocol.ConnectionID, packetHandler) { - run <- errors.New("handshake error") - }) - Expect(serv.handlePacketImpl(firstPacket)).To(Succeed()) - Consistently(done).ShouldNot(BeClosed()) - - // make the go routine return - close(serv.errorChan) - Eventually(done).Should(BeClosed()) - }) - - It("closes the sessionHandler when Close is called", func() { - sessionHandler.EXPECT().CloseServer() - Expect(serv.Close()).To(Succeed()) - }) - - It("closes twice", func() { - sessionHandler.EXPECT().CloseServer() - Expect(serv.Close()).To(Succeed()) - Expect(serv.Close()).To(Succeed()) - }) - - It("works if no quic.Config is given", func(done Done) { - ln, err := ListenAddr("127.0.0.1:0", testdata.GetTLSConfig(), nil) - Expect(err).ToNot(HaveOccurred()) - Expect(ln.Close()).To(Succeed()) - close(done) - }, 1) - - It("closes properly", func() { - ln, err := ListenAddr("127.0.0.1:0", testdata.GetTLSConfig(), config) - Expect(err).ToNot(HaveOccurred()) - - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - ln.Accept() - close(done) - }() - ln.Close() - Eventually(done).Should(BeClosed()) - }) - - It("closes the connection when it was created with ListenAddr", func() { - addr, err := net.ResolveUDPAddr("udp", "localhost:12345") - Expect(err).ToNot(HaveOccurred()) - - serv, err := ListenAddr("localhost:0", nil, nil) - Expect(err).ToNot(HaveOccurred()) - // test that we can write on the packet conn - _, err = serv.(*server).conn.WriteTo([]byte("foobar"), addr) - Expect(err).ToNot(HaveOccurred()) - Expect(serv.Close()).To(Succeed()) - // test that we can't write any more on the packet conn - _, err = serv.(*server).conn.WriteTo([]byte("foobar"), addr) - Expect(err.Error()).To(ContainSubstring("use of closed network connection")) - }) - - It("returns Accept when it is closed", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := serv.Accept() - Expect(err).To(MatchError("server closed")) - close(done) - }() - sessionHandler.EXPECT().CloseServer() - Expect(serv.Close()).To(Succeed()) - Eventually(done).Should(BeClosed()) - }) - - It("returns Accept with the right error when closeWithError is called", func() { - testErr := errors.New("connection error") - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := serv.Accept() - Expect(err).To(MatchError(testErr)) - close(done) - }() - sessionHandler.EXPECT().CloseServer() - serv.closeWithError(testErr) - Eventually(done).Should(BeClosed()) - }) - - It("doesn't try to process a packet after sending a gQUIC Version Negotiation Packet", func() { - config.Versions = []protocol.VersionNumber{99} - p := &receivedPacket{ - header: &wire.Header{ - VersionFlag: true, - DestConnectionID: connID, - PacketNumber: 1, - PacketNumberLen: protocol.PacketNumberLen2, - }, - data: make([]byte, protocol.MinClientHelloSize), - } - Expect(serv.handlePacketImpl(p)).To(Succeed()) - Expect(conn.dataWritten.Bytes()).ToNot(BeEmpty()) - }) - - It("sends a PUBLIC_RESET for new connections that don't have the VersionFlag set", func() { - err := serv.handlePacketImpl(&receivedPacket{ - remoteAddr: udpAddr, - header: &wire.Header{ - IsPublicHeader: true, - Version: versionGQUICFrames, - }, - }) - Expect(err).ToNot(HaveOccurred()) - - Expect(conn.dataWritten.Len()).ToNot(BeZero()) - Expect(conn.dataWrittenTo).To(Equal(udpAddr)) - Expect(conn.dataWritten.Bytes()[0] & 0x02).ToNot(BeZero()) // check that the ResetFlag is set - }) - - It("sends a gQUIC Version Negotaion Packet, if the client sent a gQUIC Public Header", func() { - connID := protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1} - err := serv.handlePacketImpl(&receivedPacket{ - remoteAddr: udpAddr, - header: &wire.Header{ - IsPublicHeader: true, - VersionFlag: true, - DestConnectionID: connID, - PacketNumber: 1, - PacketNumberLen: protocol.PacketNumberLen2, - Version: protocol.Version39 - 1, - }, - }) - Expect(err).ToNot(HaveOccurred()) - - Expect(conn.dataWritten.Len()).ToNot(BeZero()) - Expect(conn.dataWrittenTo).To(Equal(udpAddr)) - r := bytes.NewReader(conn.dataWritten.Bytes()) - iHdr, err := wire.ParseInvariantHeader(r, 0) - Expect(err).ToNot(HaveOccurred()) - Expect(iHdr.IsLongHeader).To(BeFalse()) - replyHdr, err := iHdr.Parse(r, protocol.PerspectiveServer, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(replyHdr.IsVersionNegotiation).To(BeTrue()) - Expect(replyHdr.DestConnectionID).To(Equal(connID)) - Expect(r.Len()).To(BeZero()) - }) - - It("sends an IETF draft style Version Negotaion Packet, if the client sent a IETF draft style header", func() { - connID := protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1} - err := serv.handlePacketImpl(&receivedPacket{ - remoteAddr: udpAddr, - header: &wire.Header{ - Type: protocol.PacketTypeInitial, - IsLongHeader: true, - DestConnectionID: connID, - SrcConnectionID: connID, - PacketNumber: 0x55, - PacketNumberLen: protocol.PacketNumberLen1, - Version: 0x1234, - PayloadLen: protocol.MinInitialPacketSize, - }, - }) - Expect(err).ToNot(HaveOccurred()) - - Expect(conn.dataWritten.Len()).ToNot(BeZero()) - Expect(conn.dataWrittenTo).To(Equal(udpAddr)) - r := bytes.NewReader(conn.dataWritten.Bytes()) - iHdr, err := wire.ParseInvariantHeader(r, 0) - Expect(err).ToNot(HaveOccurred()) - replyHdr, err := iHdr.Parse(r, protocol.PerspectiveServer, versionIETFFrames) - Expect(err).ToNot(HaveOccurred()) - Expect(replyHdr.IsVersionNegotiation).To(BeTrue()) - Expect(replyHdr.DestConnectionID).To(Equal(connID)) - Expect(replyHdr.SrcConnectionID).To(Equal(connID)) - Expect(r.Len()).To(BeZero()) - }) - }) - - It("setups with the right values", func() { - supportedVersions := []protocol.VersionNumber{protocol.VersionTLS, protocol.Version39} - acceptCookie := func(_ net.Addr, _ *Cookie) bool { return true } - config := Config{ - Versions: supportedVersions, - AcceptCookie: acceptCookie, - HandshakeTimeout: 1337 * time.Hour, - IdleTimeout: 42 * time.Minute, - KeepAlive: true, - } - ln, err := Listen(conn, &tls.Config{}, &config) - Expect(err).ToNot(HaveOccurred()) - server := ln.(*server) - Expect(server.sessionHandler).ToNot(BeNil()) - Expect(server.scfg).ToNot(BeNil()) - Expect(server.config.Versions).To(Equal(supportedVersions)) - Expect(server.config.HandshakeTimeout).To(Equal(1337 * time.Hour)) - Expect(server.config.IdleTimeout).To(Equal(42 * time.Minute)) - Expect(reflect.ValueOf(server.config.AcceptCookie)).To(Equal(reflect.ValueOf(acceptCookie))) - Expect(server.config.KeepAlive).To(BeTrue()) - }) - - It("errors when the Config contains an invalid version", func() { - version := protocol.VersionNumber(0x1234) - _, err := Listen(conn, &tls.Config{}, &Config{Versions: []protocol.VersionNumber{version}}) - Expect(err).To(MatchError("0x1234 is not a valid QUIC version")) - }) - - It("fills in default values if options are not set in the Config", func() { - ln, err := Listen(conn, &tls.Config{}, &Config{}) - Expect(err).ToNot(HaveOccurred()) - server := ln.(*server) - Expect(server.config.Versions).To(Equal(protocol.SupportedVersions)) - Expect(server.config.HandshakeTimeout).To(Equal(protocol.DefaultHandshakeTimeout)) - Expect(server.config.IdleTimeout).To(Equal(protocol.DefaultIdleTimeout)) - Expect(reflect.ValueOf(server.config.AcceptCookie)).To(Equal(reflect.ValueOf(defaultAcceptCookie))) - Expect(server.config.KeepAlive).To(BeFalse()) - }) - - It("listens on a given address", func() { - addr := "127.0.0.1:13579" - ln, err := ListenAddr(addr, nil, config) - Expect(err).ToNot(HaveOccurred()) - serv := ln.(*server) - Expect(serv.Addr().String()).To(Equal(addr)) - }) - - It("errors if given an invalid address", func() { - addr := "127.0.0.1" - _, err := ListenAddr(addr, nil, config) - Expect(err).To(BeAssignableToTypeOf(&net.AddrError{})) - }) - - It("errors if given an invalid address", func() { - addr := "1.1.1.1:1111" - _, err := ListenAddr(addr, nil, config) - Expect(err).To(BeAssignableToTypeOf(&net.OpError{})) - }) -}) - -var _ = Describe("default source address verification", func() { - It("accepts a token", func() { - remoteAddr := &net.UDPAddr{IP: net.IPv4(192, 168, 0, 1)} - cookie := &Cookie{ - RemoteAddr: "192.168.0.1", - SentTime: time.Now().Add(-protocol.CookieExpiryTime).Add(time.Second), // will expire in 1 second - } - Expect(defaultAcceptCookie(remoteAddr, cookie)).To(BeTrue()) - }) - - It("requests verification if no token is provided", func() { - remoteAddr := &net.UDPAddr{IP: net.IPv4(192, 168, 0, 1)} - Expect(defaultAcceptCookie(remoteAddr, nil)).To(BeFalse()) - }) - - It("rejects a token if the address doesn't match", func() { - remoteAddr := &net.UDPAddr{IP: net.IPv4(192, 168, 0, 1)} - cookie := &Cookie{ - RemoteAddr: "127.0.0.1", - SentTime: time.Now(), - } - Expect(defaultAcceptCookie(remoteAddr, cookie)).To(BeFalse()) - }) - - It("accepts a token for a remote address is not a UDP address", func() { - remoteAddr := &net.TCPAddr{IP: net.IPv4(192, 168, 0, 1), Port: 1337} - cookie := &Cookie{ - RemoteAddr: "192.168.0.1:1337", - SentTime: time.Now(), - } - Expect(defaultAcceptCookie(remoteAddr, cookie)).To(BeTrue()) - }) - - It("rejects an invalid token for a remote address is not a UDP address", func() { - remoteAddr := &net.TCPAddr{IP: net.IPv4(192, 168, 0, 1), Port: 1337} - cookie := &Cookie{ - RemoteAddr: "192.168.0.1:7331", // mismatching port - SentTime: time.Now(), - } - Expect(defaultAcceptCookie(remoteAddr, cookie)).To(BeFalse()) - }) - - It("rejects an expired token", func() { - remoteAddr := &net.UDPAddr{IP: net.IPv4(192, 168, 0, 1)} - cookie := &Cookie{ - RemoteAddr: "192.168.0.1", - SentTime: time.Now().Add(-protocol.CookieExpiryTime).Add(-time.Second), // expired 1 second ago - } - Expect(defaultAcceptCookie(remoteAddr, cookie)).To(BeFalse()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/server_tls_test.go b/vendor/lucas-clemente/quic-go/server_tls_test.go deleted file mode 100644 index 16326ed57..000000000 --- a/vendor/lucas-clemente/quic-go/server_tls_test.go +++ /dev/null @@ -1,125 +0,0 @@ -package quic - -import ( - "bytes" - "net" - - "github.com/bifurcation/mint" - "github.com/lucas-clemente/quic-go/internal/handshake" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Stateless TLS handling", func() { - var ( - conn *mockPacketConn - server *serverTLS - sessionChan <-chan tlsSession - ) - - BeforeEach(func() { - conn = newMockPacketConn() - config := &Config{ - Versions: []protocol.VersionNumber{protocol.VersionTLS}, - } - var err error - server, sessionChan, err = newServerTLS(conn, config, nil, testdata.GetTLSConfig(), utils.DefaultLogger) - Expect(err).ToNot(HaveOccurred()) - }) - - parseHeader := func(data []byte) *wire.Header { - b := bytes.NewReader(data) - iHdr, err := wire.ParseInvariantHeader(b, 0) - Expect(err).ToNot(HaveOccurred()) - hdr, err := iHdr.Parse(b, protocol.PerspectiveServer, protocol.VersionTLS) - Expect(err).ToNot(HaveOccurred()) - return hdr - } - - It("drops too small packets", func() { - server.HandleInitial(&receivedPacket{ - header: &wire.Header{}, - data: bytes.Repeat([]byte{0}, protocol.MinInitialPacketSize-1), // the packet is now 1 byte too small - }) - Expect(conn.dataWritten.Len()).To(BeZero()) - }) - - It("drops packets with a too short connection ID", func() { - hdr := &wire.Header{ - SrcConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8}, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4}, - PacketNumberLen: protocol.PacketNumberLen1, - } - server.HandleInitial(&receivedPacket{ - header: hdr, - data: bytes.Repeat([]byte{0}, protocol.MinInitialPacketSize), - }) - Expect(conn.dataWritten.Len()).To(BeZero()) - }) - - It("replies with a Retry packet, if a Cookie is required", func() { - server.config.AcceptCookie = func(_ net.Addr, _ *handshake.Cookie) bool { return false } - hdr := &wire.Header{ - Type: protocol.PacketTypeInitial, - SrcConnectionID: protocol.ConnectionID{5, 4, 3, 2, 1}, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, - Version: protocol.VersionTLS, - } - server.HandleInitial(&receivedPacket{ - remoteAddr: &net.UDPAddr{}, - header: hdr, - data: bytes.Repeat([]byte{0}, protocol.MinInitialPacketSize), - }) - Expect(conn.dataWritten.Len()).ToNot(BeZero()) - replyHdr := parseHeader(conn.dataWritten.Bytes()) - Expect(replyHdr.Type).To(Equal(protocol.PacketTypeRetry)) - Expect(replyHdr.SrcConnectionID).ToNot(Equal(hdr.DestConnectionID)) - Expect(replyHdr.SrcConnectionID.Len()).To(BeNumerically(">=", protocol.MinConnectionIDLenInitial)) - Expect(replyHdr.DestConnectionID).To(Equal(hdr.SrcConnectionID)) - Expect(replyHdr.OrigDestConnectionID).To(Equal(hdr.DestConnectionID)) - Expect(replyHdr.Token).ToNot(BeEmpty()) - Expect(sessionChan).ToNot(Receive()) - }) - - It("creates a session, if no Cookie is required", func() { - server.config.AcceptCookie = func(_ net.Addr, _ *handshake.Cookie) bool { return true } - hdr := &wire.Header{ - Type: protocol.PacketTypeInitial, - SrcConnectionID: protocol.ConnectionID{5, 4, 3, 2, 1}, - DestConnectionID: protocol.ConnectionID{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, - Version: protocol.VersionTLS, - } - p := &receivedPacket{ - header: hdr, - data: bytes.Repeat([]byte{0}, protocol.MinInitialPacketSize), - } - run := make(chan struct{}) - server.newSession = func(connection, sessionRunner, protocol.ConnectionID, protocol.ConnectionID, protocol.ConnectionID, protocol.PacketNumber, *Config, *mint.Config, *handshake.TransportParameters, utils.Logger, protocol.VersionNumber) (quicSession, error) { - sess := NewMockQuicSession(mockCtrl) - sess.EXPECT().handlePacket(p) - sess.EXPECT().run().Do(func() { close(run) }) - return sess, nil - } - - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - server.HandleInitial(p) - // the Handshake packet is written by the session - Expect(conn.dataWritten.Len()).To(BeZero()) - close(done) - }() - var tlsSess tlsSession - Eventually(sessionChan).Should(Receive(&tlsSess)) - // make sure we're using a server-generated connection ID - Expect(tlsSess.connID).ToNot(Equal(hdr.SrcConnectionID)) - Expect(tlsSess.connID).ToNot(Equal(hdr.DestConnectionID)) - Eventually(run).Should(BeClosed()) - Eventually(done).Should(BeClosed()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/session_test.go b/vendor/lucas-clemente/quic-go/session_test.go deleted file mode 100644 index a29060461..000000000 --- a/vendor/lucas-clemente/quic-go/session_test.go +++ /dev/null @@ -1,1844 +0,0 @@ -package quic - -import ( - "bytes" - "context" - "crypto/tls" - "errors" - "io" - "net" - "runtime/pprof" - "strings" - "time" - - "github.com/golang/mock/gomock" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "github.com/lucas-clemente/quic-go/internal/ackhandler" - "github.com/lucas-clemente/quic-go/internal/crypto" - "github.com/lucas-clemente/quic-go/internal/handshake" - "github.com/lucas-clemente/quic-go/internal/mocks" - "github.com/lucas-clemente/quic-go/internal/mocks/ackhandler" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/testdata" - "github.com/lucas-clemente/quic-go/internal/utils" - "github.com/lucas-clemente/quic-go/internal/wire" - "github.com/lucas-clemente/quic-go/qerr" -) - -type mockConnection struct { - remoteAddr net.Addr - localAddr net.Addr - written chan []byte -} - -func newMockConnection() *mockConnection { - return &mockConnection{ - remoteAddr: &net.UDPAddr{}, - written: make(chan []byte, 100), - } -} - -func (m *mockConnection) Write(p []byte) error { - b := make([]byte, len(p)) - copy(b, p) - select { - case m.written <- b: - default: - panic("mockConnection channel full") - } - return nil -} -func (m *mockConnection) Read([]byte) (int, net.Addr, error) { panic("not implemented") } - -func (m *mockConnection) SetCurrentRemoteAddr(addr net.Addr) { - m.remoteAddr = addr -} -func (m *mockConnection) LocalAddr() net.Addr { return m.localAddr } -func (m *mockConnection) RemoteAddr() net.Addr { return m.remoteAddr } -func (*mockConnection) Close() error { panic("not implemented") } - -func areSessionsRunning() bool { - var b bytes.Buffer - pprof.Lookup("goroutine").WriteTo(&b, 1) - return strings.Contains(b.String(), "quic-go.(*session).run") -} - -var _ = Describe("Session", func() { - var ( - sess *session - sessionRunner *MockSessionRunner - scfg *handshake.ServerConfig - mconn *mockConnection - cryptoSetup *mockCryptoSetup - streamManager *MockStreamManager - handshakeChan chan<- struct{} - ) - - BeforeEach(func() { - Eventually(areSessionsRunning).Should(BeFalse()) - - cryptoSetup = &mockCryptoSetup{} - newCryptoSetup = func( - _ io.ReadWriter, - _ protocol.ConnectionID, - _ net.Addr, - _ protocol.VersionNumber, - _ []byte, - _ *handshake.ServerConfig, - _ *handshake.TransportParameters, - _ []protocol.VersionNumber, - _ func(net.Addr, *Cookie) bool, - _ chan<- handshake.TransportParameters, - handshakeChanP chan<- struct{}, - _ utils.Logger, - ) (handshake.CryptoSetup, error) { - handshakeChan = handshakeChanP - return cryptoSetup, nil - } - - sessionRunner = NewMockSessionRunner(mockCtrl) - mconn = newMockConnection() - certChain := crypto.NewCertChain(testdata.GetTLSConfig()) - kex, err := crypto.NewCurve25519KEX() - Expect(err).NotTo(HaveOccurred()) - scfg, err = handshake.NewServerConfig(kex, certChain) - Expect(err).NotTo(HaveOccurred()) - var pSess Session - pSess, err = newSession( - mconn, - sessionRunner, - protocol.Version39, - protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1}, - protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1}, - scfg, - nil, - populateServerConfig(&Config{}), - utils.DefaultLogger, - ) - Expect(err).NotTo(HaveOccurred()) - sess = pSess.(*session) - streamManager = NewMockStreamManager(mockCtrl) - sess.streamsMap = streamManager - }) - - AfterEach(func() { - newCryptoSetup = handshake.NewCryptoSetup - Eventually(areSessionsRunning).Should(BeFalse()) - }) - - Context("source address validation", func() { - var ( - cookieVerify func(net.Addr, *Cookie) bool - paramClientAddr net.Addr - paramCookie *Cookie - ) - remoteAddr := &net.UDPAddr{IP: net.IPv4(192, 168, 13, 37), Port: 1000} - - BeforeEach(func() { - newCryptoSetup = func( - _ io.ReadWriter, - _ protocol.ConnectionID, - _ net.Addr, - _ protocol.VersionNumber, - _ []byte, - _ *handshake.ServerConfig, - _ *handshake.TransportParameters, - _ []protocol.VersionNumber, - cookieFunc func(net.Addr, *Cookie) bool, - _ chan<- handshake.TransportParameters, - _ chan<- struct{}, - _ utils.Logger, - ) (handshake.CryptoSetup, error) { - cookieVerify = cookieFunc - return cryptoSetup, nil - } - - conf := populateServerConfig(&Config{}) - conf.AcceptCookie = func(clientAddr net.Addr, cookie *Cookie) bool { - paramClientAddr = clientAddr - paramCookie = cookie - return false - } - pSess, err := newSession( - mconn, - sessionRunner, - protocol.Version39, - protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1}, - protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1}, - scfg, - nil, - conf, - utils.DefaultLogger, - ) - Expect(err).NotTo(HaveOccurred()) - sess = pSess.(*session) - }) - - It("calls the callback with the right parameters when the client didn't send an STK", func() { - cookieVerify(remoteAddr, nil) - Expect(paramClientAddr).To(Equal(remoteAddr)) - Expect(paramCookie).To(BeNil()) - }) - - It("calls the callback with the STK when the client sent an STK", func() { - cookieAddr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1337} - sentTime := time.Now().Add(-time.Hour) - cookieVerify(remoteAddr, &Cookie{SentTime: sentTime, RemoteAddr: cookieAddr.String()}) - Expect(paramClientAddr).To(Equal(remoteAddr)) - Expect(paramCookie).ToNot(BeNil()) - Expect(paramCookie.RemoteAddr).To(Equal(cookieAddr.String())) - Expect(paramCookie.SentTime).To(Equal(sentTime)) - }) - }) - - Context("frame handling", func() { - Context("handling STREAM frames", func() { - It("passes STREAM frames to the stream", func() { - f := &wire.StreamFrame{ - StreamID: 5, - Data: []byte{0xde, 0xca, 0xfb, 0xad}, - } - str := NewMockReceiveStreamI(mockCtrl) - str.EXPECT().handleStreamFrame(f) - streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(5)).Return(str, nil) - err := sess.handleStreamFrame(f, protocol.EncryptionForwardSecure) - Expect(err).ToNot(HaveOccurred()) - }) - - It("returns errors", func() { - testErr := errors.New("test err") - f := &wire.StreamFrame{ - StreamID: 5, - Data: []byte{0xde, 0xca, 0xfb, 0xad}, - } - str := NewMockReceiveStreamI(mockCtrl) - str.EXPECT().handleStreamFrame(f).Return(testErr) - streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(5)).Return(str, nil) - err := sess.handleStreamFrame(f, protocol.EncryptionForwardSecure) - Expect(err).To(MatchError(testErr)) - }) - - It("ignores STREAM frames for closed streams", func() { - streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(5)).Return(nil, nil) // for closed streams, the streamManager returns nil - err := sess.handleStreamFrame(&wire.StreamFrame{ - StreamID: 5, - Data: []byte("foobar"), - }, protocol.EncryptionForwardSecure) - Expect(err).ToNot(HaveOccurred()) - }) - - It("errors on a STREAM frame that would close the crypto stream", func() { - err := sess.handleStreamFrame(&wire.StreamFrame{ - StreamID: sess.version.CryptoStreamID(), - Offset: 0x1337, - FinBit: true, - }, protocol.EncryptionForwardSecure) - Expect(err).To(MatchError("Received STREAM frame with FIN bit for the crypto stream")) - }) - - It("accepts unencrypted STREAM frames on the crypto stream", func() { - f := &wire.StreamFrame{ - StreamID: versionGQUICFrames.CryptoStreamID(), - Data: []byte("foobar"), - } - err := sess.handleStreamFrame(f, protocol.EncryptionUnencrypted) - Expect(err).ToNot(HaveOccurred()) - }) - - It("unpacks encrypted STREAM frames on the crypto stream", func() { - err := sess.handleStreamFrame(&wire.StreamFrame{ - StreamID: versionGQUICFrames.CryptoStreamID(), - Data: []byte("foobar"), - }, protocol.EncryptionSecure) - Expect(err).ToNot(HaveOccurred()) - }) - - It("does not unpack unencrypted STREAM frames on higher streams", func() { - err := sess.handleStreamFrame(&wire.StreamFrame{ - StreamID: 3, - Data: []byte("foobar"), - }, protocol.EncryptionUnencrypted) - Expect(err).To(MatchError(qerr.Error(qerr.UnencryptedStreamData, "received unencrypted stream data on stream 3"))) - }) - }) - - Context("handling ACK frames", func() { - It("informs the SentPacketHandler about ACKs", func() { - f := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 2, Largest: 3}}} - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().ReceivedAck(f, protocol.PacketNumber(42), protocol.EncryptionSecure, gomock.Any()) - sph.EXPECT().GetLowestPacketNotConfirmedAcked() - sess.sentPacketHandler = sph - sess.lastRcvdPacketNumber = 42 - err := sess.handleAckFrame(f, protocol.EncryptionSecure) - Expect(err).ToNot(HaveOccurred()) - }) - - It("tells the ReceivedPacketHandler to ignore low ranges", func() { - ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 2, Largest: 3}}} - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().ReceivedAck(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()) - sph.EXPECT().GetLowestPacketNotConfirmedAcked().Return(protocol.PacketNumber(0x42)) - sess.sentPacketHandler = sph - rph := mockackhandler.NewMockReceivedPacketHandler(mockCtrl) - rph.EXPECT().IgnoreBelow(protocol.PacketNumber(0x42)) - sess.receivedPacketHandler = rph - err := sess.handleAckFrame(ack, protocol.EncryptionUnencrypted) - Expect(err).ToNot(HaveOccurred()) - }) - }) - - Context("handling RST_STREAM frames", func() { - It("closes the streams for writing", func() { - f := &wire.RstStreamFrame{ - StreamID: 555, - ErrorCode: 42, - ByteOffset: 0x1337, - } - str := NewMockReceiveStreamI(mockCtrl) - streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(555)).Return(str, nil) - str.EXPECT().handleRstStreamFrame(f) - err := sess.handleRstStreamFrame(f) - Expect(err).ToNot(HaveOccurred()) - }) - - It("returns errors", func() { - f := &wire.RstStreamFrame{ - StreamID: 7, - ByteOffset: 0x1337, - } - testErr := errors.New("flow control violation") - str := NewMockReceiveStreamI(mockCtrl) - streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(7)).Return(str, nil) - str.EXPECT().handleRstStreamFrame(f).Return(testErr) - err := sess.handleRstStreamFrame(f) - Expect(err).To(MatchError(testErr)) - }) - - It("ignores RST_STREAM frames for closed streams", func() { - streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(3)).Return(nil, nil) - err := sess.handleFrames([]wire.Frame{&wire.RstStreamFrame{ - StreamID: 3, - ErrorCode: 42, - }}, protocol.EncryptionUnspecified) - Expect(err).NotTo(HaveOccurred()) - }) - - It("erros when a RST_STREAM frame would reset the crypto stream", func() { - err := sess.handleRstStreamFrame(&wire.RstStreamFrame{ - StreamID: sess.version.CryptoStreamID(), - ErrorCode: 123, - }) - Expect(err).To(MatchError("Received RST_STREAM frame for the crypto stream")) - }) - }) - - Context("handling MAX_DATA and MAX_STREAM_DATA frames", func() { - var connFC *mocks.MockConnectionFlowController - - BeforeEach(func() { - connFC = mocks.NewMockConnectionFlowController(mockCtrl) - sess.connFlowController = connFC - }) - - It("updates the flow control window of the crypto stream", func() { - fc := mocks.NewMockStreamFlowController(mockCtrl) - offset := protocol.ByteCount(0x4321) - fc.EXPECT().UpdateSendWindow(offset) - sess.cryptoStream.(*cryptoStreamImpl).sendStream.flowController = fc - err := sess.handleMaxStreamDataFrame(&wire.MaxStreamDataFrame{ - StreamID: sess.version.CryptoStreamID(), - ByteOffset: offset, - }) - Expect(err).ToNot(HaveOccurred()) - }) - - It("updates the flow control window of a stream", func() { - f := &wire.MaxStreamDataFrame{ - StreamID: 12345, - ByteOffset: 0x1337, - } - str := NewMockSendStreamI(mockCtrl) - streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(12345)).Return(str, nil) - str.EXPECT().handleMaxStreamDataFrame(f) - err := sess.handleMaxStreamDataFrame(f) - Expect(err).ToNot(HaveOccurred()) - }) - - It("updates the flow control window of the connection", func() { - offset := protocol.ByteCount(0x800000) - connFC.EXPECT().UpdateSendWindow(offset) - sess.handleMaxDataFrame(&wire.MaxDataFrame{ByteOffset: offset}) - }) - - It("ignores MAX_STREAM_DATA frames for a closed stream", func() { - streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(10)).Return(nil, nil) - err := sess.handleFrames([]wire.Frame{&wire.MaxStreamDataFrame{ - StreamID: 10, - ByteOffset: 1337, - }}, protocol.EncryptionUnspecified) - Expect(err).NotTo(HaveOccurred()) - }) - }) - - Context("handling MAX_STREAM_ID frames", func() { - It("passes the frame to the streamsMap", func() { - f := &wire.MaxStreamIDFrame{StreamID: 10} - streamManager.EXPECT().HandleMaxStreamIDFrame(f) - err := sess.handleMaxStreamIDFrame(f) - Expect(err).ToNot(HaveOccurred()) - }) - - It("returns errors", func() { - f := &wire.MaxStreamIDFrame{StreamID: 10} - testErr := errors.New("test error") - streamManager.EXPECT().HandleMaxStreamIDFrame(f).Return(testErr) - err := sess.handleMaxStreamIDFrame(f) - Expect(err).To(MatchError(testErr)) - }) - }) - - Context("handling STOP_SENDING frames", func() { - It("passes the frame to the stream", func() { - f := &wire.StopSendingFrame{ - StreamID: 5, - ErrorCode: 10, - } - str := NewMockSendStreamI(mockCtrl) - streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(5)).Return(str, nil) - str.EXPECT().handleStopSendingFrame(f) - err := sess.handleStopSendingFrame(f) - Expect(err).ToNot(HaveOccurred()) - }) - - It("errors when receiving a STOP_SENDING for the crypto stream", func() { - err := sess.handleStopSendingFrame(&wire.StopSendingFrame{ - StreamID: sess.version.CryptoStreamID(), - ErrorCode: 10, - }) - Expect(err).To(MatchError("Received a STOP_SENDING frame for the crypto stream")) - }) - - It("ignores STOP_SENDING frames for a closed stream", func() { - streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(3)).Return(nil, nil) - err := sess.handleFrames([]wire.Frame{&wire.StopSendingFrame{ - StreamID: 3, - ErrorCode: 1337, - }}, protocol.EncryptionUnspecified) - Expect(err).NotTo(HaveOccurred()) - }) - }) - - It("handles PING frames", func() { - err := sess.handleFrames([]wire.Frame{&wire.PingFrame{}}, protocol.EncryptionUnspecified) - Expect(err).NotTo(HaveOccurred()) - }) - - It("rejects PATH_RESPONSE frames", func() { - err := sess.handleFrames([]wire.Frame{&wire.PathResponseFrame{Data: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}}}, protocol.EncryptionUnspecified) - Expect(err).To(MatchError("unexpected PATH_RESPONSE frame")) - }) - - It("handles PATH_CHALLENGE frames", func() { - err := sess.handleFrames([]wire.Frame{&wire.PathChallengeFrame{Data: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}}}, protocol.EncryptionUnspecified) - Expect(err).ToNot(HaveOccurred()) - Expect(sess.packer.controlFrames).To(HaveLen(1)) - Expect(sess.packer.controlFrames[0]).To(BeAssignableToTypeOf(&wire.PathResponseFrame{})) - Expect(sess.packer.controlFrames[0].(*wire.PathResponseFrame).Data).To(Equal([8]byte{1, 2, 3, 4, 5, 6, 7, 8})) - }) - - It("handles BLOCKED frames", func() { - err := sess.handleFrames([]wire.Frame{&wire.BlockedFrame{}}, protocol.EncryptionUnspecified) - Expect(err).NotTo(HaveOccurred()) - }) - - It("handles STREAM_BLOCKED frames", func() { - err := sess.handleFrames([]wire.Frame{&wire.StreamBlockedFrame{}}, protocol.EncryptionUnspecified) - Expect(err).NotTo(HaveOccurred()) - }) - - It("handles STREAM_ID_BLOCKED frames", func() { - err := sess.handleFrames([]wire.Frame{&wire.StreamIDBlockedFrame{}}, protocol.EncryptionUnspecified) - Expect(err).NotTo(HaveOccurred()) - }) - - It("errors on GOAWAY frames", func() { - err := sess.handleFrames([]wire.Frame{&wire.GoawayFrame{}}, protocol.EncryptionUnspecified) - Expect(err).To(MatchError("unimplemented: handling GOAWAY frames")) - }) - - It("handles STOP_WAITING frames", func() { - err := sess.handleFrames([]wire.Frame{&wire.StopWaitingFrame{LeastUnacked: 10}}, protocol.EncryptionUnspecified) - Expect(err).NotTo(HaveOccurred()) - }) - - It("handles CONNECTION_CLOSE frames", func() { - testErr := qerr.Error(qerr.ProofInvalid, "foobar") - streamManager.EXPECT().CloseWithError(testErr) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - go func() { - defer GinkgoRecover() - err := sess.run() - Expect(err).To(MatchError(testErr)) - }() - err := sess.handleFrames([]wire.Frame{&wire.ConnectionCloseFrame{ErrorCode: qerr.ProofInvalid, ReasonPhrase: "foobar"}}, protocol.EncryptionUnspecified) - Expect(err).NotTo(HaveOccurred()) - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - }) - - It("tells its versions", func() { - sess.version = 4242 - Expect(sess.GetVersion()).To(Equal(protocol.VersionNumber(4242))) - }) - - It("accepts new streams", func() { - mstr := NewMockStreamI(mockCtrl) - streamManager.EXPECT().AcceptStream().Return(mstr, nil) - str, err := sess.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(Equal(mstr)) - }) - - Context("closing", func() { - BeforeEach(func() { - Eventually(areSessionsRunning).Should(BeFalse()) - go func() { - defer GinkgoRecover() - sess.run() - }() - Eventually(areSessionsRunning).Should(BeTrue()) - }) - - It("shuts down without error", func() { - streamManager.EXPECT().CloseWithError(qerr.Error(qerr.PeerGoingAway, "")) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(areSessionsRunning).Should(BeFalse()) - Expect(mconn.written).To(HaveLen(1)) - buf := &bytes.Buffer{} - err := (&wire.ConnectionCloseFrame{ErrorCode: qerr.PeerGoingAway}).Write(buf, sess.version) - Expect(err).ToNot(HaveOccurred()) - Expect(mconn.written).To(Receive(ContainSubstring(buf.String()))) - Expect(sess.Context().Done()).To(BeClosed()) - }) - - It("only closes once", func() { - streamManager.EXPECT().CloseWithError(qerr.Error(qerr.PeerGoingAway, "")) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - sess.Close() - Eventually(areSessionsRunning).Should(BeFalse()) - Expect(mconn.written).To(HaveLen(1)) - Expect(sess.Context().Done()).To(BeClosed()) - }) - - It("closes streams with proper error", func() { - testErr := errors.New("test error") - streamManager.EXPECT().CloseWithError(qerr.Error(0x1337, testErr.Error())) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.CloseWithError(0x1337, testErr) - Eventually(areSessionsRunning).Should(BeFalse()) - Expect(sess.Context().Done()).To(BeClosed()) - }) - - It("closes the session in order to replace it with another QUIC version", func() { - streamManager.EXPECT().CloseWithError(gomock.Any()) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.destroy(errCloseSessionForNewVersion) - Eventually(areSessionsRunning).Should(BeFalse()) - Expect(mconn.written).To(BeEmpty()) // no CONNECTION_CLOSE or PUBLIC_RESET sent - }) - - It("sends a Public Reset if the client is initiating the no STOP_WAITING experiment", func() { - streamManager.EXPECT().CloseWithError(gomock.Any()) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.closeLocal(handshake.ErrNSTPExperiment) - Eventually(mconn.written).Should(HaveLen(1)) - Expect((<-mconn.written)[0] & 0x02).ToNot(BeZero()) // Public Reset - Expect(sess.Context().Done()).To(BeClosed()) - }) - - It("cancels the context when the run loop exists", func() { - streamManager.EXPECT().CloseWithError(gomock.Any()) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - returned := make(chan struct{}) - go func() { - defer GinkgoRecover() - ctx := sess.Context() - <-ctx.Done() - Expect(ctx.Err()).To(MatchError(context.Canceled)) - close(returned) - }() - Consistently(returned).ShouldNot(BeClosed()) - sess.Close() - Eventually(returned).Should(BeClosed()) - }) - }) - - Context("receiving packets", func() { - var hdr *wire.Header - var unpacker *MockUnpacker - - BeforeEach(func() { - unpacker = NewMockUnpacker(mockCtrl) - sess.unpacker = unpacker - hdr = &wire.Header{PacketNumberLen: protocol.PacketNumberLen6} - }) - - It("sets the {last,largest}RcvdPacketNumber", func() { - hdr.PacketNumber = 5 - hdr.Raw = []byte("raw header") - unpacker.EXPECT().Unpack([]byte("raw header"), hdr, []byte("foobar")).Return(&unpackedPacket{}, nil) - err := sess.handlePacketImpl(&receivedPacket{header: hdr, data: []byte("foobar")}) - Expect(err).ToNot(HaveOccurred()) - Expect(sess.lastRcvdPacketNumber).To(Equal(protocol.PacketNumber(5))) - Expect(sess.largestRcvdPacketNumber).To(Equal(protocol.PacketNumber(5))) - }) - - It("informs the ReceivedPacketHandler", func() { - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil) - now := time.Now().Add(time.Hour) - rph := mockackhandler.NewMockReceivedPacketHandler(mockCtrl) - rph.EXPECT().ReceivedPacket(protocol.PacketNumber(5), now, false) - sess.receivedPacketHandler = rph - hdr.PacketNumber = 5 - err := sess.handlePacketImpl(&receivedPacket{header: hdr, rcvTime: now}) - Expect(err).ToNot(HaveOccurred()) - }) - - It("doesn't inform the ReceivedPacketHandler about Retry packets", func() { - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil) - now := time.Now().Add(time.Hour) - rph := mockackhandler.NewMockReceivedPacketHandler(mockCtrl) - sess.receivedPacketHandler = rph - // don't EXPECT any call to ReceivedPacket - hdr.PacketNumber = 5 - hdr.Type = protocol.PacketTypeRetry - err := sess.handlePacketImpl(&receivedPacket{header: hdr, rcvTime: now}) - Expect(err).ToNot(HaveOccurred()) - }) - - It("closes when handling a packet fails", func() { - testErr := errors.New("unpack error") - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, testErr) - streamManager.EXPECT().CloseWithError(gomock.Any()) - hdr.PacketNumber = 5 - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := sess.run() - Expect(err).To(MatchError(testErr)) - close(done) - }() - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.handlePacket(&receivedPacket{header: hdr}) - Eventually(done).Should(BeClosed()) - }) - - It("sets the {last,largest}RcvdPacketNumber, for an out-of-order packet", func() { - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil).Times(2) - hdr.PacketNumber = 5 - err := sess.handlePacketImpl(&receivedPacket{header: hdr}) - Expect(err).ToNot(HaveOccurred()) - Expect(sess.lastRcvdPacketNumber).To(Equal(protocol.PacketNumber(5))) - Expect(sess.largestRcvdPacketNumber).To(Equal(protocol.PacketNumber(5))) - hdr.PacketNumber = 3 - err = sess.handlePacketImpl(&receivedPacket{header: hdr}) - Expect(err).ToNot(HaveOccurred()) - Expect(sess.lastRcvdPacketNumber).To(Equal(protocol.PacketNumber(3))) - Expect(sess.largestRcvdPacketNumber).To(Equal(protocol.PacketNumber(5))) - }) - - It("handles duplicate packets", func() { - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil).Times(2) - hdr.PacketNumber = 5 - err := sess.handlePacketImpl(&receivedPacket{header: hdr}) - Expect(err).ToNot(HaveOccurred()) - err = sess.handlePacketImpl(&receivedPacket{header: hdr}) - Expect(err).ToNot(HaveOccurred()) - }) - - It("ignores packets with a different source connection ID", func() { - // Send one packet, which might change the connection ID. - // only EXPECT one call to the unpacker - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil) - err := sess.handlePacketImpl(&receivedPacket{ - header: &wire.Header{ - IsLongHeader: true, - DestConnectionID: sess.destConnID, - SrcConnectionID: sess.srcConnID, - }, - }) - Expect(err).ToNot(HaveOccurred()) - // The next packet has to be ignored, since the source connection ID doesn't match. - err = sess.handlePacketImpl(&receivedPacket{ - header: &wire.Header{ - IsLongHeader: true, - DestConnectionID: sess.destConnID, - SrcConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef}, - }, - }) - Expect(err).ToNot(HaveOccurred()) - }) - - Context("updating the remote address", func() { - It("doesn't support connection migration", func() { - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil) - origAddr := sess.conn.(*mockConnection).remoteAddr - remoteIP := &net.IPAddr{IP: net.IPv4(192, 168, 0, 100)} - Expect(origAddr).ToNot(Equal(remoteIP)) - p := receivedPacket{ - remoteAddr: remoteIP, - header: &wire.Header{PacketNumber: 1337}, - } - err := sess.handlePacketImpl(&p) - Expect(err).ToNot(HaveOccurred()) - Expect(sess.conn.(*mockConnection).remoteAddr).To(Equal(origAddr)) - }) - }) - }) - - Context("sending packets", func() { - BeforeEach(func() { - sess.packer.hasSentPacket = true // make sure this is not the first packet the packer sends - }) - - It("sends ACK frames", func() { - packetNumber := protocol.PacketNumber(0x035e) - err := sess.receivedPacketHandler.ReceivedPacket(packetNumber, time.Now(), true) - Expect(err).ToNot(HaveOccurred()) - sent, err := sess.sendPacket() - Expect(err).NotTo(HaveOccurred()) - Expect(sent).To(BeTrue()) - Expect(mconn.written).To(HaveLen(1)) - Expect(mconn.written).To(Receive(ContainSubstring(string([]byte{0x03, 0x5e})))) - }) - - It("adds MAX_STREAM_DATA frames", func() { - sess.windowUpdateQueue.callback(&wire.MaxStreamDataFrame{ - StreamID: 2, - ByteOffset: 20, - }) - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) { - Expect(p.Frames).To(ContainElement(&wire.MaxStreamDataFrame{StreamID: 2, ByteOffset: 20})) - }) - sess.sentPacketHandler = sph - sent, err := sess.sendPacket() - Expect(err).NotTo(HaveOccurred()) - Expect(sent).To(BeTrue()) - }) - - It("adds a BLOCKED frame when it is connection-level flow control blocked", func() { - fc := mocks.NewMockConnectionFlowController(mockCtrl) - fc.EXPECT().IsNewlyBlocked().Return(true, protocol.ByteCount(1337)) - sess.connFlowController = fc - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) { - Expect(p.Frames).To(Equal([]wire.Frame{ - &wire.BlockedFrame{Offset: 1337}, - })) - }) - sess.sentPacketHandler = sph - sent, err := sess.sendPacket() - Expect(err).NotTo(HaveOccurred()) - Expect(sent).To(BeTrue()) - }) - - It("sends public reset", func() { - err := sess.sendPublicReset(1) - Expect(err).NotTo(HaveOccurred()) - Expect(mconn.written).To(HaveLen(1)) - Expect(mconn.written).To(Receive(ContainSubstring("PRST"))) - }) - - It("doesn't retransmit an Initial packet if it already received a response", func() { - unpacker := NewMockUnpacker(mockCtrl) - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil) - sess.unpacker = unpacker - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes() - sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{ - PacketNumber: 10, - PacketType: protocol.PacketTypeInitial, - }) - sph.EXPECT().DequeuePacketForRetransmission() - rph := mockackhandler.NewMockReceivedPacketHandler(mockCtrl) - rph.EXPECT().ReceivedPacket(gomock.Any(), gomock.Any(), gomock.Any()) - sess.receivedPacketHandler = rph - sess.sentPacketHandler = sph - err := sess.handlePacketImpl(&receivedPacket{ - header: &wire.Header{}, - data: []byte{0}, - }) - Expect(err).ToNot(HaveOccurred()) - Expect(sess.receivedFirstPacket).To(BeTrue()) - sent, err := sess.maybeSendRetransmission() - Expect(err).NotTo(HaveOccurred()) - Expect(sent).To(BeFalse()) - }) - - It("sends a retransmission and a regular packet in the same run", func() { - sess.windowUpdateQueue.callback(&wire.MaxDataFrame{}) - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes() - sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{ - PacketNumber: 10, - PacketType: protocol.PacketTypeHandshake, - }) - sph.EXPECT().SendMode().Return(ackhandler.SendRetransmission) - sph.EXPECT().SendMode().Return(ackhandler.SendAny) - sph.EXPECT().ShouldSendNumPackets().Return(2) - sph.EXPECT().TimeUntilSend() - sph.EXPECT().GetStopWaitingFrame(gomock.Any()).Return(&wire.StopWaitingFrame{}) - gomock.InOrder( - sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(10)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) { - Expect(packets).To(HaveLen(1)) - Expect(len(packets[0].Frames)).To(BeNumerically(">", 0)) - Expect(packets[0].Frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{})) - Expect(packets[0].SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond)) - }), - sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) { - Expect(p.Frames).To(HaveLen(1)) - Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.MaxDataFrame{})) - Expect(p.SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond)) - }), - ) - sess.sentPacketHandler = sph - err := sess.sendPackets() - Expect(err).ToNot(HaveOccurred()) - }) - - It("sends a probe packet", func() { - f := &wire.MaxDataFrame{ByteOffset: 1337} - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().TimeUntilSend() - sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes() - sph.EXPECT().SendMode().Return(ackhandler.SendTLP) - sph.EXPECT().ShouldSendNumPackets().Return(1) - sph.EXPECT().DequeueProbePacket().Return(&ackhandler.Packet{ - PacketNumber: 0x42, - Frames: []wire.Frame{f}, - }, nil) - sph.EXPECT().GetStopWaitingFrame(true).Return(&wire.StopWaitingFrame{}) - sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(0x42)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) { - Expect(packets).To(HaveLen(1)) - p := packets[0] - Expect(p.Frames).To(HaveLen(2)) - Expect(p.Frames[1]).To(Equal(f)) - }) - sess.sentPacketHandler = sph - err := sess.sendPackets() - Expect(err).ToNot(HaveOccurred()) - }) - - It("doesn't send when the SentPacketHandler doesn't allow it", func() { - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().SendMode().Return(ackhandler.SendNone) - sess.sentPacketHandler = sph - err := sess.sendPackets() - Expect(err).ToNot(HaveOccurred()) - }) - }) - - Context("packet pacing", func() { - var sph *mockackhandler.MockSentPacketHandler - - BeforeEach(func() { - sph = mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().GetAlarmTimeout().AnyTimes() - sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes() - sph.EXPECT().DequeuePacketForRetransmission().AnyTimes() - sess.sentPacketHandler = sph - sess.packer.hasSentPacket = true - streamManager.EXPECT().CloseWithError(gomock.Any()) - }) - - It("sends multiple packets one by one immediately", func() { - sph.EXPECT().SentPacket(gomock.Any()).Times(2) - sph.EXPECT().ShouldSendNumPackets().Return(1).Times(2) - sph.EXPECT().TimeUntilSend().Return(time.Now()).Times(2) - sph.EXPECT().TimeUntilSend().Return(time.Now().Add(time.Hour)) - sph.EXPECT().SendMode().Return(ackhandler.SendAny).Do(func() { - // make sure there's something to send - sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 1}) - }).Times(2) // allow 2 packets... - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess.run() - close(done) - }() - sess.scheduleSending() - Eventually(mconn.written).Should(HaveLen(2)) - Consistently(mconn.written).Should(HaveLen(2)) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - - // when becoming congestion limited, at some point the SendMode will change from SendAny to SendAck - // we shouldn't send the ACK in the same run - It("doesn't send an ACK right after becoming congestion limited", func() { - sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 1}) - sph.EXPECT().SentPacket(gomock.Any()) - sph.EXPECT().ShouldSendNumPackets().Return(1000) - sph.EXPECT().TimeUntilSend().Return(time.Now()) - sph.EXPECT().SendMode().Return(ackhandler.SendAny) - sph.EXPECT().SendMode().Return(ackhandler.SendAck) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess.run() - close(done) - }() - sess.scheduleSending() - Eventually(mconn.written).Should(HaveLen(1)) - Consistently(mconn.written).Should(HaveLen(1)) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - - It("paces packets", func() { - pacingDelay := scaleDuration(100 * time.Millisecond) - sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 1}) - sph.EXPECT().SentPacket(gomock.Any()).Times(2) - sph.EXPECT().TimeUntilSend().Return(time.Now().Add(-time.Minute)) // send one packet immediately - sph.EXPECT().TimeUntilSend().Return(time.Now().Add(pacingDelay)) // send one - sph.EXPECT().TimeUntilSend().Return(time.Now().Add(time.Hour)) - sph.EXPECT().ShouldSendNumPackets().Times(2).Return(1) - sph.EXPECT().SendMode().Return(ackhandler.SendAny).Do(func() { // after sending the first packet - // make sure there's something to send - sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 2}) - }).AnyTimes() - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess.run() - close(done) - }() - sess.scheduleSending() - Eventually(mconn.written).Should(HaveLen(1)) - Consistently(mconn.written, pacingDelay/2).Should(HaveLen(1)) - Eventually(mconn.written, 2*pacingDelay).Should(HaveLen(2)) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - - It("sends multiple packets at once", func() { - sph.EXPECT().SentPacket(gomock.Any()).Times(3) - sph.EXPECT().ShouldSendNumPackets().Return(3) - sph.EXPECT().TimeUntilSend().Return(time.Now()) - sph.EXPECT().TimeUntilSend().Return(time.Now().Add(time.Hour)) - sph.EXPECT().SendMode().Return(ackhandler.SendAny).Do(func() { - // make sure there's something to send - sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 1}) - }).Times(3) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess.run() - close(done) - }() - sess.scheduleSending() - Eventually(mconn.written).Should(HaveLen(3)) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - - It("doesn't set a pacing timer when there is no data to send", func() { - sph.EXPECT().TimeUntilSend().Return(time.Now()) - sph.EXPECT().ShouldSendNumPackets().Return(1) - sph.EXPECT().SendMode().Return(ackhandler.SendAny).AnyTimes() - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess.run() - close(done) - }() - sess.scheduleSending() // no packet will get sent - Consistently(mconn.written).ShouldNot(Receive()) - // queue a frame, and expect that it won't be sent - sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 1}) - Consistently(mconn.written).ShouldNot(Receive()) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - }) - - Context("sending ACK only packets", func() { - It("doesn't do anything if there's no ACK to be sent", func() { - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sess.sentPacketHandler = sph - err := sess.maybeSendAckOnlyPacket() - Expect(err).ToNot(HaveOccurred()) - Expect(mconn.written).To(BeEmpty()) - }) - - It("sends ACK only packets", func() { - swf := &wire.StopWaitingFrame{LeastUnacked: 10} - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes() - sph.EXPECT().GetAlarmTimeout().AnyTimes() - sph.EXPECT().SendMode().Return(ackhandler.SendAck) - sph.EXPECT().ShouldSendNumPackets().Return(1000) - sph.EXPECT().GetStopWaitingFrame(false).Return(swf) - sph.EXPECT().TimeUntilSend() - sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) { - Expect(p.Frames).To(HaveLen(2)) - Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.AckFrame{})) - Expect(p.Frames[1]).To(Equal(swf)) - Expect(p.SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond)) - }) - sess.sentPacketHandler = sph - sess.packer.packetNumberGenerator.next = 0x1338 - sess.receivedPacketHandler.ReceivedPacket(1, time.Now(), true) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess.run() - close(done) - }() - sess.scheduleSending() - Eventually(mconn.written).Should(HaveLen(1)) - // make sure that the go routine returns - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - streamManager.EXPECT().CloseWithError(gomock.Any()) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - - It("doesn't include a STOP_WAITING for an ACK-only packet for IETF QUIC", func() { - sess.version = versionIETFFrames - done := make(chan struct{}) - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes() - sph.EXPECT().GetAlarmTimeout().AnyTimes() - sph.EXPECT().SendMode().Return(ackhandler.SendAck) - sph.EXPECT().ShouldSendNumPackets().Return(1000) - sph.EXPECT().TimeUntilSend() - sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) { - Expect(p.Frames).To(HaveLen(1)) - Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.AckFrame{})) - Expect(p.SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond)) - }) - sess.sentPacketHandler = sph - sess.packer.packetNumberGenerator.next = 0x1338 - sess.receivedPacketHandler.ReceivedPacket(1, time.Now(), true) - go func() { - defer GinkgoRecover() - sess.run() - close(done) - }() - sess.scheduleSending() - Eventually(mconn.written).Should(HaveLen(1)) - // make sure that the go routine returns - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - streamManager.EXPECT().CloseWithError(gomock.Any()) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - }) - - Context("retransmissions", func() { - var sph *mockackhandler.MockSentPacketHandler - BeforeEach(func() { - // a STOP_WAITING frame is added, so make sure the packet number of the new package is higher than the packet number of the retransmitted packet - sess.packer.packetNumberGenerator.next = 0x1337 + 10 - sess.packer.hasSentPacket = true // make sure this is not the first packet the packer sends - sph = mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes() - sess.sentPacketHandler = sph - sess.packer.cryptoSetup = &mockCryptoSetup{encLevelSeal: protocol.EncryptionForwardSecure} - }) - - Context("for handshake packets", func() { - It("retransmits an unencrypted packet, and adds a STOP_WAITING frame (for gQUIC)", func() { - sf := &wire.StreamFrame{StreamID: 1, Data: []byte("foobar")} - swf := &wire.StopWaitingFrame{LeastUnacked: 0x1337} - sph.EXPECT().GetStopWaitingFrame(true).Return(swf) - sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{ - PacketNumber: 42, - Frames: []wire.Frame{sf}, - EncryptionLevel: protocol.EncryptionUnencrypted, - }) - sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(42)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) { - Expect(packets).To(HaveLen(1)) - p := packets[0] - Expect(p.EncryptionLevel).To(Equal(protocol.EncryptionUnencrypted)) - Expect(p.Frames).To(Equal([]wire.Frame{swf, sf})) - Expect(p.SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond)) - }) - sent, err := sess.maybeSendRetransmission() - Expect(err).NotTo(HaveOccurred()) - Expect(sent).To(BeTrue()) - Expect(mconn.written).To(HaveLen(1)) - }) - - It("retransmits an unencrypted packet, and doesn't add a STOP_WAITING frame (for IETF QUIC)", func() { - sess.version = versionIETFFrames - sess.packer.version = versionIETFFrames - sess.packer.srcConnID = sess.destConnID - sf := &wire.StreamFrame{StreamID: 1, Data: []byte("foobar")} - sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{ - PacketNumber: 1337, - Frames: []wire.Frame{sf}, - EncryptionLevel: protocol.EncryptionUnencrypted, - }) - sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(1337)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) { - Expect(packets).To(HaveLen(1)) - p := packets[0] - Expect(p.EncryptionLevel).To(Equal(protocol.EncryptionUnencrypted)) - Expect(p.Frames).To(Equal([]wire.Frame{sf})) - Expect(p.SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond)) - }) - sent, err := sess.maybeSendRetransmission() - Expect(err).NotTo(HaveOccurred()) - Expect(sent).To(BeTrue()) - Expect(mconn.written).To(HaveLen(1)) - }) - }) - - Context("for packets after the handshake", func() { - It("sends a STREAM frame from a packet queued for retransmission, and adds a STOP_WAITING (for gQUIC)", func() { - f := &wire.StreamFrame{ - StreamID: 0x5, - Data: []byte("foobar"), - } - swf := &wire.StopWaitingFrame{LeastUnacked: 10} - sph.EXPECT().GetStopWaitingFrame(true).Return(swf) - sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{ - PacketNumber: 0x1337, - Frames: []wire.Frame{f}, - EncryptionLevel: protocol.EncryptionForwardSecure, - }) - sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(0x1337)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) { - Expect(packets).To(HaveLen(1)) - p := packets[0] - Expect(p.Frames).To(HaveLen(2)) - Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{})) - Expect(p.Frames[1]).To(Equal(f)) - Expect(p.EncryptionLevel).To(Equal(protocol.EncryptionForwardSecure)) - }) - sent, err := sess.maybeSendRetransmission() - Expect(err).NotTo(HaveOccurred()) - Expect(sent).To(BeTrue()) - Expect(mconn.written).To(HaveLen(1)) - }) - - It("sends a STREAM frame from a packet queued for retransmission, and doesn't add a STOP_WAITING (for IETF QUIC)", func() { - sess.version = versionIETFFrames - sess.packer.version = versionIETFFrames - f := &wire.StreamFrame{ - StreamID: 0x5, - Data: []byte("foobar"), - } - sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{ - PacketNumber: 42, - Frames: []wire.Frame{f}, - EncryptionLevel: protocol.EncryptionForwardSecure, - }) - sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(42)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) { - Expect(packets).To(HaveLen(1)) - p := packets[0] - Expect(p.Frames).To(Equal([]wire.Frame{f})) - Expect(p.EncryptionLevel).To(Equal(protocol.EncryptionForwardSecure)) - }) - sent, err := sess.maybeSendRetransmission() - Expect(err).NotTo(HaveOccurred()) - Expect(sent).To(BeTrue()) - Expect(mconn.written).To(HaveLen(1)) - }) - - It("sends multiple packets, if the retransmission is split", func() { - sess.version = versionIETFFrames - sess.packer.version = versionIETFFrames - f := &wire.StreamFrame{ - StreamID: 0x5, - Data: bytes.Repeat([]byte{'b'}, int(protocol.MaxPacketSizeIPv4)*3/2), - } - sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{ - PacketNumber: 42, - Frames: []wire.Frame{f}, - EncryptionLevel: protocol.EncryptionForwardSecure, - }) - sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(42)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) { - Expect(packets).To(HaveLen(2)) - for _, p := range packets { - Expect(p.Frames).To(HaveLen(1)) - Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.StreamFrame{})) - Expect(p.EncryptionLevel).To(Equal(protocol.EncryptionForwardSecure)) - } - }) - sent, err := sess.maybeSendRetransmission() - Expect(err).NotTo(HaveOccurred()) - Expect(sent).To(BeTrue()) - Expect(mconn.written).To(HaveLen(2)) - }) - }) - }) - - Context("scheduling sending", func() { - BeforeEach(func() { - sess.packer.hasSentPacket = true // make sure this is not the first packet the packer sends - sess.packer.cryptoSetup = &mockCryptoSetup{encLevelSeal: protocol.EncryptionForwardSecure} - }) - - It("sends when scheduleSending is called", func() { - sess.packer.packetNumberGenerator.next = 10000 - sess.packer.QueueControlFrame(&wire.BlockedFrame{}) - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().GetAlarmTimeout().AnyTimes() - sph.EXPECT().TimeUntilSend().AnyTimes() - sph.EXPECT().SendMode().Return(ackhandler.SendAny).AnyTimes() - sph.EXPECT().ShouldSendNumPackets().AnyTimes().Return(1) - sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes() - sph.EXPECT().SentPacket(gomock.Any()) - sess.sentPacketHandler = sph - - go func() { - defer GinkgoRecover() - sess.run() - }() - Consistently(mconn.written).ShouldNot(Receive()) - sess.scheduleSending() - Eventually(mconn.written).Should(Receive()) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - streamManager.EXPECT().CloseWithError(gomock.Any()) - sess.Close() - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("sets the timer to the ack timer", func() { - sph := mockackhandler.NewMockSentPacketHandler(mockCtrl) - sph.EXPECT().TimeUntilSend().Return(time.Now()) - sph.EXPECT().TimeUntilSend().Return(time.Now().Add(time.Hour)) - sph.EXPECT().GetAlarmTimeout().AnyTimes() - sph.EXPECT().SendMode().Return(ackhandler.SendAny).AnyTimes() - sph.EXPECT().GetStopWaitingFrame(gomock.Any()) - sph.EXPECT().ShouldSendNumPackets().Return(1) - sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) { - Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.AckFrame{})) - Expect(p.Frames[0].(*wire.AckFrame).LargestAcked()).To(Equal(protocol.PacketNumber(0x1337))) - }) - sess.sentPacketHandler = sph - rph := mockackhandler.NewMockReceivedPacketHandler(mockCtrl) - rph.EXPECT().GetAckFrame().Return(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 0x1337}}}) - rph.EXPECT().GetAlarmTimeout().Return(time.Now().Add(10 * time.Millisecond)) - rph.EXPECT().GetAlarmTimeout().Return(time.Now().Add(time.Hour)) - sess.receivedPacketHandler = rph - - go func() { - defer GinkgoRecover() - sess.run() - }() - Eventually(mconn.written).Should(Receive()) - // make sure the go routine returns - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - streamManager.EXPECT().CloseWithError(gomock.Any()) - sess.Close() - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - }) - - It("closes when crypto stream errors", func() { - testErr := errors.New("crypto setup error") - streamManager.EXPECT().CloseWithError(qerr.Error(qerr.InternalError, testErr.Error())) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - cryptoSetup.handleErr = testErr - go func() { - defer GinkgoRecover() - err := sess.run() - Expect(err).To(MatchError(testErr)) - }() - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - Context("sending a Public Reset when receiving undecryptable packets during the handshake", func() { - // sends protocol.MaxUndecryptablePackets+1 undecrytable packets - // this completely fills up the undecryptable packets queue and triggers the public reset timer - sendUndecryptablePackets := func() { - for i := 0; i < protocol.MaxUndecryptablePackets+1; i++ { - hdr := &wire.Header{ - PacketNumber: protocol.PacketNumber(i + 1), - } - sess.handlePacket(&receivedPacket{ - header: hdr, - remoteAddr: &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1234}, - data: []byte("foobar"), - }) - } - } - - BeforeEach(func() { - unpacker := NewMockUnpacker(mockCtrl) - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, qerr.Error(qerr.DecryptionFailure, "")).AnyTimes() - sess.unpacker = unpacker - sess.cryptoStreamHandler = &mockCryptoSetup{} - streamManager.EXPECT().CloseWithError(gomock.Any()).MaxTimes(1) - }) - - It("doesn't immediately send a Public Reset after receiving too many undecryptable packets", func() { - go func() { - defer GinkgoRecover() - sess.run() - }() - sendUndecryptablePackets() - sess.scheduleSending() - Consistently(mconn.written).Should(HaveLen(0)) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("sets a deadline to send a Public Reset after receiving too many undecryptable packets", func() { - go func() { - defer GinkgoRecover() - sess.run() - }() - sendUndecryptablePackets() - Eventually(func() time.Time { return sess.receivedTooManyUndecrytablePacketsTime }).Should(BeTemporally("~", time.Now(), 20*time.Millisecond)) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("drops undecryptable packets when the undecrytable packet queue is full", func() { - go func() { - defer GinkgoRecover() - sess.run() - }() - sendUndecryptablePackets() - Eventually(func() []*receivedPacket { return sess.undecryptablePackets }).Should(HaveLen(protocol.MaxUndecryptablePackets)) - // check that old packets are kept, and the new packets are dropped - Expect(sess.undecryptablePackets[0].header.PacketNumber).To(Equal(protocol.PacketNumber(1))) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - Expect(sess.Close()).To(Succeed()) - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("sends a Public Reset after a timeout", func() { - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - Expect(sess.receivedTooManyUndecrytablePacketsTime).To(BeZero()) - go func() { - defer GinkgoRecover() - sess.run() - }() - sendUndecryptablePackets() - Eventually(func() time.Time { return sess.receivedTooManyUndecrytablePacketsTime }).Should(BeTemporally("~", time.Now(), time.Second)) - // speed up this test by manually setting back the time when too many packets were received - sess.receivedTooManyUndecrytablePacketsTime = time.Now().Add(-protocol.PublicResetTimeout) - time.Sleep(10 * time.Millisecond) // wait for the run loop to spin up - sess.scheduleSending() // wake up the run loop - Eventually(mconn.written).Should(HaveLen(1)) - Expect(mconn.written).To(Receive(ContainSubstring("PRST"))) - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("doesn't send a Public Reset if decrypting them succeeded during the timeout", func() { - go func() { - defer GinkgoRecover() - sess.run() - }() - sess.receivedTooManyUndecrytablePacketsTime = time.Now().Add(-protocol.PublicResetTimeout).Add(-time.Millisecond) - sess.scheduleSending() // wake up the run loop - // there are no packets in the undecryptable packet queue - // in reality, this happens when the trial decryption succeeded during the Public Reset timeout - Consistently(mconn.written).ShouldNot(HaveLen(1)) - Expect(sess.Context().Done()).ToNot(Receive()) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("ignores undecryptable packets after the handshake is complete", func() { - sess.handshakeComplete = true - go func() { - defer GinkgoRecover() - sess.run() - }() - sendUndecryptablePackets() - Consistently(sess.undecryptablePackets).Should(BeEmpty()) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - Expect(sess.Close()).To(Succeed()) - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("unqueues undecryptable packets for later decryption", func() { - sess.undecryptablePackets = []*receivedPacket{{ - header: &wire.Header{PacketNumber: protocol.PacketNumber(42)}, - }} - Expect(sess.receivedPackets).NotTo(Receive()) - sess.tryDecryptingQueuedPackets() - Expect(sess.undecryptablePackets).To(BeEmpty()) - Expect(sess.receivedPackets).To(Receive()) - }) - }) - - It("doesn't do anything when the crypto setup says to decrypt undecryptable packets", func() { - go func() { - defer GinkgoRecover() - sess.run() - }() - handshakeChan <- struct{}{} - // don't EXPECT any calls to sessionRunner.onHandshakeComplete() - // make sure the go routine returns - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - streamManager.EXPECT().CloseWithError(gomock.Any()) - Expect(sess.Close()).To(Succeed()) - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("calls the onHandshakeComplete callback when the handshake completes", func() { - go func() { - defer GinkgoRecover() - sess.run() - }() - sessionRunner.EXPECT().onHandshakeComplete(gomock.Any()) - close(handshakeChan) - Consistently(sess.Context().Done()).ShouldNot(BeClosed()) - // make sure the go routine returns - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - streamManager.EXPECT().CloseWithError(gomock.Any()) - Expect(sess.Close()).To(Succeed()) - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("doesn't return a run error when closing", func() { - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := sess.run() - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - streamManager.EXPECT().CloseWithError(gomock.Any()) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - Expect(sess.Close()).To(Succeed()) - Eventually(done).Should(BeClosed()) - }) - - It("passes errors to the session runner", func() { - testErr := errors.New("handshake error") - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := sess.run() - Expect(err).To(MatchError(qerr.Error(0x1337, testErr.Error()))) - close(done) - }() - streamManager.EXPECT().CloseWithError(gomock.Any()) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - Expect(sess.CloseWithError(0x1337, testErr)).To(Succeed()) - Eventually(done).Should(BeClosed()) - }) - - It("process transport parameters received from the peer", func() { - paramsChan := make(chan handshake.TransportParameters) - sess.paramsChan = paramsChan - go func() { - defer GinkgoRecover() - sess.run() - }() - params := handshake.TransportParameters{ - MaxStreams: 123, - IdleTimeout: 90 * time.Second, - StreamFlowControlWindow: 0x5000, - ConnectionFlowControlWindow: 0x5000, - OmitConnectionID: true, - MaxPacketSize: 0x42, - } - streamManager.EXPECT().UpdateLimits(¶ms) - paramsChan <- params - Eventually(func() *handshake.TransportParameters { return sess.peerParams }).Should(Equal(¶ms)) - Eventually(func() bool { return sess.packer.omitConnectionID }).Should(BeTrue()) - Eventually(func() protocol.ByteCount { return sess.packer.maxPacketSize }).Should(Equal(protocol.ByteCount(0x42))) - // make the go routine return - streamManager.EXPECT().CloseWithError(gomock.Any()) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - Context("keep-alives", func() { - // should be shorter than the local timeout for these tests - // otherwise we'd send a CONNECTION_CLOSE in the tests where we're testing that no PING is sent - remoteIdleTimeout := 20 * time.Second - - BeforeEach(func() { - sess.peerParams = &handshake.TransportParameters{IdleTimeout: remoteIdleTimeout} - }) - - It("sends a PING", func() { - sess.handshakeComplete = true - sess.config.KeepAlive = true - sess.lastNetworkActivityTime = time.Now().Add(-remoteIdleTimeout / 2) - sess.packer.hasSentPacket = true // make sure this is not the first packet the packer sends - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess.run() - close(done) - }() - var data []byte - Eventually(mconn.written).Should(Receive(&data)) - // -12 because of the crypto tag. This should be 7 (the frame id for a ping frame). - Expect(data[len(data)-12-1 : len(data)-12]).To(Equal([]byte{0x07})) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - streamManager.EXPECT().CloseWithError(gomock.Any()) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - - It("doesn't send a PING packet if keep-alive is disabled", func() { - sess.handshakeComplete = true - sess.config.KeepAlive = false - sess.lastNetworkActivityTime = time.Now().Add(-remoteIdleTimeout / 2) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess.run() - close(done) - }() - Consistently(mconn.written).ShouldNot(Receive()) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - streamManager.EXPECT().CloseWithError(gomock.Any()) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - - It("doesn't send a PING if the handshake isn't completed yet", func() { - sess.handshakeComplete = false - sess.config.KeepAlive = true - sess.lastNetworkActivityTime = time.Now().Add(-remoteIdleTimeout / 2) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - sess.run() - close(done) - }() - Consistently(mconn.written).ShouldNot(Receive()) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - streamManager.EXPECT().CloseWithError(gomock.Any()) - sess.Close() - Eventually(done).Should(BeClosed()) - }) - }) - - Context("timeouts", func() { - BeforeEach(func() { - streamManager.EXPECT().CloseWithError(gomock.Any()) - }) - - It("times out due to no network activity", func() { - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.handshakeComplete = true - sess.lastNetworkActivityTime = time.Now().Add(-time.Hour) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := sess.run() - Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.NetworkIdleTimeout)) - close(done) - }() - Eventually(done).Should(BeClosed()) - Expect(mconn.written).To(Receive(ContainSubstring("No recent network activity."))) - }) - - It("times out due to non-completed handshake", func() { - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.sessionCreationTime = time.Now().Add(-protocol.DefaultHandshakeTimeout).Add(-time.Second) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := sess.run() - Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.HandshakeTimeout)) - close(done) - }() - Eventually(done).Should(BeClosed()) - Expect(mconn.written).To(Receive(ContainSubstring("Crypto handshake did not complete in time."))) - }) - - It("does not use the idle timeout before the handshake complete", func() { - sess.config.IdleTimeout = 9999 * time.Second - defer sess.Close() - sess.lastNetworkActivityTime = time.Now().Add(-time.Minute) - // the handshake timeout is irrelevant here, since it depends on the time the session was created, - // and not on the last network activity - go func() { - defer GinkgoRecover() - sess.run() - }() - Consistently(sess.Context().Done()).ShouldNot(BeClosed()) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.Close() - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("closes the session due to the idle timeout after handshake", func() { - sessionRunner.EXPECT().onHandshakeComplete(sess) - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - sess.config.IdleTimeout = 0 - close(handshakeChan) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - err := sess.run() - Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.NetworkIdleTimeout)) - close(done) - }() - Eventually(done).Should(BeClosed()) - Expect(mconn.written).To(Receive(ContainSubstring("No recent network activity."))) - }) - }) - - It("stores up to MaxSessionUnprocessedPackets packets", func(done Done) { - // Nothing here should block - for i := protocol.PacketNumber(0); i < protocol.MaxSessionUnprocessedPackets+10; i++ { - sess.handlePacket(&receivedPacket{}) - } - close(done) - }, 0.5) - - Context("getting streams", func() { - It("returns a new stream", func() { - mstr := NewMockStreamI(mockCtrl) - streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(11)).Return(mstr, nil) - str, err := sess.GetOrOpenStream(11) - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(Equal(mstr)) - }) - - It("returns a nil-value (not an interface with value nil) for closed streams", func() { - strI := Stream(nil) - streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(1337)).Return(strI, nil) - str, err := sess.GetOrOpenStream(1337) - Expect(err).ToNot(HaveOccurred()) - // make sure that the returned value is a plain nil, not an Stream with value nil - _, ok := str.(Stream) - Expect(ok).To(BeFalse()) - }) - - It("errors when trying to get a unidirectional stream", func() { - streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(100)).Return(&sendStream{}, nil) - _, err := sess.GetOrOpenStream(100) - Expect(err).To(MatchError("Stream 100 is not a bidirectional stream")) - }) - - It("opens streams", func() { - mstr := NewMockStreamI(mockCtrl) - streamManager.EXPECT().OpenStream().Return(mstr, nil) - str, err := sess.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(Equal(mstr)) - }) - - It("opens streams synchronously", func() { - mstr := NewMockStreamI(mockCtrl) - streamManager.EXPECT().OpenStreamSync().Return(mstr, nil) - str, err := sess.OpenStreamSync() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(Equal(mstr)) - }) - - It("opens unidirectional streams", func() { - mstr := NewMockSendStreamI(mockCtrl) - streamManager.EXPECT().OpenUniStream().Return(mstr, nil) - str, err := sess.OpenUniStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(Equal(mstr)) - }) - - It("opens unidirectional streams synchronously", func() { - mstr := NewMockSendStreamI(mockCtrl) - streamManager.EXPECT().OpenUniStreamSync().Return(mstr, nil) - str, err := sess.OpenUniStreamSync() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(Equal(mstr)) - }) - - It("accepts streams", func() { - mstr := NewMockStreamI(mockCtrl) - streamManager.EXPECT().AcceptStream().Return(mstr, nil) - str, err := sess.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(Equal(mstr)) - }) - - It("accepts unidirectional streams", func() { - mstr := NewMockReceiveStreamI(mockCtrl) - streamManager.EXPECT().AcceptUniStream().Return(mstr, nil) - str, err := sess.AcceptUniStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(Equal(mstr)) - }) - }) - - It("returns the local address", func() { - addr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1337} - mconn.localAddr = addr - Expect(sess.LocalAddr()).To(Equal(addr)) - }) - - It("returns the remote address", func() { - addr := &net.UDPAddr{IP: net.IPv4(1, 2, 7, 1), Port: 7331} - mconn.remoteAddr = addr - Expect(sess.RemoteAddr()).To(Equal(addr)) - }) -}) - -var _ = Describe("Client Session", func() { - var ( - sess *session - sessionRunner *MockSessionRunner - mconn *mockConnection - handshakeChan chan<- struct{} - - cryptoSetup *mockCryptoSetup - ) - - BeforeEach(func() { - Eventually(areSessionsRunning).Should(BeFalse()) - - cryptoSetup = &mockCryptoSetup{} - newCryptoSetupClient = func( - _ io.ReadWriter, - _ string, - _ protocol.ConnectionID, - _ protocol.VersionNumber, - _ *tls.Config, - _ *handshake.TransportParameters, - _ chan<- handshake.TransportParameters, - handshakeChanP chan<- struct{}, - _ protocol.VersionNumber, - _ []protocol.VersionNumber, - _ utils.Logger, - ) (handshake.CryptoSetup, error) { - handshakeChan = handshakeChanP - return cryptoSetup, nil - } - - mconn = newMockConnection() - sessionRunner = NewMockSessionRunner(mockCtrl) - sessP, err := newClientSession( - mconn, - sessionRunner, - "hostname", - protocol.Version39, - protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1}, - protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1}, - nil, - populateClientConfig(&Config{}, false), - protocol.VersionWhatever, - nil, - utils.DefaultLogger, - ) - sess = sessP.(*session) - Expect(err).ToNot(HaveOccurred()) - }) - - AfterEach(func() { - newCryptoSetupClient = handshake.NewCryptoSetupClient - }) - - It("sends a forward-secure packet when the handshake completes", func() { - sessionRunner.EXPECT().onHandshakeComplete(gomock.Any()) - sess.packer.hasSentPacket = true - go func() { - defer GinkgoRecover() - sess.run() - }() - close(handshakeChan) - Eventually(mconn.written).Should(Receive()) - //make sure the go routine returns - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - Expect(sess.Close()).To(Succeed()) - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - It("changes the connection ID when receiving the first packet from the server", func() { - sess.version = protocol.VersionTLS - sess.packer.version = protocol.VersionTLS - sess.packer.srcConnID = sess.destConnID - unpacker := NewMockUnpacker(mockCtrl) - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil) - sess.unpacker = unpacker - go func() { - defer GinkgoRecover() - sess.run() - }() - err := sess.handlePacketImpl(&receivedPacket{ - header: &wire.Header{ - IsLongHeader: true, - Type: protocol.PacketTypeHandshake, - SrcConnectionID: protocol.ConnectionID{1, 3, 3, 7, 1, 3, 3, 7}, - DestConnectionID: sess.srcConnID, - }, - data: []byte{0}, - }) - Expect(err).ToNot(HaveOccurred()) - // the session should have changed the dest connection ID now - sess.packer.hasSentPacket = true - sess.queueControlFrame(&wire.PingFrame{}) - var packet []byte - Eventually(mconn.written).Should(Receive(&packet)) - hdr, err := wire.ParseInvariantHeader(bytes.NewReader(packet), 0) - Expect(err).ToNot(HaveOccurred()) - Expect(hdr.DestConnectionID).To(Equal(protocol.ConnectionID{1, 3, 3, 7, 1, 3, 3, 7})) - // make sure the go routine returns - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - Expect(sess.Close()).To(Succeed()) - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - - Context("receiving packets", func() { - var hdr *wire.Header - - BeforeEach(func() { - hdr = &wire.Header{PacketNumberLen: protocol.PacketNumberLen6} - }) - - It("passes the diversification nonce to the crypto setup", func() { - cryptoSetup := &mockCryptoSetup{} - sess.cryptoStreamHandler = cryptoSetup - unpacker := NewMockUnpacker(mockCtrl) - unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil) - sess.unpacker = unpacker - go func() { - defer GinkgoRecover() - sess.run() - }() - hdr.PacketNumber = 5 - hdr.DiversificationNonce = []byte("foobar") - err := sess.handlePacketImpl(&receivedPacket{header: hdr}) - Expect(err).ToNot(HaveOccurred()) - Expect(cryptoSetup.divNonce).To(Equal(hdr.DiversificationNonce)) - // make the go routine return - sessionRunner.EXPECT().removeConnectionID(gomock.Any()) - Expect(sess.Close()).To(Succeed()) - Eventually(sess.Context().Done()).Should(BeClosed()) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/stream_framer_test.go b/vendor/lucas-clemente/quic-go/stream_framer_test.go deleted file mode 100644 index fff5e2231..000000000 --- a/vendor/lucas-clemente/quic-go/stream_framer_test.go +++ /dev/null @@ -1,207 +0,0 @@ -package quic - -import ( - "bytes" - - "github.com/golang/mock/gomock" - - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Stream Framer", func() { - const ( - id1 = protocol.StreamID(10) - id2 = protocol.StreamID(11) - ) - - var ( - framer *streamFramer - cryptoStream *MockCryptoStream - stream1, stream2 *MockSendStreamI - streamGetter *MockStreamGetter - ) - - BeforeEach(func() { - streamGetter = NewMockStreamGetter(mockCtrl) - stream1 = NewMockSendStreamI(mockCtrl) - stream1.EXPECT().StreamID().Return(protocol.StreamID(5)).AnyTimes() - stream2 = NewMockSendStreamI(mockCtrl) - stream2.EXPECT().StreamID().Return(protocol.StreamID(6)).AnyTimes() - cryptoStream = NewMockCryptoStream(mockCtrl) - framer = newStreamFramer(cryptoStream, streamGetter, versionGQUICFrames) - }) - - Context("handling the crypto stream", func() { - It("says if it has crypto stream data", func() { - Expect(framer.HasCryptoStreamData()).To(BeFalse()) - framer.AddActiveStream(framer.version.CryptoStreamID()) - Expect(framer.HasCryptoStreamData()).To(BeTrue()) - }) - - It("says that it doesn't have crypto stream data after popping all data", func() { - streamID := framer.version.CryptoStreamID() - f := &wire.StreamFrame{ - StreamID: streamID, - Data: []byte("foobar"), - } - cryptoStream.EXPECT().popStreamFrame(protocol.ByteCount(1000)).Return(f, false) - framer.AddActiveStream(streamID) - Expect(framer.PopCryptoStreamFrame(1000)).To(Equal(f)) - Expect(framer.HasCryptoStreamData()).To(BeFalse()) - }) - - It("says that it has more crypto stream data if not all data was popped", func() { - streamID := framer.version.CryptoStreamID() - f := &wire.StreamFrame{ - StreamID: streamID, - Data: []byte("foobar"), - } - cryptoStream.EXPECT().popStreamFrame(protocol.ByteCount(1000)).Return(f, true) - framer.AddActiveStream(streamID) - Expect(framer.PopCryptoStreamFrame(1000)).To(Equal(f)) - Expect(framer.HasCryptoStreamData()).To(BeTrue()) - }) - }) - - Context("Popping", func() { - It("returns nil when popping an empty framer", func() { - Expect(framer.PopStreamFrames(1000)).To(BeEmpty()) - }) - - It("returns STREAM frames", func() { - streamGetter.EXPECT().GetOrOpenSendStream(id1).Return(stream1, nil) - f := &wire.StreamFrame{ - StreamID: id1, - Data: []byte("foobar"), - Offset: 42, - } - stream1.EXPECT().popStreamFrame(gomock.Any()).Return(f, false) - framer.AddActiveStream(id1) - fs := framer.PopStreamFrames(1000) - Expect(fs).To(Equal([]*wire.StreamFrame{f})) - }) - - It("skips a stream that was reported active, but was completed shortly after", func() { - streamGetter.EXPECT().GetOrOpenSendStream(id1).Return(nil, nil) - streamGetter.EXPECT().GetOrOpenSendStream(id2).Return(stream2, nil) - f := &wire.StreamFrame{ - StreamID: id2, - Data: []byte("foobar"), - } - stream2.EXPECT().popStreamFrame(gomock.Any()).Return(f, false) - framer.AddActiveStream(id1) - framer.AddActiveStream(id2) - Expect(framer.PopStreamFrames(1000)).To(Equal([]*wire.StreamFrame{f})) - }) - - It("skips a stream that was reported active, but doesn't have any data", func() { - streamGetter.EXPECT().GetOrOpenSendStream(id1).Return(stream1, nil) - streamGetter.EXPECT().GetOrOpenSendStream(id2).Return(stream2, nil) - f := &wire.StreamFrame{ - StreamID: id2, - Data: []byte("foobar"), - } - stream1.EXPECT().popStreamFrame(gomock.Any()).Return(nil, false) - stream2.EXPECT().popStreamFrame(gomock.Any()).Return(f, false) - framer.AddActiveStream(id1) - framer.AddActiveStream(id2) - Expect(framer.PopStreamFrames(1000)).To(Equal([]*wire.StreamFrame{f})) - }) - - It("pops from a stream multiple times, if it has enough data", func() { - streamGetter.EXPECT().GetOrOpenSendStream(id1).Return(stream1, nil).Times(2) - f1 := &wire.StreamFrame{StreamID: id1, Data: []byte("foobar")} - f2 := &wire.StreamFrame{StreamID: id1, Data: []byte("foobaz")} - stream1.EXPECT().popStreamFrame(gomock.Any()).Return(f1, true) - stream1.EXPECT().popStreamFrame(gomock.Any()).Return(f2, false) - framer.AddActiveStream(id1) // only add it once - Expect(framer.PopStreamFrames(protocol.MinStreamFrameSize)).To(Equal([]*wire.StreamFrame{f1})) - Expect(framer.PopStreamFrames(protocol.MinStreamFrameSize)).To(Equal([]*wire.StreamFrame{f2})) - // no further calls to popStreamFrame, after popStreamFrame said there's no more data - Expect(framer.PopStreamFrames(protocol.MinStreamFrameSize)).To(BeNil()) - }) - - It("re-queues a stream at the end, if it has enough data", func() { - streamGetter.EXPECT().GetOrOpenSendStream(id1).Return(stream1, nil).Times(2) - streamGetter.EXPECT().GetOrOpenSendStream(id2).Return(stream2, nil) - f11 := &wire.StreamFrame{StreamID: id1, Data: []byte("foobar")} - f12 := &wire.StreamFrame{StreamID: id1, Data: []byte("foobaz")} - f2 := &wire.StreamFrame{StreamID: id2, Data: []byte("raboof")} - stream1.EXPECT().popStreamFrame(gomock.Any()).Return(f11, true) - stream1.EXPECT().popStreamFrame(gomock.Any()).Return(f12, false) - stream2.EXPECT().popStreamFrame(gomock.Any()).Return(f2, false) - framer.AddActiveStream(id1) // only add it once - framer.AddActiveStream(id2) - Expect(framer.PopStreamFrames(protocol.MinStreamFrameSize)).To(Equal([]*wire.StreamFrame{f11})) // first a frame from stream 1 - Expect(framer.PopStreamFrames(protocol.MinStreamFrameSize)).To(Equal([]*wire.StreamFrame{f2})) // then a frame from stream 2 - Expect(framer.PopStreamFrames(protocol.MinStreamFrameSize)).To(Equal([]*wire.StreamFrame{f12})) // then another frame from stream 1 - }) - - It("only dequeues data from each stream once per packet", func() { - streamGetter.EXPECT().GetOrOpenSendStream(id1).Return(stream1, nil) - streamGetter.EXPECT().GetOrOpenSendStream(id2).Return(stream2, nil) - f1 := &wire.StreamFrame{StreamID: id1, Data: []byte("foobar")} - f2 := &wire.StreamFrame{StreamID: id2, Data: []byte("raboof")} - // both streams have more data, and will be re-queued - stream1.EXPECT().popStreamFrame(gomock.Any()).Return(f1, true) - stream2.EXPECT().popStreamFrame(gomock.Any()).Return(f2, true) - framer.AddActiveStream(id1) - framer.AddActiveStream(id2) - Expect(framer.PopStreamFrames(1000)).To(Equal([]*wire.StreamFrame{f1, f2})) - }) - - It("returns multiple normal frames in the order they were reported active", func() { - streamGetter.EXPECT().GetOrOpenSendStream(id1).Return(stream1, nil) - streamGetter.EXPECT().GetOrOpenSendStream(id2).Return(stream2, nil) - f1 := &wire.StreamFrame{Data: []byte("foobar")} - f2 := &wire.StreamFrame{Data: []byte("foobaz")} - stream1.EXPECT().popStreamFrame(gomock.Any()).Return(f1, false) - stream2.EXPECT().popStreamFrame(gomock.Any()).Return(f2, false) - framer.AddActiveStream(id2) - framer.AddActiveStream(id1) - Expect(framer.PopStreamFrames(1000)).To(Equal([]*wire.StreamFrame{f2, f1})) - }) - - It("only asks a stream for data once, even if it was reported active multiple times", func() { - streamGetter.EXPECT().GetOrOpenSendStream(id1).Return(stream1, nil) - f := &wire.StreamFrame{Data: []byte("foobar")} - stream1.EXPECT().popStreamFrame(gomock.Any()).Return(f, false) // only one call to this function - framer.AddActiveStream(id1) - framer.AddActiveStream(id1) - Expect(framer.PopStreamFrames(1000)).To(HaveLen(1)) - }) - - It("does not pop empty frames", func() { - fs := framer.PopStreamFrames(500) - Expect(fs).To(BeEmpty()) - }) - - It("pops frames that have the minimum size", func() { - streamGetter.EXPECT().GetOrOpenSendStream(id1).Return(stream1, nil) - stream1.EXPECT().popStreamFrame(protocol.MinStreamFrameSize).Return(&wire.StreamFrame{Data: []byte("foobar")}, false) - framer.AddActiveStream(id1) - framer.PopStreamFrames(protocol.MinStreamFrameSize) - }) - - It("does not pop frames smaller than the minimum size", func() { - // don't expect a call to PopStreamFrame() - framer.PopStreamFrames(protocol.MinStreamFrameSize - 1) - }) - - It("stops iterating when the remaining size is smaller than the minimum STREAM frame size", func() { - streamGetter.EXPECT().GetOrOpenSendStream(id1).Return(stream1, nil) - // pop a frame such that the remaining size is one byte less than the minimum STREAM frame size - f := &wire.StreamFrame{ - StreamID: id1, - Data: bytes.Repeat([]byte("f"), int(500-protocol.MinStreamFrameSize)), - } - stream1.EXPECT().popStreamFrame(protocol.ByteCount(500)).Return(f, false) - framer.AddActiveStream(id1) - fs := framer.PopStreamFrames(500) - Expect(fs).To(Equal([]*wire.StreamFrame{f})) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/stream_test.go b/vendor/lucas-clemente/quic-go/stream_test.go deleted file mode 100644 index 864e0edb4..000000000 --- a/vendor/lucas-clemente/quic-go/stream_test.go +++ /dev/null @@ -1,208 +0,0 @@ -package quic - -import ( - "io" - "os" - "strconv" - "time" - - "github.com/lucas-clemente/quic-go/internal/mocks" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" -) - -// in the tests for the stream deadlines we set a deadline -// and wait to make an assertion when Read / Write was unblocked -// on the CIs, the timing is a lot less precise, so scale every duration by this factor -func scaleDuration(t time.Duration) time.Duration { - scaleFactor := 1 - if f, err := strconv.Atoi(os.Getenv("TIMESCALE_FACTOR")); err == nil { // parsing "" errors, so this works fine if the env is not set - scaleFactor = f - } - Expect(scaleFactor).ToNot(BeZero()) - return time.Duration(scaleFactor) * t -} - -var _ = Describe("Stream", func() { - const streamID protocol.StreamID = 1337 - - var ( - str *stream - strWithTimeout io.ReadWriter // str wrapped with gbytes.Timeout{Reader,Writer} - mockFC *mocks.MockStreamFlowController - mockSender *MockStreamSender - ) - - BeforeEach(func() { - mockSender = NewMockStreamSender(mockCtrl) - mockFC = mocks.NewMockStreamFlowController(mockCtrl) - str = newStream(streamID, mockSender, mockFC, protocol.VersionWhatever) - - timeout := scaleDuration(250 * time.Millisecond) - strWithTimeout = struct { - io.Reader - io.Writer - }{ - gbytes.TimeoutReader(str, timeout), - gbytes.TimeoutWriter(str, timeout), - } - }) - - It("gets stream id", func() { - Expect(str.StreamID()).To(Equal(protocol.StreamID(1337))) - }) - - // need some stream cancelation tests here, since gQUIC doesn't cleanly separate the two stream halves - Context("stream cancelations", func() { - Context("for gQUIC", func() { - BeforeEach(func() { - str.version = versionGQUICFrames - str.receiveStream.version = versionGQUICFrames - str.sendStream.version = versionGQUICFrames - }) - - It("unblocks Write when receiving a RST_STREAM frame with non-zero error code", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockSender.EXPECT().queueControlFrame(&wire.RstStreamFrame{ - StreamID: streamID, - ByteOffset: 1000, - ErrorCode: errorCodeStoppingGQUIC, - }) - mockSender.EXPECT().onStreamCompleted(streamID) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(6), true) - str.writeOffset = 1000 - f := &wire.RstStreamFrame{ - StreamID: streamID, - ByteOffset: 6, - ErrorCode: 123, - } - writeReturned := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).To(MatchError("Stream 1337 was reset with error code 123")) - Expect(err).To(BeAssignableToTypeOf(streamCanceledError{})) - Expect(err.(streamCanceledError).Canceled()).To(BeTrue()) - Expect(err.(streamCanceledError).ErrorCode()).To(Equal(protocol.ApplicationErrorCode(123))) - close(writeReturned) - }() - Consistently(writeReturned).ShouldNot(BeClosed()) - err := str.handleRstStreamFrame(f) - Expect(err).ToNot(HaveOccurred()) - Eventually(writeReturned).Should(BeClosed()) - }) - - It("unblocks Write when receiving a RST_STREAM frame with error code 0", func() { - mockSender.EXPECT().onHasStreamData(streamID) - mockSender.EXPECT().queueControlFrame(&wire.RstStreamFrame{ - StreamID: streamID, - ByteOffset: 1000, - ErrorCode: errorCodeStoppingGQUIC, - }) - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(6), true) - str.writeOffset = 1000 - f := &wire.RstStreamFrame{ - StreamID: streamID, - ByteOffset: 6, - ErrorCode: 0, - } - writeReturned := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).To(MatchError("Stream 1337 was reset with error code 0")) - Expect(err).To(BeAssignableToTypeOf(streamCanceledError{})) - Expect(err.(streamCanceledError).Canceled()).To(BeTrue()) - Expect(err.(streamCanceledError).ErrorCode()).To(Equal(protocol.ApplicationErrorCode(0))) - close(writeReturned) - }() - Consistently(writeReturned).ShouldNot(BeClosed()) - err := str.handleRstStreamFrame(f) - Expect(err).ToNot(HaveOccurred()) - Eventually(writeReturned).Should(BeClosed()) - }) - - It("sends a RST_STREAM with error code 0, after the stream is closed", func() { - str.version = versionGQUICFrames - mockSender.EXPECT().onHasStreamData(streamID).Times(2) // once for the Write, once for the Close - mockFC.EXPECT().SendWindowSize().Return(protocol.MaxByteCount).AnyTimes() - mockFC.EXPECT().AddBytesSent(protocol.ByteCount(6)) - err := str.CancelRead(1234) - Expect(err).ToNot(HaveOccurred()) - writeReturned := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).ToNot(HaveOccurred()) - close(writeReturned) - }() - Eventually(func() *wire.StreamFrame { - frame, _ := str.popStreamFrame(1000) - return frame - }).ShouldNot(BeNil()) - Eventually(writeReturned).Should(BeClosed()) - mockSender.EXPECT().queueControlFrame(&wire.RstStreamFrame{ - StreamID: streamID, - ByteOffset: 6, - ErrorCode: 0, - }) - Expect(str.Close()).To(Succeed()) - }) - }) - - Context("for IETF QUIC", func() { - It("doesn't queue a RST_STREAM after closing the stream", func() { // this is what it does for gQUIC - mockSender.EXPECT().queueControlFrame(&wire.StopSendingFrame{ - StreamID: streamID, - ErrorCode: 1234, - }) - mockSender.EXPECT().onHasStreamData(streamID) - err := str.CancelRead(1234) - Expect(err).ToNot(HaveOccurred()) - Expect(str.Close()).To(Succeed()) - }) - }) - }) - - Context("deadlines", func() { - It("sets a write deadline, when SetDeadline is called", func() { - str.SetDeadline(time.Now().Add(-time.Second)) - n, err := strWithTimeout.Write([]byte("foobar")) - Expect(err).To(MatchError(errDeadline)) - Expect(n).To(BeZero()) - }) - - It("sets a read deadline, when SetDeadline is called", func() { - mockFC.EXPECT().UpdateHighestReceived(protocol.ByteCount(6), false).AnyTimes() - f := &wire.StreamFrame{Data: []byte("foobar")} - err := str.handleStreamFrame(f) - Expect(err).ToNot(HaveOccurred()) - str.SetDeadline(time.Now().Add(-time.Second)) - b := make([]byte, 6) - n, err := strWithTimeout.Read(b) - Expect(err).To(MatchError(errDeadline)) - Expect(n).To(BeZero()) - }) - }) - - Context("completing", func() { - It("is not completed when only the receive side is completed", func() { - // don't EXPECT a call to mockSender.onStreamCompleted() - str.receiveStream.sender.onStreamCompleted(streamID) - }) - - It("is not completed when only the send side is completed", func() { - // don't EXPECT a call to mockSender.onStreamCompleted() - str.sendStream.sender.onStreamCompleted(streamID) - }) - - It("is completed when both sides are completed", func() { - mockSender.EXPECT().onStreamCompleted(streamID) - str.sendStream.sender.onStreamCompleted(streamID) - str.receiveStream.sender.onStreamCompleted(streamID) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/streams_map_incoming_generic_test.go b/vendor/lucas-clemente/quic-go/streams_map_incoming_generic_test.go deleted file mode 100644 index e9d8dbb4d..000000000 --- a/vendor/lucas-clemente/quic-go/streams_map_incoming_generic_test.go +++ /dev/null @@ -1,165 +0,0 @@ -package quic - -import ( - "errors" - "fmt" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type mockGenericStream struct { - id protocol.StreamID - - closed bool - closeErr error -} - -func (s *mockGenericStream) closeForShutdown(err error) { - s.closed = true - s.closeErr = err -} - -var _ = Describe("Streams Map (incoming)", func() { - const ( - firstNewStream protocol.StreamID = 20 - maxNumStreams int = 10 - initialMaxStream protocol.StreamID = firstNewStream + 4*protocol.StreamID(maxNumStreams-1) - ) - - var ( - m *incomingItemsMap - newItem func(id protocol.StreamID) item - newItemCounter int - mockSender *MockStreamSender - ) - - BeforeEach(func() { - newItemCounter = 0 - newItem = func(id protocol.StreamID) item { - newItemCounter++ - return &mockGenericStream{id: id} - } - mockSender = NewMockStreamSender(mockCtrl) - m = newIncomingItemsMap(firstNewStream, initialMaxStream, maxNumStreams, mockSender.queueControlFrame, newItem) - }) - - It("opens all streams up to the id on GetOrOpenStream", func() { - _, err := m.GetOrOpenStream(firstNewStream + 4*5) - Expect(err).ToNot(HaveOccurred()) - Expect(newItemCounter).To(Equal(6)) - }) - - It("starts opening streams at the right position", func() { - // like the test above, but with 2 calls to GetOrOpenStream - _, err := m.GetOrOpenStream(firstNewStream + 4) - Expect(err).ToNot(HaveOccurred()) - Expect(newItemCounter).To(Equal(2)) - _, err = m.GetOrOpenStream(firstNewStream + 4*5) - Expect(err).ToNot(HaveOccurred()) - Expect(newItemCounter).To(Equal(6)) - }) - - It("accepts streams in the right order", func() { - _, err := m.GetOrOpenStream(firstNewStream + 4) // open stream 20 and 24 - Expect(err).ToNot(HaveOccurred()) - str, err := m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.(*mockGenericStream).id).To(Equal(firstNewStream)) - str, err = m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.(*mockGenericStream).id).To(Equal(firstNewStream + 4)) - }) - - It("allows opening the maximum stream ID", func() { - str, err := m.GetOrOpenStream(initialMaxStream) - Expect(err).ToNot(HaveOccurred()) - Expect(str.(*mockGenericStream).id).To(Equal(initialMaxStream)) - }) - - It("errors when trying to get a stream ID higher than the maximum", func() { - _, err := m.GetOrOpenStream(initialMaxStream + 4) - Expect(err).To(MatchError(fmt.Errorf("peer tried to open stream %d (current limit: %d)", initialMaxStream+4, initialMaxStream))) - }) - - It("blocks AcceptStream until a new stream is available", func() { - strChan := make(chan item) - go func() { - defer GinkgoRecover() - str, err := m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - strChan <- str - }() - Consistently(strChan).ShouldNot(Receive()) - str, err := m.GetOrOpenStream(firstNewStream) - Expect(err).ToNot(HaveOccurred()) - Expect(str.(*mockGenericStream).id).To(Equal(firstNewStream)) - var acceptedStr item - Eventually(strChan).Should(Receive(&acceptedStr)) - Expect(acceptedStr.(*mockGenericStream).id).To(Equal(firstNewStream)) - }) - - It("unblocks AcceptStream when it is closed", func() { - testErr := errors.New("test error") - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := m.AcceptStream() - Expect(err).To(MatchError(testErr)) - close(done) - }() - Consistently(done).ShouldNot(BeClosed()) - m.CloseWithError(testErr) - Eventually(done).Should(BeClosed()) - }) - - It("errors AcceptStream immediately if it is closed", func() { - testErr := errors.New("test error") - m.CloseWithError(testErr) - _, err := m.AcceptStream() - Expect(err).To(MatchError(testErr)) - }) - - It("closes all streams when CloseWithError is called", func() { - str1, err := m.GetOrOpenStream(20) - Expect(err).ToNot(HaveOccurred()) - str2, err := m.GetOrOpenStream(20 + 8) - Expect(err).ToNot(HaveOccurred()) - testErr := errors.New("test err") - m.CloseWithError(testErr) - Expect(str1.(*mockGenericStream).closed).To(BeTrue()) - Expect(str1.(*mockGenericStream).closeErr).To(MatchError(testErr)) - Expect(str2.(*mockGenericStream).closed).To(BeTrue()) - Expect(str2.(*mockGenericStream).closeErr).To(MatchError(testErr)) - }) - - It("deletes streams", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - _, err := m.GetOrOpenStream(20) - Expect(err).ToNot(HaveOccurred()) - err = m.DeleteStream(20) - Expect(err).ToNot(HaveOccurred()) - str, err := m.GetOrOpenStream(20) - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeNil()) - }) - - It("errors when deleting a non-existing stream", func() { - err := m.DeleteStream(1337) - Expect(err).To(MatchError("Tried to delete unknown stream 1337")) - }) - - It("sends MAX_STREAM_ID frames when streams are deleted", func() { - // open a bunch of streams - _, err := m.GetOrOpenStream(firstNewStream + 4*4) - Expect(err).ToNot(HaveOccurred()) - mockSender.EXPECT().queueControlFrame(&wire.MaxStreamIDFrame{StreamID: initialMaxStream + 4}) - Expect(m.DeleteStream(firstNewStream + 4)).To(Succeed()) - mockSender.EXPECT().queueControlFrame(&wire.MaxStreamIDFrame{StreamID: initialMaxStream + 8}) - Expect(m.DeleteStream(firstNewStream + 3*4)).To(Succeed()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/streams_map_legacy_test.go b/vendor/lucas-clemente/quic-go/streams_map_legacy_test.go deleted file mode 100644 index b9450bc00..000000000 --- a/vendor/lucas-clemente/quic-go/streams_map_legacy_test.go +++ /dev/null @@ -1,564 +0,0 @@ -package quic - -import ( - "errors" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/handshake" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - "github.com/lucas-clemente/quic-go/qerr" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Streams Map (for gQUIC)", func() { - var m *streamsMapLegacy - - newStream := func(id protocol.StreamID) streamI { - str := NewMockStreamI(mockCtrl) - str.EXPECT().StreamID().Return(id).AnyTimes() - return str - } - - setNewStreamsMap := func(p protocol.Perspective) { - m = newStreamsMapLegacy(newStream, protocol.DefaultMaxIncomingStreams, p).(*streamsMapLegacy) - } - - deleteStream := func(id protocol.StreamID) { - ExpectWithOffset(1, m.DeleteStream(id)).To(Succeed()) - } - - It("applies the max stream limit for small number of streams", func() { - sm := newStreamsMapLegacy(newStream, 1, protocol.PerspectiveServer).(*streamsMapLegacy) - Expect(sm.maxIncomingStreams).To(BeEquivalentTo(1 + protocol.MaxStreamsMinimumIncrement)) - }) - - It("applies the max stream limit for big number of streams", func() { - sm := newStreamsMapLegacy(newStream, 1000, protocol.PerspectiveServer).(*streamsMapLegacy) - Expect(sm.maxIncomingStreams).To(BeEquivalentTo(1000 * protocol.MaxStreamsMultiplier)) - }) - - Context("getting and creating streams", func() { - Context("as a server", func() { - BeforeEach(func() { - setNewStreamsMap(protocol.PerspectiveServer) - }) - - Context("client-side streams", func() { - It("gets new streams", func() { - s, err := m.getOrOpenStream(3) - Expect(err).NotTo(HaveOccurred()) - Expect(s).ToNot(BeNil()) - Expect(s.StreamID()).To(Equal(protocol.StreamID(3))) - Expect(m.streams).To(HaveLen(1)) - Expect(m.numIncomingStreams).To(BeEquivalentTo(1)) - Expect(m.numOutgoingStreams).To(BeZero()) - }) - - It("rejects streams with even IDs", func() { - _, err := m.getOrOpenStream(6) - Expect(err).To(MatchError("InvalidStreamID: peer attempted to open stream 6")) - }) - - It("rejects streams with even IDs, which are lower thatn the highest client-side stream", func() { - _, err := m.getOrOpenStream(5) - Expect(err).NotTo(HaveOccurred()) - _, err = m.getOrOpenStream(4) - Expect(err).To(MatchError("InvalidStreamID: peer attempted to open stream 4")) - }) - - It("gets existing streams", func() { - s, err := m.getOrOpenStream(5) - Expect(err).NotTo(HaveOccurred()) - Expect(s.StreamID()).To(Equal(protocol.StreamID(5))) - numStreams := m.numIncomingStreams - s, err = m.getOrOpenStream(5) - Expect(err).NotTo(HaveOccurred()) - Expect(s.StreamID()).To(Equal(protocol.StreamID(5))) - Expect(m.numIncomingStreams).To(Equal(numStreams)) - }) - - It("returns nil for closed streams", func() { - _, err := m.getOrOpenStream(5) - Expect(err).NotTo(HaveOccurred()) - deleteStream(5) - s, err := m.getOrOpenStream(5) - Expect(err).NotTo(HaveOccurred()) - Expect(s).To(BeNil()) - }) - - It("opens skipped streams", func() { - _, err := m.getOrOpenStream(7) - Expect(err).NotTo(HaveOccurred()) - Expect(m.streams).To(HaveKey(protocol.StreamID(3))) - Expect(m.streams).To(HaveKey(protocol.StreamID(5))) - Expect(m.streams).To(HaveKey(protocol.StreamID(7))) - }) - - It("doesn't reopen an already closed stream", func() { - _, err := m.getOrOpenStream(5) - Expect(err).ToNot(HaveOccurred()) - deleteStream(5) - Expect(err).ToNot(HaveOccurred()) - str, err := m.getOrOpenStream(5) - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeNil()) - }) - - Context("counting streams", func() { - It("errors when too many streams are opened", func() { - for i := uint32(0); i < m.maxIncomingStreams; i++ { - _, err := m.getOrOpenStream(protocol.StreamID(i*2 + 1)) - Expect(err).NotTo(HaveOccurred()) - } - _, err := m.getOrOpenStream(protocol.StreamID(2*m.maxIncomingStreams + 3)) - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - }) - - It("errors when too many streams are opened implicitly", func() { - _, err := m.getOrOpenStream(protocol.StreamID(m.maxIncomingStreams*2 + 3)) - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - }) - - It("does not error when many streams are opened and closed", func() { - for i := uint32(2); i < 10*m.maxIncomingStreams; i++ { - str, err := m.getOrOpenStream(protocol.StreamID(i*2 + 1)) - Expect(err).NotTo(HaveOccurred()) - deleteStream(str.StreamID()) - } - }) - }) - }) - - Context("server-side streams", func() { - It("doesn't allow opening streams before receiving the transport parameters", func() { - _, err := m.OpenStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - }) - - It("opens a stream 2 first", func() { - m.UpdateLimits(&handshake.TransportParameters{MaxStreams: 10000}) - s, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(s).ToNot(BeNil()) - Expect(s.StreamID()).To(Equal(protocol.StreamID(2))) - Expect(m.numIncomingStreams).To(BeZero()) - Expect(m.numOutgoingStreams).To(BeEquivalentTo(1)) - }) - - It("returns the error when the streamsMap was closed", func() { - testErr := errors.New("test error") - m.CloseWithError(testErr) - _, err := m.OpenStream() - Expect(err).To(MatchError(testErr)) - }) - - It("doesn't reopen an already closed stream", func() { - m.UpdateLimits(&handshake.TransportParameters{MaxStreams: 10000}) - str, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(protocol.StreamID(2))) - deleteStream(2) - Expect(err).ToNot(HaveOccurred()) - str, err = m.getOrOpenStream(2) - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeNil()) - }) - - Context("counting streams", func() { - const maxOutgoingStreams = 50 - - BeforeEach(func() { - m.UpdateLimits(&handshake.TransportParameters{MaxStreams: maxOutgoingStreams}) - }) - - It("errors when too many streams are opened", func() { - for i := 1; i <= maxOutgoingStreams; i++ { - _, err := m.OpenStream() - Expect(err).NotTo(HaveOccurred()) - } - _, err := m.OpenStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - }) - - It("does not error when many streams are opened and closed", func() { - for i := 2; i < 10*maxOutgoingStreams; i++ { - str, err := m.OpenStream() - Expect(err).NotTo(HaveOccurred()) - deleteStream(str.StreamID()) - } - }) - - It("allows many server- and client-side streams at the same time", func() { - for i := 1; i < maxOutgoingStreams; i++ { - _, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - } - for i := 0; i < maxOutgoingStreams; i++ { - _, err := m.getOrOpenStream(protocol.StreamID(2*i + 1)) - Expect(err).ToNot(HaveOccurred()) - } - }) - }) - - Context("opening streams synchronously", func() { - const maxOutgoingStreams = 10 - - BeforeEach(func() { - m.UpdateLimits(&handshake.TransportParameters{MaxStreams: maxOutgoingStreams}) - }) - - openMaxNumStreams := func() { - for i := 1; i <= maxOutgoingStreams; i++ { - _, err := m.OpenStream() - Expect(err).NotTo(HaveOccurred()) - } - _, err := m.OpenStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - } - - It("waits until another stream is closed", func() { - openMaxNumStreams() - var str Stream - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - var err error - str, err = m.OpenStreamSync() - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - Consistently(done).ShouldNot(BeClosed()) - deleteStream(6) - Eventually(done).Should(BeClosed()) - Expect(str.StreamID()).To(Equal(protocol.StreamID(2*maxOutgoingStreams + 2))) - }) - - It("stops waiting when an error is registered", func() { - testErr := errors.New("test error") - openMaxNumStreams() - for _, str := range m.streams { - str.(*MockStreamI).EXPECT().closeForShutdown(testErr) - } - - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := m.OpenStreamSync() - Expect(err).To(MatchError(testErr)) - close(done) - }() - - Consistently(done).ShouldNot(BeClosed()) - m.CloseWithError(testErr) - Eventually(done).Should(BeClosed()) - }) - - It("immediately returns when OpenStreamSync is called after an error was registered", func() { - testErr := errors.New("test error") - m.CloseWithError(testErr) - _, err := m.OpenStreamSync() - Expect(err).To(MatchError(testErr)) - }) - }) - }) - - Context("accepting streams", func() { - It("does nothing if no stream is opened", func() { - var accepted bool - go func() { - _, _ = m.AcceptStream() - accepted = true - }() - Consistently(func() bool { return accepted }).Should(BeFalse()) - }) - - It("starts with stream 3", func() { - var str Stream - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - var err error - str, err = m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - _, err := m.getOrOpenStream(3) - Expect(err).ToNot(HaveOccurred()) - Eventually(done).Should(BeClosed()) - Expect(str.StreamID()).To(Equal(protocol.StreamID(3))) - }) - - It("returns an implicitly opened stream, if a stream number is skipped", func() { - var str Stream - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - var err error - str, err = m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - _, err := m.getOrOpenStream(5) - Expect(err).ToNot(HaveOccurred()) - Eventually(done).Should(BeClosed()) - Expect(str.StreamID()).To(Equal(protocol.StreamID(3))) - }) - - It("returns to multiple accepts", func() { - var str1, str2 Stream - done1 := make(chan struct{}) - done2 := make(chan struct{}) - go func() { - defer GinkgoRecover() - var err error - str1, err = m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - close(done1) - }() - go func() { - defer GinkgoRecover() - var err error - str2, err = m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - close(done2) - }() - _, err := m.getOrOpenStream(5) // opens stream 3 and 5 - Expect(err).ToNot(HaveOccurred()) - Eventually(done1).Should(BeClosed()) - Eventually(done2).Should(BeClosed()) - Expect(str1.StreamID()).ToNot(Equal(str2.StreamID())) - Expect(str1.StreamID() + str2.StreamID()).To(BeEquivalentTo(3 + 5)) - }) - - It("waits until a new stream is available", func() { - var str Stream - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - var err error - str, err = m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - Consistently(done).ShouldNot(BeClosed()) - _, err := m.getOrOpenStream(3) - Expect(err).ToNot(HaveOccurred()) - Eventually(done).Should(BeClosed()) - Expect(str.StreamID()).To(Equal(protocol.StreamID(3))) - }) - - It("returns multiple streams on subsequent Accept calls, if available", func() { - var str Stream - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - var err error - str, err = m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - _, err := m.getOrOpenStream(5) - Expect(err).ToNot(HaveOccurred()) - Eventually(done).Should(BeClosed()) - Expect(str.StreamID()).To(Equal(protocol.StreamID(3))) - str, err = m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(protocol.StreamID(5))) - }) - - It("blocks after accepting a stream", func() { - _, err := m.getOrOpenStream(3) - Expect(err).ToNot(HaveOccurred()) - str, err := m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(protocol.StreamID(3))) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, _ = m.AcceptStream() - close(done) - }() - Consistently(done).ShouldNot(BeClosed()) - // make the go routine return - str.(*MockStreamI).EXPECT().closeForShutdown(gomock.Any()) - m.CloseWithError(errors.New("shut down")) - Eventually(done).Should(BeClosed()) - }) - - It("stops waiting when an error is registered", func() { - testErr := errors.New("testErr") - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := m.AcceptStream() - Expect(err).To(MatchError(testErr)) - close(done) - }() - Consistently(done).ShouldNot(BeClosed()) - m.CloseWithError(testErr) - Eventually(done).Should(BeClosed()) - }) - It("immediately returns when Accept is called after an error was registered", func() { - testErr := errors.New("testErr") - m.CloseWithError(testErr) - _, err := m.AcceptStream() - Expect(err).To(MatchError(testErr)) - }) - }) - }) - - Context("as a client", func() { - BeforeEach(func() { - setNewStreamsMap(protocol.PerspectiveClient) - m.UpdateLimits(&handshake.TransportParameters{MaxStreams: 10000}) - }) - - Context("server-side streams", func() { - It("rejects streams with odd IDs", func() { - _, err := m.getOrOpenStream(5) - Expect(err).To(MatchError("InvalidStreamID: peer attempted to open stream 5")) - }) - - It("rejects streams with odds IDs, which are lower than the highest server-side stream", func() { - _, err := m.getOrOpenStream(6) - Expect(err).NotTo(HaveOccurred()) - _, err = m.getOrOpenStream(5) - Expect(err).To(MatchError("InvalidStreamID: peer attempted to open stream 5")) - }) - - It("gets new streams", func() { - s, err := m.getOrOpenStream(2) - Expect(err).NotTo(HaveOccurred()) - Expect(s.StreamID()).To(Equal(protocol.StreamID(2))) - Expect(m.streams).To(HaveLen(1)) - Expect(m.numOutgoingStreams).To(BeZero()) - Expect(m.numIncomingStreams).To(BeEquivalentTo(1)) - }) - - It("opens skipped streams", func() { - _, err := m.getOrOpenStream(6) - Expect(err).NotTo(HaveOccurred()) - Expect(m.streams).To(HaveKey(protocol.StreamID(2))) - Expect(m.streams).To(HaveKey(protocol.StreamID(4))) - Expect(m.streams).To(HaveKey(protocol.StreamID(6))) - Expect(m.numOutgoingStreams).To(BeZero()) - Expect(m.numIncomingStreams).To(BeEquivalentTo(3)) - }) - - It("doesn't reopen an already closed stream", func() { - str, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(protocol.StreamID(3))) - deleteStream(3) - Expect(err).ToNot(HaveOccurred()) - str, err = m.getOrOpenStream(3) - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeNil()) - }) - }) - - Context("client-side streams", func() { - It("starts with stream 3", func() { - s, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(s).ToNot(BeNil()) - Expect(s.StreamID()).To(BeEquivalentTo(3)) - Expect(m.numOutgoingStreams).To(BeEquivalentTo(1)) - Expect(m.numIncomingStreams).To(BeZero()) - }) - - It("opens multiple streams", func() { - s1, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - s2, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(s2.StreamID()).To(Equal(s1.StreamID() + 2)) - }) - - It("doesn't reopen an already closed stream", func() { - _, err := m.getOrOpenStream(4) - Expect(err).ToNot(HaveOccurred()) - deleteStream(4) - Expect(err).ToNot(HaveOccurred()) - str, err := m.getOrOpenStream(4) - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeNil()) - }) - }) - - Context("accepting streams", func() { - It("accepts stream 2 first", func() { - var str Stream - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - var err error - str, err = m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - close(done) - }() - _, err := m.getOrOpenStream(2) - Expect(err).ToNot(HaveOccurred()) - Eventually(done).Should(BeClosed()) - Expect(str.StreamID()).To(Equal(protocol.StreamID(2))) - }) - }) - }) - }) - - Context("deleting streams", func() { - BeforeEach(func() { - setNewStreamsMap(protocol.PerspectiveServer) - }) - - It("deletes an incoming stream", func() { - _, err := m.getOrOpenStream(5) // open stream 3 and 5 - Expect(err).ToNot(HaveOccurred()) - Expect(m.numIncomingStreams).To(BeEquivalentTo(2)) - err = m.DeleteStream(3) - Expect(err).ToNot(HaveOccurred()) - Expect(m.streams).To(HaveLen(1)) - Expect(m.streams).To(HaveKey(protocol.StreamID(5))) - Expect(m.numIncomingStreams).To(BeEquivalentTo(1)) - }) - - It("deletes an outgoing stream", func() { - m.UpdateLimits(&handshake.TransportParameters{MaxStreams: 10000}) - _, err := m.OpenStream() // open stream 2 - Expect(err).ToNot(HaveOccurred()) - _, err = m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(m.numOutgoingStreams).To(BeEquivalentTo(2)) - err = m.DeleteStream(2) - Expect(err).ToNot(HaveOccurred()) - Expect(m.numOutgoingStreams).To(BeEquivalentTo(1)) - }) - - It("errors when the stream doesn't exist", func() { - err := m.DeleteStream(1337) - Expect(err).To(MatchError(errMapAccess)) - }) - }) - - It("sets the flow control limit", func() { - setNewStreamsMap(protocol.PerspectiveServer) - _, err := m.getOrOpenStream(5) - Expect(err).ToNot(HaveOccurred()) - m.streams[3].(*MockStreamI).EXPECT().handleMaxStreamDataFrame(&wire.MaxStreamDataFrame{ - StreamID: 3, - ByteOffset: 321, - }) - m.streams[5].(*MockStreamI).EXPECT().handleMaxStreamDataFrame(&wire.MaxStreamDataFrame{ - StreamID: 5, - ByteOffset: 321, - }) - m.UpdateLimits(&handshake.TransportParameters{StreamFlowControlWindow: 321}) - }) - - It("doesn't accept MAX_STREAM_ID frames", func() { - Expect(m.HandleMaxStreamIDFrame(&wire.MaxStreamIDFrame{})).ToNot(Succeed()) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/streams_map_outgoing_generic_test.go b/vendor/lucas-clemente/quic-go/streams_map_outgoing_generic_test.go deleted file mode 100644 index c8426899f..000000000 --- a/vendor/lucas-clemente/quic-go/streams_map_outgoing_generic_test.go +++ /dev/null @@ -1,170 +0,0 @@ -package quic - -import ( - "errors" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - "github.com/lucas-clemente/quic-go/qerr" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Streams Map (outgoing)", func() { - const firstNewStream protocol.StreamID = 10 - var ( - m *outgoingItemsMap - newItem func(id protocol.StreamID) item - mockSender *MockStreamSender - ) - - BeforeEach(func() { - newItem = func(id protocol.StreamID) item { - return &mockGenericStream{id: id} - } - mockSender = NewMockStreamSender(mockCtrl) - m = newOutgoingItemsMap(firstNewStream, newItem, mockSender.queueControlFrame) - }) - - Context("no stream ID limit", func() { - BeforeEach(func() { - m.SetMaxStream(0xffffffff) - }) - - It("opens streams", func() { - str, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.(*mockGenericStream).id).To(Equal(firstNewStream)) - str, err = m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.(*mockGenericStream).id).To(Equal(firstNewStream + 4)) - }) - - It("doesn't open streams after it has been closed", func() { - testErr := errors.New("close") - m.CloseWithError(testErr) - _, err := m.OpenStream() - Expect(err).To(MatchError(testErr)) - }) - - It("gets streams", func() { - _, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - str, err := m.GetStream(firstNewStream) - Expect(err).ToNot(HaveOccurred()) - Expect(str.(*mockGenericStream).id).To(Equal(firstNewStream)) - }) - - It("errors when trying to get a stream that has not yet been opened", func() { - _, err := m.GetStream(10) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidStreamID, "peer attempted to open stream 10"))) - }) - - It("deletes streams", func() { - _, err := m.OpenStream() // opens stream 10 - Expect(err).ToNot(HaveOccurred()) - err = m.DeleteStream(10) - Expect(err).ToNot(HaveOccurred()) - str, err := m.GetStream(10) - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeNil()) - }) - - It("errors when deleting a non-existing stream", func() { - err := m.DeleteStream(1337) - Expect(err).To(MatchError("Tried to delete unknown stream 1337")) - }) - - It("errors when deleting a stream twice", func() { - _, err := m.OpenStream() // opens stream 10 - Expect(err).ToNot(HaveOccurred()) - err = m.DeleteStream(10) - Expect(err).ToNot(HaveOccurred()) - err = m.DeleteStream(10) - Expect(err).To(MatchError("Tried to delete unknown stream 10")) - }) - - It("closes all streams when CloseWithError is called", func() { - str1, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - str2, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - testErr := errors.New("test err") - m.CloseWithError(testErr) - Expect(str1.(*mockGenericStream).closed).To(BeTrue()) - Expect(str1.(*mockGenericStream).closeErr).To(MatchError(testErr)) - Expect(str2.(*mockGenericStream).closed).To(BeTrue()) - Expect(str2.(*mockGenericStream).closeErr).To(MatchError(testErr)) - }) - }) - - Context("with stream ID limits", func() { - It("errors when no stream can be opened immediately", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - _, err := m.OpenStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - }) - - It("blocks until a stream can be opened synchronously", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - str, err := m.OpenStreamSync() - Expect(err).ToNot(HaveOccurred()) - Expect(str.(*mockGenericStream).id).To(Equal(firstNewStream)) - close(done) - }() - - Consistently(done).ShouldNot(BeClosed()) - m.SetMaxStream(firstNewStream) - Eventually(done).Should(BeClosed()) - }) - - It("stops opening synchronously when it is closed", func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - testErr := errors.New("test error") - done := make(chan struct{}) - go func() { - defer GinkgoRecover() - _, err := m.OpenStreamSync() - Expect(err).To(MatchError(testErr)) - close(done) - }() - - Consistently(done).ShouldNot(BeClosed()) - m.CloseWithError(testErr) - Eventually(done).Should(BeClosed()) - }) - - It("doesn't reduce the stream limit", func() { - m.SetMaxStream(firstNewStream) - m.SetMaxStream(firstNewStream - 4) - str, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.(*mockGenericStream).id).To(Equal(firstNewStream)) - }) - - It("queues a STREAM_ID_BLOCKED frame if no stream can be opened", func() { - m.SetMaxStream(firstNewStream) - mockSender.EXPECT().queueControlFrame(&wire.StreamIDBlockedFrame{StreamID: firstNewStream}) - _, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - _, err = m.OpenStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - }) - - It("only sends one STREAM_ID_BLOCKED frame for one stream ID", func() { - m.SetMaxStream(firstNewStream) - mockSender.EXPECT().queueControlFrame(&wire.StreamIDBlockedFrame{StreamID: firstNewStream}) - _, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - // try to open a stream twice, but expect only one STREAM_ID_BLOCKED to be sent - _, err = m.OpenStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - _, err = m.OpenStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - }) - }) -}) diff --git a/vendor/lucas-clemente/quic-go/streams_map_test.go b/vendor/lucas-clemente/quic-go/streams_map_test.go deleted file mode 100644 index 2cd58a3e3..000000000 --- a/vendor/lucas-clemente/quic-go/streams_map_test.go +++ /dev/null @@ -1,365 +0,0 @@ -package quic - -import ( - "errors" - "fmt" - "math" - - "github.com/golang/mock/gomock" - "github.com/lucas-clemente/quic-go/internal/flowcontrol" - "github.com/lucas-clemente/quic-go/internal/handshake" - "github.com/lucas-clemente/quic-go/internal/mocks" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - "github.com/lucas-clemente/quic-go/qerr" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type streamMapping struct { - firstIncomingBidiStream protocol.StreamID - firstIncomingUniStream protocol.StreamID - firstOutgoingBidiStream protocol.StreamID - firstOutgoingUniStream protocol.StreamID -} - -var _ = Describe("Streams Map (for IETF QUIC)", func() { - newFlowController := func(protocol.StreamID) flowcontrol.StreamFlowController { - return mocks.NewMockStreamFlowController(mockCtrl) - } - - serverStreamMapping := streamMapping{ - firstIncomingBidiStream: 4, - firstOutgoingBidiStream: 1, - firstIncomingUniStream: 2, - firstOutgoingUniStream: 3, - } - clientStreamMapping := streamMapping{ - firstIncomingBidiStream: 1, - firstOutgoingBidiStream: 4, - firstIncomingUniStream: 3, - firstOutgoingUniStream: 2, - } - - for _, p := range []protocol.Perspective{protocol.PerspectiveServer, protocol.PerspectiveClient} { - perspective := p - var ids streamMapping - if perspective == protocol.PerspectiveClient { - ids = clientStreamMapping - } else { - ids = serverStreamMapping - } - - Context(perspective.String(), func() { - var ( - m *streamsMap - mockSender *MockStreamSender - ) - - const ( - maxBidiStreams = 111 - maxUniStreams = 222 - ) - - allowUnlimitedStreams := func() { - m.UpdateLimits(&handshake.TransportParameters{ - MaxBidiStreams: math.MaxUint16, - MaxUniStreams: math.MaxUint16, - }) - } - - BeforeEach(func() { - mockSender = NewMockStreamSender(mockCtrl) - m = newStreamsMap(mockSender, newFlowController, maxBidiStreams, maxUniStreams, perspective, versionIETFFrames).(*streamsMap) - }) - - Context("opening", func() { - It("opens bidirectional streams", func() { - allowUnlimitedStreams() - str, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeAssignableToTypeOf(&stream{})) - Expect(str.StreamID()).To(Equal(ids.firstOutgoingBidiStream)) - str, err = m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeAssignableToTypeOf(&stream{})) - Expect(str.StreamID()).To(Equal(ids.firstOutgoingBidiStream + 4)) - }) - - It("opens unidirectional streams", func() { - allowUnlimitedStreams() - str, err := m.OpenUniStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeAssignableToTypeOf(&sendStream{})) - Expect(str.StreamID()).To(Equal(ids.firstOutgoingUniStream)) - str, err = m.OpenUniStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeAssignableToTypeOf(&sendStream{})) - Expect(str.StreamID()).To(Equal(ids.firstOutgoingUniStream + 4)) - }) - }) - - Context("accepting", func() { - It("accepts bidirectional streams", func() { - _, err := m.GetOrOpenReceiveStream(ids.firstIncomingBidiStream) - Expect(err).ToNot(HaveOccurred()) - str, err := m.AcceptStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeAssignableToTypeOf(&stream{})) - Expect(str.StreamID()).To(Equal(ids.firstIncomingBidiStream)) - }) - - It("accepts unidirectional streams", func() { - _, err := m.GetOrOpenReceiveStream(ids.firstIncomingUniStream) - Expect(err).ToNot(HaveOccurred()) - str, err := m.AcceptUniStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str).To(BeAssignableToTypeOf(&receiveStream{})) - Expect(str.StreamID()).To(Equal(ids.firstIncomingUniStream)) - }) - }) - - Context("deleting", func() { - BeforeEach(func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()).AnyTimes() - allowUnlimitedStreams() - }) - - It("deletes outgoing bidirectional streams", func() { - id := ids.firstOutgoingBidiStream - str, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(id)) - Expect(m.DeleteStream(id)).To(Succeed()) - dstr, err := m.GetOrOpenSendStream(id) - Expect(err).ToNot(HaveOccurred()) - Expect(dstr).To(BeNil()) - }) - - It("deletes incoming bidirectional streams", func() { - id := ids.firstIncomingBidiStream - str, err := m.GetOrOpenReceiveStream(id) - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(id)) - Expect(m.DeleteStream(id)).To(Succeed()) - dstr, err := m.GetOrOpenReceiveStream(id) - Expect(err).ToNot(HaveOccurred()) - Expect(dstr).To(BeNil()) - }) - - It("deletes outgoing unidirectional streams", func() { - id := ids.firstOutgoingUniStream - str, err := m.OpenUniStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(id)) - Expect(m.DeleteStream(id)).To(Succeed()) - dstr, err := m.GetOrOpenSendStream(id) - Expect(err).ToNot(HaveOccurred()) - Expect(dstr).To(BeNil()) - }) - - It("deletes incoming unidirectional streams", func() { - id := ids.firstIncomingUniStream - str, err := m.GetOrOpenReceiveStream(id) - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(id)) - Expect(m.DeleteStream(id)).To(Succeed()) - dstr, err := m.GetOrOpenReceiveStream(id) - Expect(err).ToNot(HaveOccurred()) - Expect(dstr).To(BeNil()) - }) - }) - - Context("getting streams", func() { - BeforeEach(func() { - allowUnlimitedStreams() - }) - - Context("send streams", func() { - It("gets an outgoing bidirectional stream", func() { - // need to open the stream ourselves first - // the peer is not allowed to create a stream initiated by us - _, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - str, err := m.GetOrOpenSendStream(ids.firstOutgoingBidiStream) - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(ids.firstOutgoingBidiStream)) - }) - - It("errors when the peer tries to open a higher outgoing bidirectional stream", func() { - id := ids.firstOutgoingBidiStream + 5*4 - _, err := m.GetOrOpenSendStream(id) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidStreamID, fmt.Sprintf("peer attempted to open stream %d", id)))) - }) - - It("gets an outgoing unidirectional stream", func() { - // need to open the stream ourselves first - // the peer is not allowed to create a stream initiated by us - _, err := m.OpenUniStream() - Expect(err).ToNot(HaveOccurred()) - str, err := m.GetOrOpenSendStream(ids.firstOutgoingUniStream) - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(ids.firstOutgoingUniStream)) - }) - - It("errors when the peer tries to open a higher outgoing bidirectional stream", func() { - id := ids.firstOutgoingUniStream + 5*4 - _, err := m.GetOrOpenSendStream(id) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidStreamID, fmt.Sprintf("peer attempted to open stream %d", id)))) - }) - - It("gets an incoming bidirectional stream", func() { - id := ids.firstIncomingBidiStream + 4*7 - str, err := m.GetOrOpenSendStream(id) - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(id)) - }) - - It("errors when trying to get an incoming unidirectional stream", func() { - id := ids.firstIncomingUniStream - _, err := m.GetOrOpenSendStream(id) - Expect(err).To(MatchError(fmt.Errorf("peer attempted to open send stream %d", id))) - }) - }) - - Context("receive streams", func() { - It("gets an outgoing bidirectional stream", func() { - // need to open the stream ourselves first - // the peer is not allowed to create a stream initiated by us - _, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - str, err := m.GetOrOpenReceiveStream(ids.firstOutgoingBidiStream) - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(ids.firstOutgoingBidiStream)) - }) - - It("errors when the peer tries to open a higher outgoing bidirectional stream", func() { - id := ids.firstOutgoingBidiStream + 5*4 - _, err := m.GetOrOpenReceiveStream(id) - Expect(err).To(MatchError(qerr.Error(qerr.InvalidStreamID, fmt.Sprintf("peer attempted to open stream %d", id)))) - }) - - It("gets an incoming bidirectional stream", func() { - id := ids.firstIncomingBidiStream + 4*7 - str, err := m.GetOrOpenReceiveStream(id) - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(id)) - }) - - It("gets an incoming unidirectional stream", func() { - id := ids.firstIncomingUniStream + 4*10 - str, err := m.GetOrOpenReceiveStream(id) - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(id)) - }) - - It("errors when trying to get an outgoing unidirectional stream", func() { - id := ids.firstOutgoingUniStream - _, err := m.GetOrOpenReceiveStream(id) - Expect(err).To(MatchError(fmt.Errorf("peer attempted to open receive stream %d", id))) - }) - }) - }) - - Context("updating stream ID limits", func() { - BeforeEach(func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()) - }) - - It("processes the parameter for outgoing streams, as a server", func() { - m.perspective = protocol.PerspectiveServer - _, err := m.OpenStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - m.UpdateLimits(&handshake.TransportParameters{ - MaxBidiStreams: 5, - MaxUniStreams: 5, - }) - Expect(m.outgoingBidiStreams.maxStream).To(Equal(protocol.StreamID(17))) - Expect(m.outgoingUniStreams.maxStream).To(Equal(protocol.StreamID(19))) - }) - - It("processes the parameter for outgoing streams, as a client", func() { - m.perspective = protocol.PerspectiveClient - _, err := m.OpenUniStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - m.UpdateLimits(&handshake.TransportParameters{ - MaxBidiStreams: 5, - MaxUniStreams: 5, - }) - Expect(m.outgoingBidiStreams.maxStream).To(Equal(protocol.StreamID(20))) - Expect(m.outgoingUniStreams.maxStream).To(Equal(protocol.StreamID(18))) - }) - }) - - Context("handling MAX_STREAM_ID frames", func() { - BeforeEach(func() { - mockSender.EXPECT().queueControlFrame(gomock.Any()).AnyTimes() - }) - - It("processes IDs for outgoing bidirectional streams", func() { - _, err := m.OpenStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - err = m.HandleMaxStreamIDFrame(&wire.MaxStreamIDFrame{StreamID: ids.firstOutgoingBidiStream}) - Expect(err).ToNot(HaveOccurred()) - str, err := m.OpenStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(ids.firstOutgoingBidiStream)) - }) - - It("processes IDs for outgoing bidirectional streams", func() { - _, err := m.OpenUniStream() - Expect(err).To(MatchError(qerr.TooManyOpenStreams)) - err = m.HandleMaxStreamIDFrame(&wire.MaxStreamIDFrame{StreamID: ids.firstOutgoingUniStream}) - Expect(err).ToNot(HaveOccurred()) - str, err := m.OpenUniStream() - Expect(err).ToNot(HaveOccurred()) - Expect(str.StreamID()).To(Equal(ids.firstOutgoingUniStream)) - }) - - It("rejects IDs for incoming bidirectional streams", func() { - err := m.HandleMaxStreamIDFrame(&wire.MaxStreamIDFrame{StreamID: ids.firstIncomingBidiStream}) - Expect(err).To(MatchError(fmt.Sprintf("received MAX_STREAM_DATA frame for incoming stream %d", ids.firstIncomingBidiStream))) - }) - - It("rejects IDs for incoming unidirectional streams", func() { - err := m.HandleMaxStreamIDFrame(&wire.MaxStreamIDFrame{StreamID: ids.firstIncomingUniStream}) - Expect(err).To(MatchError(fmt.Sprintf("received MAX_STREAM_DATA frame for incoming stream %d", ids.firstIncomingUniStream))) - }) - }) - - Context("sending MAX_STREAM_ID frames", func() { - It("sends MAX_STREAM_ID frames for bidirectional streams", func() { - _, err := m.GetOrOpenReceiveStream(ids.firstIncomingBidiStream + 4*10) - Expect(err).ToNot(HaveOccurred()) - mockSender.EXPECT().queueControlFrame(&wire.MaxStreamIDFrame{ - StreamID: protocol.MaxBidiStreamID(maxBidiStreams, perspective) + 4, - }) - Expect(m.DeleteStream(ids.firstIncomingBidiStream)).To(Succeed()) - }) - - It("sends MAX_STREAM_ID frames for unidirectional streams", func() { - _, err := m.GetOrOpenReceiveStream(ids.firstIncomingUniStream + 4*10) - Expect(err).ToNot(HaveOccurred()) - mockSender.EXPECT().queueControlFrame(&wire.MaxStreamIDFrame{ - StreamID: protocol.MaxUniStreamID(maxUniStreams, perspective) + 4, - }) - Expect(m.DeleteStream(ids.firstIncomingUniStream)).To(Succeed()) - }) - }) - - It("closes", func() { - testErr := errors.New("test error") - m.CloseWithError(testErr) - _, err := m.OpenStream() - Expect(err).To(MatchError(testErr)) - _, err = m.OpenUniStream() - Expect(err).To(MatchError(testErr)) - _, err = m.AcceptStream() - Expect(err).To(MatchError(testErr)) - _, err = m.AcceptUniStream() - Expect(err).To(MatchError(testErr)) - }) - }) - } -}) diff --git a/vendor/lucas-clemente/quic-go/window_update_queue_test.go b/vendor/lucas-clemente/quic-go/window_update_queue_test.go deleted file mode 100644 index 317b03502..000000000 --- a/vendor/lucas-clemente/quic-go/window_update_queue_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package quic - -import ( - "github.com/lucas-clemente/quic-go/internal/mocks" - "github.com/lucas-clemente/quic-go/internal/protocol" - "github.com/lucas-clemente/quic-go/internal/wire" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Window Update Queue", func() { - var ( - q *windowUpdateQueue - streamGetter *MockStreamGetter - connFC *mocks.MockConnectionFlowController - queuedFrames []wire.Frame - cryptoStream *MockCryptoStream - ) - - BeforeEach(func() { - streamGetter = NewMockStreamGetter(mockCtrl) - cryptoStream = NewMockCryptoStream(mockCtrl) - connFC = mocks.NewMockConnectionFlowController(mockCtrl) - cryptoStream.EXPECT().StreamID().Return(protocol.StreamID(0)).AnyTimes() - queuedFrames = queuedFrames[:0] - q = newWindowUpdateQueue(streamGetter, cryptoStream, connFC, func(f wire.Frame) { - queuedFrames = append(queuedFrames, f) - }) - }) - - It("adds stream offsets and gets MAX_STREAM_DATA frames", func() { - stream1 := NewMockStreamI(mockCtrl) - stream1.EXPECT().getWindowUpdate().Return(protocol.ByteCount(10)) - stream3 := NewMockStreamI(mockCtrl) - stream3.EXPECT().getWindowUpdate().Return(protocol.ByteCount(30)) - streamGetter.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(3)).Return(stream3, nil) - streamGetter.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(1)).Return(stream1, nil) - q.AddStream(3) - q.AddStream(1) - q.QueueAll() - Expect(queuedFrames).To(ContainElement(&wire.MaxStreamDataFrame{StreamID: 1, ByteOffset: 10})) - Expect(queuedFrames).To(ContainElement(&wire.MaxStreamDataFrame{StreamID: 3, ByteOffset: 30})) - }) - - It("deletes the entry after getting the MAX_STREAM_DATA frame", func() { - stream10 := NewMockStreamI(mockCtrl) - stream10.EXPECT().getWindowUpdate().Return(protocol.ByteCount(100)) - streamGetter.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(10)).Return(stream10, nil) - q.AddStream(10) - q.QueueAll() - Expect(queuedFrames).To(HaveLen(1)) - q.QueueAll() - Expect(queuedFrames).To(HaveLen(1)) - }) - - It("doesn't queue a MAX_STREAM_DATA for a closed stream", func() { - streamGetter.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(12)).Return(nil, nil) - q.AddStream(12) - q.QueueAll() - Expect(queuedFrames).To(BeEmpty()) - }) - - It("doesn't queue a MAX_STREAM_DATA if the flow controller returns an offset of 0", func() { - stream5 := NewMockStreamI(mockCtrl) - stream5.EXPECT().getWindowUpdate().Return(protocol.ByteCount(0)) - streamGetter.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(5)).Return(stream5, nil) - q.AddStream(5) - q.QueueAll() - Expect(queuedFrames).To(BeEmpty()) - }) - - It("adds MAX_STREAM_DATA frames for the crypto stream", func() { - cryptoStream.EXPECT().getWindowUpdate().Return(protocol.ByteCount(42)) - q.AddStream(0) - q.QueueAll() - Expect(queuedFrames).To(Equal([]wire.Frame{ - &wire.MaxStreamDataFrame{StreamID: 0, ByteOffset: 42}, - })) - }) - - It("queues MAX_DATA frames", func() { - connFC.EXPECT().GetWindowUpdate().Return(protocol.ByteCount(0x1337)) - q.AddConnection() - q.QueueAll() - Expect(queuedFrames).To(Equal([]wire.Frame{ - &wire.MaxDataFrame{ByteOffset: 0x1337}, - })) - }) - - It("deduplicates", func() { - stream10 := NewMockStreamI(mockCtrl) - stream10.EXPECT().getWindowUpdate().Return(protocol.ByteCount(200)) - streamGetter.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(10)).Return(stream10, nil) - q.AddStream(10) - q.AddStream(10) - q.QueueAll() - Expect(queuedFrames).To(Equal([]wire.Frame{ - &wire.MaxStreamDataFrame{StreamID: 10, ByteOffset: 200}, - })) - }) -})