session_test.go 67 KB

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