session_test.go 61 KB

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