session_test.go 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  1. package quic
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "errors"
  7. "io"
  8. "net"
  9. "runtime/pprof"
  10. "strings"
  11. "time"
  12. "github.com/golang/mock/gomock"
  13. . "github.com/onsi/ginkgo"
  14. . "github.com/onsi/gomega"
  15. "github.com/lucas-clemente/quic-go/internal/ackhandler"
  16. "github.com/lucas-clemente/quic-go/internal/crypto"
  17. "github.com/lucas-clemente/quic-go/internal/handshake"
  18. "github.com/lucas-clemente/quic-go/internal/mocks"
  19. "github.com/lucas-clemente/quic-go/internal/mocks/ackhandler"
  20. "github.com/lucas-clemente/quic-go/internal/protocol"
  21. "github.com/lucas-clemente/quic-go/internal/testdata"
  22. "github.com/lucas-clemente/quic-go/internal/utils"
  23. "github.com/lucas-clemente/quic-go/internal/wire"
  24. "github.com/lucas-clemente/quic-go/qerr"
  25. )
  26. type mockConnection struct {
  27. remoteAddr net.Addr
  28. localAddr net.Addr
  29. written chan []byte
  30. }
  31. func newMockConnection() *mockConnection {
  32. return &mockConnection{
  33. remoteAddr: &net.UDPAddr{},
  34. written: make(chan []byte, 100),
  35. }
  36. }
  37. func (m *mockConnection) Write(p []byte) error {
  38. b := make([]byte, len(p))
  39. copy(b, p)
  40. select {
  41. case m.written <- b:
  42. default:
  43. panic("mockConnection channel full")
  44. }
  45. return nil
  46. }
  47. func (m *mockConnection) Read([]byte) (int, net.Addr, error) { panic("not implemented") }
  48. func (m *mockConnection) SetCurrentRemoteAddr(addr net.Addr) {
  49. m.remoteAddr = addr
  50. }
  51. func (m *mockConnection) LocalAddr() net.Addr { return m.localAddr }
  52. func (m *mockConnection) RemoteAddr() net.Addr { return m.remoteAddr }
  53. func (*mockConnection) Close() error { panic("not implemented") }
  54. func areSessionsRunning() bool {
  55. var b bytes.Buffer
  56. pprof.Lookup("goroutine").WriteTo(&b, 1)
  57. return strings.Contains(b.String(), "quic-go.(*session).run")
  58. }
  59. var _ = Describe("Session", func() {
  60. var (
  61. sess *session
  62. sessionRunner *MockSessionRunner
  63. scfg *handshake.ServerConfig
  64. mconn *mockConnection
  65. cryptoSetup *mockCryptoSetup
  66. streamManager *MockStreamManager
  67. handshakeChan chan<- struct{}
  68. )
  69. BeforeEach(func() {
  70. Eventually(areSessionsRunning).Should(BeFalse())
  71. cryptoSetup = &mockCryptoSetup{}
  72. newCryptoSetup = func(
  73. _ io.ReadWriter,
  74. _ protocol.ConnectionID,
  75. _ net.Addr,
  76. _ protocol.VersionNumber,
  77. _ []byte,
  78. _ *handshake.ServerConfig,
  79. _ *handshake.TransportParameters,
  80. _ []protocol.VersionNumber,
  81. _ func(net.Addr, *Cookie) bool,
  82. _ chan<- handshake.TransportParameters,
  83. handshakeChanP chan<- struct{},
  84. _ utils.Logger,
  85. ) (handshake.CryptoSetup, error) {
  86. handshakeChan = handshakeChanP
  87. return cryptoSetup, nil
  88. }
  89. sessionRunner = NewMockSessionRunner(mockCtrl)
  90. mconn = newMockConnection()
  91. certChain := crypto.NewCertChain(testdata.GetTLSConfig())
  92. kex, err := crypto.NewCurve25519KEX()
  93. Expect(err).NotTo(HaveOccurred())
  94. scfg, err = handshake.NewServerConfig(kex, certChain)
  95. Expect(err).NotTo(HaveOccurred())
  96. var pSess Session
  97. pSess, err = newSession(
  98. mconn,
  99. sessionRunner,
  100. protocol.Version39,
  101. protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1},
  102. protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1},
  103. scfg,
  104. nil,
  105. populateServerConfig(&Config{}),
  106. utils.DefaultLogger,
  107. )
  108. Expect(err).NotTo(HaveOccurred())
  109. sess = pSess.(*session)
  110. streamManager = NewMockStreamManager(mockCtrl)
  111. sess.streamsMap = streamManager
  112. })
  113. AfterEach(func() {
  114. newCryptoSetup = handshake.NewCryptoSetup
  115. Eventually(areSessionsRunning).Should(BeFalse())
  116. })
  117. Context("source address validation", func() {
  118. var (
  119. cookieVerify func(net.Addr, *Cookie) bool
  120. paramClientAddr net.Addr
  121. paramCookie *Cookie
  122. )
  123. remoteAddr := &net.UDPAddr{IP: net.IPv4(192, 168, 13, 37), Port: 1000}
  124. BeforeEach(func() {
  125. newCryptoSetup = func(
  126. _ io.ReadWriter,
  127. _ protocol.ConnectionID,
  128. _ net.Addr,
  129. _ protocol.VersionNumber,
  130. _ []byte,
  131. _ *handshake.ServerConfig,
  132. _ *handshake.TransportParameters,
  133. _ []protocol.VersionNumber,
  134. cookieFunc func(net.Addr, *Cookie) bool,
  135. _ chan<- handshake.TransportParameters,
  136. _ chan<- struct{},
  137. _ utils.Logger,
  138. ) (handshake.CryptoSetup, error) {
  139. cookieVerify = cookieFunc
  140. return cryptoSetup, nil
  141. }
  142. conf := populateServerConfig(&Config{})
  143. conf.AcceptCookie = func(clientAddr net.Addr, cookie *Cookie) bool {
  144. paramClientAddr = clientAddr
  145. paramCookie = cookie
  146. return false
  147. }
  148. pSess, err := newSession(
  149. mconn,
  150. sessionRunner,
  151. protocol.Version39,
  152. protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1},
  153. protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1},
  154. scfg,
  155. nil,
  156. conf,
  157. utils.DefaultLogger,
  158. )
  159. Expect(err).NotTo(HaveOccurred())
  160. sess = pSess.(*session)
  161. })
  162. It("calls the callback with the right parameters when the client didn't send an STK", func() {
  163. cookieVerify(remoteAddr, nil)
  164. Expect(paramClientAddr).To(Equal(remoteAddr))
  165. Expect(paramCookie).To(BeNil())
  166. })
  167. It("calls the callback with the STK when the client sent an STK", func() {
  168. cookieAddr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1337}
  169. sentTime := time.Now().Add(-time.Hour)
  170. cookieVerify(remoteAddr, &Cookie{SentTime: sentTime, RemoteAddr: cookieAddr.String()})
  171. Expect(paramClientAddr).To(Equal(remoteAddr))
  172. Expect(paramCookie).ToNot(BeNil())
  173. Expect(paramCookie.RemoteAddr).To(Equal(cookieAddr.String()))
  174. Expect(paramCookie.SentTime).To(Equal(sentTime))
  175. })
  176. })
  177. Context("frame handling", func() {
  178. Context("handling STREAM frames", func() {
  179. It("passes STREAM frames to the stream", func() {
  180. f := &wire.StreamFrame{
  181. StreamID: 5,
  182. Data: []byte{0xde, 0xca, 0xfb, 0xad},
  183. }
  184. str := NewMockReceiveStreamI(mockCtrl)
  185. str.EXPECT().handleStreamFrame(f)
  186. streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(5)).Return(str, nil)
  187. err := sess.handleStreamFrame(f, protocol.EncryptionForwardSecure)
  188. Expect(err).ToNot(HaveOccurred())
  189. })
  190. It("returns errors", func() {
  191. testErr := errors.New("test err")
  192. f := &wire.StreamFrame{
  193. StreamID: 5,
  194. Data: []byte{0xde, 0xca, 0xfb, 0xad},
  195. }
  196. str := NewMockReceiveStreamI(mockCtrl)
  197. str.EXPECT().handleStreamFrame(f).Return(testErr)
  198. streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(5)).Return(str, nil)
  199. err := sess.handleStreamFrame(f, protocol.EncryptionForwardSecure)
  200. Expect(err).To(MatchError(testErr))
  201. })
  202. It("ignores STREAM frames for closed streams", func() {
  203. streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(5)).Return(nil, nil) // for closed streams, the streamManager returns nil
  204. err := sess.handleStreamFrame(&wire.StreamFrame{
  205. StreamID: 5,
  206. Data: []byte("foobar"),
  207. }, protocol.EncryptionForwardSecure)
  208. Expect(err).ToNot(HaveOccurred())
  209. })
  210. It("errors on a STREAM frame that would close the crypto stream", func() {
  211. err := sess.handleStreamFrame(&wire.StreamFrame{
  212. StreamID: sess.version.CryptoStreamID(),
  213. Offset: 0x1337,
  214. FinBit: true,
  215. }, protocol.EncryptionForwardSecure)
  216. Expect(err).To(MatchError("Received STREAM frame with FIN bit for the crypto stream"))
  217. })
  218. It("accepts unencrypted STREAM frames on the crypto stream", func() {
  219. f := &wire.StreamFrame{
  220. StreamID: versionGQUICFrames.CryptoStreamID(),
  221. Data: []byte("foobar"),
  222. }
  223. err := sess.handleStreamFrame(f, protocol.EncryptionUnencrypted)
  224. Expect(err).ToNot(HaveOccurred())
  225. })
  226. It("unpacks encrypted STREAM frames on the crypto stream", func() {
  227. err := sess.handleStreamFrame(&wire.StreamFrame{
  228. StreamID: versionGQUICFrames.CryptoStreamID(),
  229. Data: []byte("foobar"),
  230. }, protocol.EncryptionSecure)
  231. Expect(err).ToNot(HaveOccurred())
  232. })
  233. It("does not unpack unencrypted STREAM frames on higher streams", func() {
  234. err := sess.handleStreamFrame(&wire.StreamFrame{
  235. StreamID: 3,
  236. Data: []byte("foobar"),
  237. }, protocol.EncryptionUnencrypted)
  238. Expect(err).To(MatchError(qerr.Error(qerr.UnencryptedStreamData, "received unencrypted stream data on stream 3")))
  239. })
  240. })
  241. Context("handling ACK frames", func() {
  242. It("informs the SentPacketHandler about ACKs", func() {
  243. f := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 2, Largest: 3}}}
  244. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  245. sph.EXPECT().ReceivedAck(f, protocol.PacketNumber(42), protocol.EncryptionSecure, gomock.Any())
  246. sph.EXPECT().GetLowestPacketNotConfirmedAcked()
  247. sess.sentPacketHandler = sph
  248. sess.lastRcvdPacketNumber = 42
  249. err := sess.handleAckFrame(f, protocol.EncryptionSecure)
  250. Expect(err).ToNot(HaveOccurred())
  251. })
  252. It("tells the ReceivedPacketHandler to ignore low ranges", func() {
  253. ack := &wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 2, Largest: 3}}}
  254. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  255. sph.EXPECT().ReceivedAck(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any())
  256. sph.EXPECT().GetLowestPacketNotConfirmedAcked().Return(protocol.PacketNumber(0x42))
  257. sess.sentPacketHandler = sph
  258. rph := mockackhandler.NewMockReceivedPacketHandler(mockCtrl)
  259. rph.EXPECT().IgnoreBelow(protocol.PacketNumber(0x42))
  260. sess.receivedPacketHandler = rph
  261. err := sess.handleAckFrame(ack, protocol.EncryptionUnencrypted)
  262. Expect(err).ToNot(HaveOccurred())
  263. })
  264. })
  265. Context("handling RST_STREAM frames", func() {
  266. It("closes the streams for writing", func() {
  267. f := &wire.RstStreamFrame{
  268. StreamID: 555,
  269. ErrorCode: 42,
  270. ByteOffset: 0x1337,
  271. }
  272. str := NewMockReceiveStreamI(mockCtrl)
  273. streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(555)).Return(str, nil)
  274. str.EXPECT().handleRstStreamFrame(f)
  275. err := sess.handleRstStreamFrame(f)
  276. Expect(err).ToNot(HaveOccurred())
  277. })
  278. It("returns errors", func() {
  279. f := &wire.RstStreamFrame{
  280. StreamID: 7,
  281. ByteOffset: 0x1337,
  282. }
  283. testErr := errors.New("flow control violation")
  284. str := NewMockReceiveStreamI(mockCtrl)
  285. streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(7)).Return(str, nil)
  286. str.EXPECT().handleRstStreamFrame(f).Return(testErr)
  287. err := sess.handleRstStreamFrame(f)
  288. Expect(err).To(MatchError(testErr))
  289. })
  290. It("ignores RST_STREAM frames for closed streams", func() {
  291. streamManager.EXPECT().GetOrOpenReceiveStream(protocol.StreamID(3)).Return(nil, nil)
  292. err := sess.handleFrames([]wire.Frame{&wire.RstStreamFrame{
  293. StreamID: 3,
  294. ErrorCode: 42,
  295. }}, protocol.EncryptionUnspecified)
  296. Expect(err).NotTo(HaveOccurred())
  297. })
  298. It("erros when a RST_STREAM frame would reset the crypto stream", func() {
  299. err := sess.handleRstStreamFrame(&wire.RstStreamFrame{
  300. StreamID: sess.version.CryptoStreamID(),
  301. ErrorCode: 123,
  302. })
  303. Expect(err).To(MatchError("Received RST_STREAM frame for the crypto stream"))
  304. })
  305. })
  306. Context("handling MAX_DATA and MAX_STREAM_DATA frames", func() {
  307. var connFC *mocks.MockConnectionFlowController
  308. BeforeEach(func() {
  309. connFC = mocks.NewMockConnectionFlowController(mockCtrl)
  310. sess.connFlowController = connFC
  311. })
  312. It("updates the flow control window of the crypto stream", func() {
  313. fc := mocks.NewMockStreamFlowController(mockCtrl)
  314. offset := protocol.ByteCount(0x4321)
  315. fc.EXPECT().UpdateSendWindow(offset)
  316. sess.cryptoStream.(*cryptoStreamImpl).sendStream.flowController = fc
  317. err := sess.handleMaxStreamDataFrame(&wire.MaxStreamDataFrame{
  318. StreamID: sess.version.CryptoStreamID(),
  319. ByteOffset: offset,
  320. })
  321. Expect(err).ToNot(HaveOccurred())
  322. })
  323. It("updates the flow control window of a stream", func() {
  324. f := &wire.MaxStreamDataFrame{
  325. StreamID: 12345,
  326. ByteOffset: 0x1337,
  327. }
  328. str := NewMockSendStreamI(mockCtrl)
  329. streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(12345)).Return(str, nil)
  330. str.EXPECT().handleMaxStreamDataFrame(f)
  331. err := sess.handleMaxStreamDataFrame(f)
  332. Expect(err).ToNot(HaveOccurred())
  333. })
  334. It("updates the flow control window of the connection", func() {
  335. offset := protocol.ByteCount(0x800000)
  336. connFC.EXPECT().UpdateSendWindow(offset)
  337. sess.handleMaxDataFrame(&wire.MaxDataFrame{ByteOffset: offset})
  338. })
  339. It("ignores MAX_STREAM_DATA frames for a closed stream", func() {
  340. streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(10)).Return(nil, nil)
  341. err := sess.handleFrames([]wire.Frame{&wire.MaxStreamDataFrame{
  342. StreamID: 10,
  343. ByteOffset: 1337,
  344. }}, protocol.EncryptionUnspecified)
  345. Expect(err).NotTo(HaveOccurred())
  346. })
  347. })
  348. Context("handling MAX_STREAM_ID frames", func() {
  349. It("passes the frame to the streamsMap", func() {
  350. f := &wire.MaxStreamIDFrame{StreamID: 10}
  351. streamManager.EXPECT().HandleMaxStreamIDFrame(f)
  352. err := sess.handleMaxStreamIDFrame(f)
  353. Expect(err).ToNot(HaveOccurred())
  354. })
  355. It("returns errors", func() {
  356. f := &wire.MaxStreamIDFrame{StreamID: 10}
  357. testErr := errors.New("test error")
  358. streamManager.EXPECT().HandleMaxStreamIDFrame(f).Return(testErr)
  359. err := sess.handleMaxStreamIDFrame(f)
  360. Expect(err).To(MatchError(testErr))
  361. })
  362. })
  363. Context("handling STOP_SENDING frames", func() {
  364. It("passes the frame to the stream", func() {
  365. f := &wire.StopSendingFrame{
  366. StreamID: 5,
  367. ErrorCode: 10,
  368. }
  369. str := NewMockSendStreamI(mockCtrl)
  370. streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(5)).Return(str, nil)
  371. str.EXPECT().handleStopSendingFrame(f)
  372. err := sess.handleStopSendingFrame(f)
  373. Expect(err).ToNot(HaveOccurred())
  374. })
  375. It("errors when receiving a STOP_SENDING for the crypto stream", func() {
  376. err := sess.handleStopSendingFrame(&wire.StopSendingFrame{
  377. StreamID: sess.version.CryptoStreamID(),
  378. ErrorCode: 10,
  379. })
  380. Expect(err).To(MatchError("Received a STOP_SENDING frame for the crypto stream"))
  381. })
  382. It("ignores STOP_SENDING frames for a closed stream", func() {
  383. streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(3)).Return(nil, nil)
  384. err := sess.handleFrames([]wire.Frame{&wire.StopSendingFrame{
  385. StreamID: 3,
  386. ErrorCode: 1337,
  387. }}, protocol.EncryptionUnspecified)
  388. Expect(err).NotTo(HaveOccurred())
  389. })
  390. })
  391. It("handles PING frames", func() {
  392. err := sess.handleFrames([]wire.Frame{&wire.PingFrame{}}, protocol.EncryptionUnspecified)
  393. Expect(err).NotTo(HaveOccurred())
  394. })
  395. It("rejects PATH_RESPONSE frames", func() {
  396. err := sess.handleFrames([]wire.Frame{&wire.PathResponseFrame{Data: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}}}, protocol.EncryptionUnspecified)
  397. Expect(err).To(MatchError("unexpected PATH_RESPONSE frame"))
  398. })
  399. It("handles PATH_CHALLENGE frames", func() {
  400. err := sess.handleFrames([]wire.Frame{&wire.PathChallengeFrame{Data: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}}}, protocol.EncryptionUnspecified)
  401. Expect(err).ToNot(HaveOccurred())
  402. Expect(sess.packer.controlFrames).To(HaveLen(1))
  403. Expect(sess.packer.controlFrames[0]).To(BeAssignableToTypeOf(&wire.PathResponseFrame{}))
  404. Expect(sess.packer.controlFrames[0].(*wire.PathResponseFrame).Data).To(Equal([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))
  405. })
  406. It("handles BLOCKED frames", func() {
  407. err := sess.handleFrames([]wire.Frame{&wire.BlockedFrame{}}, protocol.EncryptionUnspecified)
  408. Expect(err).NotTo(HaveOccurred())
  409. })
  410. It("handles STREAM_BLOCKED frames", func() {
  411. err := sess.handleFrames([]wire.Frame{&wire.StreamBlockedFrame{}}, protocol.EncryptionUnspecified)
  412. Expect(err).NotTo(HaveOccurred())
  413. })
  414. It("handles STREAM_ID_BLOCKED frames", func() {
  415. err := sess.handleFrames([]wire.Frame{&wire.StreamIDBlockedFrame{}}, protocol.EncryptionUnspecified)
  416. Expect(err).NotTo(HaveOccurred())
  417. })
  418. It("errors on GOAWAY frames", func() {
  419. err := sess.handleFrames([]wire.Frame{&wire.GoawayFrame{}}, protocol.EncryptionUnspecified)
  420. Expect(err).To(MatchError("unimplemented: handling GOAWAY frames"))
  421. })
  422. It("handles STOP_WAITING frames", func() {
  423. err := sess.handleFrames([]wire.Frame{&wire.StopWaitingFrame{LeastUnacked: 10}}, protocol.EncryptionUnspecified)
  424. Expect(err).NotTo(HaveOccurred())
  425. })
  426. It("handles CONNECTION_CLOSE frames", func() {
  427. testErr := qerr.Error(qerr.ProofInvalid, "foobar")
  428. streamManager.EXPECT().CloseWithError(testErr)
  429. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  430. go func() {
  431. defer GinkgoRecover()
  432. err := sess.run()
  433. Expect(err).To(MatchError(testErr))
  434. }()
  435. err := sess.handleFrames([]wire.Frame{&wire.ConnectionCloseFrame{ErrorCode: qerr.ProofInvalid, ReasonPhrase: "foobar"}}, protocol.EncryptionUnspecified)
  436. Expect(err).NotTo(HaveOccurred())
  437. Eventually(sess.Context().Done()).Should(BeClosed())
  438. })
  439. })
  440. It("tells its versions", func() {
  441. sess.version = 4242
  442. Expect(sess.GetVersion()).To(Equal(protocol.VersionNumber(4242)))
  443. })
  444. It("accepts new streams", func() {
  445. mstr := NewMockStreamI(mockCtrl)
  446. streamManager.EXPECT().AcceptStream().Return(mstr, nil)
  447. str, err := sess.AcceptStream()
  448. Expect(err).ToNot(HaveOccurred())
  449. Expect(str).To(Equal(mstr))
  450. })
  451. Context("closing", func() {
  452. BeforeEach(func() {
  453. Eventually(areSessionsRunning).Should(BeFalse())
  454. go func() {
  455. defer GinkgoRecover()
  456. sess.run()
  457. }()
  458. Eventually(areSessionsRunning).Should(BeTrue())
  459. })
  460. It("shuts down without error", func() {
  461. streamManager.EXPECT().CloseWithError(qerr.Error(qerr.PeerGoingAway, ""))
  462. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  463. sess.Close()
  464. Eventually(areSessionsRunning).Should(BeFalse())
  465. Expect(mconn.written).To(HaveLen(1))
  466. buf := &bytes.Buffer{}
  467. err := (&wire.ConnectionCloseFrame{ErrorCode: qerr.PeerGoingAway}).Write(buf, sess.version)
  468. Expect(err).ToNot(HaveOccurred())
  469. Expect(mconn.written).To(Receive(ContainSubstring(buf.String())))
  470. Expect(sess.Context().Done()).To(BeClosed())
  471. })
  472. It("only closes once", func() {
  473. streamManager.EXPECT().CloseWithError(qerr.Error(qerr.PeerGoingAway, ""))
  474. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  475. sess.Close()
  476. sess.Close()
  477. Eventually(areSessionsRunning).Should(BeFalse())
  478. Expect(mconn.written).To(HaveLen(1))
  479. Expect(sess.Context().Done()).To(BeClosed())
  480. })
  481. It("closes streams with proper error", func() {
  482. testErr := errors.New("test error")
  483. streamManager.EXPECT().CloseWithError(qerr.Error(0x1337, testErr.Error()))
  484. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  485. sess.CloseWithError(0x1337, testErr)
  486. Eventually(areSessionsRunning).Should(BeFalse())
  487. Expect(sess.Context().Done()).To(BeClosed())
  488. })
  489. It("closes the session in order to replace it with another QUIC version", func() {
  490. streamManager.EXPECT().CloseWithError(gomock.Any())
  491. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  492. sess.destroy(errCloseSessionForNewVersion)
  493. Eventually(areSessionsRunning).Should(BeFalse())
  494. Expect(mconn.written).To(BeEmpty()) // no CONNECTION_CLOSE or PUBLIC_RESET sent
  495. })
  496. It("sends a Public Reset if the client is initiating the no STOP_WAITING experiment", func() {
  497. streamManager.EXPECT().CloseWithError(gomock.Any())
  498. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  499. sess.closeLocal(handshake.ErrNSTPExperiment)
  500. Eventually(mconn.written).Should(HaveLen(1))
  501. Expect((<-mconn.written)[0] & 0x02).ToNot(BeZero()) // Public Reset
  502. Expect(sess.Context().Done()).To(BeClosed())
  503. })
  504. It("cancels the context when the run loop exists", func() {
  505. streamManager.EXPECT().CloseWithError(gomock.Any())
  506. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  507. returned := make(chan struct{})
  508. go func() {
  509. defer GinkgoRecover()
  510. ctx := sess.Context()
  511. <-ctx.Done()
  512. Expect(ctx.Err()).To(MatchError(context.Canceled))
  513. close(returned)
  514. }()
  515. Consistently(returned).ShouldNot(BeClosed())
  516. sess.Close()
  517. Eventually(returned).Should(BeClosed())
  518. })
  519. })
  520. Context("receiving packets", func() {
  521. var hdr *wire.Header
  522. var unpacker *MockUnpacker
  523. BeforeEach(func() {
  524. unpacker = NewMockUnpacker(mockCtrl)
  525. sess.unpacker = unpacker
  526. hdr = &wire.Header{PacketNumberLen: protocol.PacketNumberLen6}
  527. })
  528. It("sets the {last,largest}RcvdPacketNumber", func() {
  529. hdr.PacketNumber = 5
  530. hdr.Raw = []byte("raw header")
  531. unpacker.EXPECT().Unpack([]byte("raw header"), hdr, []byte("foobar")).Return(&unpackedPacket{}, nil)
  532. err := sess.handlePacketImpl(&receivedPacket{header: hdr, data: []byte("foobar")})
  533. Expect(err).ToNot(HaveOccurred())
  534. Expect(sess.lastRcvdPacketNumber).To(Equal(protocol.PacketNumber(5)))
  535. Expect(sess.largestRcvdPacketNumber).To(Equal(protocol.PacketNumber(5)))
  536. })
  537. It("informs the ReceivedPacketHandler", func() {
  538. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil)
  539. now := time.Now().Add(time.Hour)
  540. rph := mockackhandler.NewMockReceivedPacketHandler(mockCtrl)
  541. rph.EXPECT().ReceivedPacket(protocol.PacketNumber(5), now, false)
  542. sess.receivedPacketHandler = rph
  543. hdr.PacketNumber = 5
  544. err := sess.handlePacketImpl(&receivedPacket{header: hdr, rcvTime: now})
  545. Expect(err).ToNot(HaveOccurred())
  546. })
  547. It("doesn't inform the ReceivedPacketHandler about Retry packets", func() {
  548. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil)
  549. now := time.Now().Add(time.Hour)
  550. rph := mockackhandler.NewMockReceivedPacketHandler(mockCtrl)
  551. sess.receivedPacketHandler = rph
  552. // don't EXPECT any call to ReceivedPacket
  553. hdr.PacketNumber = 5
  554. hdr.Type = protocol.PacketTypeRetry
  555. err := sess.handlePacketImpl(&receivedPacket{header: hdr, rcvTime: now})
  556. Expect(err).ToNot(HaveOccurred())
  557. })
  558. It("closes when handling a packet fails", func() {
  559. testErr := errors.New("unpack error")
  560. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, testErr)
  561. streamManager.EXPECT().CloseWithError(gomock.Any())
  562. hdr.PacketNumber = 5
  563. done := make(chan struct{})
  564. go func() {
  565. defer GinkgoRecover()
  566. err := sess.run()
  567. Expect(err).To(MatchError(testErr))
  568. close(done)
  569. }()
  570. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  571. sess.handlePacket(&receivedPacket{header: hdr})
  572. Eventually(done).Should(BeClosed())
  573. })
  574. It("sets the {last,largest}RcvdPacketNumber, for an out-of-order packet", func() {
  575. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil).Times(2)
  576. hdr.PacketNumber = 5
  577. err := sess.handlePacketImpl(&receivedPacket{header: hdr})
  578. Expect(err).ToNot(HaveOccurred())
  579. Expect(sess.lastRcvdPacketNumber).To(Equal(protocol.PacketNumber(5)))
  580. Expect(sess.largestRcvdPacketNumber).To(Equal(protocol.PacketNumber(5)))
  581. hdr.PacketNumber = 3
  582. err = sess.handlePacketImpl(&receivedPacket{header: hdr})
  583. Expect(err).ToNot(HaveOccurred())
  584. Expect(sess.lastRcvdPacketNumber).To(Equal(protocol.PacketNumber(3)))
  585. Expect(sess.largestRcvdPacketNumber).To(Equal(protocol.PacketNumber(5)))
  586. })
  587. It("handles duplicate packets", func() {
  588. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil).Times(2)
  589. hdr.PacketNumber = 5
  590. err := sess.handlePacketImpl(&receivedPacket{header: hdr})
  591. Expect(err).ToNot(HaveOccurred())
  592. err = sess.handlePacketImpl(&receivedPacket{header: hdr})
  593. Expect(err).ToNot(HaveOccurred())
  594. })
  595. It("ignores packets with a different source connection ID", func() {
  596. // Send one packet, which might change the connection ID.
  597. // only EXPECT one call to the unpacker
  598. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil)
  599. err := sess.handlePacketImpl(&receivedPacket{
  600. header: &wire.Header{
  601. IsLongHeader: true,
  602. DestConnectionID: sess.destConnID,
  603. SrcConnectionID: sess.srcConnID,
  604. },
  605. })
  606. Expect(err).ToNot(HaveOccurred())
  607. // The next packet has to be ignored, since the source connection ID doesn't match.
  608. err = sess.handlePacketImpl(&receivedPacket{
  609. header: &wire.Header{
  610. IsLongHeader: true,
  611. DestConnectionID: sess.destConnID,
  612. SrcConnectionID: protocol.ConnectionID{0xde, 0xad, 0xbe, 0xef},
  613. },
  614. })
  615. Expect(err).ToNot(HaveOccurred())
  616. })
  617. Context("updating the remote address", func() {
  618. It("doesn't support connection migration", func() {
  619. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil)
  620. origAddr := sess.conn.(*mockConnection).remoteAddr
  621. remoteIP := &net.IPAddr{IP: net.IPv4(192, 168, 0, 100)}
  622. Expect(origAddr).ToNot(Equal(remoteIP))
  623. p := receivedPacket{
  624. remoteAddr: remoteIP,
  625. header: &wire.Header{PacketNumber: 1337},
  626. }
  627. err := sess.handlePacketImpl(&p)
  628. Expect(err).ToNot(HaveOccurred())
  629. Expect(sess.conn.(*mockConnection).remoteAddr).To(Equal(origAddr))
  630. })
  631. })
  632. })
  633. Context("sending packets", func() {
  634. BeforeEach(func() {
  635. sess.packer.hasSentPacket = true // make sure this is not the first packet the packer sends
  636. })
  637. It("sends ACK frames", func() {
  638. packetNumber := protocol.PacketNumber(0x035e)
  639. err := sess.receivedPacketHandler.ReceivedPacket(packetNumber, time.Now(), true)
  640. Expect(err).ToNot(HaveOccurred())
  641. sent, err := sess.sendPacket()
  642. Expect(err).NotTo(HaveOccurred())
  643. Expect(sent).To(BeTrue())
  644. Expect(mconn.written).To(HaveLen(1))
  645. Expect(mconn.written).To(Receive(ContainSubstring(string([]byte{0x03, 0x5e}))))
  646. })
  647. It("adds MAX_STREAM_DATA frames", func() {
  648. sess.windowUpdateQueue.callback(&wire.MaxStreamDataFrame{
  649. StreamID: 2,
  650. ByteOffset: 20,
  651. })
  652. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  653. sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) {
  654. Expect(p.Frames).To(ContainElement(&wire.MaxStreamDataFrame{StreamID: 2, ByteOffset: 20}))
  655. })
  656. sess.sentPacketHandler = sph
  657. sent, err := sess.sendPacket()
  658. Expect(err).NotTo(HaveOccurred())
  659. Expect(sent).To(BeTrue())
  660. })
  661. It("adds a BLOCKED frame when it is connection-level flow control blocked", func() {
  662. fc := mocks.NewMockConnectionFlowController(mockCtrl)
  663. fc.EXPECT().IsNewlyBlocked().Return(true, protocol.ByteCount(1337))
  664. sess.connFlowController = fc
  665. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  666. sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) {
  667. Expect(p.Frames).To(Equal([]wire.Frame{
  668. &wire.BlockedFrame{Offset: 1337},
  669. }))
  670. })
  671. sess.sentPacketHandler = sph
  672. sent, err := sess.sendPacket()
  673. Expect(err).NotTo(HaveOccurred())
  674. Expect(sent).To(BeTrue())
  675. })
  676. It("sends public reset", func() {
  677. err := sess.sendPublicReset(1)
  678. Expect(err).NotTo(HaveOccurred())
  679. Expect(mconn.written).To(HaveLen(1))
  680. Expect(mconn.written).To(Receive(ContainSubstring("PRST")))
  681. })
  682. It("doesn't retransmit an Initial packet if it already received a response", func() {
  683. unpacker := NewMockUnpacker(mockCtrl)
  684. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil)
  685. sess.unpacker = unpacker
  686. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  687. sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes()
  688. sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{
  689. PacketNumber: 10,
  690. PacketType: protocol.PacketTypeInitial,
  691. })
  692. sph.EXPECT().DequeuePacketForRetransmission()
  693. rph := mockackhandler.NewMockReceivedPacketHandler(mockCtrl)
  694. rph.EXPECT().ReceivedPacket(gomock.Any(), gomock.Any(), gomock.Any())
  695. sess.receivedPacketHandler = rph
  696. sess.sentPacketHandler = sph
  697. err := sess.handlePacketImpl(&receivedPacket{
  698. header: &wire.Header{},
  699. data: []byte{0},
  700. })
  701. Expect(err).ToNot(HaveOccurred())
  702. Expect(sess.receivedFirstPacket).To(BeTrue())
  703. sent, err := sess.maybeSendRetransmission()
  704. Expect(err).NotTo(HaveOccurred())
  705. Expect(sent).To(BeFalse())
  706. })
  707. It("sends a retransmission and a regular packet in the same run", func() {
  708. sess.windowUpdateQueue.callback(&wire.MaxDataFrame{})
  709. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  710. sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes()
  711. sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{
  712. PacketNumber: 10,
  713. PacketType: protocol.PacketTypeHandshake,
  714. })
  715. sph.EXPECT().SendMode().Return(ackhandler.SendRetransmission)
  716. sph.EXPECT().SendMode().Return(ackhandler.SendAny)
  717. sph.EXPECT().ShouldSendNumPackets().Return(2)
  718. sph.EXPECT().TimeUntilSend()
  719. sph.EXPECT().GetStopWaitingFrame(gomock.Any()).Return(&wire.StopWaitingFrame{})
  720. gomock.InOrder(
  721. sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(10)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) {
  722. Expect(packets).To(HaveLen(1))
  723. Expect(len(packets[0].Frames)).To(BeNumerically(">", 0))
  724. Expect(packets[0].Frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{}))
  725. Expect(packets[0].SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond))
  726. }),
  727. sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) {
  728. Expect(p.Frames).To(HaveLen(1))
  729. Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.MaxDataFrame{}))
  730. Expect(p.SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond))
  731. }),
  732. )
  733. sess.sentPacketHandler = sph
  734. err := sess.sendPackets()
  735. Expect(err).ToNot(HaveOccurred())
  736. })
  737. It("sends a probe packet", func() {
  738. f := &wire.MaxDataFrame{ByteOffset: 1337}
  739. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  740. sph.EXPECT().TimeUntilSend()
  741. sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes()
  742. sph.EXPECT().SendMode().Return(ackhandler.SendTLP)
  743. sph.EXPECT().ShouldSendNumPackets().Return(1)
  744. sph.EXPECT().DequeueProbePacket().Return(&ackhandler.Packet{
  745. PacketNumber: 0x42,
  746. Frames: []wire.Frame{f},
  747. }, nil)
  748. sph.EXPECT().GetStopWaitingFrame(true).Return(&wire.StopWaitingFrame{})
  749. sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(0x42)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) {
  750. Expect(packets).To(HaveLen(1))
  751. p := packets[0]
  752. Expect(p.Frames).To(HaveLen(2))
  753. Expect(p.Frames[1]).To(Equal(f))
  754. })
  755. sess.sentPacketHandler = sph
  756. err := sess.sendPackets()
  757. Expect(err).ToNot(HaveOccurred())
  758. })
  759. It("doesn't send when the SentPacketHandler doesn't allow it", func() {
  760. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  761. sph.EXPECT().SendMode().Return(ackhandler.SendNone)
  762. sess.sentPacketHandler = sph
  763. err := sess.sendPackets()
  764. Expect(err).ToNot(HaveOccurred())
  765. })
  766. })
  767. Context("packet pacing", func() {
  768. var sph *mockackhandler.MockSentPacketHandler
  769. BeforeEach(func() {
  770. sph = mockackhandler.NewMockSentPacketHandler(mockCtrl)
  771. sph.EXPECT().GetAlarmTimeout().AnyTimes()
  772. sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes()
  773. sph.EXPECT().DequeuePacketForRetransmission().AnyTimes()
  774. sess.sentPacketHandler = sph
  775. sess.packer.hasSentPacket = true
  776. streamManager.EXPECT().CloseWithError(gomock.Any())
  777. })
  778. It("sends multiple packets one by one immediately", func() {
  779. sph.EXPECT().SentPacket(gomock.Any()).Times(2)
  780. sph.EXPECT().ShouldSendNumPackets().Return(1).Times(2)
  781. sph.EXPECT().TimeUntilSend().Return(time.Now()).Times(2)
  782. sph.EXPECT().TimeUntilSend().Return(time.Now().Add(time.Hour))
  783. sph.EXPECT().SendMode().Return(ackhandler.SendAny).Do(func() {
  784. // make sure there's something to send
  785. sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 1})
  786. }).Times(2) // allow 2 packets...
  787. done := make(chan struct{})
  788. go func() {
  789. defer GinkgoRecover()
  790. sess.run()
  791. close(done)
  792. }()
  793. sess.scheduleSending()
  794. Eventually(mconn.written).Should(HaveLen(2))
  795. Consistently(mconn.written).Should(HaveLen(2))
  796. // make the go routine return
  797. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  798. sess.Close()
  799. Eventually(done).Should(BeClosed())
  800. })
  801. // when becoming congestion limited, at some point the SendMode will change from SendAny to SendAck
  802. // we shouldn't send the ACK in the same run
  803. It("doesn't send an ACK right after becoming congestion limited", func() {
  804. sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 1})
  805. sph.EXPECT().SentPacket(gomock.Any())
  806. sph.EXPECT().ShouldSendNumPackets().Return(1000)
  807. sph.EXPECT().TimeUntilSend().Return(time.Now())
  808. sph.EXPECT().SendMode().Return(ackhandler.SendAny)
  809. sph.EXPECT().SendMode().Return(ackhandler.SendAck)
  810. done := make(chan struct{})
  811. go func() {
  812. defer GinkgoRecover()
  813. sess.run()
  814. close(done)
  815. }()
  816. sess.scheduleSending()
  817. Eventually(mconn.written).Should(HaveLen(1))
  818. Consistently(mconn.written).Should(HaveLen(1))
  819. // make the go routine return
  820. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  821. sess.Close()
  822. Eventually(done).Should(BeClosed())
  823. })
  824. It("paces packets", func() {
  825. pacingDelay := scaleDuration(100 * time.Millisecond)
  826. sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 1})
  827. sph.EXPECT().SentPacket(gomock.Any()).Times(2)
  828. sph.EXPECT().TimeUntilSend().Return(time.Now().Add(-time.Minute)) // send one packet immediately
  829. sph.EXPECT().TimeUntilSend().Return(time.Now().Add(pacingDelay)) // send one
  830. sph.EXPECT().TimeUntilSend().Return(time.Now().Add(time.Hour))
  831. sph.EXPECT().ShouldSendNumPackets().Times(2).Return(1)
  832. sph.EXPECT().SendMode().Return(ackhandler.SendAny).Do(func() { // after sending the first packet
  833. // make sure there's something to send
  834. sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 2})
  835. }).AnyTimes()
  836. done := make(chan struct{})
  837. go func() {
  838. defer GinkgoRecover()
  839. sess.run()
  840. close(done)
  841. }()
  842. sess.scheduleSending()
  843. Eventually(mconn.written).Should(HaveLen(1))
  844. Consistently(mconn.written, pacingDelay/2).Should(HaveLen(1))
  845. Eventually(mconn.written, 2*pacingDelay).Should(HaveLen(2))
  846. // make the go routine return
  847. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  848. sess.Close()
  849. Eventually(done).Should(BeClosed())
  850. })
  851. It("sends multiple packets at once", func() {
  852. sph.EXPECT().SentPacket(gomock.Any()).Times(3)
  853. sph.EXPECT().ShouldSendNumPackets().Return(3)
  854. sph.EXPECT().TimeUntilSend().Return(time.Now())
  855. sph.EXPECT().TimeUntilSend().Return(time.Now().Add(time.Hour))
  856. sph.EXPECT().SendMode().Return(ackhandler.SendAny).Do(func() {
  857. // make sure there's something to send
  858. sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 1})
  859. }).Times(3)
  860. done := make(chan struct{})
  861. go func() {
  862. defer GinkgoRecover()
  863. sess.run()
  864. close(done)
  865. }()
  866. sess.scheduleSending()
  867. Eventually(mconn.written).Should(HaveLen(3))
  868. // make the go routine return
  869. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  870. sess.Close()
  871. Eventually(done).Should(BeClosed())
  872. })
  873. It("doesn't set a pacing timer when there is no data to send", func() {
  874. sph.EXPECT().TimeUntilSend().Return(time.Now())
  875. sph.EXPECT().ShouldSendNumPackets().Return(1)
  876. sph.EXPECT().SendMode().Return(ackhandler.SendAny).AnyTimes()
  877. done := make(chan struct{})
  878. go func() {
  879. defer GinkgoRecover()
  880. sess.run()
  881. close(done)
  882. }()
  883. sess.scheduleSending() // no packet will get sent
  884. Consistently(mconn.written).ShouldNot(Receive())
  885. // queue a frame, and expect that it won't be sent
  886. sess.packer.QueueControlFrame(&wire.MaxDataFrame{ByteOffset: 1})
  887. Consistently(mconn.written).ShouldNot(Receive())
  888. // make the go routine return
  889. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  890. sess.Close()
  891. Eventually(done).Should(BeClosed())
  892. })
  893. })
  894. Context("sending ACK only packets", func() {
  895. It("doesn't do anything if there's no ACK to be sent", func() {
  896. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  897. sess.sentPacketHandler = sph
  898. err := sess.maybeSendAckOnlyPacket()
  899. Expect(err).ToNot(HaveOccurred())
  900. Expect(mconn.written).To(BeEmpty())
  901. })
  902. It("sends ACK only packets", func() {
  903. swf := &wire.StopWaitingFrame{LeastUnacked: 10}
  904. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  905. sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes()
  906. sph.EXPECT().GetAlarmTimeout().AnyTimes()
  907. sph.EXPECT().SendMode().Return(ackhandler.SendAck)
  908. sph.EXPECT().ShouldSendNumPackets().Return(1000)
  909. sph.EXPECT().GetStopWaitingFrame(false).Return(swf)
  910. sph.EXPECT().TimeUntilSend()
  911. sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) {
  912. Expect(p.Frames).To(HaveLen(2))
  913. Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.AckFrame{}))
  914. Expect(p.Frames[1]).To(Equal(swf))
  915. Expect(p.SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond))
  916. })
  917. sess.sentPacketHandler = sph
  918. sess.packer.packetNumberGenerator.next = 0x1338
  919. sess.receivedPacketHandler.ReceivedPacket(1, time.Now(), true)
  920. done := make(chan struct{})
  921. go func() {
  922. defer GinkgoRecover()
  923. sess.run()
  924. close(done)
  925. }()
  926. sess.scheduleSending()
  927. Eventually(mconn.written).Should(HaveLen(1))
  928. // make sure that the go routine returns
  929. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  930. streamManager.EXPECT().CloseWithError(gomock.Any())
  931. sess.Close()
  932. Eventually(done).Should(BeClosed())
  933. })
  934. It("doesn't include a STOP_WAITING for an ACK-only packet for IETF QUIC", func() {
  935. sess.version = versionIETFFrames
  936. done := make(chan struct{})
  937. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  938. sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes()
  939. sph.EXPECT().GetAlarmTimeout().AnyTimes()
  940. sph.EXPECT().SendMode().Return(ackhandler.SendAck)
  941. sph.EXPECT().ShouldSendNumPackets().Return(1000)
  942. sph.EXPECT().TimeUntilSend()
  943. sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) {
  944. Expect(p.Frames).To(HaveLen(1))
  945. Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.AckFrame{}))
  946. Expect(p.SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond))
  947. })
  948. sess.sentPacketHandler = sph
  949. sess.packer.packetNumberGenerator.next = 0x1338
  950. sess.receivedPacketHandler.ReceivedPacket(1, time.Now(), true)
  951. go func() {
  952. defer GinkgoRecover()
  953. sess.run()
  954. close(done)
  955. }()
  956. sess.scheduleSending()
  957. Eventually(mconn.written).Should(HaveLen(1))
  958. // make sure that the go routine returns
  959. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  960. streamManager.EXPECT().CloseWithError(gomock.Any())
  961. sess.Close()
  962. Eventually(done).Should(BeClosed())
  963. })
  964. })
  965. Context("retransmissions", func() {
  966. var sph *mockackhandler.MockSentPacketHandler
  967. BeforeEach(func() {
  968. // 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
  969. sess.packer.packetNumberGenerator.next = 0x1337 + 10
  970. sess.packer.hasSentPacket = true // make sure this is not the first packet the packer sends
  971. sph = mockackhandler.NewMockSentPacketHandler(mockCtrl)
  972. sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes()
  973. sess.sentPacketHandler = sph
  974. sess.packer.cryptoSetup = &mockCryptoSetup{encLevelSeal: protocol.EncryptionForwardSecure}
  975. })
  976. Context("for handshake packets", func() {
  977. It("retransmits an unencrypted packet, and adds a STOP_WAITING frame (for gQUIC)", func() {
  978. sf := &wire.StreamFrame{StreamID: 1, Data: []byte("foobar")}
  979. swf := &wire.StopWaitingFrame{LeastUnacked: 0x1337}
  980. sph.EXPECT().GetStopWaitingFrame(true).Return(swf)
  981. sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{
  982. PacketNumber: 42,
  983. Frames: []wire.Frame{sf},
  984. EncryptionLevel: protocol.EncryptionUnencrypted,
  985. })
  986. sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(42)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) {
  987. Expect(packets).To(HaveLen(1))
  988. p := packets[0]
  989. Expect(p.EncryptionLevel).To(Equal(protocol.EncryptionUnencrypted))
  990. Expect(p.Frames).To(Equal([]wire.Frame{swf, sf}))
  991. Expect(p.SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond))
  992. })
  993. sent, err := sess.maybeSendRetransmission()
  994. Expect(err).NotTo(HaveOccurred())
  995. Expect(sent).To(BeTrue())
  996. Expect(mconn.written).To(HaveLen(1))
  997. })
  998. It("retransmits an unencrypted packet, and doesn't add a STOP_WAITING frame (for IETF QUIC)", func() {
  999. sess.version = versionIETFFrames
  1000. sess.packer.version = versionIETFFrames
  1001. sess.packer.srcConnID = sess.destConnID
  1002. sf := &wire.StreamFrame{StreamID: 1, Data: []byte("foobar")}
  1003. sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{
  1004. PacketNumber: 1337,
  1005. Frames: []wire.Frame{sf},
  1006. EncryptionLevel: protocol.EncryptionUnencrypted,
  1007. })
  1008. sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(1337)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) {
  1009. Expect(packets).To(HaveLen(1))
  1010. p := packets[0]
  1011. Expect(p.EncryptionLevel).To(Equal(protocol.EncryptionUnencrypted))
  1012. Expect(p.Frames).To(Equal([]wire.Frame{sf}))
  1013. Expect(p.SendTime).To(BeTemporally("~", time.Now(), 100*time.Millisecond))
  1014. })
  1015. sent, err := sess.maybeSendRetransmission()
  1016. Expect(err).NotTo(HaveOccurred())
  1017. Expect(sent).To(BeTrue())
  1018. Expect(mconn.written).To(HaveLen(1))
  1019. })
  1020. })
  1021. Context("for packets after the handshake", func() {
  1022. It("sends a STREAM frame from a packet queued for retransmission, and adds a STOP_WAITING (for gQUIC)", func() {
  1023. f := &wire.StreamFrame{
  1024. StreamID: 0x5,
  1025. Data: []byte("foobar"),
  1026. }
  1027. swf := &wire.StopWaitingFrame{LeastUnacked: 10}
  1028. sph.EXPECT().GetStopWaitingFrame(true).Return(swf)
  1029. sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{
  1030. PacketNumber: 0x1337,
  1031. Frames: []wire.Frame{f},
  1032. EncryptionLevel: protocol.EncryptionForwardSecure,
  1033. })
  1034. sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(0x1337)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) {
  1035. Expect(packets).To(HaveLen(1))
  1036. p := packets[0]
  1037. Expect(p.Frames).To(HaveLen(2))
  1038. Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.StopWaitingFrame{}))
  1039. Expect(p.Frames[1]).To(Equal(f))
  1040. Expect(p.EncryptionLevel).To(Equal(protocol.EncryptionForwardSecure))
  1041. })
  1042. sent, err := sess.maybeSendRetransmission()
  1043. Expect(err).NotTo(HaveOccurred())
  1044. Expect(sent).To(BeTrue())
  1045. Expect(mconn.written).To(HaveLen(1))
  1046. })
  1047. It("sends a STREAM frame from a packet queued for retransmission, and doesn't add a STOP_WAITING (for IETF QUIC)", func() {
  1048. sess.version = versionIETFFrames
  1049. sess.packer.version = versionIETFFrames
  1050. f := &wire.StreamFrame{
  1051. StreamID: 0x5,
  1052. Data: []byte("foobar"),
  1053. }
  1054. sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{
  1055. PacketNumber: 42,
  1056. Frames: []wire.Frame{f},
  1057. EncryptionLevel: protocol.EncryptionForwardSecure,
  1058. })
  1059. sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(42)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) {
  1060. Expect(packets).To(HaveLen(1))
  1061. p := packets[0]
  1062. Expect(p.Frames).To(Equal([]wire.Frame{f}))
  1063. Expect(p.EncryptionLevel).To(Equal(protocol.EncryptionForwardSecure))
  1064. })
  1065. sent, err := sess.maybeSendRetransmission()
  1066. Expect(err).NotTo(HaveOccurred())
  1067. Expect(sent).To(BeTrue())
  1068. Expect(mconn.written).To(HaveLen(1))
  1069. })
  1070. It("sends multiple packets, if the retransmission is split", func() {
  1071. sess.version = versionIETFFrames
  1072. sess.packer.version = versionIETFFrames
  1073. f := &wire.StreamFrame{
  1074. StreamID: 0x5,
  1075. Data: bytes.Repeat([]byte{'b'}, int(protocol.MaxPacketSizeIPv4)*3/2),
  1076. }
  1077. sph.EXPECT().DequeuePacketForRetransmission().Return(&ackhandler.Packet{
  1078. PacketNumber: 42,
  1079. Frames: []wire.Frame{f},
  1080. EncryptionLevel: protocol.EncryptionForwardSecure,
  1081. })
  1082. sph.EXPECT().SentPacketsAsRetransmission(gomock.Any(), protocol.PacketNumber(42)).Do(func(packets []*ackhandler.Packet, _ protocol.PacketNumber) {
  1083. Expect(packets).To(HaveLen(2))
  1084. for _, p := range packets {
  1085. Expect(p.Frames).To(HaveLen(1))
  1086. Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.StreamFrame{}))
  1087. Expect(p.EncryptionLevel).To(Equal(protocol.EncryptionForwardSecure))
  1088. }
  1089. })
  1090. sent, err := sess.maybeSendRetransmission()
  1091. Expect(err).NotTo(HaveOccurred())
  1092. Expect(sent).To(BeTrue())
  1093. Expect(mconn.written).To(HaveLen(2))
  1094. })
  1095. })
  1096. })
  1097. Context("scheduling sending", func() {
  1098. BeforeEach(func() {
  1099. sess.packer.hasSentPacket = true // make sure this is not the first packet the packer sends
  1100. sess.packer.cryptoSetup = &mockCryptoSetup{encLevelSeal: protocol.EncryptionForwardSecure}
  1101. })
  1102. It("sends when scheduleSending is called", func() {
  1103. sess.packer.packetNumberGenerator.next = 10000
  1104. sess.packer.QueueControlFrame(&wire.BlockedFrame{})
  1105. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  1106. sph.EXPECT().GetAlarmTimeout().AnyTimes()
  1107. sph.EXPECT().TimeUntilSend().AnyTimes()
  1108. sph.EXPECT().SendMode().Return(ackhandler.SendAny).AnyTimes()
  1109. sph.EXPECT().ShouldSendNumPackets().AnyTimes().Return(1)
  1110. sph.EXPECT().GetPacketNumberLen(gomock.Any()).Return(protocol.PacketNumberLen2).AnyTimes()
  1111. sph.EXPECT().SentPacket(gomock.Any())
  1112. sess.sentPacketHandler = sph
  1113. go func() {
  1114. defer GinkgoRecover()
  1115. sess.run()
  1116. }()
  1117. Consistently(mconn.written).ShouldNot(Receive())
  1118. sess.scheduleSending()
  1119. Eventually(mconn.written).Should(Receive())
  1120. // make the go routine return
  1121. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1122. streamManager.EXPECT().CloseWithError(gomock.Any())
  1123. sess.Close()
  1124. Eventually(sess.Context().Done()).Should(BeClosed())
  1125. })
  1126. It("sets the timer to the ack timer", func() {
  1127. sph := mockackhandler.NewMockSentPacketHandler(mockCtrl)
  1128. sph.EXPECT().TimeUntilSend().Return(time.Now())
  1129. sph.EXPECT().TimeUntilSend().Return(time.Now().Add(time.Hour))
  1130. sph.EXPECT().GetAlarmTimeout().AnyTimes()
  1131. sph.EXPECT().SendMode().Return(ackhandler.SendAny).AnyTimes()
  1132. sph.EXPECT().GetStopWaitingFrame(gomock.Any())
  1133. sph.EXPECT().ShouldSendNumPackets().Return(1)
  1134. sph.EXPECT().SentPacket(gomock.Any()).Do(func(p *ackhandler.Packet) {
  1135. Expect(p.Frames[0]).To(BeAssignableToTypeOf(&wire.AckFrame{}))
  1136. Expect(p.Frames[0].(*wire.AckFrame).LargestAcked()).To(Equal(protocol.PacketNumber(0x1337)))
  1137. })
  1138. sess.sentPacketHandler = sph
  1139. rph := mockackhandler.NewMockReceivedPacketHandler(mockCtrl)
  1140. rph.EXPECT().GetAckFrame().Return(&wire.AckFrame{AckRanges: []wire.AckRange{{Smallest: 1, Largest: 0x1337}}})
  1141. rph.EXPECT().GetAlarmTimeout().Return(time.Now().Add(10 * time.Millisecond))
  1142. rph.EXPECT().GetAlarmTimeout().Return(time.Now().Add(time.Hour))
  1143. sess.receivedPacketHandler = rph
  1144. go func() {
  1145. defer GinkgoRecover()
  1146. sess.run()
  1147. }()
  1148. Eventually(mconn.written).Should(Receive())
  1149. // make sure the go routine returns
  1150. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1151. streamManager.EXPECT().CloseWithError(gomock.Any())
  1152. sess.Close()
  1153. Eventually(sess.Context().Done()).Should(BeClosed())
  1154. })
  1155. })
  1156. It("closes when crypto stream errors", func() {
  1157. testErr := errors.New("crypto setup error")
  1158. streamManager.EXPECT().CloseWithError(qerr.Error(qerr.InternalError, testErr.Error()))
  1159. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1160. cryptoSetup.handleErr = testErr
  1161. go func() {
  1162. defer GinkgoRecover()
  1163. err := sess.run()
  1164. Expect(err).To(MatchError(testErr))
  1165. }()
  1166. Eventually(sess.Context().Done()).Should(BeClosed())
  1167. })
  1168. Context("sending a Public Reset when receiving undecryptable packets during the handshake", func() {
  1169. // sends protocol.MaxUndecryptablePackets+1 undecrytable packets
  1170. // this completely fills up the undecryptable packets queue and triggers the public reset timer
  1171. sendUndecryptablePackets := func() {
  1172. for i := 0; i < protocol.MaxUndecryptablePackets+1; i++ {
  1173. hdr := &wire.Header{
  1174. PacketNumber: protocol.PacketNumber(i + 1),
  1175. }
  1176. sess.handlePacket(&receivedPacket{
  1177. header: hdr,
  1178. remoteAddr: &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1234},
  1179. data: []byte("foobar"),
  1180. })
  1181. }
  1182. }
  1183. BeforeEach(func() {
  1184. unpacker := NewMockUnpacker(mockCtrl)
  1185. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, qerr.Error(qerr.DecryptionFailure, "")).AnyTimes()
  1186. sess.unpacker = unpacker
  1187. sess.cryptoStreamHandler = &mockCryptoSetup{}
  1188. streamManager.EXPECT().CloseWithError(gomock.Any()).MaxTimes(1)
  1189. })
  1190. It("doesn't immediately send a Public Reset after receiving too many undecryptable packets", func() {
  1191. go func() {
  1192. defer GinkgoRecover()
  1193. sess.run()
  1194. }()
  1195. sendUndecryptablePackets()
  1196. sess.scheduleSending()
  1197. Consistently(mconn.written).Should(HaveLen(0))
  1198. // make the go routine return
  1199. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1200. sess.Close()
  1201. Eventually(sess.Context().Done()).Should(BeClosed())
  1202. })
  1203. It("sets a deadline to send a Public Reset after receiving too many undecryptable packets", func() {
  1204. go func() {
  1205. defer GinkgoRecover()
  1206. sess.run()
  1207. }()
  1208. sendUndecryptablePackets()
  1209. Eventually(func() time.Time { return sess.receivedTooManyUndecrytablePacketsTime }).Should(BeTemporally("~", time.Now(), 20*time.Millisecond))
  1210. // make the go routine return
  1211. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1212. sess.Close()
  1213. Eventually(sess.Context().Done()).Should(BeClosed())
  1214. })
  1215. It("drops undecryptable packets when the undecrytable packet queue is full", func() {
  1216. go func() {
  1217. defer GinkgoRecover()
  1218. sess.run()
  1219. }()
  1220. sendUndecryptablePackets()
  1221. Eventually(func() []*receivedPacket { return sess.undecryptablePackets }).Should(HaveLen(protocol.MaxUndecryptablePackets))
  1222. // check that old packets are kept, and the new packets are dropped
  1223. Expect(sess.undecryptablePackets[0].header.PacketNumber).To(Equal(protocol.PacketNumber(1)))
  1224. // make the go routine return
  1225. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1226. Expect(sess.Close()).To(Succeed())
  1227. Eventually(sess.Context().Done()).Should(BeClosed())
  1228. })
  1229. It("sends a Public Reset after a timeout", func() {
  1230. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1231. Expect(sess.receivedTooManyUndecrytablePacketsTime).To(BeZero())
  1232. go func() {
  1233. defer GinkgoRecover()
  1234. sess.run()
  1235. }()
  1236. sendUndecryptablePackets()
  1237. Eventually(func() time.Time { return sess.receivedTooManyUndecrytablePacketsTime }).Should(BeTemporally("~", time.Now(), time.Second))
  1238. // speed up this test by manually setting back the time when too many packets were received
  1239. sess.receivedTooManyUndecrytablePacketsTime = time.Now().Add(-protocol.PublicResetTimeout)
  1240. time.Sleep(10 * time.Millisecond) // wait for the run loop to spin up
  1241. sess.scheduleSending() // wake up the run loop
  1242. Eventually(mconn.written).Should(HaveLen(1))
  1243. Expect(mconn.written).To(Receive(ContainSubstring("PRST")))
  1244. Eventually(sess.Context().Done()).Should(BeClosed())
  1245. })
  1246. It("doesn't send a Public Reset if decrypting them succeeded during the timeout", func() {
  1247. go func() {
  1248. defer GinkgoRecover()
  1249. sess.run()
  1250. }()
  1251. sess.receivedTooManyUndecrytablePacketsTime = time.Now().Add(-protocol.PublicResetTimeout).Add(-time.Millisecond)
  1252. sess.scheduleSending() // wake up the run loop
  1253. // there are no packets in the undecryptable packet queue
  1254. // in reality, this happens when the trial decryption succeeded during the Public Reset timeout
  1255. Consistently(mconn.written).ShouldNot(HaveLen(1))
  1256. Expect(sess.Context().Done()).ToNot(Receive())
  1257. // make the go routine return
  1258. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1259. sess.Close()
  1260. Eventually(sess.Context().Done()).Should(BeClosed())
  1261. })
  1262. It("ignores undecryptable packets after the handshake is complete", func() {
  1263. sess.handshakeComplete = true
  1264. go func() {
  1265. defer GinkgoRecover()
  1266. sess.run()
  1267. }()
  1268. sendUndecryptablePackets()
  1269. Consistently(sess.undecryptablePackets).Should(BeEmpty())
  1270. // make the go routine return
  1271. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1272. Expect(sess.Close()).To(Succeed())
  1273. Eventually(sess.Context().Done()).Should(BeClosed())
  1274. })
  1275. It("unqueues undecryptable packets for later decryption", func() {
  1276. sess.undecryptablePackets = []*receivedPacket{{
  1277. header: &wire.Header{PacketNumber: protocol.PacketNumber(42)},
  1278. }}
  1279. Expect(sess.receivedPackets).NotTo(Receive())
  1280. sess.tryDecryptingQueuedPackets()
  1281. Expect(sess.undecryptablePackets).To(BeEmpty())
  1282. Expect(sess.receivedPackets).To(Receive())
  1283. })
  1284. })
  1285. It("doesn't do anything when the crypto setup says to decrypt undecryptable packets", func() {
  1286. go func() {
  1287. defer GinkgoRecover()
  1288. sess.run()
  1289. }()
  1290. handshakeChan <- struct{}{}
  1291. // don't EXPECT any calls to sessionRunner.onHandshakeComplete()
  1292. // make sure the go routine returns
  1293. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1294. streamManager.EXPECT().CloseWithError(gomock.Any())
  1295. Expect(sess.Close()).To(Succeed())
  1296. Eventually(sess.Context().Done()).Should(BeClosed())
  1297. })
  1298. It("calls the onHandshakeComplete callback when the handshake completes", func() {
  1299. go func() {
  1300. defer GinkgoRecover()
  1301. sess.run()
  1302. }()
  1303. sessionRunner.EXPECT().onHandshakeComplete(gomock.Any())
  1304. close(handshakeChan)
  1305. Consistently(sess.Context().Done()).ShouldNot(BeClosed())
  1306. // make sure the go routine returns
  1307. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1308. streamManager.EXPECT().CloseWithError(gomock.Any())
  1309. Expect(sess.Close()).To(Succeed())
  1310. Eventually(sess.Context().Done()).Should(BeClosed())
  1311. })
  1312. It("doesn't return a run error when closing", func() {
  1313. done := make(chan struct{})
  1314. go func() {
  1315. defer GinkgoRecover()
  1316. err := sess.run()
  1317. Expect(err).ToNot(HaveOccurred())
  1318. close(done)
  1319. }()
  1320. streamManager.EXPECT().CloseWithError(gomock.Any())
  1321. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1322. Expect(sess.Close()).To(Succeed())
  1323. Eventually(done).Should(BeClosed())
  1324. })
  1325. It("passes errors to the session runner", func() {
  1326. testErr := errors.New("handshake error")
  1327. done := make(chan struct{})
  1328. go func() {
  1329. defer GinkgoRecover()
  1330. err := sess.run()
  1331. Expect(err).To(MatchError(qerr.Error(0x1337, testErr.Error())))
  1332. close(done)
  1333. }()
  1334. streamManager.EXPECT().CloseWithError(gomock.Any())
  1335. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1336. Expect(sess.CloseWithError(0x1337, testErr)).To(Succeed())
  1337. Eventually(done).Should(BeClosed())
  1338. })
  1339. It("process transport parameters received from the peer", func() {
  1340. paramsChan := make(chan handshake.TransportParameters)
  1341. sess.paramsChan = paramsChan
  1342. go func() {
  1343. defer GinkgoRecover()
  1344. sess.run()
  1345. }()
  1346. params := handshake.TransportParameters{
  1347. MaxStreams: 123,
  1348. IdleTimeout: 90 * time.Second,
  1349. StreamFlowControlWindow: 0x5000,
  1350. ConnectionFlowControlWindow: 0x5000,
  1351. OmitConnectionID: true,
  1352. MaxPacketSize: 0x42,
  1353. }
  1354. streamManager.EXPECT().UpdateLimits(&params)
  1355. paramsChan <- params
  1356. Eventually(func() *handshake.TransportParameters { return sess.peerParams }).Should(Equal(&params))
  1357. Eventually(func() bool { return sess.packer.omitConnectionID }).Should(BeTrue())
  1358. Eventually(func() protocol.ByteCount { return sess.packer.maxPacketSize }).Should(Equal(protocol.ByteCount(0x42)))
  1359. // make the go routine return
  1360. streamManager.EXPECT().CloseWithError(gomock.Any())
  1361. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1362. sess.Close()
  1363. Eventually(sess.Context().Done()).Should(BeClosed())
  1364. })
  1365. Context("keep-alives", func() {
  1366. // should be shorter than the local timeout for these tests
  1367. // otherwise we'd send a CONNECTION_CLOSE in the tests where we're testing that no PING is sent
  1368. remoteIdleTimeout := 20 * time.Second
  1369. BeforeEach(func() {
  1370. sess.peerParams = &handshake.TransportParameters{IdleTimeout: remoteIdleTimeout}
  1371. })
  1372. It("sends a PING", func() {
  1373. sess.handshakeComplete = true
  1374. sess.config.KeepAlive = true
  1375. sess.lastNetworkActivityTime = time.Now().Add(-remoteIdleTimeout / 2)
  1376. sess.packer.hasSentPacket = true // make sure this is not the first packet the packer sends
  1377. done := make(chan struct{})
  1378. go func() {
  1379. defer GinkgoRecover()
  1380. sess.run()
  1381. close(done)
  1382. }()
  1383. var data []byte
  1384. Eventually(mconn.written).Should(Receive(&data))
  1385. // -12 because of the crypto tag. This should be 7 (the frame id for a ping frame).
  1386. Expect(data[len(data)-12-1 : len(data)-12]).To(Equal([]byte{0x07}))
  1387. // make the go routine return
  1388. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1389. streamManager.EXPECT().CloseWithError(gomock.Any())
  1390. sess.Close()
  1391. Eventually(done).Should(BeClosed())
  1392. })
  1393. It("doesn't send a PING packet if keep-alive is disabled", func() {
  1394. sess.handshakeComplete = true
  1395. sess.config.KeepAlive = false
  1396. sess.lastNetworkActivityTime = time.Now().Add(-remoteIdleTimeout / 2)
  1397. done := make(chan struct{})
  1398. go func() {
  1399. defer GinkgoRecover()
  1400. sess.run()
  1401. close(done)
  1402. }()
  1403. Consistently(mconn.written).ShouldNot(Receive())
  1404. // make the go routine return
  1405. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1406. streamManager.EXPECT().CloseWithError(gomock.Any())
  1407. sess.Close()
  1408. Eventually(done).Should(BeClosed())
  1409. })
  1410. It("doesn't send a PING if the handshake isn't completed yet", func() {
  1411. sess.handshakeComplete = false
  1412. sess.config.KeepAlive = true
  1413. sess.lastNetworkActivityTime = time.Now().Add(-remoteIdleTimeout / 2)
  1414. done := make(chan struct{})
  1415. go func() {
  1416. defer GinkgoRecover()
  1417. sess.run()
  1418. close(done)
  1419. }()
  1420. Consistently(mconn.written).ShouldNot(Receive())
  1421. // make the go routine return
  1422. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1423. streamManager.EXPECT().CloseWithError(gomock.Any())
  1424. sess.Close()
  1425. Eventually(done).Should(BeClosed())
  1426. })
  1427. })
  1428. Context("timeouts", func() {
  1429. BeforeEach(func() {
  1430. streamManager.EXPECT().CloseWithError(gomock.Any())
  1431. })
  1432. It("times out due to no network activity", func() {
  1433. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1434. sess.handshakeComplete = true
  1435. sess.lastNetworkActivityTime = time.Now().Add(-time.Hour)
  1436. done := make(chan struct{})
  1437. go func() {
  1438. defer GinkgoRecover()
  1439. err := sess.run()
  1440. Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.NetworkIdleTimeout))
  1441. close(done)
  1442. }()
  1443. Eventually(done).Should(BeClosed())
  1444. Expect(mconn.written).To(Receive(ContainSubstring("No recent network activity.")))
  1445. })
  1446. It("times out due to non-completed handshake", func() {
  1447. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1448. sess.sessionCreationTime = time.Now().Add(-protocol.DefaultHandshakeTimeout).Add(-time.Second)
  1449. done := make(chan struct{})
  1450. go func() {
  1451. defer GinkgoRecover()
  1452. err := sess.run()
  1453. Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.HandshakeTimeout))
  1454. close(done)
  1455. }()
  1456. Eventually(done).Should(BeClosed())
  1457. Expect(mconn.written).To(Receive(ContainSubstring("Crypto handshake did not complete in time.")))
  1458. })
  1459. It("does not use the idle timeout before the handshake complete", func() {
  1460. sess.config.IdleTimeout = 9999 * time.Second
  1461. defer sess.Close()
  1462. sess.lastNetworkActivityTime = time.Now().Add(-time.Minute)
  1463. // the handshake timeout is irrelevant here, since it depends on the time the session was created,
  1464. // and not on the last network activity
  1465. go func() {
  1466. defer GinkgoRecover()
  1467. sess.run()
  1468. }()
  1469. Consistently(sess.Context().Done()).ShouldNot(BeClosed())
  1470. // make the go routine return
  1471. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1472. sess.Close()
  1473. Eventually(sess.Context().Done()).Should(BeClosed())
  1474. })
  1475. It("closes the session due to the idle timeout after handshake", func() {
  1476. sessionRunner.EXPECT().onHandshakeComplete(sess)
  1477. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1478. sess.config.IdleTimeout = 0
  1479. close(handshakeChan)
  1480. done := make(chan struct{})
  1481. go func() {
  1482. defer GinkgoRecover()
  1483. err := sess.run()
  1484. Expect(err.(*qerr.QuicError).ErrorCode).To(Equal(qerr.NetworkIdleTimeout))
  1485. close(done)
  1486. }()
  1487. Eventually(done).Should(BeClosed())
  1488. Expect(mconn.written).To(Receive(ContainSubstring("No recent network activity.")))
  1489. })
  1490. })
  1491. It("stores up to MaxSessionUnprocessedPackets packets", func(done Done) {
  1492. // Nothing here should block
  1493. for i := protocol.PacketNumber(0); i < protocol.MaxSessionUnprocessedPackets+10; i++ {
  1494. sess.handlePacket(&receivedPacket{})
  1495. }
  1496. close(done)
  1497. }, 0.5)
  1498. Context("getting streams", func() {
  1499. It("returns a new stream", func() {
  1500. mstr := NewMockStreamI(mockCtrl)
  1501. streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(11)).Return(mstr, nil)
  1502. str, err := sess.GetOrOpenStream(11)
  1503. Expect(err).ToNot(HaveOccurred())
  1504. Expect(str).To(Equal(mstr))
  1505. })
  1506. It("returns a nil-value (not an interface with value nil) for closed streams", func() {
  1507. strI := Stream(nil)
  1508. streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(1337)).Return(strI, nil)
  1509. str, err := sess.GetOrOpenStream(1337)
  1510. Expect(err).ToNot(HaveOccurred())
  1511. // make sure that the returned value is a plain nil, not an Stream with value nil
  1512. _, ok := str.(Stream)
  1513. Expect(ok).To(BeFalse())
  1514. })
  1515. It("errors when trying to get a unidirectional stream", func() {
  1516. streamManager.EXPECT().GetOrOpenSendStream(protocol.StreamID(100)).Return(&sendStream{}, nil)
  1517. _, err := sess.GetOrOpenStream(100)
  1518. Expect(err).To(MatchError("Stream 100 is not a bidirectional stream"))
  1519. })
  1520. It("opens streams", func() {
  1521. mstr := NewMockStreamI(mockCtrl)
  1522. streamManager.EXPECT().OpenStream().Return(mstr, nil)
  1523. str, err := sess.OpenStream()
  1524. Expect(err).ToNot(HaveOccurred())
  1525. Expect(str).To(Equal(mstr))
  1526. })
  1527. It("opens streams synchronously", func() {
  1528. mstr := NewMockStreamI(mockCtrl)
  1529. streamManager.EXPECT().OpenStreamSync().Return(mstr, nil)
  1530. str, err := sess.OpenStreamSync()
  1531. Expect(err).ToNot(HaveOccurred())
  1532. Expect(str).To(Equal(mstr))
  1533. })
  1534. It("opens unidirectional streams", func() {
  1535. mstr := NewMockSendStreamI(mockCtrl)
  1536. streamManager.EXPECT().OpenUniStream().Return(mstr, nil)
  1537. str, err := sess.OpenUniStream()
  1538. Expect(err).ToNot(HaveOccurred())
  1539. Expect(str).To(Equal(mstr))
  1540. })
  1541. It("opens unidirectional streams synchronously", func() {
  1542. mstr := NewMockSendStreamI(mockCtrl)
  1543. streamManager.EXPECT().OpenUniStreamSync().Return(mstr, nil)
  1544. str, err := sess.OpenUniStreamSync()
  1545. Expect(err).ToNot(HaveOccurred())
  1546. Expect(str).To(Equal(mstr))
  1547. })
  1548. It("accepts streams", func() {
  1549. mstr := NewMockStreamI(mockCtrl)
  1550. streamManager.EXPECT().AcceptStream().Return(mstr, nil)
  1551. str, err := sess.AcceptStream()
  1552. Expect(err).ToNot(HaveOccurred())
  1553. Expect(str).To(Equal(mstr))
  1554. })
  1555. It("accepts unidirectional streams", func() {
  1556. mstr := NewMockReceiveStreamI(mockCtrl)
  1557. streamManager.EXPECT().AcceptUniStream().Return(mstr, nil)
  1558. str, err := sess.AcceptUniStream()
  1559. Expect(err).ToNot(HaveOccurred())
  1560. Expect(str).To(Equal(mstr))
  1561. })
  1562. })
  1563. It("returns the local address", func() {
  1564. addr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1337}
  1565. mconn.localAddr = addr
  1566. Expect(sess.LocalAddr()).To(Equal(addr))
  1567. })
  1568. It("returns the remote address", func() {
  1569. addr := &net.UDPAddr{IP: net.IPv4(1, 2, 7, 1), Port: 7331}
  1570. mconn.remoteAddr = addr
  1571. Expect(sess.RemoteAddr()).To(Equal(addr))
  1572. })
  1573. })
  1574. var _ = Describe("Client Session", func() {
  1575. var (
  1576. sess *session
  1577. sessionRunner *MockSessionRunner
  1578. mconn *mockConnection
  1579. handshakeChan chan<- struct{}
  1580. cryptoSetup *mockCryptoSetup
  1581. )
  1582. BeforeEach(func() {
  1583. Eventually(areSessionsRunning).Should(BeFalse())
  1584. cryptoSetup = &mockCryptoSetup{}
  1585. newCryptoSetupClient = func(
  1586. _ io.ReadWriter,
  1587. _ string,
  1588. _ protocol.ConnectionID,
  1589. _ protocol.VersionNumber,
  1590. _ *tls.Config,
  1591. _ *handshake.TransportParameters,
  1592. _ chan<- handshake.TransportParameters,
  1593. handshakeChanP chan<- struct{},
  1594. _ protocol.VersionNumber,
  1595. _ []protocol.VersionNumber,
  1596. _ utils.Logger,
  1597. ) (handshake.CryptoSetup, error) {
  1598. handshakeChan = handshakeChanP
  1599. return cryptoSetup, nil
  1600. }
  1601. mconn = newMockConnection()
  1602. sessionRunner = NewMockSessionRunner(mockCtrl)
  1603. sessP, err := newClientSession(
  1604. mconn,
  1605. sessionRunner,
  1606. "hostname",
  1607. protocol.Version39,
  1608. protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1},
  1609. protocol.ConnectionID{8, 7, 6, 5, 4, 3, 2, 1},
  1610. nil,
  1611. populateClientConfig(&Config{}, false),
  1612. protocol.VersionWhatever,
  1613. nil,
  1614. utils.DefaultLogger,
  1615. )
  1616. sess = sessP.(*session)
  1617. Expect(err).ToNot(HaveOccurred())
  1618. })
  1619. AfterEach(func() {
  1620. newCryptoSetupClient = handshake.NewCryptoSetupClient
  1621. })
  1622. It("sends a forward-secure packet when the handshake completes", func() {
  1623. sessionRunner.EXPECT().onHandshakeComplete(gomock.Any())
  1624. sess.packer.hasSentPacket = true
  1625. go func() {
  1626. defer GinkgoRecover()
  1627. sess.run()
  1628. }()
  1629. close(handshakeChan)
  1630. Eventually(mconn.written).Should(Receive())
  1631. //make sure the go routine returns
  1632. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1633. Expect(sess.Close()).To(Succeed())
  1634. Eventually(sess.Context().Done()).Should(BeClosed())
  1635. })
  1636. It("changes the connection ID when receiving the first packet from the server", func() {
  1637. sess.version = protocol.VersionTLS
  1638. sess.packer.version = protocol.VersionTLS
  1639. sess.packer.srcConnID = sess.destConnID
  1640. unpacker := NewMockUnpacker(mockCtrl)
  1641. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil)
  1642. sess.unpacker = unpacker
  1643. go func() {
  1644. defer GinkgoRecover()
  1645. sess.run()
  1646. }()
  1647. err := sess.handlePacketImpl(&receivedPacket{
  1648. header: &wire.Header{
  1649. IsLongHeader: true,
  1650. Type: protocol.PacketTypeHandshake,
  1651. SrcConnectionID: protocol.ConnectionID{1, 3, 3, 7, 1, 3, 3, 7},
  1652. DestConnectionID: sess.srcConnID,
  1653. },
  1654. data: []byte{0},
  1655. })
  1656. Expect(err).ToNot(HaveOccurred())
  1657. // the session should have changed the dest connection ID now
  1658. sess.packer.hasSentPacket = true
  1659. sess.queueControlFrame(&wire.PingFrame{})
  1660. var packet []byte
  1661. Eventually(mconn.written).Should(Receive(&packet))
  1662. hdr, err := wire.ParseInvariantHeader(bytes.NewReader(packet), 0)
  1663. Expect(err).ToNot(HaveOccurred())
  1664. Expect(hdr.DestConnectionID).To(Equal(protocol.ConnectionID{1, 3, 3, 7, 1, 3, 3, 7}))
  1665. // make sure the go routine returns
  1666. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1667. Expect(sess.Close()).To(Succeed())
  1668. Eventually(sess.Context().Done()).Should(BeClosed())
  1669. })
  1670. Context("receiving packets", func() {
  1671. var hdr *wire.Header
  1672. BeforeEach(func() {
  1673. hdr = &wire.Header{PacketNumberLen: protocol.PacketNumberLen6}
  1674. })
  1675. It("passes the diversification nonce to the crypto setup", func() {
  1676. cryptoSetup := &mockCryptoSetup{}
  1677. sess.cryptoStreamHandler = cryptoSetup
  1678. unpacker := NewMockUnpacker(mockCtrl)
  1679. unpacker.EXPECT().Unpack(gomock.Any(), gomock.Any(), gomock.Any()).Return(&unpackedPacket{}, nil)
  1680. sess.unpacker = unpacker
  1681. go func() {
  1682. defer GinkgoRecover()
  1683. sess.run()
  1684. }()
  1685. hdr.PacketNumber = 5
  1686. hdr.DiversificationNonce = []byte("foobar")
  1687. err := sess.handlePacketImpl(&receivedPacket{header: hdr})
  1688. Expect(err).ToNot(HaveOccurred())
  1689. Expect(cryptoSetup.divNonce).To(Equal(hdr.DiversificationNonce))
  1690. // make the go routine return
  1691. sessionRunner.EXPECT().removeConnectionID(gomock.Any())
  1692. Expect(sess.Close()).To(Succeed())
  1693. Eventually(sess.Context().Done()).Should(BeClosed())
  1694. })
  1695. })
  1696. })