raiha 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (347) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +33 -0
  3. data/LICENSE +202 -0
  4. data/README.md +94 -22
  5. data/docs/configuration.md +227 -0
  6. data/docs/development.md +99 -0
  7. data/docs/fiber-scheduler.md +591 -0
  8. data/docs/getting-started.md +190 -0
  9. data/docs/http3-client.md +303 -0
  10. data/docs/http3-server.md +301 -0
  11. data/docs/platforms.md +98 -0
  12. data/docs/qlog.md +86 -0
  13. data/docs/quic.md +268 -0
  14. data/docs/threads.md +127 -0
  15. data/examples/_certificate.rb +55 -0
  16. data/examples/high_level_loopback.rb +59 -0
  17. data/examples/http3_get_public.rb +68 -0
  18. data/examples/in_memory_handshake.rb +38 -0
  19. data/examples/qlog_output.rb +58 -0
  20. data/examples/qlog_roundtrips.rb +66 -0
  21. data/examples/quic_gem_loopback.rb +62 -0
  22. data/examples/stream_echo.rb +68 -0
  23. data/examples/udp_handshake.rb +76 -0
  24. data/lib/raiha/http3/action.rb +21 -0
  25. data/lib/raiha/http3/capsule.rb +86 -0
  26. data/lib/raiha/http3/connection.rb +983 -0
  27. data/lib/raiha/http3/error.rb +24 -0
  28. data/lib/raiha/http3/error_code.rb +27 -0
  29. data/lib/raiha/http3/event.rb +63 -0
  30. data/lib/raiha/http3/frame.rb +148 -0
  31. data/lib/raiha/http3/frame_reader.rb +114 -0
  32. data/lib/raiha/http3/message.rb +137 -0
  33. data/lib/raiha/http3/output.rb +61 -0
  34. data/lib/raiha/http3/priority.rb +52 -0
  35. data/lib/raiha/http3/qlog.rb +145 -0
  36. data/lib/raiha/http3/qpack/decoder.rb +302 -0
  37. data/lib/raiha/http3/qpack/dynamic_table.rb +83 -0
  38. data/lib/raiha/http3/qpack/encoder.rb +94 -0
  39. data/lib/raiha/http3/qpack/error.rb +39 -0
  40. data/lib/raiha/http3/qpack/error_code.rb +13 -0
  41. data/lib/raiha/http3/qpack/field.rb +15 -0
  42. data/lib/raiha/http3/qpack/huffman.rb +397 -0
  43. data/lib/raiha/http3/qpack/reader.rb +82 -0
  44. data/lib/raiha/http3/qpack/result.rb +26 -0
  45. data/lib/raiha/http3/qpack/static_table.rb +139 -0
  46. data/lib/raiha/http3/qpack/writer.rb +44 -0
  47. data/lib/raiha/http3/qpack.rb +26 -0
  48. data/lib/raiha/http3/receiving.rb +46 -0
  49. data/lib/raiha/http3/sending.rb +23 -0
  50. data/lib/raiha/http3/session.rb +31 -0
  51. data/lib/raiha/http3/settings.rb +81 -0
  52. data/lib/raiha/http3/structured_field.rb +120 -0
  53. data/lib/raiha/http3/tracer.rb +26 -0
  54. data/lib/raiha/http3/varint.rb +45 -0
  55. data/lib/raiha/http3.rb +19 -0
  56. data/lib/raiha/http3_binding.rb +139 -0
  57. data/lib/raiha/namespace.rb +11 -0
  58. data/lib/raiha/quic/config.rb +229 -0
  59. data/lib/raiha/quic/congestion/algorithms.rb +17 -0
  60. data/lib/raiha/quic/congestion/cubic.rb +258 -0
  61. data/lib/raiha/quic/congestion/new_reno.rb +161 -0
  62. data/lib/raiha/quic/congestion/pacing.rb +21 -0
  63. data/lib/raiha/quic/congestion/startup/rapid_start.rb +249 -0
  64. data/lib/raiha/quic/congestion/startup.rb +13 -0
  65. data/lib/raiha/quic/congestion.rb +15 -0
  66. data/lib/raiha/quic/connection.rb +2022 -0
  67. data/lib/raiha/quic/connection_ids.rb +62 -0
  68. data/lib/raiha/quic/crypto/aead.rb +68 -0
  69. data/lib/raiha/quic/crypto/header_protection.rb +42 -0
  70. data/lib/raiha/quic/crypto/initial.rb +23 -0
  71. data/lib/raiha/quic/crypto/keys.rb +32 -0
  72. data/lib/raiha/quic/crypto/mac.rb +15 -0
  73. data/lib/raiha/quic/crypto/random.rb +13 -0
  74. data/lib/raiha/quic/crypto.rb +18 -0
  75. data/lib/raiha/quic/crypto_stream.rb +161 -0
  76. data/lib/raiha/quic/datagrams.rb +91 -0
  77. data/lib/raiha/quic/endpoint.rb +785 -0
  78. data/lib/raiha/quic/error.rb +61 -0
  79. data/lib/raiha/quic/error_code.rb +34 -0
  80. data/lib/raiha/quic/event.rb +59 -0
  81. data/lib/raiha/quic/issued_connection_ids.rb +137 -0
  82. data/lib/raiha/quic/kept_packets.rb +41 -0
  83. data/lib/raiha/quic/mtu_search.rb +75 -0
  84. data/lib/raiha/quic/negotiation.rb +143 -0
  85. data/lib/raiha/quic/new_token.rb +55 -0
  86. data/lib/raiha/quic/pacer.rb +52 -0
  87. data/lib/raiha/quic/packet_protection.rb +310 -0
  88. data/lib/raiha/quic/path.rb +473 -0
  89. data/lib/raiha/quic/peer_connection_ids.rb +160 -0
  90. data/lib/raiha/quic/qlog.rb +260 -0
  91. data/lib/raiha/quic/ranges.rb +32 -0
  92. data/lib/raiha/quic/recovery/duty.rb +102 -0
  93. data/lib/raiha/quic/recovery/packet_number_space.rb +420 -0
  94. data/lib/raiha/quic/recovery/rate_meter.rb +95 -0
  95. data/lib/raiha/quic/recovery/rtt_estimator.rb +57 -0
  96. data/lib/raiha/quic/recovery/sent_packet.rb +16 -0
  97. data/lib/raiha/quic/recovery.rb +641 -0
  98. data/lib/raiha/quic/remembered_transport_parameters.rb +29 -0
  99. data/lib/raiha/quic/retry_token.rb +54 -0
  100. data/lib/raiha/quic/route.rb +37 -0
  101. data/lib/raiha/quic/scheduler.rb +112 -0
  102. data/lib/raiha/quic/session.rb +47 -0
  103. data/lib/raiha/quic/stateless_reset.rb +38 -0
  104. data/lib/raiha/quic/stats.rb +24 -0
  105. data/lib/raiha/quic/streams/receive_window.rb +119 -0
  106. data/lib/raiha/quic/streams/receiver.rb +217 -0
  107. data/lib/raiha/quic/streams/sender.rb +200 -0
  108. data/lib/raiha/quic/streams.rb +687 -0
  109. data/lib/raiha/quic/test/bottleneck.rb +55 -0
  110. data/lib/raiha/quic/test/congestion_contract.rb +106 -0
  111. data/lib/raiha/quic/test/network.rb +244 -0
  112. data/lib/raiha/quic/test/random_loss.rb +34 -0
  113. data/lib/raiha/quic/test/reorder.rb +51 -0
  114. data/lib/raiha/quic/test/server.rb +54 -0
  115. data/lib/raiha/quic/test/vectors.rb +337 -0
  116. data/lib/raiha/quic/test/virtual_clock.rb +21 -0
  117. data/lib/raiha/quic/test.rb +17 -0
  118. data/lib/raiha/quic/tls_binding.rb +179 -0
  119. data/lib/raiha/quic/token.rb +28 -0
  120. data/lib/raiha/quic/tracer.rb +127 -0
  121. data/lib/raiha/quic/transmit.rb +14 -0
  122. data/lib/raiha/quic/transport_parameters.rb +244 -0
  123. data/lib/raiha/quic/version.rb +63 -0
  124. data/lib/raiha/quic/wire/codec.rb +136 -0
  125. data/lib/raiha/quic/wire/frame.rb +521 -0
  126. data/lib/raiha/quic/wire/header.rb +90 -0
  127. data/lib/raiha/quic/wire/packet.rb +130 -0
  128. data/lib/raiha/quic/wire/packet_number.rb +47 -0
  129. data/lib/raiha/quic/wire/retry.rb +62 -0
  130. data/lib/raiha/quic/wire/version_negotiation.rb +53 -0
  131. data/lib/raiha/quic/wire.rb +9 -0
  132. data/lib/raiha/quic.rb +46 -0
  133. data/lib/raiha/runtime/addresses.rb +35 -0
  134. data/lib/raiha/runtime/admission.rb +37 -0
  135. data/lib/raiha/runtime/client.rb +190 -0
  136. data/lib/raiha/runtime/driver.rb +165 -0
  137. data/lib/raiha/runtime/error.rb +16 -0
  138. data/lib/raiha/runtime/http3.rb +363 -0
  139. data/lib/raiha/runtime/http3_fields.rb +38 -0
  140. data/lib/raiha/runtime/http3_server.rb +416 -0
  141. data/lib/raiha/runtime/kept.rb +36 -0
  142. data/lib/raiha/runtime/qlog.rb +204 -0
  143. data/lib/raiha/runtime/rack.rb +180 -0
  144. data/lib/raiha/runtime/server.rb +334 -0
  145. data/lib/raiha/runtime/session.rb +447 -0
  146. data/lib/raiha/runtime/threaded/client.rb +161 -0
  147. data/lib/raiha/runtime/threaded/driver.rb +230 -0
  148. data/lib/raiha/runtime/threaded/http3.rb +287 -0
  149. data/lib/raiha/runtime/threaded/http3_server.rb +432 -0
  150. data/lib/raiha/runtime/threaded/server.rb +290 -0
  151. data/lib/raiha/runtime/threaded/session.rb +604 -0
  152. data/lib/raiha/runtime/threaded.rb +45 -0
  153. data/lib/raiha/runtime/udp.rb +410 -0
  154. data/lib/raiha/runtime/worker.rb +138 -0
  155. data/lib/raiha/runtime/workers.rb +248 -0
  156. data/lib/raiha/runtime.rb +37 -0
  157. data/lib/raiha/tls/anti_replay.rb +139 -0
  158. data/lib/raiha/tls/cipher_suite.rb +62 -0
  159. data/lib/raiha/tls/codec/error.rb +43 -0
  160. data/lib/raiha/tls/codec/reader.rb +95 -0
  161. data/lib/raiha/tls/codec/writer.rb +81 -0
  162. data/lib/raiha/tls/codec.rb +5 -0
  163. data/lib/raiha/tls/config.rb +318 -0
  164. data/lib/raiha/tls/crypto/aead.rb +64 -0
  165. data/lib/raiha/tls/crypto/certificate.rb +28 -0
  166. data/lib/raiha/tls/crypto/digest.rb +30 -0
  167. data/lib/raiha/tls/crypto/ecdh.rb +74 -0
  168. data/lib/raiha/tls/crypto/hash.rb +22 -0
  169. data/lib/raiha/tls/crypto/hkdf.rb +28 -0
  170. data/lib/raiha/tls/crypto/signature.rb +87 -0
  171. data/lib/raiha/tls/crypto.rb +19 -0
  172. data/lib/raiha/tls/error.rb +36 -0
  173. data/lib/raiha/tls/event.rb +45 -0
  174. data/lib/raiha/tls/extension/alpn.rb +35 -0
  175. data/lib/raiha/tls/extension/certificate_authorities.rb +35 -0
  176. data/lib/raiha/tls/extension/compress_certificate.rb +33 -0
  177. data/lib/raiha/tls/extension/cookie.rb +27 -0
  178. data/lib/raiha/tls/extension/early_data.rb +54 -0
  179. data/lib/raiha/tls/extension/key_share.rb +90 -0
  180. data/lib/raiha/tls/extension/list.rb +49 -0
  181. data/lib/raiha/tls/extension/opaque.rb +21 -0
  182. data/lib/raiha/tls/extension/placement.rb +55 -0
  183. data/lib/raiha/tls/extension/post_handshake_auth.rb +22 -0
  184. data/lib/raiha/tls/extension/pre_shared_key.rb +81 -0
  185. data/lib/raiha/tls/extension/psk_key_exchange_modes.rb +32 -0
  186. data/lib/raiha/tls/extension/record_size_limit.rb +30 -0
  187. data/lib/raiha/tls/extension/registry.rb +50 -0
  188. data/lib/raiha/tls/extension/server_name.rb +63 -0
  189. data/lib/raiha/tls/extension/signature_algorithms.rb +39 -0
  190. data/lib/raiha/tls/extension/signature_algorithms_cert.rb +21 -0
  191. data/lib/raiha/tls/extension/supported_groups.rb +32 -0
  192. data/lib/raiha/tls/extension/supported_versions.rb +53 -0
  193. data/lib/raiha/tls/extension.rb +32 -0
  194. data/lib/raiha/tls/handshake/acceptor.rb +164 -0
  195. data/lib/raiha/tls/handshake/authentication_messages.rb +127 -0
  196. data/lib/raiha/tls/handshake/certificate.rb +56 -0
  197. data/lib/raiha/tls/handshake/certificate_request.rb +39 -0
  198. data/lib/raiha/tls/handshake/certificate_verify.rb +40 -0
  199. data/lib/raiha/tls/handshake/client_hello.rb +208 -0
  200. data/lib/raiha/tls/handshake/client_hello_builder.rb +144 -0
  201. data/lib/raiha/tls/handshake/client_side.rb +578 -0
  202. data/lib/raiha/tls/handshake/conductor.rb +390 -0
  203. data/lib/raiha/tls/handshake/encrypted_extensions.rb +33 -0
  204. data/lib/raiha/tls/handshake/end_of_early_data.rb +28 -0
  205. data/lib/raiha/tls/handshake/finished.rb +36 -0
  206. data/lib/raiha/tls/handshake/key_update.rb +38 -0
  207. data/lib/raiha/tls/handshake/key_update_handling.rb +88 -0
  208. data/lib/raiha/tls/handshake/machine.rb +238 -0
  209. data/lib/raiha/tls/handshake/message.rb +25 -0
  210. data/lib/raiha/tls/handshake/new_session_ticket.rb +48 -0
  211. data/lib/raiha/tls/handshake/reassembler.rb +88 -0
  212. data/lib/raiha/tls/handshake/server_hello.rb +98 -0
  213. data/lib/raiha/tls/handshake/server_side.rb +672 -0
  214. data/lib/raiha/tls/handshake/violation.rb +12 -0
  215. data/lib/raiha/tls/handshake.rb +62 -0
  216. data/lib/raiha/tls/iana.rb +113 -0
  217. data/lib/raiha/tls/key_exchange.rb +58 -0
  218. data/lib/raiha/tls/key_schedule.rb +269 -0
  219. data/lib/raiha/tls/keylog.rb +40 -0
  220. data/lib/raiha/tls/keyring.rb +180 -0
  221. data/lib/raiha/tls/masked_inspect.rb +33 -0
  222. data/lib/raiha/tls/output.rb +32 -0
  223. data/lib/raiha/tls/profile.rb +82 -0
  224. data/lib/raiha/tls/record/layer.rb +228 -0
  225. data/lib/raiha/tls/record/protection.rb +67 -0
  226. data/lib/raiha/tls/record.rb +11 -0
  227. data/lib/raiha/tls/server_name.rb +42 -0
  228. data/lib/raiha/tls/session.rb +106 -0
  229. data/lib/raiha/tls/signature_scheme.rb +35 -0
  230. data/lib/raiha/tls/tcp/acceptor.rb +121 -0
  231. data/lib/raiha/tls/tcp/connection.rb +371 -0
  232. data/lib/raiha/tls/tcp/event.rb +15 -0
  233. data/lib/raiha/tls/tcp/socket.rb +161 -0
  234. data/lib/raiha/tls/tcp.rb +14 -0
  235. data/lib/raiha/tls/test/fixed_kem.rb +30 -0
  236. data/lib/raiha/tls/test/fixed_random.rb +18 -0
  237. data/lib/raiha/tls/test/rfc8448.rb +923 -0
  238. data/lib/raiha/tls/test/rfc8448_handshakes.rb +118 -0
  239. data/lib/raiha/tls/test.rb +13 -0
  240. data/lib/raiha/tls/ticket.rb +184 -0
  241. data/lib/raiha/tls/ticket_keys.rb +206 -0
  242. data/lib/raiha/tls/trace.rb +58 -0
  243. data/lib/raiha/tls/transcript.rb +94 -0
  244. data/lib/raiha/tls/verifier/default.rb +72 -0
  245. data/lib/raiha/tls/verifier/host_name.rb +75 -0
  246. data/lib/raiha/tls/verifier/none.rb +14 -0
  247. data/lib/raiha/tls/verifier.rb +24 -0
  248. data/lib/raiha/tls.rb +34 -0
  249. data/lib/raiha/version.rb +3 -1
  250. data/lib/raiha.rb +8 -5
  251. data/sig/patches/array.rbs +9 -0
  252. data/sig/patches/io_buffer.rbs +13 -0
  253. data/sig/patches/openssl.rbs +25 -0
  254. data/sig/patches/socket.rbs +29 -0
  255. data/sig/patches/string.rbs +26 -0
  256. data/sig/patches/strscan.rbs +12 -0
  257. data/sig/raiha/http3/capsule.rbs +32 -0
  258. data/sig/raiha/http3/connection.rbs +324 -0
  259. data/sig/raiha/http3/frame.rbs +138 -0
  260. data/sig/raiha/http3/frame_reader.rbs +39 -0
  261. data/sig/raiha/http3/message.rbs +23 -0
  262. data/sig/raiha/http3/priority.rbs +40 -0
  263. data/sig/raiha/http3/qlog.rbs +54 -0
  264. data/sig/raiha/http3/qpack.rbs +246 -0
  265. data/sig/raiha/http3/session.rbs +11 -0
  266. data/sig/raiha/http3/settings.rbs +26 -0
  267. data/sig/raiha/http3.rbs +2 -0
  268. data/sig/raiha/http3_binding.rbs +26 -0
  269. data/sig/raiha/namespace.rbs +2 -0
  270. data/sig/raiha/quic/config.rbs +89 -0
  271. data/sig/raiha/quic/congestion.rbs +213 -0
  272. data/sig/raiha/quic/connection.rbs +249 -0
  273. data/sig/raiha/quic/connection_ids.rbs +34 -0
  274. data/sig/raiha/quic/crypto.rbs +78 -0
  275. data/sig/raiha/quic/crypto_stream.rbs +34 -0
  276. data/sig/raiha/quic/datagrams.rbs +32 -0
  277. data/sig/raiha/quic/endpoint.rbs +179 -0
  278. data/sig/raiha/quic/frame.rbs +387 -0
  279. data/sig/raiha/quic/issued_connection_ids.rbs +47 -0
  280. data/sig/raiha/quic/kept_packets.rbs +25 -0
  281. data/sig/raiha/quic/mtu_search.rbs +21 -0
  282. data/sig/raiha/quic/negotiation.rbs +33 -0
  283. data/sig/raiha/quic/new_token.rbs +14 -0
  284. data/sig/raiha/quic/pacer.rbs +16 -0
  285. data/sig/raiha/quic/packet_protection.rbs +63 -0
  286. data/sig/raiha/quic/path.rbs +106 -0
  287. data/sig/raiha/quic/peer_connection_ids.rbs +42 -0
  288. data/sig/raiha/quic/qlog.rbs +74 -0
  289. data/sig/raiha/quic/ranges.rbs +7 -0
  290. data/sig/raiha/quic/recovery.rbs +376 -0
  291. data/sig/raiha/quic/retry_token.rbs +21 -0
  292. data/sig/raiha/quic/route.rbs +51 -0
  293. data/sig/raiha/quic/scheduler.rbs +36 -0
  294. data/sig/raiha/quic/session.rbs +17 -0
  295. data/sig/raiha/quic/stateless_reset.rbs +10 -0
  296. data/sig/raiha/quic/streams.rbs +244 -0
  297. data/sig/raiha/quic/test.rbs +354 -0
  298. data/sig/raiha/quic/tls_binding.rbs +58 -0
  299. data/sig/raiha/quic/token.rbs +11 -0
  300. data/sig/raiha/quic/tracer.rbs +71 -0
  301. data/sig/raiha/quic/transport_parameters.rbs +113 -0
  302. data/sig/raiha/quic/values.rbs +200 -0
  303. data/sig/raiha/quic/version.rbs +30 -0
  304. data/sig/raiha/quic/wire.rbs +199 -0
  305. data/sig/raiha/quic.rbs +2 -0
  306. data/sig/raiha/runtime/threaded.rbs +616 -0
  307. data/sig/raiha/runtime.rbs +982 -0
  308. data/sig/raiha/tls/anti_replay.rbs +41 -0
  309. data/sig/raiha/tls/cipher_suite.rbs +41 -0
  310. data/sig/raiha/tls/codec.rbs +66 -0
  311. data/sig/raiha/tls/config.rbs +122 -0
  312. data/sig/raiha/tls/crypto.rbs +86 -0
  313. data/sig/raiha/tls/error.rbs +21 -0
  314. data/sig/raiha/tls/event.rbs +61 -0
  315. data/sig/raiha/tls/extension.rbs +331 -0
  316. data/sig/raiha/tls/handshake.rbs +311 -0
  317. data/sig/raiha/tls/iana.rbs +13 -0
  318. data/sig/raiha/tls/key_exchange.rbs +33 -0
  319. data/sig/raiha/tls/key_schedule.rbs +58 -0
  320. data/sig/raiha/tls/keylog.rbs +20 -0
  321. data/sig/raiha/tls/keyring.rbs +64 -0
  322. data/sig/raiha/tls/machine.rbs +429 -0
  323. data/sig/raiha/tls/masked_inspect.rbs +12 -0
  324. data/sig/raiha/tls/output.rbs +37 -0
  325. data/sig/raiha/tls/profile.rbs +26 -0
  326. data/sig/raiha/tls/record.rbs +79 -0
  327. data/sig/raiha/tls/server_name.rbs +10 -0
  328. data/sig/raiha/tls/session.rbs +48 -0
  329. data/sig/raiha/tls/signature_scheme.rbs +20 -0
  330. data/sig/raiha/tls/tcp.rbs +134 -0
  331. data/sig/raiha/tls/test.rbs +143 -0
  332. data/sig/raiha/tls/ticket.rbs +68 -0
  333. data/sig/raiha/tls/ticket_keys.rbs +67 -0
  334. data/sig/raiha/tls/trace.rbs +99 -0
  335. data/sig/raiha/tls/transcript.rbs +22 -0
  336. data/sig/raiha/tls/verifier.rbs +54 -0
  337. data/sig/raiha/tls.rbs +5 -0
  338. data/sig/raiha.rbs +3 -0
  339. metadata +355 -57
  340. data/.gitignore +0 -10
  341. data/CODE_OF_CONDUCT.md +0 -74
  342. data/Gemfile +0 -4
  343. data/Gemfile.lock +0 -22
  344. data/Rakefile +0 -10
  345. data/bin/console +0 -14
  346. data/bin/setup +0 -8
  347. data/raiha.gemspec +0 -40
