uquic/client_test.go
2017-02-22 23:03:09 +07:00

233 lines
8.2 KiB
Go

package quic
import (
"bytes"
"encoding/binary"
"errors"
"net"
"reflect"
"runtime"
"time"
"unsafe"
"github.com/lucas-clemente/quic-go/protocol"
"github.com/lucas-clemente/quic-go/qerr"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Client", func() {
var (
cl *client
config *Config
sess *mockSession
packetConn *mockPacketConn
addr net.Addr
versionNegotiateConnStateCalled bool
)
BeforeEach(func() {
versionNegotiateConnStateCalled = false
packetConn = &mockPacketConn{}
config = &Config{
ConnState: func(_ Session, state ConnState) {
if state == ConnStateVersionNegotiated {
versionNegotiateConnStateCalled = true
}
},
}
addr = &net.UDPAddr{IP: net.IPv4(192, 168, 100, 200), Port: 1337}
sess = &mockSession{connectionID: 0x1337}
cl = &client{
config: config,
connectionID: 0x1337,
session: sess,
version: protocol.Version36,
conn: &conn{pconn: packetConn, currentAddr: addr},
}
})
It("creates a new client", func() {
packetConn.dataToRead = []byte{0x0, 0x1, 0x0}
var err error
sess, err := Dial(packetConn, addr, "quic.clemente.io:1337", config)
Expect(err).ToNot(HaveOccurred())
Expect(*(*[]protocol.VersionNumber)(unsafe.Pointer(reflect.ValueOf(sess.(*session).cryptoSetup).Elem().FieldByName("negotiatedVersions").UnsafeAddr()))).To(BeNil())
Expect(*(*string)(unsafe.Pointer(reflect.ValueOf(sess.(*session).cryptoSetup).Elem().FieldByName("hostname").UnsafeAddr()))).To(Equal("quic.clemente.io"))
})
It("errors on invalid public header", func() {
err := cl.handlePacket(nil, nil)
Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.InvalidPacketHeader))
})
It("errors on large packets", func() {
err := cl.handlePacket(nil, bytes.Repeat([]byte{'a'}, int(protocol.MaxPacketSize)+1))
Expect(err).To(MatchError(qerr.PacketTooLarge))
})
PIt("properly closes the client", func(done Done) {
testErr := errors.New("test error")
time.Sleep(10 * time.Millisecond) // Wait for old goroutines to finish
numGoRoutines := runtime.NumGoroutine()
var stoppedListening bool
go func() {
cl.Listen()
stoppedListening = true
}()
err := cl.Close(testErr)
Expect(err).ToNot(HaveOccurred())
Eventually(sess.closed).Should(BeTrue())
Expect(sess.closeReason).To(MatchError(testErr))
Expect(cl.closed).To(Equal(uint32(1)))
Eventually(func() bool { return stoppedListening }).Should(BeTrue())
Eventually(runtime.NumGoroutine()).Should(Equal(numGoRoutines))
close(done)
}, 10)
It("only closes the client once", func() {
cl.closed = 1
err := cl.Close(errors.New("test error"))
Expect(err).ToNot(HaveOccurred())
Eventually(sess.closed).Should(BeFalse())
Expect(sess.closeReason).ToNot(HaveOccurred())
})
It("creates new sessions with the right parameters", func() {
cl.session = nil
cl.hostname = "hostname"
err := cl.createNewSession(nil)
Expect(err).ToNot(HaveOccurred())
Expect(cl.session).ToNot(BeNil())
Expect(cl.session.(*session).connectionID).To(Equal(cl.connectionID))
Expect(cl.session.(*session).version).To(Equal(cl.version))
err = cl.Close(nil)
Expect(err).ToNot(HaveOccurred())
})
Context("handling packets", func() {
It("errors on too large packets", func() {
err := cl.handlePacket(nil, bytes.Repeat([]byte{'f'}, int(protocol.MaxPacketSize+1)))
Expect(err).To(MatchError(qerr.PacketTooLarge))
})
It("handles packets", func() {
ph := PublicHeader{
PacketNumber: 1,
PacketNumberLen: protocol.PacketNumberLen2,
ConnectionID: 0x1337,
}
b := &bytes.Buffer{}
err := ph.Write(b, protocol.Version36, protocol.PerspectiveServer)
Expect(err).ToNot(HaveOccurred())
packetConn.dataToRead = b.Bytes()
Expect(sess.packetCount).To(BeZero())
var stoppedListening bool
go func() {
cl.Listen()
// it should continue listening when receiving valid packets
stoppedListening = true
}()
Eventually(func() int { return sess.packetCount }).Should(Equal(1))
Expect(sess.closed).To(BeFalse())
Consistently(func() bool { return stoppedListening }).Should(BeFalse())
})
It("closes the session when encountering an error while handling a packet", func() {
Expect(sess.closeReason).ToNot(HaveOccurred())
packetConn.dataToRead = bytes.Repeat([]byte{0xff}, 100)
cl.Listen()
Expect(sess.closed).To(BeTrue())
Expect(sess.closeReason).To(HaveOccurred())
})
It("closes the session when encountering an error while reading from the connection", func() {
testErr := errors.New("test error")
packetConn.readErr = testErr
cl.Listen()
Expect(sess.closed).To(BeTrue())
Expect(sess.closeReason).To(MatchError(testErr))
})
})
Context("version negotiation", func() {
getVersionNegotiation := func(versions []protocol.VersionNumber) []byte {
oldVersionNegotiationPacket := composeVersionNegotiation(0x1337)
oldSupportVersionTags := protocol.SupportedVersionsAsTags
var b bytes.Buffer
for _, v := range versions {
s := make([]byte, 4)
binary.LittleEndian.PutUint32(s, protocol.VersionNumberToTag(v))
b.Write(s)
}
protocol.SupportedVersionsAsTags = b.Bytes()
packet := composeVersionNegotiation(cl.connectionID)
protocol.SupportedVersionsAsTags = oldSupportVersionTags
Expect(composeVersionNegotiation(0x1337)).To(Equal(oldVersionNegotiationPacket))
return packet
}
It("recognizes that a packet without VersionFlag means that the server accepted the suggested version", func() {
ph := PublicHeader{
PacketNumber: 1,
PacketNumberLen: protocol.PacketNumberLen2,
ConnectionID: 0x1337,
}
b := &bytes.Buffer{}
err := ph.Write(b, protocol.VersionWhatever, protocol.PerspectiveServer)
Expect(err).ToNot(HaveOccurred())
err = cl.handlePacket(nil, b.Bytes())
Expect(err).ToNot(HaveOccurred())
Expect(cl.versionNegotiated).To(BeTrue())
Eventually(func() bool { return versionNegotiateConnStateCalled }).Should(BeTrue())
})
It("changes the version after receiving a version negotiation packet", func() {
newVersion := protocol.Version35
Expect(newVersion).ToNot(Equal(cl.version))
Expect(sess.packetCount).To(BeZero())
cl.connectionID = 0x1337
err := cl.handlePacket(nil, getVersionNegotiation([]protocol.VersionNumber{newVersion}))
Expect(cl.version).To(Equal(newVersion))
Expect(cl.versionNegotiated).To(BeTrue())
Eventually(func() bool { return versionNegotiateConnStateCalled }).Should(BeTrue())
// it swapped the sessions
Expect(cl.session).ToNot(Equal(sess))
Expect(cl.connectionID).ToNot(Equal(0x1337)) // it generated a new connection ID
Expect(err).ToNot(HaveOccurred())
// it didn't pass the version negoation packet to the session (since it has no payload)
Expect(sess.packetCount).To(BeZero())
Expect(*(*[]protocol.VersionNumber)(unsafe.Pointer(reflect.ValueOf(cl.session.(*session).cryptoSetup).Elem().FieldByName("negotiatedVersions").UnsafeAddr()))).To(Equal([]protocol.VersionNumber{35}))
err = cl.Close(nil)
Expect(err).ToNot(HaveOccurred())
})
It("errors if no matching version is found", func() {
err := cl.handlePacket(nil, getVersionNegotiation([]protocol.VersionNumber{1}))
Expect(err).To(MatchError(qerr.InvalidVersion))
})
It("ignores delayed version negotiation packets", func() {
// if the version was not yet negotiated, handlePacket would return a VersionNegotiationMismatch error, see above test
cl.versionNegotiated = true
Expect(sess.packetCount).To(BeZero())
err := cl.handlePacket(nil, getVersionNegotiation([]protocol.VersionNumber{1}))
Expect(err).ToNot(HaveOccurred())
Expect(cl.versionNegotiated).To(BeTrue())
Expect(sess.packetCount).To(BeZero())
Consistently(func() bool { return versionNegotiateConnStateCalled }).Should(BeFalse())
})
It("errors if the server should have accepted the offered version", func() {
err := cl.handlePacket(nil, getVersionNegotiation([]protocol.VersionNumber{cl.version}))
Expect(err).To(MatchError(qerr.Error(qerr.InvalidVersionNegotiationPacket, "Server already supports client's version and should have accepted the connection.")))
})
})
})