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,248 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module Raiha::Runtime
6
+ # The workers of a server, each in a Ractor of its own: `run` binds a
7
+ # socket for each worker to `host` and `port` with SO_REUSEPORT, one to
8
+ # "0.0.0.0" on that port where "::" takes no IPv4 (OpenBSD), and one
9
+ # for each preferred address of `config` those do not take, moves
10
+ # them to the workers' Ractors, and runs the block in each with its
11
+ # Worker and `args`, which have to be shareable or copied. The block
12
+ # makes a server with `worker:` and `config: worker.config` and runs it,
13
+ # under a Fiber scheduler of its own.
14
+ #
15
+ # `config` is the QUIC Config every worker shares; the Retry token and
16
+ # stateless reset keys it leaves out are drawn once here, so that each
17
+ # worker takes the tokens and reads the connection IDs another issued.
18
+ # Its connection IDs are WorkerConnectionIDs::MIN_LENGTH bytes at least,
19
+ # to carry the worker's ID. The workers share one record of 0-RTT
20
+ # (TLS::AntiReplay::Shared), in a Ractor of its own.
21
+ #
22
+ # Once one worker's block is over, the others are told to stop; `run`
23
+ # returns when all are over, raising what the first that raised raised.
24
+ # The record stopping before them is a failure too.
25
+ #
26
+ # `stop` asks every worker to stop, from a signal handler as well,
27
+ # `reconfigure` has every worker take other TLS settings, building its
28
+ # Keyring of `identities`, and `stats` gives what each worker counted of
29
+ # the datagrams handed on, nil for one that does not answer in time.
30
+ #
31
+ # SO_REUSEPORT spreads datagrams over sockets on Linux. Elsewhere, as on
32
+ # OpenBSD, the kernel may give them all to one socket: the worker that
33
+ # has it takes every new connection, and hands on what comes for the
34
+ # others' connections as it does after a migration, so that more than
35
+ # one worker runs but the load is not spread.
36
+ class Workers
37
+ MAX = Raiha::QUIC::WorkerConnectionIDs::MAX_WORKERS
38
+ # How long `stats` waits for a worker to answer.
39
+ STATS_TIMEOUT = 1.0
40
+
41
+ attr_reader :count
42
+
43
+ def initialize(count:, config:, host: "::", port: 443, args: [], &block)
44
+ raise ArgumentError, "a block to run in each worker is needed" unless block
45
+ raise ArgumentError, "count #{count} is not 1 to #{MAX}" unless count.is_a?(Integer) && (1..MAX).cover?(count)
46
+ if config.connection_id_length < Raiha::QUIC::WorkerConnectionIDs::MIN_LENGTH
47
+ raise ArgumentError, "a worker's connection IDs are #{Raiha::QUIC::WorkerConnectionIDs::MIN_LENGTH} bytes at least"
48
+ end
49
+ @count = count
50
+ @config = config.with(retry_token_key: config.retry_token_key || SecureRandom.bytes(Raiha::QUIC::Config::MIN_KEY_LENGTH),
51
+ stateless_reset_key: config.stateless_reset_key || SecureRandom.bytes(Raiha::QUIC::Config::MIN_KEY_LENGTH))
52
+ @host = host
53
+ @port = port
54
+ @args = args
55
+ @body = Ractor.shareable_proc(&block) # steep:ignore
56
+ @local_address = nil #: UDP::address?
57
+ @controls = [] #: Array[Ractor::Port[Worker::control]]
58
+ # What `stop` asked, and the pipe it wakes `run` through.
59
+ @stop = nil #: (Float | Integer)?
60
+ @wake = nil #: IO?
61
+ end
62
+
63
+ # [address, port] the workers' sockets are bound to, once `run` bound
64
+ # them.
65
+ def local_address = @local_address
66
+
67
+ # Runs the workers until all are over; raises what the first that
68
+ # raised raised.
69
+ def run
70
+ reader, @wake = IO.pipe
71
+ sockets = bind
72
+ shared, record = Raiha::TLS::AntiReplay::Shared.start(now: Time.now)
73
+ out = Ractor::Port.new
74
+ ractors = Array.new(@count) { |id| start(id, out, shared) }
75
+ started = Array.new(@count) { out.receive }.sort_by(&:first)
76
+ peers = Ractor.make_shareable(started.map { |_, inbox, _| inbox })
77
+ @controls = started.map { |_, _, control| control }
78
+ ractors.each_with_index { |ractor, id| ractor.send([sockets[id], peers], move: true) }
79
+ sockets = nil
80
+ relay = Thread.new { relay_stops(reader) }
81
+ (timeout = @stop) and stop_workers(timeout)
82
+ wait(ractors, record)
83
+ ensure
84
+ relay&.kill
85
+ reader&.close
86
+ @wake&.close
87
+ sockets&.flatten&.each(&:close)
88
+ shared&.stop
89
+ begin
90
+ record&.join
91
+ rescue Ractor::RemoteError
92
+ nil
93
+ end
94
+ end
95
+
96
+ # Asks every worker to stop, giving its sessions `timeout` seconds; the
97
+ # first call is the one that counts. It writes to a pipe without
98
+ # waiting, so a signal handler may call it, and `run` tells the workers.
99
+ def stop(timeout: Server::STOP_TIMEOUT)
100
+ @stop ||= timeout
101
+ @wake&.write_nonblock(".", exception: false)
102
+ nil
103
+ rescue IOError, SystemCallError
104
+ # `run` is returning and has closed the pipe.
105
+ nil
106
+ end
107
+
108
+ # Has every worker take the connections to come with `tls_config` and
109
+ # a Keyring of `identities` (TLS::Keyring::Identity); those taken keep
110
+ # theirs.
111
+ def reconfigure(tls_config:, identities:)
112
+ raise Error::Usage, "the workers are not running" if @controls.empty?
113
+ message = Ractor.make_shareable([:reconfigure, tls_config, identities], copy: true) #: Worker::control
114
+ @controls.each do |control|
115
+ control.send(message)
116
+ rescue Ractor::ClosedError
117
+ nil
118
+ end
119
+ nil
120
+ end
121
+
122
+ # What each worker counted of the datagrams handed on, by ID; nil for
123
+ # one that has ended, or does not answer in `timeout` seconds, as one
124
+ # whose server is not running yet. Every worker is asked at once, so
125
+ # that the answers take `timeout` at most, however many there are.
126
+ def stats(timeout: STATS_TIMEOUT)
127
+ replies = @controls.map do |control|
128
+ reply = Ractor::Port.new #: Ractor::Port[Worker::Stats?]
129
+ begin
130
+ control.send([:stats, reply])
131
+ rescue Ractor::ClosedError
132
+ reply.send(nil)
133
+ end
134
+ reply
135
+ end
136
+ timer = Thread.new do
137
+ sleep timeout
138
+ replies.each do |reply|
139
+ reply.send(nil)
140
+ rescue Ractor::ClosedError
141
+ nil
142
+ end
143
+ end
144
+ replies.map(&:receive)
145
+ ensure
146
+ timer&.kill
147
+ replies&.each(&:close)
148
+ end
149
+
150
+ # Tells the workers to stop each time `stop` writes to the pipe.
151
+ private def relay_stops(reader)
152
+ loop do
153
+ reader.wait_readable
154
+ reader.read_nonblock(64, exception: false)
155
+ stop_workers(@stop || Server::STOP_TIMEOUT)
156
+ end
157
+ rescue IOError
158
+ nil
159
+ end
160
+
161
+ # A socket for each worker on `host` and `port`, the port the first was
162
+ # given for those after it, and one for each preferred address the
163
+ # first does not send from: the sockets of each worker, its first the
164
+ # one on `port`.
165
+ private def bind
166
+ bound = [] #: Array[UDPSocket]
167
+ begin
168
+ first = UDP.open(@host, @port, reuse_port: true).tap { |socket| bound << socket }
169
+ address = first.local_address
170
+ @local_address = [UDP.unmapped(address.ip_address), address.ip_port]
171
+ # Before the preferred addresses, which a specific address of IPv4
172
+ # on the same port would keep "0.0.0.0" from.
173
+ ipv4 = if address.ipv6? && address.ipv6_unspecified? && !UDP.takes_ipv4?(first)
174
+ UDP.open("0.0.0.0", address.ip_port, reuse_port: true).tap { |socket| bound << socket }
175
+ end
176
+ preferred = (@config.preferred_address&.values || []).reject do |preferred|
177
+ [first, ipv4].compact.any? { |socket| UDP.covers?(socket, preferred) }
178
+ end
179
+ Array.new(@count) do |id|
180
+ main = id.zero? ? first : UDP.open(@host, address.ip_port, reuse_port: true).tap { |socket| bound << socket }
181
+ main_ipv4 = id.zero? ? ipv4 : (UDP.open("0.0.0.0", address.ip_port, reuse_port: true).tap { |socket| bound << socket } if ipv4)
182
+ # A socket is an Enumerable of its lines; splatted, it would be read.
183
+ [main, *[main_ipv4].compact, *preferred.map { |host, port| UDP.open(host, port, reuse_port: true).tap { |socket| bound << socket } }]
184
+ end
185
+ rescue StandardError
186
+ bound.each(&:close)
187
+ raise
188
+ end
189
+ end
190
+
191
+ # The Ractor of worker `id`: it makes its inbox and control port, tells
192
+ # `out` of them, takes its sockets and the inboxes of all, and runs the
193
+ # block with its Worker; the ports and sockets close when it is over.
194
+ private def start(id, out, shared)
195
+ Ractor.new(out, id, @count, @config, shared, @body, *@args) do |out, id, count, config, shared, body, *args|
196
+ # What the block raises comes out of `run`, and is not reported here
197
+ # as well.
198
+ Thread.current.report_on_exception = false
199
+ inbox = Ractor::Port.new
200
+ control = Ractor::Port.new
201
+ out.send([id, inbox, control])
202
+ sockets, peers = Ractor.receive
203
+ worker = Raiha::Runtime::Worker.new(id:, count:, config:, sockets:, inbox:, control:, peers:, anti_replay: shared)
204
+ begin
205
+ body.call(worker, *args)
206
+ ensure
207
+ worker.close
208
+ sockets.each { |socket| socket.close unless socket.closed? }
209
+ end
210
+ end
211
+ end
212
+
213
+ # Waits for the workers and the record; once one worker is over, or
214
+ # the record, the workers left are told to stop.
215
+ private def wait(ractors, record)
216
+ failure = nil #: Exception?
217
+ left = ractors.dup
218
+ watched = record #: Ractor?
219
+ stopping = false
220
+ until left.empty?
221
+ begin
222
+ over, = Ractor.select(*left, *watched)
223
+ rescue Ractor::RemoteError => error
224
+ over = error.ractor
225
+ failure ||= error.cause || error
226
+ end
227
+ if over.equal?(watched)
228
+ watched = nil
229
+ failure ||= Error::Stopped.new("the record of 0-RTT the workers share stopped")
230
+ else
231
+ left.delete(over)
232
+ end
233
+ stop_workers unless stopping
234
+ stopping = true
235
+ end
236
+ raise failure if failure
237
+ nil
238
+ end
239
+
240
+ private def stop_workers(timeout = Server::STOP_TIMEOUT)
241
+ @controls.each do |control|
242
+ control.send([:stop, timeout])
243
+ rescue Ractor::ClosedError
244
+ nil
245
+ end
246
+ end
247
+ end
248
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "tls"
4
+ require_relative "quic"
5
+ require_relative "http3"
6
+
7
+ # The I/O runtime (Fiber, Ractor, Socket). May refer to TLS, QUIC and HTTP/3.
8
+ module Raiha::Runtime
9
+ # The namespace of the runtime that runs with `concurrency`: Raiha::Runtime
10
+ # itself for :fiber, the default, whose clients and servers wait through a
11
+ # Fiber scheduler, and Raiha::Runtime::Threaded for :thread, whose run on
12
+ # threads of their own. Both have Server, Client, Session and HTTP3 by the
13
+ # same names.
14
+ def self.for(concurrency: :fiber)
15
+ case concurrency
16
+ when :fiber then self
17
+ when :thread then Threaded
18
+ else raise ArgumentError, "concurrency is :fiber or :thread, not #{concurrency.inspect}"
19
+ end
20
+ end
21
+ end
22
+
23
+ require_relative "runtime/error"
24
+ require_relative "runtime/udp"
25
+ require_relative "runtime/driver"
26
+ require_relative "runtime/worker"
27
+ require_relative "runtime/workers"
28
+ require_relative "runtime/qlog"
29
+ require_relative "runtime/admission"
30
+ require_relative "runtime/addresses"
31
+ require_relative "runtime/kept"
32
+ require_relative "runtime/session"
33
+ require_relative "runtime/client"
34
+ require_relative "runtime/server"
35
+ require_relative "runtime/http3"
36
+ require_relative "runtime/http3_server"
37
+ require_relative "runtime/threaded"
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS
4
+ # Records the ClientHellos whose 0-RTT a server took, so that it takes the
5
+ # 0-RTT of each at most once (RFC 9846 "0-RTT and Anti-Replay", "Client
6
+ # Hello Recording"). A record answers
7
+ #
8
+ # check(binder, expires_at:, now:) -> :accepted | :replayed | :unavailable
9
+ #
10
+ # for the binder of a ClientHello that verified and passed the freshness
11
+ # check: :accepted when it was not recorded and now is, :replayed when it
12
+ # was or may have been, :unavailable when the record cannot tell. It keeps
13
+ # what it recorded until `expires_at` at least. It must not raise; what it
14
+ # cannot tell is :unavailable, and a server takes no 0-RTT but on
15
+ # :accepted.
16
+ module AntiReplay
17
+ # The longest a record must be kept, in seconds: the window of the
18
+ # freshness check, 10 seconds early and 1 late.
19
+ WINDOW = 11
20
+
21
+ # Records kept in memory, by one instance (a Ractor or a process): each
22
+ # ClientHello's 0-RTT is taken at most once by it, but once by each
23
+ # instance that can open the ticket.
24
+ #
25
+ # Two generations of WINDOW seconds by the `now:` it is given, so that a
26
+ # record stays from 11 to 22 seconds. For WINDOW seconds after it is
27
+ # made it records but answers :unavailable, so that a ClientHello whose
28
+ # 0-RTT was taken before a restart is not taken again (RFC 9846 "Client
29
+ # Hello Recording"). `warmup: false` skips that, and is right only when
30
+ # every ticket key it opens tickets with is newer than the record, such
31
+ # as keys made at random on start: then no ClientHello from before
32
+ # opens. With keys that outlive it, a replay of 0-RTT taken before a
33
+ # restart could be taken again.
34
+ class Memory
35
+ def initialize(now:, warmup: true)
36
+ raise ArgumentError, "now must be a Time" unless now.is_a?(Time)
37
+ raise ArgumentError, "warmup must be true or false" unless warmup == true || warmup == false
38
+ @current = {} #: Hash[String, true]
39
+ @previous = {} #: Hash[String, true]
40
+ @rotated_at = now.to_r
41
+ @available_at = warmup ? now.to_r + WINDOW : now.to_r
42
+ @lock = Thread::Mutex.new
43
+ end
44
+
45
+ def check(binder, expires_at:, now:)
46
+ @lock.synchronize do
47
+ rotate(now.to_r)
48
+ return :replayed if @current.key?(binder) || @previous.key?(binder)
49
+ # Not kept that long: the record could not tell a replay then.
50
+ return :unavailable if expires_at.to_r > now.to_r + WINDOW
51
+ @current[binder] = true
52
+ now.to_r < @available_at ? :unavailable : :accepted
53
+ end
54
+ end
55
+
56
+ def inspect = "#<#{self.class.name}>"
57
+
58
+ # A generation is dropped WINDOW seconds after the one after it began,
59
+ # so a record outlives WINDOW seconds; a clock that went back drops
60
+ # nothing.
61
+ private def rotate(now)
62
+ elapsed = now - @rotated_at
63
+ return if elapsed < WINDOW
64
+ @previous = elapsed < 2 * WINDOW ? @current : {}
65
+ @current = {}
66
+ @rotated_at = now
67
+ end
68
+ end
69
+
70
+ # A record that the Ractors of one process share: `start` begins a
71
+ # Ractor that keeps a Memory and answers each check sent to it, and the
72
+ # Shared it gives, which can itself be shared, sends them. A check waits
73
+ # TIMEOUT seconds at most for the answer, as a Ractor::Port waits with
74
+ # no limit of its own and is not woken by closing it; one not answered
75
+ # in time, or that cannot reach the record, is :unavailable. What the
76
+ # record raises for a check is :unavailable too, so it answers each.
77
+ class Shared
78
+ TIMEOUT = 0.1
79
+ STOP = :stop
80
+
81
+ # A Shared and the Ractor of its record, which `stop` ends.
82
+ def self.start(now:, warmup: true)
83
+ out = Ractor::Port.new
84
+ ractor = Ractor.new(out, now, warmup) do |out, now, warmup|
85
+ requests = Ractor::Port.new
86
+ out.send(requests)
87
+ memory = Memory.new(now:, warmup:)
88
+ loop do
89
+ request = requests.receive
90
+ break if request == STOP
91
+ binder, expires_at, at, reply = request
92
+ result = begin
93
+ memory.check(binder, expires_at:, now: at)
94
+ rescue StandardError
95
+ :unavailable
96
+ end
97
+ begin
98
+ reply.send(result)
99
+ rescue Ractor::ClosedError
100
+ nil
101
+ end
102
+ end
103
+ end
104
+ [new(out.receive), ractor]
105
+ end
106
+
107
+ def initialize(requests)
108
+ @requests = requests
109
+ freeze
110
+ end
111
+
112
+ def check(binder, expires_at:, now:)
113
+ reply = Ractor::Port.new
114
+ @requests.send([binder, expires_at, now, reply])
115
+ timer = Thread.new do
116
+ sleep TIMEOUT
117
+ reply.send(:unavailable)
118
+ rescue Ractor::ClosedError
119
+ nil
120
+ end
121
+ reply.receive
122
+ rescue Ractor::ClosedError
123
+ :unavailable
124
+ ensure
125
+ timer&.kill
126
+ reply&.close
127
+ end
128
+
129
+ # Ends the record; checks from then are :unavailable.
130
+ def stop
131
+ @requests.send(STOP)
132
+ rescue Ractor::ClosedError
133
+ nil
134
+ end
135
+
136
+ def inspect = "#<#{self.class.name}>"
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "crypto"
4
+
5
+ module Raiha::TLS
6
+ # A TLS 1.3 cipher suite: the AEAD and hash it names, and how much one key
7
+ # may be used before it has to be updated.
8
+ #
9
+ # The usage limits differ by transport. Over TCP they come from RFC 9846
10
+ # ("Limits on Key Usage"), which counts full-size records and sets no
11
+ # integrity limit because a TLS connection ends at the first forgery. Over
12
+ # QUIC they come from RFC 9001 ("Limits on AEAD Usage"), which counts
13
+ # packets and also limits failed decryptions. nil means no limit.
14
+ #
15
+ # The hash is `hash_algorithm`, not `hash`, so that `Object#hash` still
16
+ # works and a suite can be a Hash key.
17
+ class CipherSuite < Data.define(:id, :name, :hash_algorithm, :aead, :key_length, :iv_length, :tag_length, :limits)
18
+ Limits = Data.define(:confidentiality, :integrity)
19
+
20
+ def hash_length = Crypto.hash_length(hash_algorithm)
21
+
22
+ def confidentiality_limit(transport) = limits.fetch(transport).confidentiality
23
+
24
+ def integrity_limit(transport) = limits.fetch(transport).integrity
25
+
26
+ # 2^24.5 records, rounded down.
27
+ AES_GCM_TCP_CONFIDENTIALITY_LIMIT = 23_726_566
28
+
29
+ AES_GCM_LIMITS = {
30
+ tcp: Limits.new(confidentiality: AES_GCM_TCP_CONFIDENTIALITY_LIMIT, integrity: nil),
31
+ quic: Limits.new(confidentiality: 1 << 23, integrity: 1 << 52)
32
+ }.freeze
33
+
34
+ TLS_AES_128_GCM_SHA256 = new(
35
+ id: 0x1301, name: :TLS_AES_128_GCM_SHA256, hash_algorithm: :sha256, aead: :aes_128_gcm,
36
+ key_length: 16, iv_length: 12, tag_length: 16, limits: AES_GCM_LIMITS
37
+ )
38
+
39
+ TLS_AES_256_GCM_SHA384 = new(
40
+ id: 0x1302, name: :TLS_AES_256_GCM_SHA384, hash_algorithm: :sha384, aead: :aes_256_gcm,
41
+ key_length: 32, iv_length: 12, tag_length: 16, limits: AES_GCM_LIMITS
42
+ )
43
+
44
+ # The record sequence number wraps before any confidentiality limit, and
45
+ # RFC 9001 puts it beyond the 2^62 packets QUIC can send.
46
+ CHACHA20_POLY1305_LIMITS = {
47
+ tcp: Limits.new(confidentiality: nil, integrity: nil),
48
+ quic: Limits.new(confidentiality: nil, integrity: 1 << 36)
49
+ }.freeze
50
+
51
+ TLS_CHACHA20_POLY1305_SHA256 = new(
52
+ id: 0x1303, name: :TLS_CHACHA20_POLY1305_SHA256, hash_algorithm: :sha256, aead: :chacha20_poly1305,
53
+ key_length: 32, iv_length: 12, tag_length: 16, limits: CHACHA20_POLY1305_LIMITS
54
+ )
55
+
56
+ # The suites this implementation can negotiate. The two CCM suites of RFC
57
+ # 9846 are left out; when offered they are ignored like any unknown suite.
58
+ SUITES = [TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256].to_h { |suite| [suite.id, suite] }.freeze
59
+
60
+ def self.find(id) = SUITES[id]
61
+ end
62
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS::Codec
4
+ # A byte string from the peer that cannot be a valid message. `#alert` is the
5
+ # TLS alert to abort the handshake with.
6
+ class Malformed < StandardError
7
+ def alert = :decode_error
8
+ end
9
+
10
+ # Fewer bytes than a length prefix or a fixed-size field says.
11
+ class Truncated < Malformed; end
12
+
13
+ # A vector length outside the bounds of its definition.
14
+ class RangeViolation < Malformed; end
15
+
16
+ # Bytes left over at the end of a vector.
17
+ class TrailingData < Malformed; end
18
+
19
+ # Two extensions of the same type in one extension block.
20
+ class Duplicate < Malformed
21
+ def alert = :illegal_parameter
22
+ end
23
+
24
+ # A known extension in a message it must not appear in.
25
+ class IllegalPlacement < Malformed
26
+ def alert = :illegal_parameter
27
+ end
28
+
29
+ # A field whose value its definition forbids, though it parses.
30
+ class IllegalValue < Malformed
31
+ def alert = :illegal_parameter
32
+ end
33
+
34
+ # A handshake message type this implementation does not know. On the state
35
+ # machine's path `Reassembler#expect` rejects it before parsing, so only
36
+ # direct callers of `Handshake.parse` see this.
37
+ class UnknownMessageType < Malformed
38
+ def alert = :unexpected_message
39
+ end
40
+
41
+ # A value that cannot be written to the wire.
42
+ class EncodeError < StandardError; end
43
+ end
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "error"
4
+
5
+ module Raiha::TLS::Codec
6
+ # A cursor over a byte string. `#vector` hands its block a view that shares
7
+ # the buffer and only narrows `(pos, limit)`, and checks that the block
8
+ # consumed the whole vector. Integers are read with `getbyte`, which YJIT and
9
+ # ZJIT compile far better than `unpack1(offset:)`.
10
+ class Reader
11
+ def initialize(buf, pos = 0, limit = buf.bytesize)
12
+ @buf = buf
13
+ @pos = pos
14
+ @limit = limit
15
+ end
16
+
17
+ def u8
18
+ i = @pos
19
+ raise Truncated if i + 1 > @limit
20
+ @pos = i + 1
21
+ @buf.getbyte(i) #: Integer
22
+ end
23
+
24
+ # The bounds check above guarantees that every `getbyte` below is in range.
25
+ def u16
26
+ i = @pos
27
+ raise Truncated if i + 2 > @limit
28
+ b = @buf
29
+ @pos = i + 2
30
+ (b.getbyte(i) << 8) | b.getbyte(i + 1) # steep:ignore
31
+ end
32
+
33
+ def u24
34
+ i = @pos
35
+ raise Truncated if i + 3 > @limit
36
+ b = @buf
37
+ @pos = i + 3
38
+ (b.getbyte(i) << 16) | (b.getbyte(i + 1) << 8) | b.getbyte(i + 2) # steep:ignore
39
+ end
40
+
41
+ def u32
42
+ i = @pos
43
+ raise Truncated if i + 4 > @limit
44
+ b = @buf
45
+ @pos = i + 4
46
+ (b.getbyte(i) << 24) | (b.getbyte(i + 1) << 16) | (b.getbyte(i + 2) << 8) | b.getbyte(i + 3) # steep:ignore
47
+ end
48
+
49
+ # A frozen BINARY copy of the next `n` bytes.
50
+ def bytes(n)
51
+ i = @pos
52
+ raise Truncated if i + n > @limit
53
+ @pos = i + n
54
+ @buf.byteslice(i, n).force_encoding(Encoding::BINARY).freeze # steep:ignore
55
+ end
56
+
57
+ # `opaque field<min..max>` with a `len_bytes`-byte length prefix.
58
+ def opaque(len_bytes, max:, min: 0)
59
+ bytes(read_length(len_bytes, min, max))
60
+ end
61
+
62
+ # Yields a view over the vector's contents, raises TrailingData if the
63
+ # block leaves any of it unread, and returns what the block returns.
64
+ def vector(len_bytes, max:, min: 0)
65
+ len = read_length(len_bytes, min, max)
66
+ i = @pos
67
+ raise Truncated if i + len > @limit
68
+ sub = Reader.new(@buf, i, i + len)
69
+ result = yield sub
70
+ sub.finish!
71
+ @pos = i + len
72
+ result
73
+ end
74
+
75
+ def eof? = @pos >= @limit
76
+
77
+ def remaining = @limit - @pos
78
+
79
+ def finish!
80
+ raise TrailingData unless @pos == @limit
81
+ end
82
+
83
+ private def read_length(len_bytes, min, max)
84
+ len =
85
+ case len_bytes
86
+ when 1 then u8
87
+ when 2 then u16
88
+ when 3 then u24
89
+ else raise ArgumentError, "length prefix must be 1 to 3 bytes: #{len_bytes}"
90
+ end
91
+ raise RangeViolation unless min <= len && len <= max
92
+ len
93
+ end
94
+ end
95
+ end