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,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::QUIC
4
+ # What a tracer is told, one method per event of the qlog drafts. Every
5
+ # method is optional: a tracer includes this module and overrides the ones
6
+ # it wants, and the rest do nothing. The layer takes a tracer, or nil for
7
+ # none, and calls it only when it has one, so that without a tracer not
8
+ # even the arguments are made.
9
+ #
10
+ # Times are Float seconds of the monotonic clock; a qlog writer turns them
11
+ # into milliseconds. `space` is :initial, :handshake or :application_data.
12
+ module Tracer
13
+ # A packet's header as qlog writes it (qlog `PacketHeader`): its type
14
+ # and number, and the version and connection IDs of a long header or
15
+ # the Key Phase bit of a short one.
16
+ class PacketHeader < Data.define(:packet_type, :packet_number, :version, :dcid, :scid, :key_phase)
17
+ # The header of the packet with the Wire header `header` numbered
18
+ # `packet_number`.
19
+ def self.of(header, packet_number)
20
+ case header
21
+ when Wire::LongHeader
22
+ new(packet_type: header.type, packet_number:, version: header.version.number, dcid: header.dcid, scid: header.scid, key_phase: nil)
23
+ else new(packet_type: :one_rtt, packet_number:, version: nil, dcid: header.dcid, scid: nil, key_phase: header.key_phase)
24
+ end
25
+ end
26
+ end
27
+
28
+ # A packet sent (qlog `packet_sent`) and one received and processed
29
+ # (qlog `packet_received`): its PacketHeader, its frames when
30
+ # `trace_frames?`, nil otherwise, and how many bytes it took.
31
+ def packet_sent(header:, frames:, raw_length:, now:) = nil
32
+
33
+ def packet_received(header:, frames:, raw_length:, now:) = nil
34
+
35
+ # Whether `packet_sent` and `packet_received` are given the frames.
36
+ def trace_frames? = false
37
+
38
+ # Packets of `raw_length` bytes dropped (qlog `packet_dropped`).
39
+ # `reason` is a trigger of qlog: :invalid, :unsupported,
40
+ # :connection_unknown, :key_unavailable, :decryption_failure, :duplicate
41
+ # or :general.
42
+ def packet_dropped(reason:, raw_length:, now:) = nil
43
+
44
+ # The transport parameters of this end (`owner` :local) or of the peer,
45
+ # once authenticated (:remote) (qlog `parameters_set`).
46
+ def parameters_set(owner:, parameters:, now:) = nil
47
+
48
+ # The keys of `level` changed with a key update, which only :one_rtt
49
+ # has (qlog `key_updated`).
50
+ def key_updated(level:, now:) = nil
51
+
52
+ # A packet declared lost (qlog `packet_lost`). `trigger` is
53
+ # :reordering_threshold or :time_threshold.
54
+ def packet_lost(packet_number:, space:, trigger:, mtu_probe:, now:) = nil
55
+
56
+ # The values of loss recovery and congestion control that changed
57
+ # (qlog `recovery_metrics_updated`).
58
+ def metrics_updated(now:, **metrics) = nil
59
+
60
+ # A timer set, expired or cancelled (qlog `timer_updated`). `timer_type`
61
+ # is :loss_timeout or :ack, `event_type` :set, :expired or :cancelled,
62
+ # and `delta` the seconds from now to the deadline when set.
63
+ def timer_updated(timer_type:, event_type:, space:, delta:, now:) = nil
64
+
65
+ # The ECN state of the path changed (qlog `ecn_state_updated`): :testing,
66
+ # :capable or :failed.
67
+ def ecn_state_updated(old:, new:, now:) = nil
68
+
69
+ # The constants of loss recovery and congestion control, once at the
70
+ # start of a connection (qlog `recovery_parameters_set`).
71
+ def recovery_parameters_set(now:, **parameters) = nil
72
+
73
+ # A packet declared lost and acknowledged after all; qlog has no event
74
+ # for it, so a writer makes one of its own.
75
+ def spurious_loss(packet_number:, space:, now:) = nil
76
+
77
+ # The congestion controller changed state (qlog
78
+ # `congestion_state_updated`). The states are the algorithm's own.
79
+ def congestion_state_updated(old:, new:, now:) = nil
80
+
81
+ # Sending on the connection, or on stream `stream_id`, became :blocked
82
+ # by the peer's limit, `reason` :connection_flow_control or
83
+ # :stream_flow_control, or :unblocked as the limit grew (qlog
84
+ # `connection_data_blocked_updated` and `stream_data_blocked_updated`).
85
+ def connection_data_blocked_updated(old:, new:, reason:, now:) = nil
86
+
87
+ def stream_data_blocked_updated(stream_id:, old:, new:, reason:, now:) = nil
88
+
89
+ # The datagrams of the path grew or shrank from `old` bytes to `new`,
90
+ # or the search for its MTU ended at `old` (qlog `mtu_updated`); `done`
91
+ # once the search has ended.
92
+ def mtu_updated(old:, new:, done:, now:) = nil
93
+
94
+ # The connection ID in use changed from `old` to `new` (qlog
95
+ # `connection_id_updated`): the peer's this end sends with (`owner`
96
+ # :remote), or this end's the peer sends with (:local).
97
+ def connection_id_updated(owner:, old:, new:, now:) = nil
98
+
99
+ # How a path between `local` and `remote` stands (qlog
100
+ # `migration_state_updated`): :probing_started, :probing_successful
101
+ # and :probing_abandoned as one besides the path in use is validated,
102
+ # and :migration_started, :migration_complete and :migration_abandoned
103
+ # as the connection moves to one.
104
+ def migration_state_updated(state:, local:, remote:, now:) = nil
105
+
106
+ # How the version of the connection was negotiated (qlog
107
+ # `version_information`): the versions the client offers, those the
108
+ # server takes or lists, and the version chosen, each a version number
109
+ # or nil when not known at this end. A client tells as it starts an
110
+ # attempt, takes a Version Negotiation packet, or follows the server to
111
+ # another version; a server as it takes the client's version
112
+ # information.
113
+ def version_information(now:, client_versions: nil, server_versions: nil, chosen_version: nil) = nil
114
+
115
+ # A client's session to resume went unused for `reason`, :version_mismatch
116
+ # when its version is not one the client is configured with: a ticket
117
+ # is of the version of the connection it came on (RFC 9369 "TLS
118
+ # Resumption and NEW_TOKEN Tokens"). No qlog event has it.
119
+ def session_ignored(reason:, now:) = nil
120
+
121
+ # A client's token of NEW_TOKEN went unused for `reason`,
122
+ # :version_mismatch when it is of another version than the one the
123
+ # connection starts in (RFC 9369 "TLS Resumption and NEW_TOKEN Tokens").
124
+ # No qlog event has it.
125
+ def token_ignored(reason:, now:) = nil
126
+ end
127
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::QUIC
4
+ # What to send: `payload` to `destination` ([host, port]) from `source`
5
+ # (nil leaves it to the OS) with the ECN codepoint `ecn` (:not_ect, :ect0
6
+ # or :ect1). With a `segment_size`, the payload is several datagrams of
7
+ # that size, the last one possibly shorter, for GSO or to send one by one.
8
+ class Transmit < Data.define(:payload, :destination, :source, :ecn, :segment_size)
9
+ ECN = %i[not_ect ect0 ect1].freeze
10
+ # The most datagrams a connection puts in one: what Linux's GSO takes
11
+ # at most (UDP_MAX_SEGMENTS).
12
+ MAX_SEGMENTS = 64
13
+ end
14
+ end
@@ -0,0 +1,244 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ipaddr"
4
+
5
+ module Raiha::QUIC
6
+ # The transport parameters of one end (RFC 9000 "Transport Parameter
7
+ # Definitions", and max_datagram_frame_size of RFC 9221), as the
8
+ # quic_transport_parameters extension carries them. The names are the
9
+ # RFC's. Times are Float seconds, milliseconds on the wire. A parameter
10
+ # left out has its default: max_idle_timeout 0 is no timeout,
11
+ # max_datagram_frame_size 0 is no DATAGRAM frames, and the connection
12
+ # IDs, the token and the preferred address are nil.
13
+ class TransportParameters < Data.define(
14
+ :original_destination_connection_id, :max_idle_timeout, :stateless_reset_token, :max_udp_payload_size,
15
+ :initial_max_data, :initial_max_stream_data_bidi_local, :initial_max_stream_data_bidi_remote, :initial_max_stream_data_uni,
16
+ :initial_max_streams_bidi, :initial_max_streams_uni,
17
+ :ack_delay_exponent, :max_ack_delay, :disable_active_migration, :preferred_address, :active_connection_id_limit,
18
+ :initial_source_connection_id, :retry_source_connection_id, :version_information, :max_datagram_frame_size
19
+ )
20
+ IDS = {
21
+ original_destination_connection_id: 0x00, max_idle_timeout: 0x01, stateless_reset_token: 0x02, max_udp_payload_size: 0x03,
22
+ initial_max_data: 0x04, initial_max_stream_data_bidi_local: 0x05, initial_max_stream_data_bidi_remote: 0x06,
23
+ initial_max_stream_data_uni: 0x07, initial_max_streams_bidi: 0x08, initial_max_streams_uni: 0x09,
24
+ ack_delay_exponent: 0x0a, max_ack_delay: 0x0b, disable_active_migration: 0x0c, preferred_address: 0x0d,
25
+ active_connection_id_limit: 0x0e, initial_source_connection_id: 0x0f, retry_source_connection_id: 0x10,
26
+ version_information: 0x11, max_datagram_frame_size: 0x20
27
+ }.freeze #: Hash[Symbol, Integer]
28
+ NAMES = IDS.invert.freeze #: Hash[Integer, Symbol]
29
+ MILLISECONDS = %i[max_idle_timeout max_ack_delay].freeze
30
+ CONNECTION_IDS = %i[original_destination_connection_id initial_source_connection_id retry_source_connection_id].freeze
31
+ # A client that sends one of these breaks RFC 9000 "Transport Parameter
32
+ # Definitions".
33
+ SERVER_ONLY = %i[original_destination_connection_id stateless_reset_token preferred_address retry_source_connection_id].freeze
34
+ MAX_STREAM_COUNT = 1 << 60
35
+ STATELESS_RESET_TOKEN_LENGTH = 16
36
+
37
+ # A server's preferred address (RFC 9000 "Preferred Address"): an IPv4
38
+ # and an IPv6 address, each `[host, port]` or nil when the server
39
+ # offers none of that family, and the connection ID and stateless reset
40
+ # token for using it.
41
+ class PreferredAddress < Data.define(:ipv4, :ipv6, :connection_id, :stateless_reset_token)
42
+ def initialize(ipv4:, ipv6:, connection_id:, stateless_reset_token:)
43
+ raise ArgumentError, "#{ipv4.inspect} is no IPv4 address" if ipv4 && !IPAddr.new(ipv4[0]).ipv4?
44
+ raise ArgumentError, "#{ipv6.inspect} is no IPv6 address" if ipv6 && !IPAddr.new(ipv6[0]).ipv6?
45
+ unless connection_id.bytesize.between?(1, Wire::CONNECTION_ID_MAX_LENGTH)
46
+ raise ArgumentError, "the preferred address has a connection ID of #{connection_id.bytesize} bytes"
47
+ end
48
+ unless stateless_reset_token.bytesize == STATELESS_RESET_TOKEN_LENGTH
49
+ raise ArgumentError, "a stateless reset token has 16 bytes, not #{stateless_reset_token.bytesize}"
50
+ end
51
+ super
52
+ end
53
+
54
+ def self.read(reader)
55
+ ipv4 = address(reader.bytes(4), reader.u16)
56
+ ipv6 = address(reader.bytes(16), reader.u16)
57
+ new(ipv4:, ipv6:, connection_id: reader.bytes(reader.u8), stateless_reset_token: reader.bytes(STATELESS_RESET_TOKEN_LENGTH))
58
+ end
59
+
60
+ # All zeros, address and port, stand for no address of the family.
61
+ private_class_method def self.address(bytes, port)
62
+ return nil if port.zero? && bytes.bytes.all?(&:zero?)
63
+ [IPAddr.new_ntoh(bytes).to_s, port]
64
+ end
65
+
66
+ # The address a client that sends to `families` (Config#address_families)
67
+ # moves to from the server's address `server`: IPv6 before IPv4, and
68
+ # none that is unspecified or multicast, nor loopback unless `server`
69
+ # is (RFC 9000 "Generic Request Forgery Countermeasures"); nil when
70
+ # none is.
71
+ def choose(families:, server:)
72
+ loopback = IPAddr.new(server[0]).loopback?
73
+ [(ipv6 if families.include?(:ipv6)), (ipv4 if families.include?(:ipv4))].compact.find do |address|
74
+ ip = IPAddr.new(address[0]).native
75
+ bits = ip.to_i
76
+ multicast = ip.ipv4? ? bits >> 28 == 0xe : bits >> 120 == 0xff
77
+ !bits.zero? && !multicast && (loopback || !ip.loopback?)
78
+ end
79
+ end
80
+
81
+ def encode
82
+ writer = Wire::Writer.new
83
+ writer.bytes(ipv4 ? IPAddr.new(ipv4[0]).hton : "\0".b * 4).u16(ipv4 ? ipv4[1] : 0)
84
+ writer.bytes(ipv6 ? IPAddr.new(ipv6[0]).hton : "\0".b * 16).u16(ipv6 ? ipv6[1] : 0)
85
+ writer.u8(connection_id.bytesize).bytes(connection_id).bytes(stateless_reset_token).to_s
86
+ end
87
+ end
88
+
89
+ # The version information of RFC 9368 "Version Information": the
90
+ # Chosen Version, the version of the packets that carry it, and the
91
+ # Available Versions, the numbers of the versions its sender would use,
92
+ # reserved ones among them. A Chosen Version of 0 and an Available
93
+ # Version of 0 are not allowed.
94
+ class VersionInformation < Data.define(:chosen, :available)
95
+ def initialize(chosen:, available:)
96
+ [chosen, *available].each do |number|
97
+ raise ArgumentError, "#{number.inspect} is no version number" unless number.is_a?(Integer) && number.between?(1, 0xffff_ffff)
98
+ end
99
+ super
100
+ end
101
+
102
+ # The version information in `reader`, which `sender` (:client or
103
+ # :server) sent (RFC 9368 "Version Information"). Its length is a
104
+ # multiple of four and no version in it is 0. A client offers its
105
+ # Chosen Version among its Available Versions; a server's may leave
106
+ # it out, or be empty. Anything else raises Wire::Malformed.
107
+ def self.read(reader, sender:)
108
+ length = reader.remaining
109
+ raise Wire::Malformed, "version_information of #{length} bytes" if length < 4 || length % 4 != 0
110
+ chosen = reader.u32
111
+ available = [] #: Array[Integer]
112
+ available << reader.u32 until reader.eof?
113
+ raise Wire::Malformed, "a chosen version of 0" if chosen.zero?
114
+ raise Wire::Malformed, "an available version of 0" if available.include?(0)
115
+ if sender == :client && !available.include?(chosen)
116
+ raise Wire::Malformed, format("the chosen version 0x%08x is none of the client's available versions", chosen)
117
+ end
118
+ new(chosen:, available: available.freeze)
119
+ end
120
+
121
+ def encode = available.each_with_object(Wire::Writer.new.u32(chosen)) { |number, writer| writer.u32(number) }.to_s
122
+ end
123
+
124
+ # The rules of RFC 9000 "Transport Parameter Definitions" on the values.
125
+ def initialize(
126
+ original_destination_connection_id: nil, max_idle_timeout: 0.0, stateless_reset_token: nil, max_udp_payload_size: 65_527,
127
+ initial_max_data: 0, initial_max_stream_data_bidi_local: 0, initial_max_stream_data_bidi_remote: 0, initial_max_stream_data_uni: 0,
128
+ initial_max_streams_bidi: 0, initial_max_streams_uni: 0,
129
+ ack_delay_exponent: 3, max_ack_delay: 0.025, disable_active_migration: false, preferred_address: nil, active_connection_id_limit: 2,
130
+ initial_source_connection_id: nil, retry_source_connection_id: nil, version_information: nil, max_datagram_frame_size: 0
131
+ )
132
+ integers = [
133
+ max_udp_payload_size, initial_max_data, initial_max_stream_data_bidi_local, initial_max_stream_data_bidi_remote,
134
+ initial_max_stream_data_uni, initial_max_streams_bidi, initial_max_streams_uni, ack_delay_exponent,
135
+ active_connection_id_limit, max_datagram_frame_size, (max_idle_timeout * 1000).round
136
+ ]
137
+ integers.each { |value| raise ArgumentError, "#{value} is no varint" unless value.between?(0, Wire::Varint::MAX) }
138
+ raise ArgumentError, "max_udp_payload_size #{max_udp_payload_size} is under 1200" if max_udp_payload_size < 1200
139
+ raise ArgumentError, "ack_delay_exponent #{ack_delay_exponent} is over 20" if ack_delay_exponent > 20
140
+ raise ArgumentError, "max_ack_delay #{max_ack_delay} is 2^14 milliseconds or more" if max_ack_delay * 1000 >= 1 << 14
141
+ raise ArgumentError, "active_connection_id_limit #{active_connection_id_limit} is under 2" if active_connection_id_limit < 2
142
+ [initial_max_streams_bidi, initial_max_streams_uni].each do |count|
143
+ raise ArgumentError, "a stream count of #{count} is past 2^60" if count > MAX_STREAM_COUNT
144
+ end
145
+ [original_destination_connection_id, initial_source_connection_id, retry_source_connection_id].compact.each do |cid|
146
+ raise ArgumentError, "a connection ID of #{cid.bytesize} bytes" if cid.bytesize > Wire::CONNECTION_ID_MAX_LENGTH
147
+ end
148
+ if stateless_reset_token && stateless_reset_token.bytesize != STATELESS_RESET_TOKEN_LENGTH
149
+ raise ArgumentError, "a stateless reset token has 16 bytes, not #{stateless_reset_token.bytesize}"
150
+ end
151
+ # RFC 9000 "Preferred Address": a server that sends with zero-length
152
+ # connection IDs offers no preferred address.
153
+ raise ArgumentError, "a preferred address with zero-length connection IDs" if preferred_address && initial_source_connection_id&.empty?
154
+ super
155
+ end
156
+
157
+ DEFAULTS = new.to_h.freeze
158
+
159
+ # The parameters as the extension carries them, in the order of their
160
+ # IDs, those at their defaults left out.
161
+ def encode
162
+ writer = Wire::Writer.new
163
+ to_h.each { |name, value| TransportParameters.write(writer, name, value) unless value == DEFAULTS.fetch(name) }
164
+ writer.to_s
165
+ end
166
+
167
+ # Writes the parameter `name` with `value`: its ID, length and value. A
168
+ # flag has no value; it is there when true and left out when false, as
169
+ # is a parameter whose value is nil.
170
+ def self.write(writer, name, value)
171
+ body =
172
+ if value == true then ""
173
+ elsif value.is_a?(String) then value
174
+ elsif value.is_a?(PreferredAddress) || value.is_a?(VersionInformation) then value.encode
175
+ elsif value.is_a?(Float) then Wire::Varint.encode((value * 1000).round)
176
+ elsif value.is_a?(Integer) then Wire::Varint.encode(value)
177
+ else return writer
178
+ end
179
+ writer.varint(IDS.fetch(name)).varint(body.bytesize).bytes(body)
180
+ end
181
+
182
+ # The parameters a client may remember for 0-RTT.
183
+ def remembered = RememberedTransportParameters.new(**to_h.slice(*RememberedTransportParameters.members)) # steep:ignore
184
+
185
+ # The parameters in `bytes`, sent by `sender` (:client or :server).
186
+ # Unknown parameters, the reserved ones for GREASE among them, are
187
+ # ignored (RFC 9000 "Reserved Transport Parameters"). Anything else that
188
+ # is not right raises Wire::Malformed with TRANSPORT_PARAMETER_ERROR: a
189
+ # value against the rules, a parameter only a server sends coming from a
190
+ # client, and a missing initial_source_connection_id, or a missing
191
+ # original_destination_connection_id from a server (RFC 9000
192
+ # "Authenticating Connection IDs"). So does any ID twice, unknown ones
193
+ # too: a peer may not send one twice (RFC 9000 "Transport Parameters"),
194
+ # and taking the first or the last would let two readers of the same
195
+ # bytes disagree.
196
+ def self.decode(bytes, sender:)
197
+ reader = Wire::Reader.new(bytes)
198
+ # @type var parameters: Hash[Symbol, Integer | Float | bool | String | PreferredAddress | VersionInformation]
199
+ parameters = {}
200
+ seen = Set.new #: Set[Integer]
201
+ until reader.eof?
202
+ id = reader.varint
203
+ value = reader.sub(reader.varint)
204
+ raise Wire::Malformed, "transport parameter 0x#{id.to_s(16)} twice" unless seen.add?(id)
205
+ name = NAMES[id] or next
206
+ raise Wire::Malformed, "#{name} from a client" if sender == :client && SERVER_ONLY.include?(name)
207
+ parameters[name] = read_value(name, value, sender)
208
+ raise Wire::Malformed, "#{name} has #{value.remaining} bytes past its value" unless value.eof?
209
+ end
210
+ raise Wire::Malformed, "no initial_source_connection_id" unless parameters.key?(:initial_source_connection_id)
211
+ if sender == :server && !parameters.key?(:original_destination_connection_id)
212
+ raise Wire::Malformed, "no original_destination_connection_id from the server"
213
+ end
214
+ new(**parameters)
215
+ rescue ArgumentError, Wire::Malformed => error
216
+ raise Wire::Malformed.new(error.message, code: ErrorCode::TRANSPORT_PARAMETER_ERROR)
217
+ end
218
+
219
+ private_class_method def self.read_value(name, value, sender)
220
+ case name
221
+ when :disable_active_migration then true
222
+ when :preferred_address then PreferredAddress.read(value)
223
+ when :version_information then VersionInformation.read(value, sender:)
224
+ when :stateless_reset_token, *CONNECTION_IDS then value.rest
225
+ when *MILLISECONDS then value.varint / 1000.0
226
+ else value.varint
227
+ end
228
+ end
229
+
230
+ # The quic_transport_parameters extension (RFC 9001 "QUIC Transport
231
+ # Parameters Extension") for the TLS layer's Extension::Registry. It
232
+ # keeps the bytes that came: decoding them is the QUIC binding's, which
233
+ # closes with TRANSPORT_PARAMETER_ERROR rather than with a TLS alert.
234
+ # Registered, it lets TLS refuse the extension in any message but
235
+ # ClientHello and EncryptedExtensions.
236
+ module Extension
237
+ TYPE = 0x39
238
+ CODECS = {
239
+ client_hello: Raiha::TLS::Extension::Opaque::Parser.new(type: TYPE),
240
+ encrypted_extensions: Raiha::TLS::Extension::Opaque::Parser.new(type: TYPE)
241
+ }.freeze
242
+ end
243
+ end
244
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::QUIC
4
+ # What changes between QUIC versions, in one value, so that no other code
5
+ # writes a version's literals: the version number, the salt of the Initial
6
+ # secrets, the prefix of the key derivation labels, the long header packet
7
+ # types, and the key and nonce of the Retry integrity tag. RFC 9369 (QUIC
8
+ # version 2) changes every one of them, the packet type bits included.
9
+ class Version < Data.define(:number, :initial_salt, :label_prefix, :packet_types, :retry_key, :retry_nonce)
10
+ LONG_PACKET_TYPES = %i[initial zero_rtt handshake retry].freeze
11
+
12
+ # The packet protection label `name` ("key", "iv", "hp", "ku").
13
+ def label(name) = "#{label_prefix} #{name}"
14
+
15
+ # The two type bits of a long header packet of `type`.
16
+ def type_bits(type) = packet_types.fetch(type) { raise ArgumentError, "no long header packet type #{type.inspect}" }
17
+
18
+ # The packet type the two `bits` stand for.
19
+ def packet_type(bits) = packet_types.key(bits) || raise(ArgumentError, "type bits are 0..3, not #{bits.inspect}")
20
+
21
+ # RFC 9000 and RFC 9001 ("Initial Secrets", "Retry Packet Integrity").
22
+ V1 = Ractor.make_shareable(new(
23
+ number: 0x0000_0001,
24
+ initial_salt: ["38762cf7f55934b34d179ae6a4c80cadccbb7f0a"].pack("H*"),
25
+ label_prefix: "quic",
26
+ packet_types: { initial: 0b00, zero_rtt: 0b01, handshake: 0b10, retry: 0b11 },
27
+ retry_key: ["be0c690b9f66575a1d766b54e368c84e"].pack("H*"),
28
+ retry_nonce: ["461599d35d632bf2239825bb"].pack("H*")
29
+ ))
30
+
31
+ # RFC 9369 "Version-Specific Constants".
32
+ V2 = Ractor.make_shareable(new(
33
+ number: 0x6b33_43cf,
34
+ initial_salt: ["0dede3def700a6db819381be6e269dcbf9bd2ed9"].pack("H*"),
35
+ label_prefix: "quicv2",
36
+ packet_types: { initial: 0b01, zero_rtt: 0b10, handshake: 0b11, retry: 0b00 },
37
+ retry_key: ["8fb4b01b56ac48e260fbcbcead7ccc92"].pack("H*"),
38
+ retry_nonce: ["d86969bc2d7c6d9990efb04a"].pack("H*")
39
+ ))
40
+
41
+ SUPPORTED = [V1, V2].freeze
42
+
43
+ # The pairs of version numbers a connection may change between by
44
+ # compatible version negotiation (RFC 9368 "Compatible Versions"), in
45
+ # both directions: versions 1 and 2 (RFC 9369 "Compatibility with QUIC
46
+ # Version 1"). No other pair is to be taken as compatible.
47
+ COMPATIBLE = Ractor.make_shareable([[V1.number, V2.number]].to_set { |pair| pair.sort })
48
+
49
+ # The supported Version numbered `number`, or nil.
50
+ def self.find(number) = SUPPORTED.find { |version| version.number == number }
51
+
52
+ # A reserved version, 0x?a?a?a?a, from `random` (RFC 9000 "Versions"),
53
+ # which RFC 9368 lets a Version Negotiation packet and Available
54
+ # Versions carry to exercise the peer's negotiation. It is never one to
55
+ # use: `find` has none of them.
56
+ def self.reserved(random) = (random.bytes(4).unpack1("N") & 0xf0f0_f0f0) | 0x0a0a_0a0a
57
+
58
+ # Whether a connection of this version may change to `other` by
59
+ # compatible version negotiation. A version is not taken as compatible
60
+ # with itself: whoever asks tells the two apart.
61
+ def compatible_with?(other) = COMPATIBLE.include?([number, other.number].sort)
62
+ end
63
+ end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../error"
4
+
5
+ module Raiha::QUIC
6
+ # The encoding of QUIC packets and frames: values in, bytes out, and back.
7
+ # Module functions over Reader and Writer; nothing here holds state.
8
+ module Wire
9
+ # Bytes from the peer that do not decode. `code` is the transport error
10
+ # to close the connection with when the bytes were authenticated (a
11
+ # frame, or the reserved bits of a header); a packet that does not decode
12
+ # before that is dropped instead. `frame_type` is the type of the frame
13
+ # that did not decode, for the CONNECTION_CLOSE frame.
14
+ class Malformed < Violation
15
+ def initialize(message = nil, code: ErrorCode::FRAME_ENCODING_ERROR, frame_type: nil) = super
16
+ end
17
+
18
+ # The bytes ran out before a field did.
19
+ class Truncated < Malformed; end
20
+
21
+ # RFC 9000 "Variable-Length Integer Encoding": the two high bits of the
22
+ # first byte give the length, 1, 2, 4 or 8 bytes.
23
+ module Varint
24
+ MAX = (1 << 62) - 1
25
+
26
+ def self.size(value)
27
+ raise ArgumentError, "a varint is 0..2^62-1, not #{value.inspect}" unless value.is_a?(Integer) && value.between?(0, MAX)
28
+ if value < (1 << 6) then 1
29
+ elsif value < (1 << 14) then 2
30
+ elsif value < (1 << 30) then 4
31
+ else 8
32
+ end
33
+ end
34
+
35
+ # The shortest encoding of `value`.
36
+ def self.encode(value)
37
+ case size(value)
38
+ when 1 then [value].pack("C")
39
+ when 2 then [0x4000 | value].pack("n")
40
+ when 4 then [0x8000_0000 | value].pack("N")
41
+ else [0xc000_0000_0000_0000 | value].pack("Q>")
42
+ end
43
+ end
44
+ end
45
+
46
+ # Reads fields from `bytes` between `offset` and `limit` without copying
47
+ # them first. A field past the limit raises Truncated.
48
+ class Reader
49
+ NON_ZERO = /[^\x00]/n
50
+
51
+ attr_reader :offset
52
+
53
+ def initialize(bytes, offset = 0, limit = bytes.bytesize)
54
+ @bytes = bytes
55
+ @offset = offset
56
+ @limit = limit
57
+ end
58
+
59
+ def remaining = @limit - @offset
60
+
61
+ def eof? = @offset >= @limit
62
+
63
+ def u8 = take(1).getbyte(0) # steep:ignore
64
+
65
+ def u16 = take(2).unpack1("n")
66
+
67
+ def u32 = take(4).unpack1("N")
68
+
69
+ # The value and how many bytes it took, for the checks of a shortest
70
+ # encoding (frame types must use one).
71
+ def varint_with_size
72
+ first = @bytes.getbyte(@offset) or raise Truncated, "a varint is cut short"
73
+ size = 1 << (first >> 6)
74
+ raw = take(size)
75
+ value = case size
76
+ when 1 then first
77
+ when 2 then raw.unpack1("n") & 0x3fff
78
+ when 4 then raw.unpack1("N") & 0x3fff_ffff
79
+ else raw.unpack1("Q>") & Varint::MAX
80
+ end
81
+ [value, size]
82
+ end
83
+
84
+ def varint = varint_with_size.first
85
+
86
+ def bytes(length) = take(length)
87
+
88
+ # Skips the zero bytes from here on, and tells how many there were.
89
+ def zero_run
90
+ stop = @bytes.byteindex(NON_ZERO, @offset) || @limit
91
+ stop = @limit if stop > @limit
92
+ count = stop - @offset
93
+ @offset = stop
94
+ count
95
+ end
96
+
97
+ # The rest, up to the limit.
98
+ def rest = take(remaining)
99
+
100
+ # A Reader over the next `length` bytes, which this one skips.
101
+ def sub(length)
102
+ raise Truncated, "#{length} bytes wanted, #{remaining} left" if length > remaining
103
+ reader = Reader.new(@bytes, @offset, @offset + length)
104
+ @offset += length
105
+ reader
106
+ end
107
+
108
+ private def take(length) # steep:ignore
109
+ raise Truncated, "#{length} bytes wanted, #{remaining} left" if length > remaining
110
+ value = @bytes.byteslice(@offset, length)
111
+ @offset += length
112
+ value
113
+ end
114
+ end
115
+
116
+ class Writer
117
+ def initialize
118
+ @buffer = String.new(encoding: Encoding::BINARY)
119
+ end
120
+
121
+ def u8(value) = tap { @buffer << [value].pack("C") }
122
+
123
+ def u16(value) = tap { @buffer << [value].pack("n") }
124
+
125
+ def u32(value) = tap { @buffer << [value].pack("N") }
126
+
127
+ def varint(value) = tap { @buffer << Varint.encode(value) }
128
+
129
+ def bytes(value) = tap { @buffer << value.b }
130
+
131
+ def bytesize = @buffer.bytesize
132
+
133
+ def to_s = @buffer
134
+ end
135
+ end
136
+ end