@@ -0,0 +1,2022 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::QUIC
4
+ # One QUIC connection, sans-IO: it is
5
+ # given datagrams with `receive` and the time with `handle_timeout`, and
6
+ # hands back the datagrams to send with `each_transmit` and what happened
7
+ # with `each_event`. It never reads a clock; `now:` is the monotonic
8
+ # clock in Float seconds, and TLS's wall clock is `time:`, given once when
9
+ # the connection is made, moved on by the monotonic clock since.
10
+ #
11
+ # A connection knows only itself: an Endpoint finds it by connection ID.
12
+ class Connection
13
+ # The encryption levels, in the order their packets go in a datagram.
14
+ LEVELS = %i[initial zero_rtt handshake one_rtt].freeze
15
+ # The packet number space of each level.
16
+ SPACES = { initial: :initial, zero_rtt: :application_data, handshake: :handshake, one_rtt: :application_data }.freeze
17
+ # The spaces a PTO may probe.
18
+ PROBED_SPACES = SPACES.values.uniq.freeze
19
+ # RFC 9000 "Datagram Size": a datagram with an Initial packet in it
20
+ # from a client, or with an ack-eliciting one from a server, is padded
21
+ # to this.
22
+ MIN_INITIAL_DATAGRAM = 1200
23
+ # The length of a client's first Destination Connection ID (RFC 9000
24
+ # "Negotiating Connection IDs": 8 bytes at least).
25
+ INITIAL_DCID_LENGTH = 8
26
+ # The ACK Delay exponent before the peer's is known, and for the ACK
27
+ # frames of Initial and Handshake packets.
28
+ DEFAULT_ACK_DELAY_EXPONENT = 3
29
+ # Bytes a long header adds to its connection IDs and token, with a
30
+ # 2-byte Length and a 4-byte packet number at most, and the AEAD tag.
31
+ LONG_HEADER_OVERHEAD = 1 + 4 + 1 + 1 + 2 + 4 + 16
32
+ SHORT_HEADER_OVERHEAD = 1 + 4 + 16
33
+
34
+ # RFC 9000 "Immediate Close": the closing and draining states last three
35
+ # PTOs.
36
+ CLOSE_PTOS = 3
37
+ # The longest reason phrase a CONNECTION_CLOSE frame carries.
38
+ MAX_REASON_LENGTH = 256
39
+ # The levels a CONNECTION_CLOSE frame goes in.
40
+ CLOSE_LEVELS = %i[initial handshake one_rtt].freeze
41
+
42
+ # How many PTOs a connection ID the peer retired still leads to the
43
+ # connection.
44
+ RETIRED_PTOS = 3
45
+ # RFC 9000 "Failed Path Validation": a path not validated in three
46
+ # times the larger of the current PTO and the new path's fails.
47
+ VALIDATION_PTOS = 3
48
+ # The most paths besides the one in use a connection keeps, being
49
+ # validated or validated (CVE-2026-12707).
50
+ MAX_VALIDATING_PATHS = 3
51
+ # The bytes of unpredictable data a PATH_CHALLENGE carries.
52
+ CHALLENGE_LENGTH = 8
53
+ # The least a probe of a path takes, which a path with less left of its
54
+ # amplification limit cannot send: no timer waits for it.
55
+ MIN_PROBE = 64
56
+ # The largest datagram a path is searched up to, by the family of its
57
+ # peer's address: 1500 bytes of Ethernet less the IP and UDP headers.
58
+ MAX_MTU_PROBE = { ipv4: 1472, ipv6: 1452 }.freeze
59
+ # How many times a server sends its Initial flight again at once on a
60
+ # ClientHello that comes again (RFC 9002 "Speeding up Handshake
61
+ # Completion"): once is enough for one loss, and twice for a burst.
62
+ SEND_AGAIN_AT_ONCE = 2
63
+
64
+ # The most events the application may leave untaken: past it, the peer
65
+ # makes the connection hold what nobody takes, and it closes with
66
+ # INTERNAL_ERROR. DATAGRAMs received past their own limit are dropped
67
+ # before they get here.
68
+ MAX_EVENTS = 4096
69
+ # Event::SessionTicket held until taken (session_ticket).
70
+ MAX_HELD_TICKETS = 8
71
+ # The levels of the packets kept until their keys come (KeptPackets).
72
+ KEPT_LEVELS = %i[handshake one_rtt].freeze
73
+ # The limits 0-RTT may have used, which a server that took it must not
74
+ # lower (RFC 9000 "Values of Transport Parameters for 0-RTT"), nor
75
+ # max_datagram_frame_size (RFC 9221). They come with EncryptedExtensions,
76
+ # after which 0-RTT still pending was taken (check_zero_rtt_limits).
77
+ ZERO_RTT_LIMITS = %i[
78
+ active_connection_id_limit initial_max_data initial_max_stream_data_bidi_local initial_max_stream_data_bidi_remote
79
+ initial_max_stream_data_uni initial_max_streams_bidi initial_max_streams_uni max_datagram_frame_size
80
+ ].freeze
81
+
82
+
83
+ # A packet put together, not yet protected.
84
+ Pending = Data.define(:level, :header, :packet_number, :packet_number_length, :frames, :duties)
85
+
86
+ # A packet of only an ACK in the Initial space an Endpoint sent the
87
+ # client before the connection was made: its number, its size, and
88
+ # when it went.
89
+ EarlyAck = Data.define(:packet_number, :bytes, :time)
90
+
91
+ attr_reader :role, :path
92
+
93
+ # A client connection to `remote` ([host, port]), with its first
94
+ # Initial packet waiting to be sent. `tls_config` has the QUIC profile.
95
+ # The connection's Source Connection ID is `source_connection_id`, which
96
+ # an Endpoint routes by, or one of its own. `token` is a QUIC::Token a
97
+ # server gave in a NEW_TOKEN frame, which the Initials carry until a
98
+ # Retry's takes its place (RFC 9000 "Address Validation for Future
99
+ # Connections"), when it is of the version the connection starts in;
100
+ # the tracer hears of one that is not.
101
+ # `session` is a QUIC::Session to resume, offered if TLS still may. The
102
+ # connection starts in the session's version when `config` has it, and
103
+ # in the first of `config.versions` otherwise, without the session,
104
+ # which is of another version (RFC 9369 "TLS Resumption and NEW_TOKEN
105
+ # Tokens"); the tracer hears of it. With `early_data: true` the client
106
+ # sends 0-RTT on the session when TLS can: what streams and DATAGRAM
107
+ # frames carry before the handshake completes goes in 0-RTT packets, to
108
+ # the limits the session remembers (`zero_rtt_state`). An Endpoint's
109
+ # `issuer` makes the connection IDs it issues once the handshake is
110
+ # confirmed; with none, it issues none. Its `peers` learn the address
111
+ # of each path the connection has, for a stateless reset to find it.
112
+ def self.client(config:, tls_config:, keyring:, server_name:, remote:, time:, now:, tracer: nil, keylog: nil, source_connection_id: nil,
113
+ token: nil, session: nil, early_data: false, issuer: nil, peers: nil)
114
+ raise ArgumentError, "token must be a QUIC::Token" unless token.nil? || token.is_a?(Token)
115
+ raise ArgumentError, "session must be a QUIC::Session" unless session.nil? || session.is_a?(Session)
116
+ raise ArgumentError, "early_data must be true or false" unless early_data == true || early_data == false
117
+ version = config.versions.find { |candidate| candidate.number == session&.version }
118
+ if session && version.nil?
119
+ tracer.session_ignored(reason: :version_mismatch, now:) if tracer
120
+ session = nil
121
+ end
122
+ version ||= config.versions.fetch(0)
123
+ if token && token.version != version.number
124
+ tracer.token_ignored(reason: :version_mismatch, now:) if tracer
125
+ token = nil
126
+ end
127
+ zero_rtt = early_data && !session.nil?
128
+ first = version
129
+ new(role: :client, config:, now:, time:, remote:, tracer:, random: keyring.random, version:, source_connection_id:, token: token&.value,
130
+ session:, issuer:, peers:) do |connection, parameters, attempt|
131
+ # An attempt after Version Negotiation is in another version than
132
+ # the session's, and resumes nothing.
133
+ resumed = session if attempt == first
134
+ TLSBinding.client(connection:, config: tls_config, keyring:, server_name:, transport_parameters: parameters, time:, tracer:, keylog:,
135
+ session: resumed&.tls, early_data: zero_rtt && !resumed.nil?)
136
+ end
137
+ end
138
+
139
+ # A server connection, which takes the client's first Initial packet as
140
+ # it comes and starts TLS then, when the client's first Destination
141
+ # Connection ID, which its transport parameters carry, is known.
142
+ #
143
+ # An Endpoint that has taken the offer of the connection gives what it
144
+ # learned: the ClientHello its Acceptor read (`client_hello`), and after
145
+ # a Retry the client's first Destination Connection ID and the Retry's
146
+ # Source Connection ID, which the transport parameters name, and that
147
+ # the client's address is validated. It also chooses the connection's
148
+ # Source Connection ID, and gives its `stateless_reset_token`, which the
149
+ # transport parameters carry (RFC 9000 "Stateless Reset"). Its
150
+ # `early_acks` (EarlyAck) are the packets it acknowledged the client's
151
+ # Initials with, which the connection takes as its own: its Initial
152
+ # packet numbers follow theirs, an ACK of them is of packets it sent,
153
+ # and their bytes count toward the amplification limit.
154
+ #
155
+ # The client's Initials came in `original_version`, and the Endpoint
156
+ # chose `negotiated_version` for the connection by compatible version
157
+ # negotiation (RFC 9368): the server's Initials, from the first that
158
+ # carries CRYPTO frames, and its Handshake and 1-RTT packets go in it.
159
+ # Without them, both are the version of the first Initial that opens.
160
+ # Its tickets are bound to the version negotiated, so that a ticket of
161
+ # another opens on none of it (RFC 9369 "TLS Resumption and NEW_TOKEN
162
+ # Tokens").
163
+ # `anti_replay` is the record of the 0-RTT taken, which a TLS Config that
164
+ # takes 0-RTT needs, and `app_early_data_context` what of the application
165
+ # 0-RTT is taken only if the same of (TLSBinding.server). `issuer` and
166
+ # `peers` are as of a client. The Endpoint's `tokens` seal a NEW_TOKEN
167
+ # token for a new address of the client the connection validates.
168
+ def self.server(config:, tls_config:, keyring:, time:, now:, tracer: nil, keylog: nil, client_hello: nil,
169
+ original_destination_connection_id: nil, retry_source_connection_id: nil, address_validated: false, source_connection_id: nil,
170
+ stateless_reset_token: nil, new_token: nil, anti_replay: nil, app_early_data_context: "".b, issuer: nil, peers: nil, tokens: nil,
171
+ early_acks: [], original_version: nil, negotiated_version: nil)
172
+ raise ArgumentError, "app_early_data_context must be a String" unless app_early_data_context.is_a?(String)
173
+ raise ArgumentError, "original_version and negotiated_version go together" if original_version.nil? != negotiated_version.nil?
174
+ new(role: :server, config:, now:, time:, remote: nil, tracer:, random: keyring.random, version: original_version, negotiated_version:,
175
+ original_destination_connection_id:,
176
+ retry_source_connection_id:, address_validated:, source_connection_id:, stateless_reset_token:, new_token:,
177
+ issuer:, peers:, tokens:, early_acks:) do |connection, parameters, version|
178
+ TLSBinding.server(connection:, config: tls_config, keyring:, transport_parameters: parameters, time:, client_hello:, tracer:, keylog:,
179
+ version:, anti_replay:, app_early_data_context:)
180
+ end
181
+ end
182
+
183
+ private_class_method :new
184
+
185
+ def initialize(role:, config:, now:, time:, remote:, tracer:, random:, version:, negotiated_version: nil, original_destination_connection_id: nil,
186
+ retry_source_connection_id: nil, address_validated: role == :client, source_connection_id: nil, stateless_reset_token: nil, token: nil,
187
+ new_token: nil, session: nil, issuer: nil, peers: nil, tokens: nil, early_acks: [], &start)
188
+ @role = role
189
+ @config = config
190
+ @random = random
191
+ # A server made without the versions takes those of the first Initial
192
+ # that opens (accept_first_initial).
193
+ @versions_given = !version.nil?
194
+ chosen = version || config.versions.fetch(0)
195
+ @negotiation = role == :client ? Negotiation.client(versions: config.versions, chosen:, random:) :
196
+ server_negotiation(chosen, negotiated_version || chosen)
197
+ @created_at = now
198
+ @time = time
199
+ @tracer = tracer
200
+ @path = Path.new(config:, remote:, validated: address_validated, tracer:)
201
+ @recovery = Recovery.new(role:, config:, path: @path, random:, now:, tracer:)
202
+ early_acks.each { |ack| take_early_ack(ack) }
203
+ # The paths besides the one in use, being validated or validated, the
204
+ # oldest first, and the one last validated, which the connection goes
205
+ # back to when a new one fails; the first is, by the handshake.
206
+ @validating = [] #: Array[Path]
207
+ @last_validated = @path
208
+ # The path a client validates to the server's preferred address, once
209
+ # it has started to.
210
+ @preferred_path = nil #: Path?
211
+ # The path the 1-RTT packet that is no probe with the largest number
212
+ # so far came on, which a server moves to at its preferred address
213
+ # once it has validated the path, and the largest number received
214
+ # when it moved.
215
+ @newest_path = nil #: Path?
216
+ @moved_after = nil #: Integer?
217
+ @events = [] #: Array[Event::t]
218
+ @streams = Streams.new(role:, config:, events: @events, now:, tracer:)
219
+ @datagrams = Datagrams.new(config:, events: @events)
220
+ @kept = KeptPackets.new
221
+ @protection = PacketProtection.new(role:) { |phase| keys_updated(phase) }
222
+ @source_connection_id = source_connection_id || random.bytes(config.connection_id_length).b
223
+ # The Destination Connection ID of the last 1-RTT packet that came on
224
+ # the path in use, at first the one the handshake's packets came to: a
225
+ # packet from a new address with the same one is a NAT rebinding most
226
+ # likely, the first 1-RTT packet as well.
227
+ @received_dcid = @source_connection_id #: String
228
+ @issued = IssuedConnectionIDs.new(@source_connection_id, issuer:, connection: self)
229
+ @peers = peers
230
+ @stateless_reset_token = stateless_reset_token
231
+ @peer_parameters = nil #: TransportParameters?
232
+ @handshake_complete = false
233
+ @handshake_confirmed = false
234
+ @handshake_done_due = false
235
+ # The Source Connection ID of the peer's first Initial packet; a long
236
+ # header packet with another is dropped (RFC 9000 "Negotiating
237
+ # Connection IDs").
238
+ @peer_source_connection_id = nil #: String?
239
+ # :open, :closing, :draining or :closed (RFC 9000 "Connection
240
+ # Termination").
241
+ @state = :open
242
+ @close_error = nil #: ConnectionError?
243
+ @close_deadline = nil #: Float?
244
+ @close_frame_due = false
245
+ @closing_datagrams = 0
246
+ @idle_deadline = nil #: Float?
247
+ @eliciting_since_received = false
248
+ @now = now
249
+ # What Stats counts: the packets and their bytes each way, and when
250
+ # the handshake completed.
251
+ @packets_sent = 0
252
+ @bytes_sent = 0
253
+ @packets_received = 0
254
+ @bytes_received = 0
255
+ @handshake_completed_at = nil #: Float?
256
+ # Whether the amplification limit of the path, while the client's
257
+ # address is not validated, has stopped a server.
258
+ @amplification_limited = false
259
+ # Whether a packet that is no probe is to go, after a PATH_CHALLENGE
260
+ # on the path in use (RFC 9000 "Off-Path Packet Forwarding").
261
+ @non_probing_due = false
262
+ # How many datagrams that elicit an ACK PTOs still ask for, and the
263
+ # spaces they probe.
264
+ @probe_datagrams = 0
265
+ @probed_spaces = [] #: Array[space]
266
+ @sent_again_at_once = 0
267
+ restart_idle(now)
268
+ @start_binding = start
269
+ @binding = nil #: TLSBinding?
270
+ # A client's first Destination Connection ID, and the Source
271
+ # Connection ID of a Retry, which the server's transport parameters
272
+ # must name.
273
+ @original_destination_connection_id = original_destination_connection_id
274
+ @retry_source_connection_id = retry_source_connection_id
275
+ # The token a client's Initials carry, from a NEW_TOKEN or a Retry.
276
+ @token = token&.b || Wire::EMPTY
277
+ # The token a server gives in a NEW_TOKEN frame once it confirms the
278
+ # handshake, and whether the frame is to go (again, if lost).
279
+ @new_token = new_token
280
+ @new_token_due = false
281
+ @tokens = tokens
282
+ # A client's session to resume, and how its 0-RTT goes: :disabled,
283
+ # :pending while 0-RTT packets go, then :accepted or :rejected.
284
+ @session = session
285
+ @zero_rtt_state = :disabled #: :disabled | :pending | :accepted | :rejected
286
+ # The streams a server received data of in 0-RTT packets.
287
+ @early_data_streams = Set.new #: Set[Integer]
288
+ @zero_rtt_rejection_unacknowledged = false
289
+ # The connection IDs the peer issued, from its transport parameters
290
+ # on.
291
+ @peer_ids = nil #: PeerConnectionIDs?
292
+ @destination_connection_id = "".b
293
+ start_attempt(now) if role == :client
294
+ end
295
+
296
+ # The version the connection is in: the one it started in until a
297
+ # client learns the one the server chose (RFC 9368).
298
+ def version = @negotiation.current
299
+
300
+ # Whether TLS has completed the handshake on this end.
301
+ def handshake_complete? = @handshake_complete
302
+
303
+ # Whether the handshake is confirmed (RFC 9001 "Handshake Confirmed"): on
304
+ # a server once it is complete, on a client once HANDSHAKE_DONE comes.
305
+ def handshake_confirmed? = @handshake_confirmed
306
+
307
+ # Whether the peer's address on the path in use is validated (RFC 9000
308
+ # "Address Validation"), past which no amplification limit holds; a
309
+ # server's is once a token shows it, or a Handshake packet comes.
310
+ def address_validated? = @path.validated?
311
+
312
+ def closing? = @state == :closing
313
+
314
+ def draining? = @state == :draining
315
+
316
+ # Whether the connection is over, its closing or draining period past.
317
+ def closed? = @state == :closed
318
+
319
+ # Why the connection closed, nil while it is open.
320
+ def close_reason = @close_error
321
+
322
+ # What the connection has done so far.
323
+ def stats
324
+ rtt = @path.rtt
325
+ completed = @handshake_completed_at
326
+ Stats.new(rtt: rtt.smoothed_rtt, rtt_var: rtt.rttvar, min_rtt: rtt.min_rtt, congestion_window: @path.congestion.window,
327
+ bytes_in_flight: @path.bytes_in_flight, packets_sent: @packets_sent, packets_received: @packets_received,
328
+ packets_lost: @recovery.packets_lost, packets_spuriously_lost: @recovery.packets_spuriously_lost, bytes_sent: @bytes_sent,
329
+ bytes_received: @bytes_received, path_mtu: @path.max_datagram_size, handshake_duration: completed && completed - @created_at,
330
+ receive_window: @streams.window.size, send_buffer_bytes: @streams.buffered, blocked_sent: @streams.blocked_sent,
331
+ blocked_received: @streams.blocked_received)
332
+ end
333
+
334
+ # Up to `max_bytes` received on `stream_id`, read by the application:
335
+ # "" when nothing is there yet, nil once the stream has ended, as
336
+ # IO#read gives. What is read goes back to the peer as credit.
337
+ def stream_read(stream_id, max_bytes)
338
+ zero_rtt_settled!(stream_id)
339
+ @streams.read(stream_id, max_bytes)
340
+ end
341
+
342
+ # The streams a read would give something on.
343
+ def readable_streams = @streams.readable.each
344
+
345
+ # Opens a stream going `direction`, :bidi or :uni: its ID, or nil when
346
+ # the peer allows no more yet.
347
+ def open_stream(direction: :bidi)
348
+ raise ArgumentError, "a stream goes :bidi or :uni, not #{direction.inspect}" unless %i[bidi uni].include?(direction)
349
+ open!
350
+ zero_rtt_settled!
351
+ @streams.open(direction, now: @now)
352
+ end
353
+
354
+ # Writes `data` to `stream_id`, as much of it as the stream's credit,
355
+ # the connection's and the send buffer leave room for, and ends the
356
+ # stream with `fin` when all of it is taken: how many bytes were taken.
357
+ # Less than all of it, and Event::StreamWritable tells when the stream
358
+ # can take more.
359
+ def stream_write(stream_id, data, fin: false)
360
+ open!
361
+ zero_rtt_settled!(stream_id)
362
+ @streams.write(stream_id, data, fin:, now: @now)
363
+ end
364
+
365
+ # Queues `data` to go in a DATAGRAM frame, never sent again, by
366
+ # `expires_at` on the monotonic clock if given, before those of a higher
367
+ # `urgency` (0 to 7, as RFC 9218 counts it): whether it was queued. Not
368
+ # when the peer does not take DATAGRAM frames, `data` is over
369
+ # `datagram_max_size`, or too many wait.
370
+ def datagram_send(data, expires_at: nil, urgency: 3)
371
+ open!
372
+ raise ArgumentError, "urgency is 0 to 7, not #{urgency.inspect}" unless urgency.is_a?(Integer) && urgency.between?(0, 7)
373
+ @datagrams.send(data, expires_at:, urgency:, max_size: datagram_max_size)
374
+ end
375
+
376
+ # The most data a DATAGRAM frame can carry now: the peer's
377
+ # max_datagram_frame_size, its max_udp_payload_size and the path's
378
+ # datagram size each less what goes around it. nil while the peer has
379
+ # not taken DATAGRAM frames, which may be for good.
380
+ def datagram_max_size
381
+ peer = @peer_parameters || zero_rtt_parameters or return nil
382
+ frame = peer.max_datagram_frame_size
383
+ return nil if frame.zero?
384
+ packet = [@path.max_datagram_size, peer.max_udp_payload_size].min - SHORT_HEADER_OVERHEAD - @destination_connection_id.bytesize
385
+ size = [frame, packet].min
386
+ size - 1 - Wire::Varint.size(size)
387
+ end
388
+
389
+ # How many bytes a write to `stream_id` would take now.
390
+ def stream_writable_bytes(stream_id)
391
+ zero_rtt_settled!(stream_id)
392
+ @streams.writable_bytes(stream_id)
393
+ end
394
+
395
+ # Abandons sending on `stream_id`: RESET_STREAM goes with
396
+ # `error_code`, and what was written and not acknowledged goes nowhere.
397
+ def stream_reset(stream_id, error_code:)
398
+ open!
399
+ zero_rtt_settled!(stream_id)
400
+ @streams.reset(stream_id, error_code)
401
+ end
402
+
403
+ # Stops reading `stream_id`: STOP_SENDING asks the peer with
404
+ # `error_code` to stop sending, and what comes is let go.
405
+ def stream_stop_sending(stream_id, error_code:)
406
+ open!
407
+ zero_rtt_settled!(stream_id)
408
+ @streams.stop_sending(stream_id, error_code)
409
+ end
410
+
411
+ # Sends `stream_id` with `urgency` (0 to 7, as RFC 9218 counts it) and
412
+ # as `incremental` or not: the streams of a lower urgency go first, and
413
+ # of one urgency, the incremental streams take turns with the one not
414
+ # incremental of the lowest ID. A stream given none is of urgency 3 and
415
+ # incremental.
416
+ def stream_priority(stream_id, urgency:, incremental:)
417
+ open!
418
+ zero_rtt_settled!(stream_id)
419
+ raise ArgumentError, "urgency is 0 to 7, not #{urgency.inspect}" unless urgency.is_a?(Integer) && urgency.between?(0, 7)
420
+ raise ArgumentError, "incremental is true or false, not #{incremental.inspect}" unless incremental == true || incremental == false
421
+ @streams.prioritize(stream_id, urgency:, incremental:)
422
+ end
423
+
424
+ # The streams a write would take something on.
425
+ def writable_streams = @streams.writable.each
426
+
427
+ # Closes the connection with `error_code`, an application's unless
428
+ # `application` is false: a CONNECTION_CLOSE frame goes out, and the
429
+ # connection stays closing, answering what comes with it again, for
430
+ # three PTOs (RFC 9000 "Immediate Close"). `each_transmit` and
431
+ # `handle_timeout` still have work until `closed?`.
432
+ def close(error_code: ErrorCode::NO_ERROR, reason: "", application: true, now:)
433
+ @now = now
434
+ return unless @state == :open
435
+ enter_closing(ConnectionError.new(code: error_code, frame_type: application ? nil : 0, reason:, application:), now)
436
+ end
437
+
438
+ def next_event
439
+ event = @events.shift
440
+ @datagrams.taken(event) if event
441
+ event
442
+ end
443
+
444
+ def each_event
445
+ while (event = next_event)
446
+ yield event
447
+ end
448
+ end
449
+
450
+ # Takes a datagram that came from `from` with the ECN codepoint `ecn`.
451
+ # The packets coalesced in it are handled one after another; nothing
452
+ # the peer sends raises. While
453
+ # closing, a datagram is answered with the CONNECTION_CLOSE frame again,
454
+ # the first, second, fourth and so on; while draining, nothing.
455
+ def receive(datagram, from:, to: nil, ecn: :not_ect, now:)
456
+ @now = now
457
+ case @state
458
+ when :open then nil
459
+ when :closing
460
+ @closing_datagrams += 1
461
+ @close_frame_due = true if (@closing_datagrams & (@closing_datagrams - 1)).zero?
462
+ return
463
+ else return
464
+ end
465
+ @path.learn(local: to, remote: from) if @role == :client
466
+ path = path_of(to, from)
467
+ # RFC 9000 "Connection Migration": nothing comes from a new address
468
+ # before the handshake is confirmed, and a client takes nothing from
469
+ # a server address it did not migrate to; it is dropped, and no path
470
+ # is made for it.
471
+ return dropped(:rejected, datagram.bytesize, now) unless path || (@role == :server && @handshake_confirmed)
472
+ count_received(datagram, path, now) if path
473
+ processed = false
474
+ offset = 0
475
+ while offset < datagram.bytesize
476
+ packet = parse_packet(datagram, offset, now) or break
477
+ processed = true if receive_packet(packet, from:, to:, ecn:, now:, path:)
478
+ open_kept(now) unless @kept.empty?
479
+ offset = packet.end_offset
480
+ break unless @state == :open
481
+ end
482
+ take_stateless_reset(datagram, from:, now:) unless processed
483
+ if @state == :open && @events.size > MAX_EVENTS
484
+ raise Violation.new("more than #{MAX_EVENTS} events not taken", code: ErrorCode::INTERNAL_ERROR)
485
+ end
486
+ rescue Violation => error
487
+ # What a packet that opened breaks closes the connection; only an
488
+ # authenticated peer gets here, or one past the integrity limit (250
489
+ # "Errors").
490
+ close_for(error, now)
491
+ end
492
+
493
+ # RFC 9000 "Detecting a Stateless Reset": whether `datagram`, none of
494
+ # whose packets this connection could take, ends in a stateless reset
495
+ # token the peer gave of an ID this end sends with on a path to `from`,
496
+ # the address it came from, the path to go back to's too; the
497
+ # connection then drains on it, sending nothing more. Each token is
498
+ # compared in constant time.
499
+ def take_stateless_reset(datagram, from:, now:)
500
+ paths = [@path, *@validating, @last_validated].compact.uniq.select { |path| path.remote == from }
501
+ ids = paths.filter_map { |path| path.equal?(@path) ? @destination_connection_id : path.destination_connection_id }
502
+ return false unless @state == :open && StatelessReset.match?(datagram, @peer_ids&.reset_tokens(ids) || [])
503
+ enter_draining(ConnectionError.new(code: ErrorCode::NO_ERROR, frame_type: 0, reason: "stateless reset", application: false), now)
504
+ true
505
+ end
506
+
507
+ # Each datagram there is to send now, on the path it goes on. With the
508
+ # Config's max_transmit_size, those that follow the first on the same
509
+ # path and are as large, the last of them possibly shorter, go with it
510
+ # in one Transmit, as many as fit and Transmit::MAX_SEGMENTS at most
511
+ # (GSO); seeing whether the next one fits builds it, and one that does
512
+ # not starts the next Transmit. A datagram to go alone goes in a
513
+ # Transmit of its own.
514
+ def each_transmit(now:)
515
+ @now = now
516
+ limit = @config.max_transmit_size
517
+ unless limit
518
+ while (sent = next_datagram(now))
519
+ datagram, path = sent
520
+ yield transmit(datagram, path, nil)
521
+ end
522
+ return
523
+ end
524
+ sent = next_datagram(now)
525
+ while sent
526
+ payload, path, alone = sent
527
+ size = payload.bytesize
528
+ count = 1
529
+ sent = next_datagram(now)
530
+ while !alone && sent && !sent[2] && sent[1].equal?(path) && count < Transmit::MAX_SEGMENTS && sent[0].bytesize <= size &&
531
+ payload.bytesize + sent[0].bytesize <= limit
532
+ payload = payload.b if count == 1
533
+ payload << sent[0]
534
+ count += 1
535
+ last = sent[0].bytesize < size
536
+ sent = next_datagram(now)
537
+ break if last
538
+ end
539
+ yield transmit(payload, path, count > 1 ? size : nil)
540
+ end
541
+ end
542
+
543
+ def transmits(now:)
544
+ transmits = [] #: Array[Transmit]
545
+ each_transmit(now:) { |transmit| transmits << transmit }
546
+ transmits
547
+ end
548
+
549
+ # When something is to be done next: a timer of loss recovery, the
550
+ # idle timeout, the end of the previous 1-RTT keys or when pacing lets
551
+ # what it held back go while open, the end of closing or draining after.
552
+ def next_timeout
553
+ case @state
554
+ when :open
555
+ # A server at its amplification limit cannot send an ACK either, so
556
+ # an ACK's deadline would only come round again and again.
557
+ [@amplification_limited ? @recovery.loss_detection_timer : @recovery.next_timeout, @idle_deadline,
558
+ @protection.next_timeout, @path.pacing_release_at, @issued.next_timeout, *validation_timeouts].compact.min
559
+ when :closing, :draining then @close_deadline
560
+ end
561
+ end
562
+
563
+ def handle_timeout(now:)
564
+ @now = now
565
+ case @state
566
+ when :open
567
+ idle = @idle_deadline
568
+ return time_out_idly if idle && now >= idle
569
+ @protection.handle_timeout(now:)
570
+ @issued.handle_timeout(now)
571
+ @validating.select { |path| path.validation_failed?(now) }.each do |path|
572
+ trace_migration(:probing_abandoned, path, now)
573
+ abandon_path(path)
574
+ end
575
+ fall_back(now) if @path.validation_failed?(now)
576
+ return unless @state == :open
577
+ outcome = @recovery.on_timeout(now:)
578
+ Recovery::Duty.dispatch(outcome, to: self)
579
+ probe(outcome.probe) if outcome.probe
580
+ when :closing, :draining
581
+ deadline = @close_deadline
582
+ @state = :closed if deadline && now >= deadline
583
+ end
584
+ end
585
+
586
+ # TLSBinding::_Connection
587
+
588
+ def install_keys(level, direction, secret:, suite:)
589
+ @protection.install(level, direction, secret:, suite:)
590
+ @recovery.handshake_keys_installed! if level == :handshake
591
+ start_zero_rtt if level == :zero_rtt && direction == :write
592
+ end
593
+
594
+ # The server took no 0-RTT (RFC 9001 "Accepting and Rejecting 0-RTT"):
595
+ # no more 0-RTT packets go, and none that went is sent again. The
596
+ # streams this client opened are gone and their IDs start over, the
597
+ # DATAGRAMs waiting are dropped, and Event::ZeroRttRejected says so;
598
+ # until the application acknowledges it, its streams and open_stream
599
+ # raise Error::ZeroRttRejected, so that an old ID cannot name a new
600
+ # stream. What to send again is the application's.
601
+ def zero_rtt_rejected(reason)
602
+ return unless @zero_rtt_state == :pending
603
+ @recovery.on_zero_rtt_rejected(now: @now)
604
+ roll_back_zero_rtt(reason)
605
+ end
606
+
607
+ # 0-RTT went for nothing, for `reason`: the streams this client opened
608
+ # are gone and their IDs start over, the DATAGRAMs waiting are dropped,
609
+ # and Event::ZeroRttRejected says so.
610
+ private def roll_back_zero_rtt(reason)
611
+ @zero_rtt_state = :rejected
612
+ @streams.roll_back_own_streams
613
+ @datagrams.drop_queued
614
+ @protection.discard(:zero_rtt)
615
+ @zero_rtt_rejection_unacknowledged = true
616
+ @events << Event::ZeroRttRejected.new(reason:)
617
+ end
618
+
619
+ # The application knows its 0-RTT was rejected (Event::ZeroRttRejected),
620
+ # and opens streams again from here.
621
+ def acknowledge_zero_rtt_rejection
622
+ @zero_rtt_rejection_unacknowledged = false
623
+ nil
624
+ end
625
+
626
+ # Whether a STREAM frame of `stream_id` came in a 0-RTT packet, which
627
+ # may be a replay of another connection's (RFC 9846 "Replay Attacks on
628
+ # 0-RTT"); it stays true, and is always false at a client and at a
629
+ # server that took no 0-RTT. An application keeps it apart from
630
+ # whether the handshake has completed, after which 0-RTT data on this
631
+ # connection is no replay (RFC 8470 "Using Early Data in HTTP").
632
+ def stream_early_data?(stream_id) = @early_data_streams.include?(stream_id)
633
+
634
+ # How a client's 0-RTT goes: :disabled when it sends none, :pending
635
+ # while it sends 0-RTT packets, :accepted or :rejected once the server
636
+ # says.
637
+ def zero_rtt_state = @zero_rtt_state
638
+
639
+ # The peer's transport parameters: their connection IDs must be the ones
640
+ # its Initial packets used, and its max_ack_delay and max_idle_timeout
641
+ # count from now on.
642
+ def peer_transport_parameters(data)
643
+ parameters = TransportParameters.decode(data, sender: @role == :client ? :server : :client)
644
+ authenticate_connection_ids(parameters)
645
+ if @tracer && @role == :server
646
+ @tracer.version_information(server_versions: @config.versions.map(&:number), # steep:ignore
647
+ client_versions: parameters.version_information&.available, chosen_version: @negotiation.current.number, now: @now)
648
+ end
649
+ violation = @negotiation.check(parameters.version_information) and raise violation
650
+ check_zero_rtt_limits(parameters)
651
+ @peer_ids = PeerConnectionIDs.new(@destination_connection_id, stateless_reset_token: parameters.stateless_reset_token,
652
+ limit: @config.active_connection_id_limit, preferred_address: parameters.preferred_address)
653
+ @tracer.parameters_set(owner: :remote, parameters:, now: @now) if @tracer # steep:ignore
654
+ @peer_parameters = parameters
655
+ @streams.peer_parameters = parameters
656
+ @recovery.peer_max_ack_delay = parameters.max_ack_delay
657
+ restart_idle(@now)
658
+ end
659
+
660
+ # A server confirms the handshake as it completes, and tells the client
661
+ # with HANDSHAKE_DONE.
662
+ def handshake_completed(event)
663
+ @zero_rtt_state = event.early_data_accepted ? :accepted : :rejected if @zero_rtt_state == :pending
664
+ @handshake_complete = true
665
+ @handshake_completed_at = @now
666
+ @events << Event::Connected.new(handshake: event)
667
+ return unless @role == :server
668
+ @handshake_done_due = true
669
+ @new_token_due = !@new_token.nil?
670
+ confirm(@now)
671
+ end
672
+
673
+ # TLS failed and has forgotten its secrets: the connection closes with
674
+ # `code`, a transport error of the CRYPTO frame.
675
+ def tls_failed(code, reason)
676
+ return unless @state == :open
677
+ enter_closing(ConnectionError.new(code:, frame_type: CryptoStream::FRAME_TYPE, reason: reason.to_s, application: false), @now)
678
+ end
679
+
680
+ def tls_event(event) = @events << Event::TLSEvent.new(event:)
681
+
682
+ # A ticket becomes a QUIC::Session with the server's transport
683
+ # parameters that 0-RTT may use. The newest MAX_HELD_TICKETS are held
684
+ # until taken: one more drops the oldest, so that a server sending
685
+ # tickets without end cannot make a client keep them all.
686
+ def session_ticket(tls_session)
687
+ parameters = @peer_parameters or raise "a ticket comes after the server's transport parameters"
688
+ held = @events.select { |event| event.is_a?(Event::SessionTicket) }
689
+ if held.size >= MAX_HELD_TICKETS
690
+ @events.delete(held.fetch(0))
691
+ @tracer.tls_trace(Raiha::TLS::Trace::TicketIgnored.new(reason: :too_many_tickets)) if @tracer.respond_to?(:tls_trace) # steep:ignore
692
+ end
693
+ @events << Event::SessionTicket.new(session: Session.new(tls: tls_session, transport_parameters: parameters.remembered,
694
+ alpn: tls_session.alpn, version: @negotiation.current.number))
695
+ end
696
+
697
+ # Recovery::Duty::_Owner
698
+
699
+ def crypto_data_acked(duty) = binding.crypto_acked(duty)
700
+
701
+ def crypto_data_lost(duty) = binding.crypto_lost(duty)
702
+
703
+ def ack_frame_acked(duty) = @recovery.ack_frame_acknowledged(duty.space, largest: duty.largest)
704
+
705
+ def stream_data_acked(duty) = @streams.stream_data_acked(duty)
706
+
707
+ def stream_data_lost(duty) = @streams.stream_data_lost(duty)
708
+
709
+ def reset_stream_acked(duty) = @streams.reset_stream_acked(duty)
710
+
711
+ def reset_stream_lost(duty) = @streams.reset_stream_lost(duty)
712
+
713
+ def stop_sending_lost(duty) = @streams.stop_sending_lost(duty)
714
+
715
+ def max_data_lost(duty) = @streams.max_data_lost(duty)
716
+
717
+ def max_stream_data_lost(duty) = @streams.max_stream_data_lost(duty)
718
+
719
+ def data_blocked_lost(duty) = @streams.data_blocked_lost(duty)
720
+
721
+ def stream_data_blocked_lost(duty) = @streams.stream_data_blocked_lost(duty)
722
+
723
+ def streams_blocked_lost(duty) = @streams.streams_blocked_lost(duty)
724
+
725
+ def max_streams_lost(duty) = @streams.max_streams_lost(duty)
726
+
727
+ def retire_connection_id_acked(duty) = @peer_ids&.retire_acked(duty)
728
+
729
+ def retire_connection_id_lost(duty) = @peer_ids&.retire_lost(duty)
730
+
731
+ # A NEW_CONNECTION_ID frame lost goes again.
732
+ def new_connection_id_lost(duty) = @issued.lost(duty)
733
+
734
+ # An ID this end issued is acknowledged: the peer has one to send with
735
+ # on a new path, and a client moves to the server's preferred address.
736
+ def new_connection_id_acked(_duty) = move_to_preferred_address(@now)
737
+
738
+ def new_token_lost(duty)
739
+ @new_token_due = true if @state == :open && @new_token
740
+ end
741
+ # RFC 9000 "Retransmission of Information": HANDSHAKE_DONE goes again
742
+ # until it is acknowledged.
743
+ def handshake_done_lost
744
+ @handshake_done_due = true if @state == :open
745
+ end
746
+
747
+ # The session's remembered transport parameters while 0-RTT goes, the
748
+ # limits until the server's come.
749
+ private def zero_rtt_parameters = (@session&.transport_parameters if @zero_rtt_state == :pending)
750
+
751
+ # Until the application acknowledges a rejected 0-RTT, nothing may name a
752
+ # stream this client opened, nor open one.
753
+ private def check_zero_rtt_limits(parameters)
754
+ remembered = zero_rtt_parameters or return
755
+ lowered = ZERO_RTT_LIMITS.select { |name| parameters.public_send(name) < remembered.public_send(name) }
756
+ return if lowered.empty?
757
+ raise Violation.new("#{lowered.join(" and ")} lower than 0-RTT used", code: ErrorCode::PROTOCOL_VIOLATION,
758
+ frame_type: CryptoStream::FRAME_TYPE)
759
+ end
760
+
761
+ private def zero_rtt_settled!(stream_id = nil)
762
+ return unless @zero_rtt_rejection_unacknowledged
763
+ return if stream_id && stream_id & Streams::SERVER_INITIATED != 0
764
+ raise Error::ZeroRttRejected, "0-RTT was rejected; call acknowledge_zero_rtt_rejection first"
765
+ end
766
+
767
+ private def start_zero_rtt
768
+ @zero_rtt_state = :pending
769
+ parameters = zero_rtt_parameters
770
+ @streams.peer_parameters = parameters if parameters && @peer_parameters.nil?
771
+ end
772
+
773
+
774
+ # A connection closing or closed takes no more from the application.
775
+ private def open!
776
+ raise Error::StateError, "the connection is #{@state}" unless @state == :open
777
+ end
778
+
779
+ private def binding = @binding || raise(Error::StateError, "no Initial packet has come from the client yet")
780
+
781
+ # The 1-RTT keys changed to those of key phase `phase`.
782
+ private def keys_updated(phase)
783
+ @events << Event::KeyUpdated.new(phase:)
784
+ @tracer.key_updated(level: :one_rtt, now: @now) if @tracer # steep:ignore
785
+ end
786
+
787
+ # The packet at `offset` in `datagram`, nil when there is none to take.
788
+ # A header that does not read is dropped with the rest of the datagram
789
+ # and nothing else: before its protection is off, anyone could have sent
790
+ # it. So is a packet of a version not supported. A Retry or a Version
791
+ # Negotiation packet, which fill the datagram, a client may take.
792
+ private def parse_packet(datagram, offset, now)
793
+ packet = Wire::Packet.parse(datagram, offset:, dcid_length: @source_connection_id.bytesize, versions: @config.versions)
794
+ case packet
795
+ when Wire::Packet::Parsed then packet
796
+ when Wire::Retry then take_retry(packet, datagram.bytesize - offset, now)
797
+ when Wire::VersionNegotiation then take_version_negotiation(packet, datagram.bytesize - offset, now)
798
+ else dropped(:unsupported, datagram.bytesize - offset, now)
799
+ end
800
+ rescue Wire::Malformed
801
+ dropped(:invalid, datagram.bytesize - offset, now)
802
+ end
803
+
804
+ # RFC 9000 "Handling Version Negotiation Packets": a client takes a
805
+ # Version Negotiation before it has taken any other packet, one that
806
+ # echoes its connection IDs, as the server's has to (RFC 9000 "Version
807
+ # Negotiation Packet"). RFC 9368 "Version Downgrade Prevention" has it
808
+ # ignore one that lists the version it first started in, and any after
809
+ # it reacted to one. It starts a new attempt in the first of its versions
810
+ # the packet lists (RFC 9368 "Incompatible Version Negotiation"), or
811
+ # abandons the connection, sending nothing, when it lists none. Any
812
+ # other is dropped. Nil, as the packet fills the datagram.
813
+ private def take_version_negotiation(packet, length, now)
814
+ unless @role == :client && @peer_source_connection_id.nil? && @retry_source_connection_id.nil? && !@negotiation.reacted &&
815
+ packet.dcid == @source_connection_id && packet.scid == @original_destination_connection_id &&
816
+ !packet.versions.include?(@negotiation.original.number)
817
+ return dropped(:general, length, now)
818
+ end
819
+ version = @config.versions.find { |candidate| packet.versions.include?(candidate.number) }
820
+ if @tracer
821
+ @tracer.version_information(client_versions: @config.versions.map(&:number), server_versions: packet.versions, # steep:ignore
822
+ chosen_version: version&.number, now:)
823
+ end
824
+ return start_over_after_version_negotiation(version, now) if version
825
+ reason = "the server takes none of the versions offered, but #{packet.versions.map { |version| format("0x%08x", version) }.join(", ")}"
826
+ error = ConnectionError.new(code: ErrorCode::CONNECTION_REFUSED, frame_type: 0, reason:, application: false)
827
+ @state = :closed
828
+ @close_error = error
829
+ @binding&.discard
830
+ @events << Event::Closed.new(error:, by_peer: true)
831
+ nil
832
+ end
833
+
834
+ # A new attempt in `version`, in the same connection (RFC 9368
835
+ # "Connections and Version Negotiation"): what the first attempt sent
836
+ # is thrown away, 0-RTT rolled back, and TLS starts again with a new
837
+ # ClientHello, which negotiates ALPN again (RFC 9368 "Application-Layer
838
+ # Protocol Considerations"), to a new first Destination Connection ID
839
+ # under new keys. Neither the session nor the token goes, as they are
840
+ # of the first attempt's version (RFC 9369 "TLS Resumption and
841
+ # NEW_TOKEN Tokens"). The Source Connection ID stays, which the
842
+ # Endpoint finds the connection by. Nil, as the packet fills the
843
+ # datagram.
844
+ private def start_over_after_version_negotiation(version, now)
845
+ roll_back_zero_rtt(:version_negotiation) if @zero_rtt_state == :pending
846
+ @recovery.start_over(now:)
847
+ @path.test_ecn_again
848
+ @binding&.discard
849
+ @negotiation = @negotiation.react(version, random: @random)
850
+ @protection = PacketProtection.new(role: @role) { |phase| keys_updated(phase) }
851
+ @kept = KeptPackets.new
852
+ @probe_datagrams = 0
853
+ @probed_spaces = []
854
+ @token = Wire::EMPTY
855
+ @session = nil
856
+ restart_idle(now)
857
+ start_attempt(now)
858
+ nil
859
+ end
860
+
861
+ # RFC 9000 "Retry Packet": a client takes one Retry, to its connection
862
+ # ID, before any packet of the server has opened, with the tag of its
863
+ # first Destination Connection ID and a Source Connection ID other than
864
+ # that. Its Initials go from then on to that connection ID with the
865
+ # Retry's token, under the Initial keys of it, and what they carried
866
+ # goes again (RFC 9002 "Handling Retry"); the transport parameters of
867
+ # the server must name the Retry's Source Connection ID. The Retry is of
868
+ # the version the attempt started in; one of another is ignored (RFC
869
+ # 9369 "Compatible Negotiation Requirements"). Nil, as the Retry fills
870
+ # the datagram.
871
+ private def take_retry(packet, length, now)
872
+ odcid = @original_destination_connection_id
873
+ unless @role == :client && packet.version == @negotiation.chosen && @retry_source_connection_id.nil? &&
874
+ @peer_source_connection_id.nil? && odcid &&
875
+ packet.dcid == @source_connection_id && packet.scid != @destination_connection_id && packet.authentic?(odcid)
876
+ return dropped(:general, length, now)
877
+ end
878
+ @retry_source_connection_id = packet.scid
879
+ use_peer_connection_id(packet.scid, now)
880
+ @token = packet.token
881
+ @protection.install_initial(packet.scid, versions: @negotiation.initial_versions)
882
+ Recovery::Duty.dispatch(@recovery.on_retry(now:), to: self)
883
+ nil
884
+ end
885
+
886
+ # Tells the tracer that `length` bytes of packets were dropped for
887
+ # `reason`, a trigger of qlog `packet_dropped`.
888
+ private def dropped(reason, length, now)
889
+ @tracer.packet_dropped(reason:, raw_length: length, now:) if @tracer # steep:ignore
890
+ nil
891
+ end
892
+
893
+ # An Endpoint's packet of only an ACK, which went before the connection,
894
+ # is one the connection sent.
895
+ private def take_early_ack(ack)
896
+ number = @recovery.next_packet_number(:initial)
897
+ raise ArgumentError, "early ACK #{ack.packet_number} is not packet #{number}" unless ack.packet_number == number
898
+ @recovery.on_packet_sent(packet_type: :initial, packet_number: number, sent_bytes: ack.bytes, ack_eliciting: false, in_flight: false,
899
+ duties: [], now: ack.time)
900
+ @path.datagram_sent(ack.bytes)
901
+ end
902
+
903
+ # Keeps a Handshake or 1-RTT packet whose keys have not come yet, as
904
+ # RFC 9001 "Receiving Out-of-Order Protected Packets" asks: a client's
905
+ # that came before the server's Initial, or a server's 1-RTT that came
906
+ # before the client's Finished, whose keys come only once the handshake
907
+ # is complete (RFC 9001 "Receiving 1-RTT Packets Before the Handshake
908
+ # Completes"). Past what KeptPackets keeps, and of a level whose keys
909
+ # are gone or none, it is dropped.
910
+ private def keep(packet, level, length, from:, to:, ecn:, now:)
911
+ kept = KEPT_LEVELS.include?(level) && !@protection.discarded?(level) &&
912
+ @kept.keep(packet.datagram.byteslice(packet.offset, length) || "".b, level:, from:, to:, ecn:, received_at: now)
913
+ dropped(:key_unavailable, length, now) unless kept
914
+ nil
915
+ end
916
+
917
+ # Opens the packets kept whose keys have come, in the order they came,
918
+ # each on the path it came on, as at once (receive); those of a level
919
+ # whose keys are gone are dropped. One opened may bring the keys of
920
+ # another.
921
+ private def open_kept(now)
922
+ while @state == :open
923
+ ready = @kept.take { |level| @protection.can_read?(level) || @protection.discarded?(level) }
924
+ break if ready.empty?
925
+ ready.each do |kept|
926
+ break unless @state == :open
927
+ next dropped(:key_unavailable, kept.bytes.bytesize, now) if @protection.discarded?(kept.level)
928
+ packet = parse_packet(kept.bytes, 0, now) or next
929
+ path = path_of(kept.to, kept.from)
930
+ next dropped(:rejected, kept.bytes.bytesize, now) unless path || (@role == :server && @handshake_confirmed)
931
+ receive_packet(packet, from: kept.from, to: kept.to, ecn: kept.ecn, now:, path:, received_at: kept.received_at)
932
+ end
933
+ end
934
+ end
935
+
936
+ # `path` is the one `from` and `to` name, nil when the connection does
937
+ # not know it. A packet whose keys have not come is kept until they do
938
+ # (keep); `received_at` is when one kept came.
939
+ private def receive_packet(packet, from:, to:, ecn:, now:, path:, received_at: now)
940
+ header = packet.header
941
+ level = header.type
942
+ length = packet.end_offset - packet.offset
943
+ if header.is_a?(Wire::LongHeader) && (id = @peer_source_connection_id) && header.scid != id
944
+ return dropped(:connection_unknown, length, now)
945
+ end
946
+ # RFC 9369 "Compatible Negotiation Requirements": a packet of a
947
+ # version this end does not take now is dropped.
948
+ unless !header.is_a?(Wire::LongHeader) || @negotiation.accepts?(header.type, header.version) || (@binding.nil? && !@versions_given)
949
+ return dropped(:unsupported, length, now)
950
+ end
951
+ # RFC 9000 "Datagram Size": a server drops an Initial packet in a
952
+ # datagram under 1200 bytes.
953
+ return dropped(:invalid, length, now) if @role == :server && level == :initial && packet.datagram.bytesize < MIN_INITIAL_DATAGRAM
954
+ first = @role == :server && @binding.nil?
955
+ version = header.is_a?(Wire::LongHeader) ? header.version : nil
956
+ keys = (first ? first_initial_keys(header) : @protection.read_keys(level, version:)) or return keep(packet, level, length, from:, to:, ecn:, now:)
957
+ unmasked = packet.unmask(keys.header_protection, largest: @recovery.largest_received(level))
958
+ payload = (first ? unmasked.open(keys.aead) : @protection.open(level, unmasked, now:, pto: @path.rtt.pto_period))
959
+ return dropped(:decryption_failure, length, now) unless payload
960
+ # RFC 9000 "Migration to a Preferred Address": a server moved there
961
+ # drops what comes to another address newer than the move, and takes
962
+ # what is older, late on the way.
963
+ moved = @moved_after
964
+ return dropped(:rejected, length, now) if moved && level == :one_rtt && unmasked.packet_number > moved && !preferred_local?(to)
965
+ accept_first_initial(header, from, to) if first && header.is_a?(Wire::LongHeader)
966
+ frames = Wire::Frame.parse(payload, packet_type: level, ack_delay_exponent: peer_ack_delay_exponent(level))
967
+ learn_version(header, frames) if @role == :client && level == :initial
968
+ largest = @recovery.largest_received(level)
969
+ processed = @recovery.on_packet_received(packet_type: level, packet_number: unmasked.packet_number, ecn:,
970
+ ack_eliciting: frames.any?(&:ack_eliciting?), now:, received_at:)
971
+ return dropped(:duplicate, length, now) unless processed
972
+ if @tracer
973
+ @tracer.packet_received(header: Tracer::PacketHeader.of(unmasked.header, unmasked.packet_number), # steep:ignore
974
+ frames: @tracer.trace_frames? ? frames : nil, raw_length: length, now:) # steep:ignore
975
+ end
976
+ # RFC 9000 "Idle Timeout": a packet received and processed, which a
977
+ # duplicate is not.
978
+ restart_idle(now)
979
+ @packets_received += 1
980
+ @bytes_received += length
981
+ @eliciting_since_received = false
982
+ adopt_peer_connection_id(header, now) if @role == :client && header.is_a?(Wire::LongHeader) && level == :initial
983
+ dcid = unmasked.header.dcid
984
+ if probing_frames?(frames)
985
+ path ||= probed_path(to, from, packet.datagram.bytesize, now)
986
+ elsif level == :one_rtt && (largest.nil? || unmasked.packet_number > largest)
987
+ path = migrate(path, to, from, dcid, packet.datagram.bytesize, now) || path unless path.equal?(@path)
988
+ @newest_path = path
989
+ end
990
+ # A packet from an address no path has, late or with no ID to answer
991
+ # with, is taken with no path: a challenge in it goes unanswered,
992
+ # rather than answered on another path (RFC 9000 "Path Validation").
993
+ if level == :one_rtt && path.equal?(@path)
994
+ before = @received_dcid
995
+ @received_dcid = dcid
996
+ @tracer.connection_id_updated(owner: :local, old: before, new: dcid, now:) if @tracer && before && before != dcid # steep:ignore
997
+ end
998
+ frames.each { |frame| receive_frame(level, frame, now, dcid, path) }
999
+ if @role == :server && level == :handshake
1000
+ validate_address(now)
1001
+ discard_level(:initial, now)
1002
+ end
1003
+ true
1004
+ end
1005
+
1006
+ # RFC 9000 "Authenticating Connection IDs": the connection IDs the peer
1007
+ # names in its transport parameters are those of the Initial packets,
1008
+ # and a Retry's when there was one, or the connection fails with
1009
+ # TRANSPORT_PARAMETER_ERROR.
1010
+ private def authenticate_connection_ids(parameters)
1011
+ wrong = [] #: Array[Symbol]
1012
+ wrong << :initial_source_connection_id unless parameters.initial_source_connection_id == @peer_source_connection_id
1013
+ if @role == :client
1014
+ wrong << :original_destination_connection_id unless parameters.original_destination_connection_id == @original_destination_connection_id
1015
+ wrong << :retry_source_connection_id unless parameters.retry_source_connection_id == @retry_source_connection_id
1016
+ end
1017
+ return if wrong.empty?
1018
+ raise Violation.new("#{wrong.join(" and ")} not as the packets had it", code: ErrorCode::TRANSPORT_PARAMETER_ERROR,
1019
+ frame_type: CryptoStream::FRAME_TYPE)
1020
+ end
1021
+
1022
+ # The keys a client's first Initial is sealed with, from its own
1023
+ # Destination Connection ID; nil for any other packet.
1024
+ private def first_initial_keys(header)
1025
+ return nil unless header.is_a?(Wire::LongHeader) && header.type == :initial
1026
+ Crypto::Initial.derive(dcid: header.dcid, version: header.version).client
1027
+ end
1028
+
1029
+ private def server_negotiation(original, negotiated)
1030
+ Negotiation.server(versions: @config.versions, deployed: @config.deployed, original:, negotiated:, random: @random)
1031
+ end
1032
+
1033
+ # The peer's ID this end sends with from now on: the tracer hears when
1034
+ # it changes (qlog `connection_id_updated`).
1035
+ private def use_peer_connection_id(connection_id, now)
1036
+ before = @destination_connection_id
1037
+ @destination_connection_id = connection_id
1038
+ return if before == connection_id
1039
+ @tracer.connection_id_updated(owner: :remote, old: before, new: connection_id, now:) if @tracer # steep:ignore
1040
+ end
1041
+
1042
+ # The server learns from the client's first Initial, once it has opened,
1043
+ # its connection ID, address and the Destination Connection ID its
1044
+ # Initial keys come from, and the addresses of the path. Until then
1045
+ # anyone could have sent it.
1046
+ private def accept_first_initial(header, from, to)
1047
+ @path.learn(local: to, remote: from)
1048
+ @destination_connection_id = header.scid
1049
+ @peer_source_connection_id = header.scid
1050
+ @negotiation = server_negotiation(header.version, header.version) unless @versions_given
1051
+ negotiation = @negotiation
1052
+ # RFC 9369 "Compatible Negotiation Requirements": the client's Initials
1053
+ # keep coming in its version until it learns the server's, which every
1054
+ # CRYPTO frame of the server goes in. The Handshake keys, which TLS
1055
+ # gives as it starts, take the labels of the server's.
1056
+ @protection.install_initial(header.dcid, versions: negotiation.initial_versions)
1057
+ @protection.negotiate(negotiation.current)
1058
+ @original_destination_connection_id ||= header.dcid
1059
+ parameters = @config.transport_parameters(initial_source_connection_id: @source_connection_id,
1060
+ original_destination_connection_id: @original_destination_connection_id, retry_source_connection_id: @retry_source_connection_id,
1061
+ stateless_reset_token: @stateless_reset_token, preferred_address: @issued.preferred_address(@config.preferred_address),
1062
+ version_information: @negotiation.information)
1063
+ @tracer.parameters_set(owner: :local, parameters:, now: @now) if @tracer # steep:ignore
1064
+ @binding = @start_binding.call(self, parameters, negotiation.current)
1065
+ end
1066
+
1067
+ # A client's attempt to connect in the version its negotiation is in: a
1068
+ # first Destination Connection ID of its own, the Initial keys from it,
1069
+ # and TLS started with the transport parameters.
1070
+ private def start_attempt(now)
1071
+ @destination_connection_id = @random.bytes(INITIAL_DCID_LENGTH).b
1072
+ @original_destination_connection_id = @destination_connection_id
1073
+ @protection.install_initial(@destination_connection_id, versions: @negotiation.initial_versions)
1074
+ parameters = @config.transport_parameters(initial_source_connection_id: @source_connection_id,
1075
+ version_information: @negotiation.information)
1076
+ if @tracer
1077
+ @tracer.version_information(client_versions: @negotiation.available, chosen_version: @negotiation.chosen.number, now:) # steep:ignore
1078
+ @tracer.parameters_set(owner: :local, parameters:, now:) # steep:ignore
1079
+ end
1080
+ @binding = @start_binding.call(self, parameters, @negotiation.chosen)
1081
+ end
1082
+
1083
+ # RFC 9369 "Compatible Negotiation Requirements": a client learns the
1084
+ # version from the server's first Initial that opens in another version
1085
+ # than the one it started in, or from one in that version with a CRYPTO
1086
+ # frame, before it takes the frames; it sends its Initials in that
1087
+ # version from then on, and the keys TLS gives take its labels.
1088
+ private def learn_version(header, frames)
1089
+ return if @negotiation.negotiated || !header.is_a?(Wire::LongHeader)
1090
+ version = header.version
1091
+ return if version == @negotiation.chosen && frames.none?(Wire::Frame::Crypto)
1092
+ @negotiation = @negotiation.learn(version)
1093
+ @protection.negotiate(version)
1094
+ return unless @tracer && version != @negotiation.chosen
1095
+ @tracer.version_information(client_versions: @negotiation.available, chosen_version: version.number, now: @now) # steep:ignore
1096
+ end
1097
+
1098
+ # A client takes the Source Connection ID of the server's first Initial
1099
+ # packet as the Destination Connection ID of its own, and only that one
1100
+ # (RFC 9000 "Negotiating Connection IDs").
1101
+ private def adopt_peer_connection_id(header, now)
1102
+ return if @peer_source_connection_id
1103
+ use_peer_connection_id(header.scid, now)
1104
+ @peer_source_connection_id = header.scid
1105
+ end
1106
+
1107
+ private def receive_frame(level, frame, now, dcid, path)
1108
+ return unless @state == :open
1109
+ case frame
1110
+ when Wire::Frame::Crypto
1111
+ again = binding.receive_crypto(level, frame, time: tls_time(now))
1112
+ send_again_at_once if again && level == :initial && @role == :server
1113
+ when Wire::Frame::Ack
1114
+ Recovery::Duty.dispatch(@recovery.on_ack_received(packet_type: level, ack: frame, now:), to: self)
1115
+ @protection.acknowledged(frame.largest) if level == :one_rtt
1116
+ when Wire::Frame::ConnectionClose
1117
+ enter_draining(ConnectionError.new(code: frame.code, frame_type: frame.frame_type, reason: frame.reason, application: frame.application), now)
1118
+ when Wire::Frame::HandshakeDone
1119
+ raise Violation.new("HANDSHAKE_DONE from a client", frame_type: 0x1e) if @role == :server
1120
+ confirm(now)
1121
+ # Only a server sends NEW_TOKEN (RFC 9000 "NEW_TOKEN Frames"); a
1122
+ # client passes the token on for a later connection.
1123
+ when Wire::Frame::NewToken
1124
+ raise Violation.new("NEW_TOKEN from a client", frame_type: 0x07) if @role == :server
1125
+ @events << Event::NewToken.new(token: Token.new(value: frame.token, version: @negotiation.current.number))
1126
+ when Wire::Frame::Stream
1127
+ @streams.receive_stream(frame, now:)
1128
+ @early_data_streams << frame.stream_id if level == :zero_rtt
1129
+ when Wire::Frame::MaxData then @streams.receive_max_data(frame, now:)
1130
+ when Wire::Frame::MaxStreamData then @streams.receive_max_stream_data(frame, now:)
1131
+ when Wire::Frame::MaxStreams then @streams.receive_max_streams(frame)
1132
+ when Wire::Frame::DataBlocked then @streams.receive_data_blocked(frame)
1133
+ when Wire::Frame::StreamDataBlocked then @streams.receive_stream_data_blocked(frame, now:)
1134
+ when Wire::Frame::ResetStream then @streams.receive_reset_stream(frame, now:)
1135
+ when Wire::Frame::StopSending then @streams.receive_stop_sending(frame, now:)
1136
+ when Wire::Frame::StreamsBlocked then @streams.receive_streams_blocked(frame)
1137
+ when Wire::Frame::Datagram then @datagrams.receive(frame)
1138
+ when Wire::Frame::NewConnectionID
1139
+ ids = @peer_ids or raise Violation.new("NEW_CONNECTION_ID before the transport parameters", frame_type: PeerConnectionIDs::FRAME_TYPE)
1140
+ ids.receive(frame)
1141
+ use_peer_connection_id(ids.current, now)
1142
+ reassign_connection_ids(ids)
1143
+ when Wire::Frame::RetireConnectionID then @issued.retire(frame, dcid:, forget_at: now + RETIRED_PTOS * @path.rtt.pto_period)
1144
+ when Wire::Frame::PathChallenge
1145
+ # A challenge on a path the connection takes no probe on goes
1146
+ # unanswered.
1147
+ if path
1148
+ path.challenged(frame.data)
1149
+ @non_probing_due = true if path.equal?(@path)
1150
+ end
1151
+ when Wire::Frame::PathResponse
1152
+ answered = [@path, *@validating].find { |each| each.responded(frame.data, now:) }
1153
+ if answered.equal?(@path)
1154
+ # The path is the one to go back to once its validation is over,
1155
+ # the full datagram answered too, not when the answer to a short
1156
+ # one validates its address.
1157
+ unless @path.validating?
1158
+ trace_migration(:migration_complete, @path, now)
1159
+ previous = @last_validated
1160
+ remember_validated(@path)
1161
+ give_new_token(now) unless previous&.remote&.first == @path.remote&.first
1162
+ end
1163
+ lift_amplification_limit(now)
1164
+ elsif answered && !answered.validating?
1165
+ trace_migration(:probing_successful, answered, now)
1166
+ if answered.equal?(@preferred_path)
1167
+ switch_to(answered, now, revalidate: false)
1168
+ elsif answered.equal?(@newest_path) && preferred_local?(answered.local)
1169
+ move_to_own_preferred_address(answered, now)
1170
+ end
1171
+ end
1172
+ end
1173
+ end
1174
+
1175
+ # RFC 9001 "Discarding Handshake Keys": once the handshake is
1176
+ # confirmed, the Handshake keys go, and loss recovery counts Application
1177
+ # Data.
1178
+ private def confirm(now)
1179
+ return if @handshake_confirmed
1180
+ @handshake_confirmed = true
1181
+ @recovery.handshake_confirmed!(now:)
1182
+ @protection.handshake_confirmed!
1183
+ discard_level(:handshake, now)
1184
+ peer = @peer_parameters
1185
+ @issued.issue(peer.active_connection_id_limit) if peer
1186
+ # A server sends to zero-length IDs on any path, with none to wait for.
1187
+ move_to_preferred_address(now) if @source_connection_id.empty?
1188
+ end
1189
+
1190
+ # RFC 9000 "Immediate Close": what was being sent stops, and only the
1191
+ # CONNECTION_CLOSE frame goes, as soon as it can.
1192
+ private def enter_closing(error, now)
1193
+ @state = :closing
1194
+ @close_error = error
1195
+ @close_deadline = now + CLOSE_PTOS * @path.rtt.pto_period
1196
+ @close_frame_due = true
1197
+ @binding&.discard
1198
+ @events << Event::Closed.new(error:, by_peer: false)
1199
+ end
1200
+
1201
+ private def close_for(violation, now)
1202
+ error = ConnectionError.new(code: violation.code, frame_type: violation.frame_type || 0, reason: violation.message, application: false)
1203
+ enter_closing(error, now)
1204
+ end
1205
+
1206
+ # The peer closed: nothing more is sent, and what comes is dropped for
1207
+ # three PTOs (RFC 9000 "Draining Connection State").
1208
+ private def enter_draining(error, now)
1209
+ @state = :draining
1210
+ @close_error = error
1211
+ @close_deadline = now + CLOSE_PTOS * @path.rtt.pto_period
1212
+ @binding&.discard
1213
+ @events << Event::Closed.new(error:, by_peer: true)
1214
+ end
1215
+
1216
+ # RFC 9000 "Idle Timeout": the connection ends at once, with nothing
1217
+ # sent.
1218
+ private def time_out_idly = close_silently("idle timeout")
1219
+
1220
+ # The connection ends at once for `reason`, with nothing sent.
1221
+ private def close_silently(reason)
1222
+ error = ConnectionError.new(code: ErrorCode::NO_ERROR, frame_type: 0, reason:, application: false)
1223
+ @state = :closed
1224
+ @close_error = error
1225
+ @binding&.discard
1226
+ @events << Event::Closed.new(error:, by_peer: false)
1227
+ end
1228
+
1229
+ # The idle timeout starts again from `now`: the smaller of the two ends'
1230
+ # max_idle_timeout, 0 being none, and three PTOs at least.
1231
+ private def restart_idle(now)
1232
+ timeouts = [@config.max_idle_timeout, @peer_parameters&.max_idle_timeout].compact.reject(&:zero?)
1233
+ timeout = timeouts.min
1234
+ @idle_deadline = timeout && now + [timeout, CLOSE_PTOS * @path.rtt.pto_period].max
1235
+ end
1236
+
1237
+ # The next datagram to send, as [datagram, its path, whether it goes
1238
+ # alone], nil when there is nothing. What elicits an ACK goes only
1239
+ # while the congestion window has room for a datagram more and pacing
1240
+ # lets it go, or a probe is due, which waits on neither (RFC 9002
1241
+ # "Probe Timeout"); a datagram of ACKs alone waits on nothing (RFC 9002
1242
+ # "Pacing"). The 1-RTT keys change first when a key update is due, before
1243
+ # a probe of a path too; when they cannot and are at their
1244
+ # confidentiality limit, the connection closes. While closing, only the
1245
+ # CONNECTION_CLOSE frame, when due. When nothing goes, the path hears
1246
+ # why.
1247
+ private def next_datagram(now)
1248
+ unless @state == :open
1249
+ closing = closing_datagram(now) or return nil
1250
+ return [closing, @path, false]
1251
+ end
1252
+ begin
1253
+ @protection.update_keys_if_due
1254
+ rescue Violation => error
1255
+ close_for(error, now)
1256
+ closing = closing_datagram(now) or return nil
1257
+ return [closing, @path, false]
1258
+ end
1259
+ probe = probing_datagram(now) || mtu_probe_datagram(now) and return probe
1260
+ limit = @path.max_datagram_size
1261
+ budget = amplification_budget(now)
1262
+ limit = [limit, budget].min if budget
1263
+ return stopped(:amplification, now) if limit < MIN_INITIAL_DATAGRAM
1264
+ fits = @path.bytes_in_flight + limit <= @path.window
1265
+ paced = fits && @path.paced?(limit, now)
1266
+ eliciting = paced || @probe_datagrams.positive?
1267
+ pending = [] #: Array[Pending]
1268
+ used = 0
1269
+ LEVELS.each do |level|
1270
+ next unless @protection.can_write?(level)
1271
+ # 0-RTT only until the server says, and never once 1-RTT can go.
1272
+ next if level == :zero_rtt && (@zero_rtt_state != :pending || @protection.can_write?(:one_rtt))
1273
+ header = header_for(level)
1274
+ room = limit - used - overhead(header)
1275
+ frames, duties = frames_for(level, room, eliciting, now)
1276
+ next if frames.empty?
1277
+ packet_number = @recovery.next_packet_number(level)
1278
+ length = @recovery.packet_number_length(level, packet_number)
1279
+ pending << Pending.new(level:, header:, packet_number:, packet_number_length: length, frames:, duties:)
1280
+ used += overhead(header) + Wire::Frame.encode(frames, ack_delay_exponent: own_ack_delay_exponent(level)).bytesize
1281
+ end
1282
+ return stopped(eliciting ? :drained : (fits ? :pacing : :congestion), now) if pending.empty?
1283
+ datagram = seal(pending, now)
1284
+ @probe_datagrams -= 1 if @probe_datagrams.positive? && pending.any? { |packet| packet.frames.any?(&:ack_eliciting?) }
1285
+ @path.datagram_sent(datagram.bytesize)
1286
+ discard_level(:initial, now) if @role == :client && pending.any? { |packet| packet.level == :handshake }
1287
+ [datagram, @path, false]
1288
+ end
1289
+
1290
+ # Sending stops for `reason`: the path keeps whether the congestion
1291
+ # window went unused, which loss recovery tells the congestion
1292
+ # controller (RFC 9002 "Underutilizing the Congestion Window"), and
1293
+ # hears whether stream data or DATAGRAMs wait, for its rate meter. With
1294
+ # the window too full for a datagram more, what is left waits on it.
1295
+ private def stopped(reason, now)
1296
+ waiting = !@streams.urgency.nil? || !@datagrams.urgency(now:).nil?
1297
+ @path.transmission_stopped(reason, waiting:, next_packet_number: @recovery.upcoming_packet_number(:one_rtt))
1298
+ nil
1299
+ end
1300
+
1301
+ # How many bytes a server may still send on the path before the
1302
+ # client's address is validated, nil once it is. Under a datagram's
1303
+ # worth, it stops, and loss recovery sets no timer meanwhile (RFC 9002
1304
+ # "Handling Anti-Amplification Limits").
1305
+ private def amplification_budget(now)
1306
+ budget = @path.amplification_budget or return nil
1307
+ if budget < MIN_INITIAL_DATAGRAM && !@amplification_limited
1308
+ @amplification_limited = true
1309
+ @recovery.amplification_limited(true, now:)
1310
+ end
1311
+ budget
1312
+ end
1313
+
1314
+ private def count_received(datagram, path, now)
1315
+ path.datagram_received(datagram.bytesize)
1316
+ return unless path.equal?(@path) && @amplification_limited
1317
+ budget = @path.amplification_budget
1318
+ return if budget && budget < MIN_INITIAL_DATAGRAM
1319
+ @amplification_limited = false
1320
+ @recovery.amplification_limited(false, now:)
1321
+ end
1322
+
1323
+ # A Handshake packet from the client proves its address.
1324
+ private def validate_address(now)
1325
+ return if @path.validated?
1326
+ @path.validate
1327
+ lift_amplification_limit(now)
1328
+ end
1329
+
1330
+ # The path in use has its address validated: what its amplification
1331
+ # limit stopped goes again, and loss recovery sets its timer again.
1332
+ private def lift_amplification_limit(now)
1333
+ return unless @amplification_limited
1334
+ @amplification_limited = false
1335
+ @recovery.amplification_limited(false, now:)
1336
+ end
1337
+
1338
+ # RFC 9002 "Speeding up Handshake Completion": a client whose Initial
1339
+ # carries CRYPTO data again has not had all of the server's Initial
1340
+ # packets, or takes its RTT for shorter than it is. What the server's
1341
+ # oldest Initial and Handshake packets in flight carry goes again
1342
+ # without waiting for the PTO, coalesced, their records left as a
1343
+ # probe's are; SEND_AGAIN_AT_ONCE times a connection at most, so that
1344
+ # the two ends do not answer each other for ever. It is no probe: it
1345
+ # waits on the congestion window and pacing as anything that elicits an
1346
+ # ACK, and the amplification limit holds as ever. The ClientHellos of
1347
+ # one PTO of the client, which come together, count once: CRYPTO data
1348
+ # of Initial waiting to go takes the others, so that the times left go
1349
+ # to later rounds a loss in a burst does not reach.
1350
+ private def send_again_at_once
1351
+ return if @sent_again_at_once >= SEND_AGAIN_AT_ONCE || !@recovery.oldest_ack_eliciting(:initial)
1352
+ return if binding.crypto_pending?(:initial)
1353
+ @sent_again_at_once += 1
1354
+ fill_probe(:initial)
1355
+ fill_probe(:handshake)
1356
+ end
1357
+
1358
+ # A PTO asks for `probe.packets` datagrams that elicit an ACK, each with
1359
+ # a packet of `probe.space` and those of the other spaces with
1360
+ # ack-eliciting packets in flight that fit (RFC 9002 "Sending Probe
1361
+ # Packets"): a server's Initial and Handshake probes go together, as the
1362
+ # client may have the keys of only one, and a loss of a burst takes no
1363
+ # one space's probes alone. What does not fit goes in no more datagrams
1364
+ # past the congestion window.
1365
+ private def probe(probe)
1366
+ @probed_spaces.clear unless @probe_datagrams.positive?
1367
+ PROBED_SPACES.each do |space|
1368
+ next unless space == probe.space || @recovery.oldest_ack_eliciting(space)
1369
+ @probed_spaces << space unless @probed_spaces.include?(space)
1370
+ end
1371
+ @probe_datagrams += probe.packets
1372
+ end
1373
+
1374
+ private def probing?(space) = @probe_datagrams.positive? && @probed_spaces.include?(space)
1375
+
1376
+ # A probe of `level`, or what a server sends again at once, carries what
1377
+ # is new when there is some, else the duties of the oldest packet in
1378
+ # flight that has any again, its record left as it is, else (a probe) a
1379
+ # PING (loss recovery's design, "Probes").
1380
+ private def fill_probe(level)
1381
+ return if binding.crypto_pending?(level) || (level == :one_rtt && @handshake_done_due)
1382
+ oldest = @recovery.oldest_to_send_again(SPACES.fetch(level)) or return
1383
+ Recovery::Duty.dispatch(Recovery::Outcome.new(acked: Recovery::Outcome::NO_PACKETS, lost: [oldest], probe: nil), to: self)
1384
+ end
1385
+
1386
+ # RFC 9001 "Discarding Unused Keys": the keys of `level`, its CRYPTO
1387
+ # stream and what was sent in it go, once. A client's Initial keys go when
1388
+ # it first sends a Handshake packet, a server's when it first processes
1389
+ # one.
1390
+ private def discard_level(level, now)
1391
+ return if @protection.discarded?(level)
1392
+ @probed_spaces.delete(SPACES.fetch(level))
1393
+ @protection.discard(level)
1394
+ binding.discard_level(level)
1395
+ @recovery.discard_space(level, now:)
1396
+ end
1397
+
1398
+ # The CONNECTION_CLOSE frame in a packet of each level there are keys to
1399
+ # write, since the peer may not have all of them yet (RFC 9000 "Immediate
1400
+ # Close during the Handshake").
1401
+ private def closing_datagram(now)
1402
+ return nil unless @state == :closing && @close_frame_due
1403
+ budget = amplification_budget(now)
1404
+ return nil if budget && budget < MIN_INITIAL_DATAGRAM
1405
+ @close_frame_due = false
1406
+ pending = CLOSE_LEVELS.filter_map do |level|
1407
+ next unless @protection.can_write?(level)
1408
+ packet_number = @recovery.next_packet_number(level)
1409
+ Pending.new(level:, header: header_for(level), packet_number:, packet_number_length: @recovery.packet_number_length(level, packet_number),
1410
+ frames: [close_frame(level)], duties: [])
1411
+ end
1412
+ return nil if pending.empty?
1413
+ datagram = seal(pending, now)
1414
+ @path.datagram_sent(datagram.bytesize)
1415
+ datagram
1416
+ end
1417
+
1418
+ # An application's error closes with APPLICATION_ERROR and no reason in
1419
+ # Initial and Handshake packets, where only a transport error may go.
1420
+ private def close_frame(level)
1421
+ error = @close_error or raise Error::StateError, "the connection is not closing"
1422
+ reason = error.reason.b.byteslice(0, MAX_REASON_LENGTH) #: String
1423
+ if error.application && level != :one_rtt
1424
+ Wire::Frame::ConnectionClose.new(code: ErrorCode::APPLICATION_ERROR, frame_type: 0, reason: "".b, application: false)
1425
+ else
1426
+ Wire::Frame::ConnectionClose.new(code: error.code, frame_type: error.application ? nil : error.frame_type || 0, reason:,
1427
+ application: error.application)
1428
+ end
1429
+ end
1430
+
1431
+ # The frames of `level` that fit in `room` bytes, and their duties: an
1432
+ # ACK when one is owed and the packet goes anyway, or is due, then, when
1433
+ # frames that elicit an ACK may go, HANDSHAKE_DONE and CRYPTO, credit,
1434
+ # RESET_STREAM and STOP_SENDING, RETIRE_CONNECTION_ID, BLOCKED frames,
1435
+ # DATAGRAM frames and stream data in order of urgency, and a PING for a
1436
+ # probe with nothing else. A 1-RTT packet that would carry an ACK alone carries a PING too
1437
+ # once a round trip, so that the peer acknowledges the ACKs and what they
1438
+ # acknowledge can be let go (RFC 9000 "Limiting Ranges by Tracking ACK
1439
+ # Frames"); the ranges of Initial and Handshake go with their keys.
1440
+ private def frames_for(level, room, eliciting, now)
1441
+ frames = [] #: Array[Wire::Frame::t]
1442
+ duties = [] #: Array[Recovery::Duty::t]
1443
+ space = SPACES.fetch(level)
1444
+ # RFC 9000 "Frames and Frame Types": no ACK in a 0-RTT packet.
1445
+ ack = @recovery.ack_frame(space, now:) if level != :zero_rtt && (@recovery.ack_owed?(space) || @recovery.ack_due?(space, now:))
1446
+ application = level == :one_rtt || level == :zero_rtt
1447
+ room -= Wire::Frame.encode([ack], ack_delay_exponent: own_ack_delay_exponent(level)).bytesize if ack
1448
+ fill_probe(level) if probing?(space)
1449
+ if eliciting && level == :one_rtt && @handshake_done_due && room.positive?
1450
+ @handshake_done_due = false
1451
+ frames << Wire::Frame::HandshakeDone.new
1452
+ duties << Recovery::Duty::HandshakeDone.new
1453
+ room -= 1
1454
+ end
1455
+ new_token = @new_token
1456
+ if eliciting && level == :one_rtt && @new_token_due && new_token
1457
+ frame = Wire::Frame::NewToken.new(token: new_token)
1458
+ size = Wire::Frame.encode([frame], ack_delay_exponent: 0).bytesize
1459
+ if size <= room
1460
+ @new_token_due = false
1461
+ frames << frame
1462
+ duties << Recovery::Duty::NewToken.new
1463
+ room -= size
1464
+ end
1465
+ end
1466
+ while eliciting && room.positive? && (frame, duty = binding.next_crypto_frame(level, room))
1467
+ frames << frame
1468
+ duties << duty
1469
+ room -= Wire::Frame.encode([frame], ack_delay_exponent: 0).bytesize
1470
+ end
1471
+ while eliciting && application && (credit, credit_duty = @streams.next_credit(room, now:, rtt: rtt_sample))
1472
+ frames << credit
1473
+ duties << credit_duty
1474
+ room -= Wire::Frame.encode([credit], ack_delay_exponent: 0).bytesize
1475
+ end
1476
+ while eliciting && application && (abandon, abandon_duty = @streams.next_abandon(room))
1477
+ frames << abandon
1478
+ duties << abandon_duty
1479
+ room -= Wire::Frame.encode([abandon], ack_delay_exponent: 0).bytesize
1480
+ end
1481
+ while eliciting && level == :one_rtt && (retire, retire_duty = @peer_ids&.next_frame(room))
1482
+ frames << retire
1483
+ duties << retire_duty
1484
+ room -= Wire::Frame.encode([retire], ack_delay_exponent: 0).bytesize
1485
+ end
1486
+ while eliciting && level == :one_rtt && (issued, issued_duty = @issued.next_frame(room))
1487
+ frames << issued
1488
+ duties << issued_duty
1489
+ room -= Wire::Frame.encode([issued], ack_delay_exponent: 0).bytesize
1490
+ end
1491
+ while eliciting && application && (blocked, blocked_duty = @streams.next_blocked(room))
1492
+ frames << blocked
1493
+ duties << blocked_duty
1494
+ room -= Wire::Frame.encode([blocked], ack_delay_exponent: 0).bytesize
1495
+ end
1496
+ while eliciting && application && room.positive? && (data, data_duty = next_application_frame(room, now))
1497
+ frames << data
1498
+ duties << data_duty if data_duty
1499
+ room -= Wire::Frame.encode([data], ack_delay_exponent: 0).bytesize
1500
+ end
1501
+ if probing?(space) && frames.none?(&:ack_eliciting?) && room.positive?
1502
+ frames << Wire::Frame::Ping.new
1503
+ room -= 1
1504
+ end
1505
+ if eliciting && level == :one_rtt && @non_probing_due && room.positive?
1506
+ @non_probing_due = false
1507
+ unless frames.any? { |frame| frame.ack_eliciting? && !frame.is_a?(Wire::Frame::NewConnectionID) }
1508
+ frames << Wire::Frame::Ping.new
1509
+ room -= 1
1510
+ end
1511
+ end
1512
+ if ack && eliciting && level == :one_rtt && frames.none?(&:ack_eliciting?) && room.positive? &&
1513
+ @recovery.ack_due?(space, now:) && @recovery.ping_with_ack?(space, now:)
1514
+ frames << Wire::Frame::Ping.new
1515
+ room -= 1
1516
+ end
1517
+ if ack && (frames.any? || @recovery.ack_due?(space, now:))
1518
+ frames.unshift(ack)
1519
+ duties.unshift(Recovery::Duty::Ack.new(space:, largest: ack.largest))
1520
+ @recovery.on_ack_sent(space, now:)
1521
+ end
1522
+ [frames, duties]
1523
+ end
1524
+
1525
+ # The next DATAGRAM frame or STREAM frame in no more than `room` bytes,
1526
+ # and the duty of a STREAM frame. A DATAGRAM goes before the streams of
1527
+ # its urgency and those less urgent, as RFC 9218 counts urgency; what
1528
+ # goes second takes the room the first does not fit in.
1529
+ private def next_application_frame(room, now)
1530
+ urgency = @streams.urgency
1531
+ datagram_urgency = @datagrams.urgency(now:)
1532
+ if datagram_urgency && (urgency.nil? || datagram_urgency <= urgency)
1533
+ next_datagram_frame(room, now) || @streams.next_stream_frame(room)
1534
+ else
1535
+ @streams.next_stream_frame(room) || next_datagram_frame(room, now)
1536
+ end
1537
+ end
1538
+
1539
+ private def next_datagram_frame(room, now)
1540
+ frame = @datagrams.next_frame(room, now:) or return nil
1541
+ [frame, nil]
1542
+ end
1543
+
1544
+ # A datagram of a path's probes alone (loss recovery's design,
1545
+ # "Probes"): the PATH_RESPONSE to a PATH_CHALLENGE waiting for its
1546
+ # answer, and a PATH_CHALLENGE of the path's validation when one is
1547
+ # due, the paths in turn, the one in use first and the one to go back
1548
+ # to last, on the path the challenge came on (RFC 9000 "Path
1549
+ # Validation"); a path besides the one in use with no ID of its own
1550
+ # sends nothing. Padded to
1551
+ # MIN_INITIAL_DATAGRAM bytes when the path's amplification limit lets
1552
+ # it, else as small as it is, so that what is left of the limit takes
1553
+ # the challenges after (RFC 9000 "Path Validation"), it waits on
1554
+ # neither the congestion window nor pacing, and counts nothing in
1555
+ # flight. Lost, it does not go again: the peer sends a new challenge,
1556
+ # and the validation its next.
1557
+ private def probing_datagram(now)
1558
+ return nil unless @protection.can_write?(:one_rtt)
1559
+ [@path, *@validating, @last_validated].compact.uniq.each do |path|
1560
+ current = path.equal?(@path)
1561
+ next unless current || path.destination_connection_id
1562
+ response = path.challenge
1563
+ data = @random.bytes(CHALLENGE_LENGTH).b if path.challenge_due?(now)
1564
+ frames = [] #: Array[Wire::Frame::t]
1565
+ frames << Wire::Frame::PathResponse.new(data: response) if response
1566
+ frames << Wire::Frame::PathChallenge.new(data:) if data
1567
+ next if frames.empty?
1568
+ header = Wire::ShortHeader.new(dcid: (current ? nil : path.destination_connection_id) || @destination_connection_id,
1569
+ key_phase: @protection.key_phase_bit)
1570
+ budget = current ? amplification_budget(now) : path.amplification_budget
1571
+ next if budget && budget < overhead(header) + Wire::Frame.encode(frames, ack_delay_exponent: 0).bytesize
1572
+ path.answered if response
1573
+ packet_number = @recovery.next_packet_number(:one_rtt)
1574
+ pending = Pending.new(level: :one_rtt, header:, packet_number:,
1575
+ packet_number_length: @recovery.packet_number_length(:one_rtt, packet_number), frames:, duties: [])
1576
+ target = budget.nil? || budget >= MIN_INITIAL_DATAGRAM ? MIN_INITIAL_DATAGRAM : 0
1577
+ datagram = seal([pending], now, target:, probing: true, path:)
1578
+ path.challenge_sent(data, full_size: datagram.bytesize >= MIN_INITIAL_DATAGRAM, now:) if data
1579
+ path.datagram_sent(datagram.bytesize)
1580
+ return [datagram, path, false]
1581
+ end
1582
+ nil
1583
+ end
1584
+
1585
+ # RFC 8899 "Datagram Packetization Layer Path MTU Discovery": once the
1586
+ # handshake is confirmed and the path in use is validated, the path is
1587
+ # searched for the largest datagram it carries, up to MAX_MTU_PROBE of
1588
+ # its family and the peer's max_udp_payload_size, unless the Config
1589
+ # says no (enable_pmtud). A probe due goes when the congestion window
1590
+ # has room for it and pacing lets it go, after any probe of loss
1591
+ # recovery: a 1-RTT packet of PING and PADDING alone, which fills a
1592
+ # datagram of the size and goes alone, so that a datagram too large
1593
+ # takes nothing else with it. It counts in flight, and its loss tells
1594
+ # the congestion controller nothing.
1595
+ private def mtu_probe_datagram(now)
1596
+ path = @path
1597
+ peer = @peer_parameters
1598
+ remote = path.remote
1599
+ return nil unless @config.enable_pmtud && @handshake_confirmed && @probe_datagrams.zero? && peer && remote
1600
+ return nil unless path.validated? && !path.validating?
1601
+ path.search_mtu(up_to: [MAX_MTU_PROBE.fetch(remote[0].include?(":") ? :ipv6 : :ipv4), peer.max_udp_payload_size].min)
1602
+ size = path.mtu_probe_size or return nil
1603
+ return nil unless path.bytes_in_flight + size <= path.window && path.paced?(size, now)
1604
+ packet_number = @recovery.next_packet_number(:one_rtt)
1605
+ pending = Pending.new(level: :one_rtt, header: header_for(:one_rtt), packet_number:,
1606
+ packet_number_length: @recovery.packet_number_length(:one_rtt, packet_number), frames: [Wire::Frame::Ping.new], duties: [])
1607
+ datagram = seal([pending], now, target: size, mtu_probe: true)
1608
+ path.mtu_probe_sent(size)
1609
+ path.datagram_sent(datagram.bytesize)
1610
+ [datagram, path, true]
1611
+ end
1612
+
1613
+ # A Transmit of `payload` on `path`: a server's from the address the
1614
+ # path came to, a client's from where the OS chooses, which may change
1615
+ # under the connection.
1616
+ private def transmit(payload, path, segment_size)
1617
+ destination = path.remote or raise Error::StateError, "no packet has come from the client yet"
1618
+ Transmit.new(payload:, destination:, source: (path.local if @role == :server), ecn: path.ecn, segment_size:)
1619
+ end
1620
+
1621
+ # The path `local` and `remote` name of those the connection keeps;
1622
+ # nil when it keeps none. An address not known on either side matches
1623
+ # any, and a server knows nothing of the path before the client's
1624
+ # first Initial. A client goes by the server's address alone: its own
1625
+ # is the OS's to choose, which may change it, and a server answers
1626
+ # where the client's packets come from.
1627
+ private def path_of(local, remote)
1628
+ return @path if @path.remote.nil?
1629
+ [@path, *@validating, @last_validated].compact.find do |path|
1630
+ path.remote == remote && (@role == :client || local.nil? || path.local.nil? || path.local == local)
1631
+ end
1632
+ end
1633
+
1634
+ # Whether all of `frames` are probing frames (RFC 9000 "Probing a New
1635
+ # Path").
1636
+ private def probing_frames?(frames)
1637
+ frames.all? do |frame|
1638
+ frame.is_a?(Wire::Frame::PathChallenge) || frame.is_a?(Wire::Frame::PathResponse) ||
1639
+ frame.is_a?(Wire::Frame::NewConnectionID) || frame.is_a?(Wire::Frame::Padding)
1640
+ end
1641
+ end
1642
+
1643
+ # A path for a probe from `remote` to `local` that the connection does
1644
+ # not know, which `bytes` came on. Once the handshake is confirmed, it
1645
+ # sends with an ID of the peer's no path sends with, and is validated
1646
+ # at once: a probe is answered with a probe (RFC 9000 "Probing a New
1647
+ # Path"). Past MAX_VALIDATING_PATHS, the oldest goes (CVE-2026-12707).
1648
+ # nil before the handshake is confirmed, or with no ID to send with,
1649
+ # when the probe goes unanswered.
1650
+ private def probed_path(local, remote, bytes, now)
1651
+ return nil unless @handshake_confirmed
1652
+ connection_id = @peer_ids&.claim or return nil
1653
+ path = Path.new(config: @config, local:, remote:, destination_connection_id: connection_id, tracer: @tracer)
1654
+ path.datagram_received(bytes)
1655
+ start_validation(path, now)
1656
+ trace_migration(:probing_started, path, now)
1657
+ @peers&.add(self, remote)
1658
+ @validating << path
1659
+ make_room
1660
+ path
1661
+ end
1662
+
1663
+ # RFC 9000 "Responding to Connection Migration": a server's sending
1664
+ # moves at once to the path a packet that is no probe came on, from an
1665
+ # address no path has or from a path besides the one in use, when its
1666
+ # packet number is the largest of its space so far, and the path is
1667
+ # validated unless it is. With the Destination Connection ID the peer
1668
+ # used before, a NAT rebinding most likely, a new path goes on with the
1669
+ # peer's ID in use (RFC 9000 "Privacy Implications of Connection
1670
+ # Migration"), but only when there is an ID no path sent with for the
1671
+ # path left to be validated again with: RFC 9000 "Off-Path Packet
1672
+ # Forwarding" has the path left validated, and the ID in use may not go
1673
+ # to two addresses, so without one there is no move. With another
1674
+ # Destination Connection ID, or to a preferred address, where the move
1675
+ # waits while both paths send, the new path takes an ID no path sent
1676
+ # with, and without one there is no path.
1677
+ #
1678
+ # To the server's preferred address, the sending moves only once the
1679
+ # server has validated the path itself, here or when the validation
1680
+ # ends, as an attacker could start the move otherwise (RFC 9000
1681
+ # "Migration to a Preferred Address"); it is under way already. The
1682
+ # path the packet came on; nil when there is none.
1683
+ private def migrate(path, local, remote, dcid, bytes, now)
1684
+ return nil unless @role == :server && @handshake_confirmed
1685
+ unless path
1686
+ connection_id = nil #: String?
1687
+ if dcid == @received_dcid && !preferred_local?(local)
1688
+ return give_up_an_id(now) unless @peer_ids&.spare?
1689
+ else
1690
+ connection_id = (@peer_ids&.claim or return nil)
1691
+ end
1692
+ path = Path.new(config: @config, local:, remote:, destination_connection_id: connection_id, tracer: @tracer)
1693
+ path.datagram_received(bytes)
1694
+ path.take_over(@path) if port_only?(local, remote)
1695
+ @peers&.add(self, remote)
1696
+ end
1697
+ if !preferred_local?(local)
1698
+ switch_to(path, now)
1699
+ elsif path.validated? && !path.validating? && !path.validation_owed?
1700
+ move_to_own_preferred_address(path, now)
1701
+ elsif !@validating.include?(path)
1702
+ start_validation(path, now)
1703
+ trace_migration(:probing_started, path, now)
1704
+ @validating << path
1705
+ make_room
1706
+ end
1707
+ path
1708
+ end
1709
+
1710
+ # A server moves to `path`, at its preferred address. With the client
1711
+ # at the address the path in use goes to, from now on it drops what
1712
+ # comes to another address numbered past what it has received (RFC 9000
1713
+ # "Migration to a Preferred Address"). With the client at another
1714
+ # address, the client seems to have moved too: the path left is
1715
+ # validated again, as RFC 9000 "Off-Path Packet Forwarding" asks, and
1716
+ # what comes there is taken, so that a newer packet on it takes the
1717
+ # connection back from an attacker forwarding copies of packets.
1718
+ private def move_to_own_preferred_address(path, now)
1719
+ client_moved = path.remote != @path.remote
1720
+ @moved_after = client_moved ? nil : @recovery.largest_received(:one_rtt)
1721
+ switch_to(path, now, revalidate: client_moved)
1722
+ end
1723
+
1724
+ # Whether `local` is one of a server's preferred addresses.
1725
+ private def preferred_local?(local) = @config.preferred_address&.value?(local) || false
1726
+
1727
+ # RFC 9000 "Migration to a Preferred Address": a client, once the
1728
+ # handshake is confirmed and the server has an ID of the client's to
1729
+ # answer with, validates a path to the server's preferred address that
1730
+ # PreferredAddress#choose gives, with an ID of the server's no path
1731
+ # sent with, the preferred address's own first; it does once. The path
1732
+ # is the client's own making, to an address authenticated transport
1733
+ # parameters gave, and has no amplification limit. Only probes go on
1734
+ # it until it is validated, when the connection moves to it; failed,
1735
+ # the connection stays where it is.
1736
+ private def move_to_preferred_address(now)
1737
+ return unless @role == :client && @handshake_confirmed && @preferred_path.nil?
1738
+ preferred = @peer_parameters&.preferred_address or return
1739
+ server = @path.remote or return
1740
+ remote = preferred.choose(families: @config.address_families, server:) or return
1741
+ connection_id = @peer_ids&.claim or return
1742
+ path = Path.new(config: @config, remote:, validated: true, destination_connection_id: connection_id, tracer: @tracer)
1743
+ start_validation(path, now)
1744
+ trace_migration(:probing_started, path, now)
1745
+ @peers&.add(self, remote)
1746
+ @validating << path
1747
+ @preferred_path = path
1748
+ end
1749
+
1750
+ # RFC 9000 "Responding to Connection Migration": a server that validated
1751
+ # a new address of the client, another IP address than the path to go
1752
+ # back to before, gives it a token for that address, which goes until
1753
+ # acknowledged; a port has nothing to do with the token.
1754
+ private def give_new_token(now)
1755
+ tokens = @tokens or return
1756
+ remote = @path.remote or return
1757
+ @new_token = tokens.mint(remote, version: @negotiation.current.number, now:)
1758
+ @new_token_due = true
1759
+ end
1760
+
1761
+ # Whether `local` and `remote` differ from the path in use in the
1762
+ # peer's port alone, when the new path takes over what the path in use
1763
+ # learned (Path#take_over).
1764
+ private def port_only?(local, remote)
1765
+ current = @path.remote or return false
1766
+ current[0] == remote[0] && current[1] != remote[1] && (local.nil? || @path.local.nil? || @path.local == local)
1767
+ end
1768
+
1769
+ # The connection sends on `path` from now on, and the path left stays
1770
+ # the one last validated when it was. A path with an ID of its own
1771
+ # sends with it, and the path left keeps the ID in use before; else
1772
+ # the path left takes an ID no path sent with, if there is one. When
1773
+ # the peer moved (`revalidate`), the path left is validated again with
1774
+ # its ID, as RFC 9000 "Off-Path Packet Forwarding" asks, so that a
1775
+ # path an attacker forwarded packets to does not keep the connection;
1776
+ # with no ID, it is not.
1777
+ private def switch_to(path, now, revalidate: true)
1778
+ @validating.delete(path)
1779
+ start_validation(path, now) unless path.validating? || (path.validated? && !path.validation_owed?)
1780
+ left = @path
1781
+ previous = @last_validated
1782
+ @last_validated = left if left.validated? && !left.validating?
1783
+ connection_id = path.destination_connection_id
1784
+ if connection_id && connection_id != @destination_connection_id
1785
+ @peer_ids&.switch(connection_id)
1786
+ left.send_with(@destination_connection_id)
1787
+ use_peer_connection_id(connection_id, now)
1788
+ elsif revalidate
1789
+ left.send_with(@peer_ids&.claim)
1790
+ end
1791
+ lift_amplification_limit(now)
1792
+ @path = path
1793
+ @recovery.switch_path(path, now:)
1794
+ trace_migration(:migration_started, path, now)
1795
+ trace_migration(:migration_complete, path, now) unless path.validating?
1796
+ if revalidate && left.destination_connection_id
1797
+ start_validation(left, now)
1798
+ trace_migration(:probing_started, left, now)
1799
+ @validating << left
1800
+ make_room
1801
+ end
1802
+ # What goes is decided once the move is over: the path moved to may
1803
+ # be the one to go back to before.
1804
+ [left, previous].uniq.each { |each| abandon_path(each) if each && !kept?(each) }
1805
+ end
1806
+
1807
+ # `path` is the one to go back to; the one before goes unless the
1808
+ # connection keeps it otherwise.
1809
+ private def remember_validated(path)
1810
+ previous = @last_validated
1811
+ @last_validated = path
1812
+ abandon_path(previous) if previous && !kept?(previous)
1813
+ end
1814
+
1815
+ # Whether the connection keeps `path`: the one in use, one besides it,
1816
+ # or the one to go back to. A path it does not keep goes through
1817
+ # abandon_path, so that its ID is retired and its address forgotten.
1818
+ private def kept?(path) = path.equal?(@path) || path.equal?(@last_validated) || @validating.include?(path)
1819
+
1820
+ # RFC 9000 "Responding to Connection Migration": the path in use failed
1821
+ # its validation, and the connection goes back to the path last
1822
+ # validated; with none, it closes at once with nothing sent, as an
1823
+ # idle one does.
1824
+ private def fall_back(now)
1825
+ failed = @path
1826
+ trace_migration(:migration_abandoned, failed, now)
1827
+ last = @last_validated
1828
+ return close_silently("no validated path") if last.nil? || last.equal?(failed)
1829
+ switch_to(last, now, revalidate: false)
1830
+ end
1831
+
1832
+ # How the paths stand (qlog `migration_state_updated`): `state` is
1833
+ # :probing_started, :probing_successful or :probing_abandoned for a
1834
+ # path besides the one in use, and :migration_started,
1835
+ # :migration_complete or :migration_abandoned for one the connection
1836
+ # moved to.
1837
+ private def trace_migration(state, path, now)
1838
+ @tracer.migration_state_updated(state:, local: path.local, remote: path.remote, now:) if @tracer # steep:ignore
1839
+ end
1840
+
1841
+ # Validation of `path` starts at `now`: a challenge each PTO of the
1842
+ # path, twice as late each time, until three times the larger of the
1843
+ # current path's PTO and that of a path of the initial RTT (RFC 9000
1844
+ # "Failed Path Validation"), however short an RTT the path took over.
1845
+ private def start_validation(path, now)
1846
+ initial = Recovery::RttEstimator.new.pto_period + (@peer_parameters&.max_ack_delay || 0.0)
1847
+ path.start_validation(now:, interval: path_pto(path), deadline: now + VALIDATION_PTOS * [path_pto(@path), initial].max)
1848
+ end
1849
+
1850
+ # The paths besides the one in use whose ID Retire Prior To retired
1851
+ # send with an ID no path sent with, or go when there is none.
1852
+ private def reassign_connection_ids(ids)
1853
+ [*@validating, @last_validated].compact.uniq.each do |path|
1854
+ connection_id = path.destination_connection_id
1855
+ next if path.equal?(@path) || connection_id.nil? || ids.claimed?(connection_id)
1856
+ ids.release(connection_id)
1857
+ fresh = ids.claim
1858
+ fresh ? path.send_with(fresh) : abandon_path(path)
1859
+ end
1860
+ end
1861
+
1862
+ # Past MAX_VALIDATING_PATHS, the oldest path besides the one in use
1863
+ # goes, or, when it is the path last validated, stops being validated
1864
+ # again and stays, with its ID, to go back to: it is kept apart from
1865
+ # the paths being validated, so that probes from new addresses cannot
1866
+ # leave a connection nothing to go back to. Its validation stops, so
1867
+ # that its deadline does not fail it once it is gone back to, and is
1868
+ # owed: gone back to, it is validated anew (RFC 9000 "Off-Path Packet
1869
+ # Forwarding").
1870
+ private def make_room
1871
+ while @validating.size > MAX_VALIDATING_PATHS
1872
+ oldest = @validating.fetch(0)
1873
+ next abandon_path(oldest) unless oldest.equal?(@last_validated)
1874
+ @validating.delete(oldest)
1875
+ oldest.stop_validation
1876
+ end
1877
+ end
1878
+
1879
+ # A path besides the one in use goes, and the peer's ID it sent with
1880
+ # is retired.
1881
+ private def abandon_path(path)
1882
+ @validating.delete(path)
1883
+ @last_validated = nil if path.equal?(@last_validated)
1884
+ path.abandon
1885
+ remote = path.remote
1886
+ kept = [@path, *@validating, @last_validated].compact.any? { |each| each.remote == remote }
1887
+ @peers&.remove(self, remote) if remote && !kept
1888
+ connection_id = path.destination_connection_id
1889
+ @peer_ids&.release(connection_id) if connection_id
1890
+ end
1891
+
1892
+ # With no ID for the path left on a rebinding, the oldest path left that
1893
+ # is validated again, not the one to go back to, goes, and its ID is
1894
+ # retired: the peer issues another for it, and the move can be made at
1895
+ # a packet after that comes. Paths left by rebindings faster than their
1896
+ # validations end would hold every ID otherwise. Gives nil, as there is
1897
+ # no path to move to now.
1898
+ private def give_up_an_id(now)
1899
+ oldest = @validating.find { |path| !path.equal?(@last_validated) && path.destination_connection_id }
1900
+ if oldest
1901
+ trace_migration(:probing_abandoned, oldest, now)
1902
+ abandon_path(oldest)
1903
+ end
1904
+ nil
1905
+ end
1906
+
1907
+ # RFC 9002 "Computing PTO" for `path`, with the peer's max_ack_delay of
1908
+ # Application Data.
1909
+ private def path_pto(path) = path.rtt.pto_period + (@peer_parameters&.max_ack_delay || 0.0)
1910
+
1911
+ # When the validations of the paths want something next. A path with
1912
+ # too little of its amplification limit left for a probe waits for no
1913
+ # challenge, only for its deadline.
1914
+ private def validation_timeouts
1915
+ [@path, *@validating].filter_map do |path|
1916
+ budget = path.amplification_budget
1917
+ budget && budget < MIN_PROBE ? path.validation_deadline : path.validation_timeout
1918
+ end
1919
+ end
1920
+
1921
+ # Protects the packets of a datagram and records them as sent. The
1922
+ # last is padded to make the datagram `target` bytes; unless told, that
1923
+ # is MIN_INITIAL_DATAGRAM when it carries a client's Initial, or a
1924
+ # server's that elicits an ACK. Every packet is padded so that header
1925
+ # protection has its sample. A `probing` datagram counts nothing in
1926
+ # flight; one that is an `mtu_probe` is recorded as one.
1927
+ private def seal(pending, now, target: nil, probing: false, mtu_probe: false, path: @path)
1928
+ target ||= pending.any? { |packet| padded_initial?(packet) } ? MIN_INITIAL_DATAGRAM : 0
1929
+ payloads = pending.map do |packet|
1930
+ payload = Wire::Frame.encode(packet.frames, ack_delay_exponent: own_ack_delay_exponent(packet.level))
1931
+ short = Wire::Packet::SAMPLE_OFFSET - packet.packet_number_length - payload.bytesize
1932
+ short.positive? ? payload + "\0".b * short : payload
1933
+ end
1934
+ size = pending.each_with_index.sum { |packet, index| sealed_size(packet, payloads.fetch(index).bytesize) }
1935
+ payloads[-1] = padded(pending.fetch(-1), payloads.fetch(-1), target - size) if target > size
1936
+ pending.each_with_index.map { |packet, index| protect(packet, payloads.fetch(index), now, probing:, mtu_probe:, path:) }.join
1937
+ end
1938
+
1939
+ # RFC 9000 "Datagram Size": every Initial of a client, and those of a
1940
+ # server that elicit an ACK, go in datagrams of 1200 bytes at least.
1941
+ private def padded_initial?(packet)
1942
+ packet.level == :initial && (@role == :client || packet.frames.any?(&:ack_eliciting?))
1943
+ end
1944
+
1945
+ # `payload` with `missing` bytes of PADDING, less what the Length field
1946
+ # grows by.
1947
+ private def padded(packet, payload, missing)
1948
+ grown = sealed_size(packet, payload.bytesize + missing) - sealed_size(packet, payload.bytesize) - missing
1949
+ payload + "\0".b * (missing - grown)
1950
+ end
1951
+
1952
+ private def protect(packet, payload, now, probing:, mtu_probe:, path:)
1953
+ keys = @protection.write_keys(packet.level) or raise Error::StateError, "no keys to write #{packet.level}"
1954
+ sealed = Wire::Packet.seal(packet.header, packet_number: packet.packet_number, packet_number_length: packet.packet_number_length,
1955
+ payload:, keys:)
1956
+ if packet.level == :one_rtt
1957
+ acknowledging = packet.frames.filter_map { |frame| frame.largest if frame.is_a?(Wire::Frame::Ack) }.first
1958
+ @protection.sent(packet.packet_number, acknowledging:)
1959
+ end
1960
+ if @tracer
1961
+ @tracer.packet_sent(header: Tracer::PacketHeader.of(packet.header, packet.packet_number), # steep:ignore
1962
+ frames: @tracer.trace_frames? ? packet.frames : nil, raw_length: sealed.bytesize, now:) # steep:ignore
1963
+ end
1964
+ @packets_sent += 1
1965
+ @bytes_sent += sealed.bytesize
1966
+ ack_eliciting = packet.frames.any?(&:ack_eliciting?)
1967
+ in_flight = !probing && (ack_eliciting || payload.bytesize > Wire::Frame.encode(packet.frames, ack_delay_exponent: 0).bytesize)
1968
+ if ack_eliciting && !@eliciting_since_received
1969
+ @eliciting_since_received = true
1970
+ restart_idle(now)
1971
+ end
1972
+ @recovery.on_packet_sent(packet_type: packet.level, packet_number: packet.packet_number, sent_bytes: sealed.bytesize,
1973
+ ack_eliciting:, in_flight:, duties: packet.duties, now:, pmtu_probe: mtu_probe, path:)
1974
+ sealed
1975
+ end
1976
+
1977
+ private def header_for(level)
1978
+ case level
1979
+ when :one_rtt then Wire::ShortHeader.new(dcid: @destination_connection_id, key_phase: @protection.key_phase_bit)
1980
+ when :initial
1981
+ Wire::LongHeader.new(type: level, version: @protection.version_of(level), dcid: @destination_connection_id, scid: @source_connection_id,
1982
+ token: @token)
1983
+ else Wire::LongHeader.new(type: level, version: @protection.version_of(level), dcid: @destination_connection_id, scid: @source_connection_id)
1984
+ end
1985
+ end
1986
+
1987
+ private def overhead(header)
1988
+ case header
1989
+ when Wire::LongHeader then LONG_HEADER_OVERHEAD + header.dcid.bytesize + header.scid.bytesize + token_field(header)
1990
+ else SHORT_HEADER_OVERHEAD + header.dcid.bytesize
1991
+ end
1992
+ end
1993
+
1994
+ # The Token Length and Token fields, which only an Initial packet has.
1995
+ private def token_field(header) = header.type == :initial ? Wire::Varint.size(header.token.bytesize) + header.token.bytesize : 0
1996
+
1997
+ # The bytes of `packet` with a payload of `length` bytes, protected.
1998
+ private def sealed_size(packet, length)
1999
+ header = packet.header
2000
+ keys = @protection.write_keys(packet.level) or raise Error::StateError, "no keys to write #{packet.level}"
2001
+ body = packet.packet_number_length + length + keys.aead.tag_length
2002
+ case header
2003
+ when Wire::LongHeader
2004
+ 1 + 4 + 1 + header.dcid.bytesize + 1 + header.scid.bytesize + token_field(header) + Wire::Varint.size(body) + body
2005
+ else 1 + header.dcid.bytesize + body
2006
+ end
2007
+ end
2008
+
2009
+ private def own_ack_delay_exponent(level) = level == :one_rtt ? @config.ack_delay_exponent : DEFAULT_ACK_DELAY_EXPONENT
2010
+
2011
+ private def peer_ack_delay_exponent(level)
2012
+ return DEFAULT_ACK_DELAY_EXPONENT unless level == :one_rtt
2013
+ @peer_parameters&.ack_delay_exponent || DEFAULT_ACK_DELAY_EXPONENT
2014
+ end
2015
+
2016
+ # The path's smoothed RTT, nil before its first sample.
2017
+ private def rtt_sample = @path.rtt.first_sample_at && @path.rtt.smoothed_rtt
2018
+
2019
+ # TLS's wall clock at `now`.
2020
+ private def tls_time(now) = @time + (now - @created_at)
2021
+ end
2022
+ end