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,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::QUIC
4
+ module Wire
5
+ # A packet with a packet number under packet protection (RFC 9001
6
+ # "Packet Protection"): the payload sealed by the AEAD with the header
7
+ # up to the packet number as associated data, then header protection
8
+ # over the low bits of the first byte and the packet number, with a
9
+ # mask from a sample of the ciphertext.
10
+ module Packet
11
+ # The sample starts this many bytes into the packet number, as if
12
+ # the packet number were always 4 bytes long.
13
+ SAMPLE_OFFSET = 4
14
+
15
+ # The packet with `header`, `packet_number` in `packet_number_length`
16
+ # bytes, and `payload` (frames, padded already), protected by `keys`.
17
+ def self.seal(header, packet_number:, packet_number_length:, payload:, keys:)
18
+ encoded_number = PacketNumber.encode(packet_number, packet_number_length)
19
+ if packet_number_length + payload.bytesize < SAMPLE_OFFSET
20
+ raise ArgumentError, "#{payload.bytesize} bytes of payload after a #{packet_number_length}-byte packet number leave no room for the sample"
21
+ end
22
+ writer = Writer.new.u8(header.first_byte(packet_number_length))
23
+ header.write_fields(writer, length: packet_number_length + payload.bytesize + keys.aead.tag_length)
24
+ number_offset = writer.bytesize
25
+ packet = writer.bytes(encoded_number).to_s
26
+ sealed = keys.aead.seal(packet_number:, header: packet, plaintext: payload)
27
+ mask = keys.header_protection.mask(sealed.byteslice(SAMPLE_OFFSET - packet_number_length, Crypto::HeaderProtection::SAMPLE_LENGTH)) # steep:ignore
28
+ packet.setbyte(0, packet.unpack1("C") ^ (mask.unpack1("C") & header.protected_bits))
29
+ packet_number_length.times do |i|
30
+ packet.setbyte(number_offset + i, packet.unpack1("C", offset: number_offset + i) ^ mask.unpack1("C", offset: 1 + i))
31
+ end
32
+ packet << sealed
33
+ end
34
+
35
+ # The packet at `offset` in `datagram`, as far as it reads with its
36
+ # protection on: the header, where the packet number starts, and where
37
+ # the packet ends, which is where a packet coalesced after it starts.
38
+ # A short header packet runs to the end of the datagram, and its
39
+ # connection ID is `dcid_length` bytes. Bytes that do not make such a
40
+ # packet raise Malformed, and the packet is to be dropped.
41
+ #
42
+ # A Version Negotiation packet comes back as VersionNegotiation, a
43
+ # Retry packet as Retry, and a long header packet in a version not
44
+ # supported as UnsupportedVersion. The first two fill the datagram.
45
+ # The versions supported are `versions`, those the endpoint is
46
+ # configured with.
47
+ def self.parse(datagram, offset: 0, dcid_length:, versions:)
48
+ reader = Reader.new(datagram, offset)
49
+ first = reader.u8
50
+ if first & 0x80 == 0
51
+ raise Malformed, "the fixed bit is clear" if first & 0x40 == 0
52
+ header = ShortHeader.new(dcid: reader.bytes(dcid_length), spin: first & 0x20 != 0, key_phase: nil)
53
+ end_offset = datagram.bytesize
54
+ else
55
+ number = reader.u32
56
+ # Version 0 is Version Negotiation, whatever the other bits say.
57
+ return VersionNegotiation.read(reader) if number.zero?
58
+ version = versions.find { |candidate| candidate.number == number } or return UnsupportedVersion.read(number, reader)
59
+ raise Malformed, "the fixed bit is clear" if first & 0x40 == 0
60
+ dcid = connection_id(reader)
61
+ scid = connection_id(reader)
62
+ case type = version.packet_type((first >> 4) & 0x03)
63
+ when :retry then return Retry.read(reader, version:, dcid:, scid:, unused: first & 0x0f)
64
+ else header = LongHeader.new(type:, version:, dcid:, scid:, token: type == :initial ? reader.bytes(reader.varint) : EMPTY)
65
+ end
66
+ length = reader.varint
67
+ raise Truncated, "the Length field says #{length} bytes, #{reader.remaining} are left" if length > reader.remaining
68
+ end_offset = reader.offset + length
69
+ end
70
+ number_offset = reader.offset
71
+ if end_offset - number_offset < SAMPLE_OFFSET + Crypto::HeaderProtection::SAMPLE_LENGTH
72
+ raise Malformed, "#{end_offset - number_offset} bytes after the header are too few for a sample"
73
+ end
74
+ Parsed.new(header:, datagram:, offset:, number_offset:, end_offset:)
75
+ end
76
+
77
+ private_class_method def self.connection_id(reader)
78
+ length = reader.u8
79
+ raise Malformed, "a connection ID of #{length} bytes" if length > CONNECTION_ID_MAX_LENGTH
80
+ reader.bytes(length)
81
+ end
82
+
83
+ # A packet as `parse` read it, both protections still on: `header`
84
+ # (a short header without its key phase yet), and where in `datagram`
85
+ # the packet starts, its packet number starts, and it ends.
86
+ class Parsed < Data.define(:header, :datagram, :offset, :number_offset, :end_offset)
87
+ # Takes header protection off with `header_protection`. The packet
88
+ # number is decoded against `largest`, the largest one processed in
89
+ # this packet number space (nil when none), and a short header gets
90
+ # its key phase, which tells the keys for the payload.
91
+ def unmask(header_protection, largest:)
92
+ mask = header_protection.mask(datagram.byteslice(number_offset + SAMPLE_OFFSET, Crypto::HeaderProtection::SAMPLE_LENGTH)) # steep:ignore
93
+ first = datagram.unpack1("C", offset:) ^ (mask.unpack1("C") & header.protected_bits)
94
+ number_length = (first & 0x03) + 1
95
+ header_length = number_offset - offset
96
+ associated_data = datagram.byteslice(offset, header_length + number_length)
97
+ associated_data.setbyte(0, first) # steep:ignore
98
+ truncated = 0
99
+ number_length.times do |i|
100
+ byte = associated_data.unpack1("C", offset: header_length + i) ^ mask.unpack1("C", offset: 1 + i) # steep:ignore
101
+ associated_data.setbyte(header_length + i, byte) # steep:ignore
102
+ truncated = (truncated << 8) | byte
103
+ end
104
+ Unmasked.new(
105
+ header: header.unmasked(first),
106
+ packet_number: PacketNumber.decode(truncated, length: number_length, largest:),
107
+ reserved: first & header.reserved_bits,
108
+ associated_data:, # steep:ignore
109
+ ciphertext: datagram.byteslice(number_offset + number_length, end_offset - number_offset - number_length) # steep:ignore
110
+ )
111
+ end
112
+ end
113
+
114
+ # A packet with header protection off and the payload still sealed:
115
+ # the header, the packet number, the value of the reserved bits, the
116
+ # header as the AEAD's associated data, and the ciphertext.
117
+ class Unmasked < Data.define(:header, :packet_number, :reserved, :associated_data, :ciphertext)
118
+ # The payload, or nil when `aead` does not open it, which is not an
119
+ # error: the packet is dropped. A packet that opens with reserved
120
+ # bits other than zero is a protocol violation (RFC 9000 "Long Header
121
+ # Packets", "Short Header Packets").
122
+ def open(aead)
123
+ payload = aead.open(packet_number:, header: associated_data, ciphertext:) or return nil
124
+ raise Malformed.new("the reserved bits are #{reserved}", code: ErrorCode::PROTOCOL_VIOLATION) unless reserved.zero?
125
+ payload
126
+ end
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::QUIC
4
+ module Wire
5
+ # RFC 9000 "Packet Number Encoding and Decoding": a packet carries only
6
+ # the low 1 to 4 bytes of its number, and the receiver picks the full
7
+ # number nearest to the one after the largest it has processed.
8
+ module PacketNumber
9
+ MAX = (1 << 62) - 1
10
+
11
+ # The fewest bytes for `packet_number` whose window covers twice the
12
+ # packets not yet acknowledged, the new one included (RFC 9000
13
+ # appendix A.2). `largest_acked` is nil when the peer has acknowledged
14
+ # none in this packet number space.
15
+ def self.length(packet_number, largest_acked:)
16
+ unacked = largest_acked ? packet_number - largest_acked : packet_number + 1
17
+ raise ArgumentError, "packet #{packet_number} was acknowledged already" unless unacked.positive?
18
+ length = ((2 * unacked - 1).bit_length + 7) / 8
19
+ raise ArgumentError, "#{unacked} unacknowledged packets need #{length} bytes" if length > 4
20
+ length
21
+ end
22
+
23
+ # The low `length` bytes of `packet_number`.
24
+ def self.encode(packet_number, length) # steep:ignore
25
+ raise ArgumentError, "a packet number field is 1 to 4 bytes, not #{length}" unless length.between?(1, 4)
26
+ [packet_number & 0xffff_ffff].pack("N").byteslice(4 - length, length)
27
+ end
28
+
29
+ # The full packet number of a packet whose `length`-byte field reads
30
+ # `truncated` (RFC 9000 appendix A.3). `largest` is the largest
31
+ # packet number processed in this packet number space, nil when none.
32
+ def self.decode(truncated, length:, largest:)
33
+ expected = largest ? largest + 1 : 0
34
+ window = 1 << (8 * length)
35
+ half_window = window / 2
36
+ candidate = (expected & ~(window - 1)) | truncated
37
+ if candidate <= expected - half_window && candidate <= MAX - window
38
+ candidate + window
39
+ elsif candidate > expected + half_window && candidate >= window
40
+ candidate - window
41
+ else
42
+ candidate
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::QUIC
4
+ module Wire
5
+ # A Retry packet (RFC 9000 "Retry Packet") and its integrity tag (RFC
6
+ # 9001 "Retry Packet Integrity"): AES-128-GCM under the version's fixed
7
+ # key and nonce over no plaintext, with the packet prefixed by the
8
+ # Destination Connection ID of the client's Initial as associated data.
9
+ # Only who saw that Initial can make a Retry the client takes.
10
+ #
11
+ # A Retry built to be sent has no tag until `seal` computes it.
12
+ class Retry < Data.define(:version, :dcid, :scid, :token, :unused, :tag)
13
+ TAG_LENGTH = 16
14
+ # The four low bits of the first byte are unused and arbitrary. These
15
+ # are set, as in RFC 9001 appendix A.4.
16
+ UNUSED = 0x0f
17
+
18
+ def initialize(version:, dcid:, scid:, token:, unused: UNUSED, tag: nil)
19
+ [dcid, scid].each do |cid|
20
+ raise ArgumentError, "a connection ID has #{CONNECTION_ID_MAX_LENGTH} bytes at most, not #{cid.bytesize}" if cid.bytesize > CONNECTION_ID_MAX_LENGTH
21
+ end
22
+ raise ArgumentError, "a Retry carries a token" if token.empty?
23
+ raise ArgumentError, "the unused bits are four, not #{unused}" unless unused.between?(0, 0x0f)
24
+ super
25
+ end
26
+
27
+ # The packet, with the tag for an Initial whose Destination
28
+ # Connection ID was `original_dcid`.
29
+ # The rest of a Retry packet after its connection IDs, from `reader`:
30
+ # the token and the tag. A client drops a Retry without a token (RFC
31
+ # 9000 "Retry Packet").
32
+ def self.read(reader, version:, dcid:, scid:, unused:)
33
+ token_length = reader.remaining - TAG_LENGTH
34
+ raise Malformed, "a Retry without a token" unless token_length.positive?
35
+ new(version:, dcid:, scid:, token: reader.bytes(token_length), unused:, tag: reader.bytes(TAG_LENGTH))
36
+ end
37
+
38
+ def seal(original_dcid) = body + integrity.seal(packet_number: 0, header: pseudo_packet(original_dcid), plaintext: EMPTY)
39
+
40
+ # Whether the tag is right for an Initial whose Destination Connection
41
+ # ID was `original_dcid`; a client drops a Retry whose tag is not.
42
+ # Opening the tag with the AEAD compares it in constant time.
43
+ def authentic?(original_dcid)
44
+ return false unless tag
45
+ !integrity.open(packet_number: 0, header: pseudo_packet(original_dcid), ciphertext: tag).nil?
46
+ end
47
+
48
+ # The packet up to the tag.
49
+ private def body
50
+ Writer.new.u8(0xc0 | (version.type_bits(:retry) << 4) | unused).u32(version.number)
51
+ .u8(dcid.bytesize).bytes(dcid).u8(scid.bytesize).bytes(scid).bytes(token).to_s
52
+ end
53
+
54
+ # The Retry Pseudo-Packet: what the tag covers.
55
+ private def pseudo_packet(original_dcid) = Writer.new.u8(original_dcid.bytesize).bytes(original_dcid).bytes(body).to_s
56
+
57
+ private def integrity
58
+ Crypto::AEAD.new(suite: Raiha::TLS::CipherSuite::TLS_AES_128_GCM_SHA256, key: version.retry_key, iv: version.retry_nonce)
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::QUIC
4
+ module Wire
5
+ # A Version Negotiation packet (RFC 9000 "Version Negotiation Packet"):
6
+ # a server's answer to a packet in a version it does not support, with
7
+ # the version numbers it does. It belongs to no version, so its
8
+ # connection IDs may have up to 255 bytes (RFC 8999), and it fills the
9
+ # datagram.
10
+ class VersionNegotiation < Data.define(:dcid, :scid, :versions)
11
+ # The bit that is the fixed bit in version 1 is set, so that the
12
+ # packet does not look like another protocol sharing the port; the
13
+ # rest of the byte is unused.
14
+ FIRST_BYTE = 0xc0
15
+ INVARIANT_CONNECTION_ID_MAX_LENGTH = 255
16
+
17
+ def initialize(dcid:, scid:, versions:)
18
+ [dcid, scid].each do |cid|
19
+ raise ArgumentError, "a connection ID has #{INVARIANT_CONNECTION_ID_MAX_LENGTH} bytes at most" if cid.bytesize > INVARIANT_CONNECTION_ID_MAX_LENGTH
20
+ end
21
+ raise ArgumentError, "a version is a 32-bit number" unless versions.all? { |version| version.between?(0, 0xffff_ffff) }
22
+ super
23
+ end
24
+
25
+ # The rest of the packet after the Version field, from `reader`.
26
+ def self.read(reader)
27
+ dcid = reader.bytes(reader.u8)
28
+ scid = reader.bytes(reader.u8)
29
+ raise Malformed, "#{reader.remaining} bytes are no list of 4-byte versions" unless (reader.remaining % 4).zero?
30
+ new(dcid:, scid:, versions: Array.new(reader.remaining / 4) { reader.u32 })
31
+ end
32
+
33
+ def encode
34
+ writer = Writer.new.u8(FIRST_BYTE).u32(0).u8(dcid.bytesize).bytes(dcid).u8(scid.bytesize).bytes(scid)
35
+ versions.each { |version| writer.u32(version) }
36
+ writer.to_s
37
+ end
38
+ end
39
+
40
+ # A long header packet in a version this end does not support, read
41
+ # only as far as what every version shares (RFC 8999): enough for a
42
+ # server to answer it with Version Negotiation.
43
+ class UnsupportedVersion < Data.define(:version, :dcid, :scid)
44
+ # The connection IDs after the Version field, from `reader`.
45
+ def self.read(version, reader) = new(version:, dcid: reader.bytes(reader.u8), scid: reader.bytes(reader.u8))
46
+
47
+ # The Version Negotiation that answers this packet with `versions`,
48
+ # its connection IDs echoed in each other's places (RFC 9000 "Version
49
+ # Negotiation Packet").
50
+ def negotiation(versions) = VersionNegotiation.new(dcid: scid, scid: dcid, versions:)
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "wire/codec"
4
+ require_relative "wire/packet_number"
5
+ require_relative "wire/header"
6
+ require_relative "wire/packet"
7
+ require_relative "wire/version_negotiation"
8
+ require_relative "wire/retry"
9
+ require_relative "wire/frame"
data/lib/raiha/quic.rb ADDED
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "tls"
4
+
5
+ # QUIC. May refer to the TLS layer.
6
+ module Raiha::QUIC
7
+ end
8
+
9
+ require_relative "quic/error"
10
+ require_relative "quic/error_code"
11
+ require_relative "quic/transmit"
12
+ require_relative "quic/stats"
13
+ require_relative "quic/event"
14
+ require_relative "quic/tracer"
15
+ require_relative "quic/version"
16
+ require_relative "quic/wire"
17
+ require_relative "quic/crypto"
18
+ require_relative "quic/transport_parameters"
19
+ require_relative "quic/remembered_transport_parameters"
20
+ require_relative "quic/session"
21
+ require_relative "quic/token"
22
+ require_relative "quic/negotiation"
23
+ require_relative "quic/congestion"
24
+ require_relative "quic/recovery"
25
+ require_relative "quic/pacer"
26
+ require_relative "quic/mtu_search"
27
+ require_relative "quic/path"
28
+ require_relative "quic/config"
29
+ require_relative "quic/retry_token"
30
+ require_relative "quic/new_token"
31
+ require_relative "quic/stateless_reset"
32
+ require_relative "quic/packet_protection"
33
+ require_relative "quic/ranges"
34
+ require_relative "quic/crypto_stream"
35
+ require_relative "quic/tls_binding"
36
+ require_relative "quic/scheduler"
37
+ require_relative "quic/streams"
38
+ require_relative "quic/datagrams"
39
+ require_relative "quic/kept_packets"
40
+ require_relative "quic/peer_connection_ids"
41
+ require_relative "quic/issued_connection_ids"
42
+ require_relative "quic/connection_ids"
43
+ require_relative "quic/connection"
44
+ require_relative "quic/route"
45
+ require_relative "quic/endpoint"
46
+ require_relative "quic/qlog"
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+
5
+ module Raiha::Runtime
6
+ # How a client of the runtime finds the addresses of a host, and the
7
+ # socket it tries each from, apart from how it waits for the handshake.
8
+ # A client of fibers and one of threads try them alike.
9
+ module Addresses
10
+ # [address, port] of `host` for UDP, each once, in the order the
11
+ # resolver gives them; an IPv4-mapped address as the IPv4 address it
12
+ # maps, which a socket of IPv6 alone cannot send to.
13
+ def self.resolve(host, port)
14
+ Addrinfo.getaddrinfo(host, port, nil, :DGRAM).map do |info|
15
+ [UDP.unmapped(info.ip_address), info.ip_port] #: UDP::address
16
+ end.uniq
17
+ end
18
+
19
+ # A socket for a connection to `address`, and `config` for the address
20
+ # families it can send to: one bound to "::", which sends to IPv4 too,
21
+ # unless IPv4 does not come to it, when it is kept for IPv6 alone; for
22
+ # IPv4 then, and where "::" cannot be bound, one bound to "0.0.0.0".
23
+ def self.bind(address, config)
24
+ udp = UDP.bind("::", 0)
25
+ return [udp, config] if udp.takes_ipv4?
26
+ return [udp, config.with(address_families: %i[ipv6])] if address[0].include?(":")
27
+ udp.close
28
+ [UDP.bind("0.0.0.0", 0), config.with(address_families: %i[ipv4])]
29
+ rescue SystemCallError
30
+ # Without "::" there is no IPv6 to send to `address` by.
31
+ raise if address[0].include?(":")
32
+ [UDP.bind("0.0.0.0", 0), config.with(address_families: %i[ipv4])]
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::Runtime
4
+ # What a server of the runtime decides of the clients that come, apart
5
+ # from how it waits: whether to take one, how many addresses are not
6
+ # validated yet, and the ticket keys of the next connection. A server of
7
+ # fibers and one of threads decide alike.
8
+ module Admission
9
+ # What to do with an Incoming `route`: :refuse once the server is
10
+ # `full`, :retry when the client's address is not validated and the
11
+ # block, how many are not, has reached `max_unvalidated`, :admit
12
+ # otherwise. The block is called only when the address is not
13
+ # validated.
14
+ def self.decide(route, full:, max_unvalidated:)
15
+ return :refuse if full
16
+ return :retry if !route.address_validated && yield >= max_unvalidated
17
+ :admit
18
+ end
19
+
20
+ # How many of the offers `admitted` and of the `connections` taken have
21
+ # addresses not validated, the offers over left out.
22
+ def self.unvalidated(admitted, connections, now)
23
+ admitted.count { |handle| !handle.expired?(now) && !handle.failed? } + connections.count { |connection| !connection.address_validated? }
24
+ end
25
+
26
+ # The Keyring for the connections from `time` on, with the ticket keys
27
+ # of `tls_config` built again once their epoch is over (a
28
+ # TicketKeys.ratchet); nil while they stay. A `keyring` of another
29
+ # Config is left for the handshake to refuse.
30
+ def self.advance_ticket_keys(tls_config, keyring, time)
31
+ keys = tls_config.ticket_keys or return nil
32
+ at = keys.next_advance_at or return nil
33
+ return nil if time < at || !keyring.config.equal?(tls_config)
34
+ keyring.with_ticket_keys(keys.advance(now: time))
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,190 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+ require "securerandom"
5
+ require_relative "../http3/session"
6
+
7
+ module Raiha::Runtime
8
+ # No address of a host took a connection. `errors` has, for each address
9
+ # tried, [address, what failed]: the QUIC::ClosedError of a connection
10
+ # that closed or ran out of time, or the error of a name that did not
11
+ # resolve.
12
+ class ConnectError < StandardError
13
+ attr_reader :errors
14
+
15
+ def initialize(host, port, errors)
16
+ @errors = errors
17
+ tried = errors.map { |address, error| "#{address.inspect}: #{error.message}" }
18
+ super("could not connect to #{host}:#{port} (#{tried.join("; ")})")
19
+ end
20
+ end
21
+
22
+ # The client of the runtime. Client.connect finds the addresses of a
23
+ # host and connects to each in turn, a socket of its own for each, until
24
+ # one completes its handshake within `connect_timeout` seconds, then gives
25
+ # the block a Session of the connection. There is no discovery of HTTP/3
26
+ # (Alt-Svc, HTTPS records) and no fallback to TCP: the host and port are
27
+ # taken to speak QUIC. The block's value is returned.
28
+ #
29
+ # Once the block is over, what the streams sent is let be acknowledged,
30
+ # until three PTOs go with no more of it acknowledged or 30 seconds in
31
+ # all, so that a response written last is not cut short, and the
32
+ # connection closes with the application's error 0, or that of the
33
+ # protocol attached to the Session: H3_NO_ERROR for HTTP/3. The closing
34
+ # period is not waited out: the CONNECTION_CLOSE goes, and the socket
35
+ # closes.
36
+ #
37
+ # With `qlog_dir`, each connection tried has a qlog there, named by the
38
+ # time it began.
39
+ #
40
+ # A `config` without max_transmit_size takes UDP::MAX_TRANSMIT, as the
41
+ # socket sends the datagrams of a Transmit with GSO (UDP.batching), and
42
+ # enable_pmtud false where the socket cannot keep IP from fragmenting
43
+ # (UDP.pmtud), and no ECN on IPv4 where the OS cannot mark it (UDP.ecn).
44
+ #
45
+ # Each socket is bound to "::", which sends to IPv4 too, so that a
46
+ # connection can move to a server's preferred address of either family.
47
+ # Where IPv4 does not come to it, as on OpenBSD, it is kept for a server
48
+ # of IPv6, and the connection takes IPv6 addresses alone; for one of IPv4,
49
+ # and where IPv6 is off and "::" cannot be bound, the socket is bound to
50
+ # "0.0.0.0" and the connection takes IPv4 addresses alone
51
+ # (Config#address_families). Without "::", an address of IPv6 fails at
52
+ # once and the next is tried. The address a datagram goes from is the
53
+ # OS's to choose.
54
+ #
55
+ # With `session`, a ticket an earlier connection's Session#tickets gave,
56
+ # the first connection tried resumes it, and with `token`, one of its
57
+ # Session#tokens, its Initials carry it, so that the server need not
58
+ # validate the address again. Each is for one connection, which those
59
+ # tried after the first do not reuse (RFC 9846 "Client and Server
60
+ # Tracking Prevention", RFC 9000 "Address Validation for Future
61
+ # Connections"); once used, the application drops it. A ticket of HTTP3::Client#tickets, an
62
+ # HTTP3::Session, resumes its QUIC::Session, and HTTP/3 keeps to its
63
+ # SETTINGS while 0-RTT goes.
64
+ #
65
+ # With `early_data` true as well, and a ticket that allows it, the
66
+ # connection sends what the block writes before its handshake completes,
67
+ # in 0-RTT: the block is given the Session at once. A connection given to
68
+ # the block is not tried at another address, as what it sent in 0-RTT is
69
+ # not to be sent again unless the application says so (RFC 9846 "Replay
70
+ # Attacks on 0-RTT"): one that fails raises QUIC::ClosedError in the
71
+ # block. An attacker may replay 0-RTT, so only what is safe to repeat
72
+ # goes before Session#wait_handshake.
73
+ class Client
74
+ CONNECT_TIMEOUT = 5.0
75
+
76
+ def self.connect(host, port, config:, tls_config:, keyring:, server_name: host, connect_timeout: CONNECT_TIMEOUT, qlog_dir: nil,
77
+ session: nil, token: nil, early_data: false, &)
78
+ new(config:, tls_config:, keyring:, connect_timeout:, qlog_dir:).connect(host, port, server_name:, session:, token:, early_data:, &)
79
+ end
80
+
81
+ def initialize(config:, tls_config:, keyring:, connect_timeout: CONNECT_TIMEOUT, qlog_dir: nil)
82
+ @config = UDP.ecn(UDP.pmtud(UDP.batching(config)))
83
+ @tls_config = tls_config
84
+ @keyring = keyring
85
+ @connect_timeout = connect_timeout
86
+ @session = nil #: Session?
87
+ @deadline = nil #: Float?
88
+ @qlog = qlog_dir && Qlog.new(qlog_dir)
89
+ @trace = nil #: Qlog::Pending?
90
+ end
91
+
92
+ def connect(host, port, server_name: host, session: nil, token: nil, early_data: false)
93
+ raise Error::Usage, "the runtime waits through a Fiber scheduler; this thread has none" unless Fiber.scheduler
94
+ errors = [] #: Array[[UDP::address | String, StandardError]]
95
+ addresses = begin
96
+ resolve(host, port)
97
+ rescue SocketError => error
98
+ raise ConnectError.new(host, port, [[host, error]])
99
+ end
100
+ addresses.each do |address|
101
+ begin
102
+ driver, opened = attempt(address, server_name, session:, token:, early_data:)
103
+ rescue SystemCallError => error
104
+ errors << [address, error]
105
+ next
106
+ end
107
+ session = token = nil
108
+ connected = false
109
+ begin
110
+ driver.start
111
+ opened.wait_ready
112
+ connected = true
113
+ rescue Raiha::QUIC::ClosedError => error
114
+ errors << [address, error]
115
+ next
116
+ ensure
117
+ # However the attempt is left, a task stopped included.
118
+ driver.stop unless connected
119
+ end
120
+ begin
121
+ return yield opened
122
+ ensure
123
+ finish(driver, opened)
124
+ end
125
+ end
126
+ raise ConnectError.new(host, port, errors)
127
+ end
128
+
129
+ # The driver's owner: a client has no Route to take.
130
+ def route(route, now) = nil
131
+
132
+ # The driver's turn: the Session's, and the end of the time to connect.
133
+ def turn(now)
134
+ session = @session or return
135
+ session.turn
136
+ @qlog&.flush
137
+ deadline = @deadline or return
138
+ return @deadline = nil if session.connection.handshake_complete?
139
+ return if now < deadline
140
+ @deadline = nil
141
+ session.connection.close(error_code: Raiha::QUIC::ErrorCode::NO_ERROR, reason: "no handshake in #{@connect_timeout} seconds",
142
+ application: false, now:)
143
+ end
144
+
145
+ def next_timeout = @deadline
146
+
147
+ def stopped(failure)
148
+ @session&.abort(failure)
149
+ @trace&.over!
150
+ @qlog&.flush
151
+ end
152
+
153
+ # Closes the connection once what was sent is acknowledged, or three
154
+ # PTOs have gone with no more of it acknowledged, or 30 seconds in all;
155
+ # sends the CONNECTION_CLOSE, of a close in the block as well; and stops
156
+ # the driver.
157
+ private def finish(driver, session)
158
+ session.close_when_acknowledged unless session.closed?
159
+ driver.flush
160
+ rescue Raiha::QUIC::ClosedError
161
+ nil
162
+ ensure
163
+ driver.stop
164
+ end
165
+
166
+ # The addresses to try, as Addresses.resolve finds them.
167
+ private def resolve(host, port) = Addresses.resolve(host, port)
168
+
169
+ # A connection to `address` on a socket of its own, its handshake to
170
+ # begin once the driver starts: [driver, session].
171
+ private def attempt(address, server_name, session:, token:, early_data:)
172
+ made = false
173
+ udp, config = Addresses.bind(address, @config)
174
+ endpoint = Raiha::QUIC::Endpoint.client(config:, random: SecureRandom, time: Time.now, now: Driver.clock)
175
+ driver = Driver.new(endpoint, udp, self)
176
+ tracer, @trace = @qlog&.trace(:client, Time.now.utc.strftime("%Y%m%dT%H%M%S.%6N"), tls_config: @tls_config)
177
+ quic = session.is_a?(Raiha::HTTP3::Session) ? session.quic : session
178
+ connection = endpoint.connect(tls_config: @tls_config, keyring: @keyring, server_name:, remote: address, now: Driver.clock, tracer:,
179
+ session: quic, token:, early_data:)
180
+ opened = @session = Session.new(connection, driver, role: :client, tracer:, server_name:, resumed: session)
181
+ @deadline = Driver.clock + @connect_timeout
182
+ made = true
183
+ [driver, opened] #: [Driver, Session]
184
+ ensure
185
+ # A connection that cannot be made, a Keyring for another Config say,
186
+ # leaves no socket behind.
187
+ udp&.close unless made
188
+ end
189
+ end
190
+ end