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,180 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../runtime"
4
+
5
+ module Raiha::Runtime
6
+ # Rack 3 over the server of HTTP/3 of the runtime:
7
+ #
8
+ # server.run(&Raiha::Runtime::Rack.new(app))
9
+ #
10
+ # Each request is made an env, its body read as it comes through
11
+ # rack.input, and what the application returns is written as the
12
+ # response: a body that answers `each` chunk by chunk, one that answers
13
+ # `call` (a streaming body) with a stream that reads the request and
14
+ # writes the response. A header value of an Array goes as a field line
15
+ # of each. The trailer fields, the priority and the rest of the request
16
+ # are in env["raiha.request"]. It depends on no rack gem.
17
+ #
18
+ # A header field whose name has an underscore is left out of the env, as
19
+ # it would be taken for the one with a hyphen there (HTTP_X_FORWARDED_FOR
20
+ # of x_forwarded_for), and HTTP_HOST, SERVER_NAME and SERVER_PORT come
21
+ # once from :authority, or the host field when there is none. A request
22
+ # of a scheme other than http and https is answered with 400.
23
+ class Rack
24
+ SCHEMES = %w[http https].freeze
25
+
26
+ # rack.input: the body of the request as it comes, read as an IO is.
27
+ class Input
28
+ def initialize(body)
29
+ @body = body
30
+ @buffer = "".b
31
+ @ended = false
32
+ end
33
+
34
+ # With `length`, up to that many bytes, nil at the end; without, all
35
+ # that is left, "" at the end.
36
+ def read(length = nil, outbuf = nil)
37
+ fill until @ended || (length && @buffer.bytesize >= length)
38
+ data = length ? @buffer.byteslice(0, length) || "".b : @buffer
39
+ @buffer = @buffer.byteslice(data.bytesize..) || "".b
40
+ return nil if length && length.positive? && data.empty?
41
+ outbuf ? outbuf.replace(data) : data
42
+ end
43
+
44
+ # The next line, nil at the end.
45
+ def gets
46
+ fill until @ended || @buffer.include?("\n")
47
+ return nil if @buffer.empty?
48
+ line = @buffer.byteslice(0, (@buffer.index("\n") || (@buffer.bytesize - 1)) + 1) || "".b
49
+ @buffer = @buffer.byteslice(line.bytesize..) || "".b
50
+ line
51
+ end
52
+
53
+ def each
54
+ while (line = gets)
55
+ yield line
56
+ end
57
+ end
58
+
59
+ def close = nil
60
+
61
+ private def fill
62
+ chunk = @body.read_chunk
63
+ chunk ? @buffer << chunk : @ended = true
64
+ end
65
+ end
66
+
67
+ # The stream a streaming body is called with: it reads the request and
68
+ # writes the response, which ends at `close_write` though the body
69
+ # goes on.
70
+ class Stream
71
+ def initialize(input, output)
72
+ @input = input
73
+ @output = output
74
+ @read_closed = false
75
+ @write_closed = false
76
+ end
77
+
78
+ def read(...) = @input.read(...)
79
+
80
+ def write(data)
81
+ raise IOError, "the stream is closed for writing" if @write_closed
82
+ @output.write(data)
83
+ end
84
+
85
+ def <<(data)
86
+ write(data)
87
+ self
88
+ end
89
+
90
+ def flush = self
91
+
92
+ def close_read
93
+ @read_closed = true
94
+ nil
95
+ end
96
+
97
+ def close_write
98
+ @write_closed = true
99
+ @output.close
100
+ nil
101
+ end
102
+
103
+ def close
104
+ close_read
105
+ close_write
106
+ end
107
+
108
+ def closed? = @read_closed && @write_closed
109
+ end
110
+
111
+ # What the body of a response to HEAD is written to: nothing, as such a
112
+ # response has no content (RFC 9110 "HEAD").
113
+ class Discard
114
+ def write(data) = data.bytesize
115
+
116
+ def <<(_data) = self
117
+
118
+ def close = nil
119
+ end
120
+
121
+ def initialize(app)
122
+ @app = app
123
+ end
124
+
125
+ def to_proc = method(:call).to_proc
126
+
127
+ # Answers `request` with what the application gives for its env.
128
+ def call(request)
129
+ return request.respond(400) unless SCHEMES.include?(request.scheme)
130
+ env = env(request)
131
+ status, headers, body = @app.call(env)
132
+ # A body of Rack answers `each` or `call`, which steep does not narrow
133
+ # to by `respond_to?`.
134
+ request.respond(status, fields(headers)) do |response|
135
+ output = request.method == "HEAD" ? Discard.new : response
136
+ if body.respond_to?(:each)
137
+ body.each { |chunk| output << chunk } # steep:ignore
138
+ else
139
+ body.call(Stream.new(env.fetch("rack.input"), output)) # steep:ignore
140
+ end
141
+ end
142
+ ensure
143
+ body.close if body.respond_to?(:close) # steep:ignore
144
+ end
145
+
146
+ private def env(request)
147
+ authority = request.authority || request.headers.find { |name, _| name == "host" }&.last || ""
148
+ host, port = authority.match(/\A(\[[^\]]*\]|[^:]*)(?::(\d+))?\z/)&.captures
149
+ path, query = request.path.split("?", 2)
150
+ # An authority with no port is of the scheme's (RFC 9110 "http URI
151
+ # Scheme", "https URI Scheme").
152
+ port ||= request.scheme == "http" ? "80" : "443"
153
+ env = {
154
+ "REQUEST_METHOD" => request.method, "SCRIPT_NAME" => "", "PATH_INFO" => path || "", "QUERY_STRING" => query || "",
155
+ "SERVER_NAME" => host || "", "SERVER_PORT" => port, "SERVER_PROTOCOL" => "HTTP/3", "HTTP_HOST" => authority,
156
+ "rack.url_scheme" => request.scheme || "https", "rack.input" => Input.new(request.body), "rack.errors" => $stderr,
157
+ "raiha.request" => request
158
+ } #: Hash[String, String | Input | IO | HTTP3::Request | Array[String]]
159
+ env["rack.protocol"] = [request.protocol] if request.protocol
160
+ request.headers.each do |name, value|
161
+ next if name == "host" || name.include?("_")
162
+ key = { "content-type" => "CONTENT_TYPE", "content-length" => "CONTENT_LENGTH" }.fetch(name) { "HTTP_#{name.upcase.tr("-", "_")}" }
163
+ # Content-Length lines, which HTTP/3 lets come only the same, are one
164
+ # number. Cookie lines are joined with "; " (RFC 9114 "Header
165
+ # Compression"), others with ", ".
166
+ next if key == "CONTENT_LENGTH" && env.key?(key)
167
+ env[key] = env.key?(key) ? "#{env[key]}#{name == "cookie" ? "; " : ", "}#{value}" : value
168
+ end
169
+ env
170
+ end
171
+
172
+ # The field lines of the headers of a response.
173
+ private def fields(headers)
174
+ headers.flat_map do |name, value|
175
+ next [] if name.start_with?("rack.")
176
+ Array(value).map { |line| [name, line.to_s] }
177
+ end
178
+ end
179
+ end
180
+ end
@@ -0,0 +1,334 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module Raiha::Runtime
6
+ # The server of the runtime: an Endpoint on a UDP socket of its own that
7
+ # takes every client up to `max_connections` at a time, refusing more
8
+ # with CONNECTION_REFUSED, and gives the block of `run` the Session of
9
+ # each connection once its handshake completes, in a fiber of its own.
10
+ # Once `max_unvalidated` connections, half of `max_connections` unless
11
+ # told, have addresses not validated, a client whose address no token
12
+ # has shown is sent a Retry first, so that Initials from addresses
13
+ # spoofed by the thousand cannot take the rest: those are the offers
14
+ # admitted and not yet taken, and the connections whose address the
15
+ # handshake has not validated yet, as one from a spoofed address never
16
+ # is. With 0, every such client is sent one.
17
+ #
18
+ # When the block is over, what the streams sent is let be acknowledged,
19
+ # until three PTOs go with no more of it acknowledged or 30 seconds in
20
+ # all, and the connection closes with the application's error 0; when it
21
+ # raises, the connection closes with INTERNAL_ERROR, and the exception
22
+ # goes on to the scheduler. Other connections are not touched.
23
+ #
24
+ # `stop` asks the server to stop, from a signal handler as well: no new
25
+ # connection is taken, each Session is told it is `stopping?`, and the
26
+ # sessions are given `timeout` seconds to end their connections and wait
27
+ # out the closing period; those left are closed with the application's
28
+ # `error_code`. `run` returns then.
29
+ #
30
+ # With `qlog_dir`, each connection has a qlog there, named by the
31
+ # Destination Connection ID the client first chose.
32
+ #
33
+ # A `config` without max_transmit_size takes UDP::MAX_TRANSMIT, as the
34
+ # socket sends the datagrams of a Transmit with GSO (UDP.batching), and
35
+ # enable_pmtud false where the socket cannot keep IP from fragmenting
36
+ # (UDP.pmtud), and no ECN on IPv4 where the OS cannot mark it (UDP.ecn).
37
+ #
38
+ # A `config` with a preferred_address has a socket bound to each of its
39
+ # addresses as well, unless the first socket takes what comes there
40
+ # already, bound to any address on its port; `run` raises the error of
41
+ # one it cannot bind, so that no client is offered an address the server
42
+ # does not listen at.
43
+ #
44
+ # When the ticket keys of `tls_config` are a TicketKeys.ratchet, the
45
+ # server builds them again once their epoch is over, before the next
46
+ # connection it takes, with a Keyring to match. Keys of another kind are
47
+ # the application's to turn over, with `reconfigure`.
48
+ #
49
+ # The 0-RTT a `tls_config` takes is recorded in `anti_replay`, so that
50
+ # the server takes each ClientHello's at most once; without one, the
51
+ # server has a TLS::AntiReplay::Memory of its own, which takes none for
52
+ # its first seconds (RFC 9846 "Client Hello Recording"). Servers of
53
+ # other processes that open the same tickets record apart, so each may
54
+ # take a ClientHello's 0-RTT once. `app_early_data_context` is what of
55
+ # the application its 0-RTT relies on, so that the 0-RTT of a ticket
56
+ # issued with other settings is rejected (Endpoint#accept).
57
+ #
58
+ # Given a `worker`, the server is one of the workers of Workers: it binds
59
+ # nothing and reads the sockets bound for it, its first, one of
60
+ # "0.0.0.0" where the first is "::" taking no IPv4, and those of the
61
+ # preferred addresses; it issues connection IDs that tell its worker
62
+ # (QUIC::WorkerConnectionIDs), fills the keys a `config` leaves out with
63
+ # those every worker shares, records 0-RTT in the worker's shared
64
+ # `anti_replay` unless given one, and its driver hands on to the other
65
+ # workers what came for their connections. What Workers asks through the
66
+ # worker's control port, to stop or to take other TLS settings, is done
67
+ # in the driver's turn, a stop with `stop_error_code` for the connections
68
+ # left. A `host` or `port` beside it is ArgumentError.
69
+ class Server
70
+ MAX_CONNECTIONS = 1024
71
+ STOP_TIMEOUT = 30
72
+
73
+ def initialize(config:, tls_config:, keyring:, host: nil, port: nil, max_connections: MAX_CONNECTIONS, max_unvalidated: max_connections / 2,
74
+ qlog_dir: nil, anti_replay: nil, app_early_data_context: "".b, worker: nil, stop_error_code: 0)
75
+ raise ArgumentError, "a worker's server binds no host or port of its own" if worker && (host || port)
76
+ unless max_unvalidated.is_a?(Integer) && (0..max_connections).cover?(max_unvalidated)
77
+ raise ArgumentError, "max_unvalidated #{max_unvalidated.inspect} is not 0 to max_connections (#{max_connections})"
78
+ end
79
+ @worker = worker
80
+ @stop_error_code = stop_error_code
81
+ config = config.with(retry_token_key: config.retry_token_key || worker.config.retry_token_key,
82
+ stateless_reset_key: config.stateless_reset_key || worker.config.stateless_reset_key) if worker
83
+ @config = UDP.ecn(UDP.pmtud(UDP.batching(config)))
84
+ @tls_config = tls_config
85
+ @keyring = keyring
86
+ @anti_replay = anti_replay || worker&.anti_replay || Raiha::TLS::AntiReplay::Memory.new(now: Time.now)
87
+ @app_early_data_context = app_early_data_context
88
+ @host = host || "::"
89
+ @port = port || 443
90
+ # What the worker's control port asked, for the driver's turn, and
91
+ # what failed in the thread that waits on it.
92
+ @controls = Thread::Queue.new
93
+ @worker_failure = nil #: StandardError?
94
+ @max_connections = max_connections
95
+ @max_unvalidated = max_unvalidated
96
+ # The offers admitted whose ClientHello is not whole yet and whose
97
+ # client's address is not validated, let go each turn once over.
98
+ @admitted = [] #: Array[Raiha::QUIC::Endpoint::Handle]
99
+ @qlog = qlog_dir && Qlog.new(qlog_dir)
100
+ @traces = {} #: Hash[Session, Qlog::Pending]
101
+ @traces.compare_by_identity
102
+ # The sessions of the connections taken, and those given to the block.
103
+ @sessions = [] #: Array[Session]
104
+ @started = {} #: Hash[Session, true]
105
+ @started.compare_by_identity
106
+ @handler = nil #: ^(Session) -> void | nil
107
+ @driver = nil #: Driver?
108
+ @udp = nil #: UDP?
109
+ @lock = Thread::Mutex.new
110
+ @stopped = Thread::ConditionVariable.new
111
+ # What `stop` asked, [timeout, error_code], when it was asked, and
112
+ # when the sessions are out of time; and the pipe that wakes the
113
+ # driver for it.
114
+ @stop = nil #: [Float | Integer, Integer]?
115
+ @stop_deadline = nil #: Float?
116
+ @wake = nil #: IO?
117
+ end
118
+
119
+ # Binds the socket and serves until stopped, giving the block each
120
+ # Session; raises what failed in the driver, if anything did.
121
+ def run(&handler)
122
+ raise Error::Usage, "the runtime waits through a Fiber scheduler; this thread has none" unless Fiber.scheduler
123
+ @handler = handler
124
+ udp, others, connection_ids = sockets
125
+ endpoint = Raiha::QUIC::Endpoint.server(config: @config, random: SecureRandom, time: Time.now, now: Driver.clock, connection_ids:)
126
+ # Known before it starts, so that leaving `run` while it starts stops
127
+ # it too.
128
+ driver = @driver = Driver.new(endpoint, udp, self, others:, worker: @worker)
129
+ driver.start
130
+ @worker&.listen(changed: -> { driver.changed }, failed: ->(error) { (@worker_failure = error) && driver.changed }) do |message|
131
+ @controls << message
132
+ driver.changed
133
+ end
134
+ reader, @wake = IO.pipe
135
+ Fiber.schedule { wake_on(reader, driver) }
136
+ @lock.synchronize { @stopped.wait(@lock) until driver.stopped? }
137
+ failure = driver.failure and raise failure
138
+ nil
139
+ ensure
140
+ # Left by an exception, or by the task running it being stopped.
141
+ @driver&.stop
142
+ @worker&.close
143
+ reader&.close
144
+ @wake&.close
145
+ end
146
+
147
+ # [address, port] the socket is bound to, once `run` has bound it.
148
+ def local_address = @udp&.local_address
149
+
150
+ # Takes the connections to come with `tls_config` and `keyring`, a new
151
+ # certificate, say; those already taken keep theirs. The QUIC Config
152
+ # stays: its keys and the length of its connection IDs are what the
153
+ # Endpoint was made with.
154
+ def reconfigure(tls_config:, keyring:)
155
+ @tls_config = tls_config
156
+ @keyring = keyring
157
+ nil
158
+ end
159
+
160
+ # Asks the server to stop, giving the sessions `timeout` seconds; the
161
+ # first call is the one that counts. It takes no lock and writes to a
162
+ # pipe without waiting, so a signal handler may call it.
163
+ def stop(timeout: STOP_TIMEOUT, error_code: 0)
164
+ @stop ||= [timeout, error_code]
165
+ @wake&.write_nonblock(".", exception: false)
166
+ nil
167
+ rescue IOError, SystemCallError
168
+ # `run` is returning and has closed the pipe, or the end it reads.
169
+ nil
170
+ end
171
+
172
+ # The driver's owner: a new connection is taken while there is room for
173
+ # it.
174
+ def route(route, now)
175
+ endpoint = @driver&.endpoint or return
176
+ case route
177
+ when Raiha::QUIC::Route::Incoming
178
+ case Admission.decide(route, full: !@stop.nil? || @sessions.size >= @max_connections, max_unvalidated: @max_unvalidated) { unvalidated(now) }
179
+ when :refuse then return endpoint.refuse(route.handle)
180
+ when :retry then return endpoint.retry(route.handle, now:)
181
+ end
182
+ hello = endpoint.admit(route.handle, now:)
183
+ return route(hello, now) if hello
184
+ @admitted << route.handle unless route.address_validated
185
+ when Raiha::QUIC::Route::ClientHello
186
+ @admitted.delete(route.handle)
187
+ advance_ticket_keys
188
+ tracer, pending = @qlog&.trace(:server, route.handle.original_destination_connection_id.unpack1("H*"), tls_config: @tls_config)
189
+ connection = endpoint.accept(route.handle, tls_config: @tls_config, keyring: @keyring, now:, tracer:, anti_replay: @anti_replay,
190
+ app_early_data_context: @app_early_data_context)
191
+ session = Session.new(connection, driver!, role: :server, tracer:)
192
+ @sessions << session
193
+ @traces[session] = pending if pending
194
+ end
195
+ end
196
+
197
+ # The driver's turn: each Session's, the block for each whose handshake
198
+ # has completed, and the sessions of connections over let go.
199
+ def turn(now)
200
+ failure = @worker_failure and raise failure
201
+ @admitted.reject! { |handle| handle.expired?(now) || handle.failed? }
202
+ while (message = @controls.pop(timeout: 0))
203
+ control(message)
204
+ end
205
+ @sessions.each do |session|
206
+ session.turn
207
+ start(session) if !@stop && !@started.key?(session) && session.connection.handshake_complete?
208
+ end
209
+ over = @sessions.select { |session| session.connection.closed? }
210
+ over.each do |session|
211
+ @started.delete(session)
212
+ @traces.delete(session)&.over!
213
+ end
214
+ @sessions -= over
215
+ stopping(now) if @stop
216
+ @qlog&.flush
217
+ end
218
+
219
+ def next_timeout = @stop_deadline
220
+
221
+ # How many of the offers admitted and the connections taken have
222
+ # addresses not validated.
223
+ private def unvalidated(now) = Admission.unvalidated(@admitted, @sessions.map(&:connection), now)
224
+
225
+ def stopped(failure)
226
+ @sessions.each { |session| session.abort(failure) }
227
+ @traces.each_value(&:over!)
228
+ @qlog&.flush
229
+ ensure
230
+ @lock.synchronize { @stopped.broadcast }
231
+ end
232
+
233
+ private def driver! = @driver || raise(Error::Usage, "the server is not running")
234
+
235
+ # The socket, those besides it, and the connection IDs to issue: of the
236
+ # worker, or bound here.
237
+ private def sockets
238
+ if (worker = @worker)
239
+ first, *others = worker.sockets.map { |socket| UDP.new(socket) }
240
+ ids = Raiha::QUIC::WorkerConnectionIDs.new(SecureRandom, worker_id: worker.id, worker_count: worker.count,
241
+ key: @config.stateless_reset_key || raise(Error::Usage, "a worker's Config has no stateless_reset_key"))
242
+ udp = first or raise Error::Usage, "the worker has no socket"
243
+ @udp = udp
244
+ return [udp, others, ids]
245
+ end
246
+ udp = @udp = UDP.bind(@host, @port)
247
+ [udp, preferred_sockets(udp), Raiha::QUIC::RandomConnectionIDs.new(SecureRandom)]
248
+ end
249
+
250
+ # What Workers asked through the worker's control port.
251
+ private def control(message)
252
+ case message
253
+ in [:stop, timeout] then stop(timeout:, error_code: @stop_error_code)
254
+ in [:reconfigure, tls_config, identities] then reconfigure(tls_config:, keyring: Raiha::TLS::Keyring.server(config: tls_config, identities:))
255
+ else nil
256
+ end
257
+ end
258
+
259
+ # A socket bound to "0.0.0.0" on the port of `udp` where `udp` is bound
260
+ # to "::" and takes no IPv4 (OpenBSD), and one bound to each preferred
261
+ # address that none bound so far sends from; none is left open when one
262
+ # cannot be bound, nor `udp`. "0.0.0.0" comes first, as a specific
263
+ # address of IPv4 bound on the same port would keep it from binding.
264
+ private def preferred_sockets(udp)
265
+ others = [] #: Array[UDP]
266
+ bound = udp.to_io.local_address
267
+ addresses = @config.preferred_address&.values || [] #: Array[UDP::address]
268
+ if bound.ipv6? && bound.ipv6_unspecified? && !udp.takes_ipv4?
269
+ addresses = [["0.0.0.0", bound.ip_port], *addresses] #: Array[UDP::address]
270
+ end
271
+ addresses.each do |host, port|
272
+ others << UDP.bind(host, port) unless [udp, *others].any? { |socket| socket.sends_from?([host, port]) }
273
+ rescue SystemCallError
274
+ [udp, *others].each(&:close)
275
+ raise
276
+ end
277
+ others
278
+ end
279
+
280
+ # A ticket is sealed with the key of the epoch it is issued in, and keys
281
+ # of epochs long gone stop opening any.
282
+ private def advance_ticket_keys
283
+ keyring = Admission.advance_ticket_keys(@tls_config, @keyring, Time.now) or return
284
+ @keyring = keyring
285
+ @tls_config = keyring.config
286
+ end
287
+
288
+ # Has the driver go round each time `stop` writes to the pipe.
289
+ private def wake_on(reader, driver)
290
+ until driver.stopped?
291
+ reader.wait_readable
292
+ reader.read_nonblock(64, exception: false)
293
+ driver.changed
294
+ end
295
+ rescue IOError
296
+ nil
297
+ end
298
+
299
+ # A turn while stopping: the sessions are told, and a connection whose
300
+ # session the block never had is closed at once; once the sessions are
301
+ # all over, or out of time, those left closed with the `error_code`
302
+ # `stop` was given, the driver stops.
303
+ private def stopping(now)
304
+ timeout, error_code = @stop || return
305
+ unless @stop_deadline
306
+ @stop_deadline = now + timeout
307
+ @sessions.each do |session|
308
+ session.stopping!(@stop_deadline)
309
+ session.connection.close(error_code:, application: true, now:) unless @started.key?(session)
310
+ end
311
+ end
312
+ deadline = @stop_deadline
313
+ return unless @sessions.empty? || (deadline && now >= deadline)
314
+ @sessions.each { |session| session.expire(error_code:) }
315
+ driver!.flush
316
+ driver!.stop
317
+ end
318
+
319
+ private def start(session)
320
+ @started[session] = true
321
+ handler = @handler or return
322
+ Fiber.schedule do
323
+ handler.call(session)
324
+ session.close_when_acknowledged
325
+ rescue Raiha::QUIC::ClosedError
326
+ nil
327
+ rescue StandardError
328
+ session.connection.close(error_code: Raiha::QUIC::ErrorCode::INTERNAL_ERROR, application: false, now: Driver.clock)
329
+ driver!.changed
330
+ raise
331
+ end
332
+ end
333
+ end
334
+ end