kobako 0.30.0 → 0.32.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 (288) hide show
  1. checksums.yaml +4 -4
  2. data/.githooks/linux-tests.sh +29 -0
  3. data/.release-please-manifest.json +1 -1
  4. data/CHANGELOG.md +460 -0
  5. data/Cargo.lock +868 -447
  6. data/README.md +43 -4
  7. data/ROADMAP.md +1 -2
  8. data/crates/kobako-runtime/CHANGELOG.md +309 -0
  9. data/crates/kobako-runtime/Cargo.toml +58 -11
  10. data/crates/kobako-runtime/README.md +7 -4
  11. data/crates/kobako-runtime/src/cred.rs +136 -0
  12. data/crates/kobako-runtime/src/dispatch.rs +4 -5
  13. data/crates/kobako-runtime/src/endpoint/buffer.rs +153 -44
  14. data/crates/kobako-runtime/src/endpoint/dispatch.rs +80 -41
  15. data/crates/kobako-runtime/src/endpoint/invoke.rs +23 -36
  16. data/crates/kobako-runtime/src/endpoint.rs +137 -36
  17. data/crates/kobako-runtime/src/errno.rs +391 -0
  18. data/crates/kobako-runtime/src/error.rs +31 -10
  19. data/crates/kobako-runtime/src/filesystem/anon_inodes.rs +52 -0
  20. data/crates/kobako-runtime/src/filesystem/bind/fid.rs +300 -22
  21. data/crates/kobako-runtime/src/filesystem/bind/lookup.rs +101 -29
  22. data/crates/kobako-runtime/src/filesystem/bind/unicode.rs +109 -0
  23. data/crates/kobako-runtime/src/filesystem/bind/walk.rs +52 -34
  24. data/crates/kobako-runtime/src/filesystem/bind.rs +812 -447
  25. data/crates/kobako-runtime/src/filesystem/overlay/file.rs +6 -6
  26. data/crates/kobako-runtime/src/filesystem/overlay/path.rs +43 -65
  27. data/crates/kobako-runtime/src/filesystem/overlay/stack/copy_up.rs +11 -16
  28. data/crates/kobako-runtime/src/filesystem/overlay/stack/dir.rs +47 -72
  29. data/crates/kobako-runtime/src/filesystem/overlay/stack/namei.rs +12 -12
  30. data/crates/kobako-runtime/src/filesystem/overlay/stack/readdir.rs +4 -7
  31. data/crates/kobako-runtime/src/filesystem/overlay/stack.rs +120 -37
  32. data/crates/kobako-runtime/src/filesystem/overlay.rs +578 -388
  33. data/crates/kobako-runtime/src/filesystem/pipe.rs +12 -9
  34. data/crates/kobako-runtime/src/filesystem/rdir.rs +14 -50
  35. data/crates/kobako-runtime/src/filesystem/testing.rs +31 -0
  36. data/crates/kobako-runtime/src/filesystem/tmpfs/seed.rs +32 -0
  37. data/crates/kobako-runtime/src/filesystem/tmpfs/tmpfile.rs +3 -3
  38. data/crates/kobako-runtime/src/filesystem/tmpfs/whiteout.rs +57 -35
  39. data/crates/kobako-runtime/src/filesystem/tmpfs/xattr.rs +2 -2
  40. data/crates/kobako-runtime/src/filesystem/tmpfs.rs +219 -173
  41. data/crates/kobako-runtime/src/filesystem/wrap.rs +36 -52
  42. data/crates/kobako-runtime/src/filesystem.rs +8 -3
  43. data/crates/kobako-runtime/src/fork.rs +319 -0
  44. data/crates/kobako-runtime/src/grant.rs +3 -0
  45. data/crates/kobako-runtime/src/hashtable.rs +4 -2
  46. data/crates/kobako-runtime/src/lib.rs +18 -7
  47. data/crates/kobako-runtime/src/limits.rs +171 -0
  48. data/crates/kobako-runtime/src/locking/seqlock.rs +29 -3
  49. data/crates/kobako-runtime/src/locking.rs +518 -113
  50. data/crates/kobako-runtime/src/memcg.rs +306 -0
  51. data/crates/kobako-runtime/src/mount.rs +37 -9
  52. data/crates/kobako-runtime/src/net/backends.rs +43 -0
  53. data/crates/kobako-runtime/src/net/connections.rs +219 -0
  54. data/crates/kobako-runtime/src/net/credential.rs +125 -0
  55. data/crates/kobako-runtime/src/net/egress.rs +180 -0
  56. data/crates/kobako-runtime/src/net/family.rs +181 -0
  57. data/crates/kobako-runtime/src/net/http.rs +3165 -0
  58. data/crates/kobako-runtime/src/net/lookup.rs +385 -0
  59. data/crates/kobako-runtime/src/net/mock.rs +251 -0
  60. data/crates/kobako-runtime/src/net/namespace.rs +1368 -0
  61. data/crates/kobako-runtime/src/net/reactor.rs +626 -0
  62. data/crates/kobako-runtime/src/net/resolv/darwin.rs +280 -0
  63. data/crates/kobako-runtime/src/net/resolv/stub/tests.rs +519 -0
  64. data/crates/kobako-runtime/src/net/resolv/stub.rs +542 -0
  65. data/crates/kobako-runtime/src/net/resolv/windows.rs +218 -0
  66. data/crates/kobako-runtime/src/net/resolv.rs +251 -0
  67. data/crates/kobako-runtime/src/net/skbuff.rs +109 -0
  68. data/crates/kobako-runtime/src/net/socket.rs +869 -0
  69. data/crates/kobako-runtime/src/net/task.rs +223 -0
  70. data/crates/kobako-runtime/src/net/tcp.rs +1840 -0
  71. data/crates/kobako-runtime/src/net/tls.rs +120 -0
  72. data/crates/kobako-runtime/src/net/transport.rs +304 -0
  73. data/crates/kobako-runtime/src/net/udp.rs +1105 -0
  74. data/crates/kobako-runtime/src/net.rs +45 -0
  75. data/crates/kobako-runtime/src/network/builder.rs +177 -0
  76. data/crates/kobako-runtime/src/network/ruleset.rs +777 -0
  77. data/crates/kobako-runtime/src/network.rs +551 -0
  78. data/crates/kobako-runtime/src/policy.rs +16 -0
  79. data/crates/kobako-runtime/src/profile.rs +29 -144
  80. data/crates/kobako-runtime/src/runtime.rs +3 -5
  81. data/crates/kobako-runtime/src/sched.rs +338 -51
  82. data/crates/kobako-runtime/src/security/entry_policy.rs +22 -0
  83. data/crates/kobako-runtime/src/{vfs/cred.rs → security/hooks.rs} +52 -144
  84. data/crates/kobako-runtime/src/security/mount_policy.rs +158 -0
  85. data/crates/kobako-runtime/src/security.rs +125 -209
  86. data/crates/kobako-runtime/src/snapshot.rs +121 -2
  87. data/crates/kobako-runtime/src/vfs/attr.rs +5 -5
  88. data/crates/kobako-runtime/src/vfs/dentry.rs +210 -117
  89. data/crates/kobako-runtime/src/vfs/file.rs +243 -248
  90. data/crates/kobako-runtime/src/vfs/inode.rs +41 -45
  91. data/crates/kobako-runtime/src/vfs/kern_path.rs +62 -53
  92. data/crates/kobako-runtime/src/vfs/mount.rs +10 -9
  93. data/crates/kobako-runtime/src/vfs/namei.rs +1162 -818
  94. data/crates/kobako-runtime/src/vfs/namespace.rs +245 -0
  95. data/crates/kobako-runtime/src/vfs/open_files.rs +69 -0
  96. data/crates/kobako-runtime/src/vfs/openat2.rs +3 -3
  97. data/crates/kobako-runtime/src/vfs/path.rs +6 -6
  98. data/crates/kobako-runtime/src/vfs/readdir.rs +6 -6
  99. data/crates/kobako-runtime/src/vfs/stat.rs +248 -23
  100. data/crates/kobako-runtime/src/vfs/super_block.rs +18 -14
  101. data/crates/kobako-runtime/src/vfs/utimes.rs +37 -27
  102. data/crates/kobako-runtime/src/vfs.rs +10 -6
  103. data/crates/kobako-runtime/src/wait.rs +381 -0
  104. data/crates/kobako-transport/CHANGELOG.md +38 -0
  105. data/crates/kobako-transport/Cargo.toml +1 -1
  106. data/crates/kobako-transport/README.md +3 -4
  107. data/crates/kobako-transport/src/abi.rs +78 -72
  108. data/crates/kobako-transport/src/envelope/bytes.rs +17 -6
  109. data/crates/kobako-transport/src/envelope/call.rs +32 -4
  110. data/crates/kobako-transport/src/envelope/error_record.rs +21 -0
  111. data/crates/kobako-transport/src/envelope/name.rs +99 -0
  112. data/crates/kobako-transport/src/envelope/outcome.rs +9 -9
  113. data/crates/kobako-transport/src/envelope/preamble.rs +24 -21
  114. data/crates/kobako-transport/src/envelope/reply.rs +27 -27
  115. data/crates/kobako-transport/src/envelope/unsupported.rs +10 -10
  116. data/crates/kobako-transport/src/envelope.rs +13 -8
  117. data/crates/kobako-wasmtime/CHANGELOG.md +208 -0
  118. data/crates/kobako-wasmtime/Cargo.toml +47 -7
  119. data/crates/kobako-wasmtime/README.md +4 -3
  120. data/crates/kobako-wasmtime/build/preview2.rs +1339 -0
  121. data/crates/kobako-wasmtime/build.rs +16 -0
  122. data/crates/kobako-wasmtime/src/abi.rs +18 -37
  123. data/crates/kobako-wasmtime/src/ambient.rs +43 -19
  124. data/crates/kobako-wasmtime/src/cache/unix.rs +95 -0
  125. data/crates/kobako-wasmtime/src/cache/windows.rs +359 -0
  126. data/crates/kobako-wasmtime/src/cache.rs +106 -113
  127. data/crates/kobako-wasmtime/src/config.rs +52 -68
  128. data/crates/kobako-wasmtime/src/driver.rs +80 -82
  129. data/crates/kobako-wasmtime/src/exports.rs +143 -17
  130. data/crates/kobako-wasmtime/src/guest.rs +12 -6
  131. data/crates/kobako-wasmtime/src/guest_binary.rs +14 -0
  132. data/crates/kobako-wasmtime/src/imports.rs +42 -18
  133. data/crates/kobako-wasmtime/src/instance_pre.rs +4 -4
  134. data/crates/kobako-wasmtime/src/invocation.rs +91 -15
  135. data/crates/kobako-wasmtime/src/lib.rs +7 -3
  136. data/crates/kobako-wasmtime/src/limiter.rs +130 -12
  137. data/crates/kobako-wasmtime/src/preview1/descriptors.rs +305 -0
  138. data/crates/kobako-wasmtime/src/preview1/differential/mount.rs +9 -20
  139. data/crates/kobako-wasmtime/src/preview1/differential.rs +27 -31
  140. data/crates/kobako-wasmtime/src/preview1/errno.rs +55 -66
  141. data/crates/kobako-wasmtime/src/preview1/fd.rs +347 -312
  142. data/crates/kobako-wasmtime/src/preview1/memory.rs +21 -12
  143. data/crates/kobako-wasmtime/src/preview1/mount_view/wrap.rs +34 -53
  144. data/crates/kobako-wasmtime/src/preview1/mount_view.rs +335 -388
  145. data/crates/kobako-wasmtime/src/preview1/path.rs +56 -121
  146. data/crates/kobako-wasmtime/src/preview1/poll.rs +255 -125
  147. data/crates/kobako-wasmtime/src/preview1/random.rs +125 -0
  148. data/crates/kobako-wasmtime/src/preview1/sock.rs +10 -8
  149. data/crates/kobako-wasmtime/src/preview1/testing.rs +31 -0
  150. data/crates/kobako-wasmtime/src/preview1/testsuite.rs +5 -15
  151. data/crates/kobako-wasmtime/src/preview1.rs +131 -51
  152. data/crates/kobako-wasmtime/src/preview2/abi.rs +227 -0
  153. data/crates/kobako-wasmtime/src/preview2/error.rs +118 -0
  154. data/crates/kobako-wasmtime/src/preview2/filesystem.rs +122 -0
  155. data/crates/kobako-wasmtime/src/preview2/host.rs +4319 -0
  156. data/crates/kobako-wasmtime/src/preview2/http.rs +1587 -0
  157. data/crates/kobako-wasmtime/src/preview2/io.rs +328 -0
  158. data/crates/kobako-wasmtime/src/preview2/sockets.rs +379 -0
  159. data/crates/kobako-wasmtime/src/preview2/table.rs +257 -0
  160. data/crates/kobako-wasmtime/src/preview2.rs +57 -0
  161. data/crates/kobako-wasmtime/src/trap.rs +88 -28
  162. data/crates/kobako-wasmtime/src/waits.rs +59 -0
  163. data/crates/kobako-wasmtime/src/wasi.rs +291 -81
  164. data/crates/kobako-wasmtime/wit/deps/cli.wit +233 -0
  165. data/crates/kobako-wasmtime/wit/deps/clocks.wit +162 -0
  166. data/crates/kobako-wasmtime/wit/deps/filesystem.wit +589 -0
  167. data/crates/kobako-wasmtime/wit/deps/http.wit +733 -0
  168. data/crates/kobako-wasmtime/wit/deps/io.wit +299 -0
  169. data/crates/kobako-wasmtime/wit/deps/random.wit +92 -0
  170. data/crates/kobako-wasmtime/wit/deps/sockets.wit +949 -0
  171. data/crates/kobako-wasmtime/witx/wasi_snapshot_preview1.witx +13 -0
  172. data/data/kobako.wasm +0 -0
  173. data/ext/kobako/Cargo.toml +6 -2
  174. data/ext/kobako/src/{runtime/errors.rs → errors.rs} +34 -26
  175. data/ext/kobako/src/escape.rs +404 -0
  176. data/ext/kobako/src/{runtime/filesystem → filesystem}/grants.rs +34 -32
  177. data/ext/kobako/src/{runtime/filesystem → filesystem}/ruby.rs +158 -170
  178. data/ext/kobako/src/{runtime/filesystem.rs → filesystem.rs} +71 -23
  179. data/ext/kobako/src/fork.rs +72 -0
  180. data/ext/kobako/src/gvl.rs +729 -0
  181. data/ext/kobako/src/handoff.rs +490 -0
  182. data/ext/kobako/src/lib.rs +74 -3
  183. data/ext/kobako/src/network/mock.rs +187 -0
  184. data/ext/kobako/src/network.rs +593 -0
  185. data/ext/kobako/src/pinned_value.rs +44 -0
  186. data/ext/kobako/src/runtime/bridge.rs +58 -50
  187. data/ext/kobako/src/runtime/snapshot.rs +4 -4
  188. data/ext/kobako/src/runtime.rs +272 -163
  189. data/ext/kobako/src/wire.rs +42 -0
  190. data/lib/kobako/catalog/extensions.rb +14 -2
  191. data/lib/kobako/catalog/flags.rb +3 -5
  192. data/lib/kobako/catalog/grants.rb +5 -4
  193. data/lib/kobako/catalog/handles.rb +14 -32
  194. data/lib/kobako/catalog/mount.rb +11 -3
  195. data/lib/kobako/catalog/network.rb +35 -0
  196. data/lib/kobako/catalog/replacements.rb +28 -0
  197. data/lib/kobako/catalog/services.rb +5 -19
  198. data/lib/kobako/catalog/snippets.rb +3 -18
  199. data/lib/kobako/catalog.rb +3 -0
  200. data/lib/kobako/codec/{utils.rb → boundary.rb} +4 -2
  201. data/lib/kobako/codec/decoder.rb +5 -5
  202. data/lib/kobako/codec/ext_types.rb +3 -3
  203. data/lib/kobako/codec/handle_walk.rb +3 -43
  204. data/lib/kobako/codec/state.rb +2 -18
  205. data/lib/kobako/codec/value_budget.rb +133 -41
  206. data/lib/kobako/codec.rb +6 -7
  207. data/lib/kobako/context.rb +24 -11
  208. data/lib/kobako/errors.rb +18 -18
  209. data/lib/kobako/extension.rb +3 -2
  210. data/lib/kobako/filesystem.rb +10 -3
  211. data/lib/kobako/fork.rb +42 -0
  212. data/lib/kobako/handle.rb +2 -3
  213. data/lib/kobako/names.rb +28 -0
  214. data/lib/kobako/network.rb +210 -0
  215. data/lib/kobako/outcome.rb +7 -7
  216. data/lib/kobako/runtime.rb +3 -2
  217. data/lib/kobako/sandbox.rb +73 -35
  218. data/lib/kobako/sandbox_options.rb +42 -109
  219. data/lib/kobako/transport/argument_wrap.rb +64 -0
  220. data/lib/kobako/transport/block_failure.rb +1 -1
  221. data/lib/kobako/transport/dispatcher.rb +6 -6
  222. data/lib/kobako/transport/exposure.rb +26 -15
  223. data/lib/kobako/transport/reflection.rb +21 -4
  224. data/lib/kobako/transport/run.rb +8 -23
  225. data/lib/kobako/transport/yielder.rb +2 -9
  226. data/lib/kobako/transport.rb +1 -0
  227. data/lib/kobako/usage.rb +4 -2
  228. data/lib/kobako/version.rb +1 -1
  229. data/lib/kobako.rb +8 -4
  230. data/release-please-config.json +15 -0
  231. data/sig/kobako/catalog/extensions.rbs +2 -0
  232. data/sig/kobako/catalog/grants.rbs +7 -4
  233. data/sig/kobako/catalog/handles.rbs +2 -2
  234. data/sig/kobako/catalog/mount.rbs +3 -1
  235. data/sig/kobako/catalog/network.rbs +20 -0
  236. data/sig/kobako/catalog/replacements.rbs +14 -0
  237. data/sig/kobako/catalog/services.rbs +0 -4
  238. data/sig/kobako/catalog/snippets.rbs +0 -2
  239. data/sig/kobako/codec/{utils.rbs → boundary.rbs} +2 -2
  240. data/sig/kobako/codec/handle_walk.rbs +0 -6
  241. data/sig/kobako/codec/state.rbs +0 -4
  242. data/sig/kobako/codec/value_budget.rbs +48 -5
  243. data/sig/kobako/codec.rbs +2 -2
  244. data/sig/kobako/context.rbs +3 -1
  245. data/sig/kobako/errors.rbs +4 -7
  246. data/sig/kobako/filesystem.rbs +21 -3
  247. data/sig/kobako/fork.rbs +17 -0
  248. data/sig/kobako/network.rbs +115 -0
  249. data/sig/kobako/outcome.rbs +1 -1
  250. data/sig/kobako/runtime.rbs +32 -3
  251. data/sig/kobako/sandbox.rbs +10 -2
  252. data/sig/kobako/sandbox_options.rbs +29 -40
  253. data/sig/kobako/transport/argument_wrap.rbs +15 -0
  254. data/sig/kobako/transport/error.rbs +1 -1
  255. data/sig/kobako/transport/exposure.rbs +2 -4
  256. data/sig/kobako/transport/reflection.rbs +10 -0
  257. data/sig/kobako/transport/run.rbs +0 -2
  258. data/sig/kobako/transport/yielder.rbs +0 -3
  259. data/sig/kobako/transport.rbs +1 -1
  260. data/sig/kobako.rbs +13 -0
  261. metadata +97 -37
  262. data/crates/kobako-runtime/src/endpoint/capture.rs +0 -115
  263. data/crates/kobako-runtime/src/endpoint/memory_cap.rs +0 -238
  264. data/crates/kobako-runtime/src/filesystem/path.rs +0 -21
  265. data/crates/kobako-runtime/src/vfs/errno.rs +0 -153
  266. data/crates/kobako-runtime/tests/linux_baseline/calls.rs +0 -171
  267. data/crates/kobako-runtime/tests/linux_baseline/concurrent.rs +0 -276
  268. data/crates/kobako-runtime/tests/linux_baseline/kobako.rs +0 -323
  269. data/crates/kobako-runtime/tests/linux_baseline/linux-baseline-expected.txt +0 -16
  270. data/crates/kobako-runtime/tests/linux_baseline/linux.rs +0 -449
  271. data/crates/kobako-runtime/tests/linux_baseline/main.rs +0 -611
  272. data/crates/kobako-runtime/tests/linux_baseline/permissions.rs +0 -236
  273. data/crates/kobako-wasmtime/src/descriptors.rs +0 -200
  274. data/crates/kobako-wasmtime/tests/integration/compile_posture.rs +0 -43
  275. data/crates/kobako-wasmtime/tests/integration/guest_file.rs +0 -1085
  276. data/crates/kobako-wasmtime/tests/integration/main.rs +0 -29
  277. data/crates/kobako-wasmtime/tests/integration/preamble_flags.rs +0 -70
  278. data/crates/kobako-wasmtime/tests/integration/snippet_compile.rs +0 -95
  279. data/crates/kobako-wasmtime/tests/integration/support/mod.rs +0 -30
  280. data/crates/kobako-wasmtime/tests/integration/unanswered_call.rs +0 -86
  281. data/crates/kobako-wasmtime/tests/integration/unsupported_call.rs +0 -51
  282. data/ext/kobako/src/runtime/escape.rs +0 -67
  283. data/ext/kobako/src/runtime/gvl.rs +0 -147
  284. data/ext/kobako/src/runtime/pinned_value.rs +0 -31
  285. data/lib/kobako/constant_name.rb +0 -8
  286. data/lib/kobako/pool.rb +0 -140
  287. data/sig/kobako/constant_name.rbs +0 -3
  288. data/sig/kobako/pool.rbs +0 -42
@@ -0,0 +1,3165 @@
1
+ //! An HTTP request the guest sends, as a userspace proxy forwards one: the
2
+ //! namespace judges what the guest named on the guest thread, then a task on
3
+ //! the reactor hands the request to the outbound seam, whose only dialer is
4
+ //! kobako's connector. The request's body streams through a buffer the guest
5
+ //! writes into, and the response's body fills a buffer the guest reads
6
+ //! through the wait queue, so a full buffer either way stops its side and the
7
+ //! TCP window pushes back.
8
+
9
+ use std::future::{poll_fn, Future};
10
+ use std::io;
11
+ use std::pin::Pin;
12
+ use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak};
13
+ use std::task::{Context, Poll, Waker};
14
+ use std::time::{Duration, Instant};
15
+
16
+ use bytes::{Bytes, BytesMut};
17
+ use http_body::Body;
18
+ use http_body_util::combinators::UnsyncBoxBody;
19
+ use http_body_util::BodyExt;
20
+ use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
21
+
22
+ use super::connections::{open, OpenConnections, Place};
23
+ use super::credential::Swap;
24
+ use super::skbuff::SkBuffHead;
25
+ use super::task::Task;
26
+ use super::transport::Connector;
27
+ use super::{new_platform_tls, MAX_SOCKET_BUFFER};
28
+ use crate::cred::Cred;
29
+ use crate::errno::CarriedErrno;
30
+ use crate::filesystem::anon_inode_getfile;
31
+ use crate::vfs::{FMode, File, FileOperations, Kiocb, OpenHow, PollMask};
32
+ use crate::wait::{poll_wait, PollTable, WaitQueueHead};
33
+ use crate::Errno;
34
+
35
+ /// Whether a request travels in clear or over TLS.
36
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
37
+ #[non_exhaustive]
38
+ pub enum Scheme {
39
+ Http,
40
+ Https,
41
+ }
42
+
43
+ /// The headers no guest sets: wasmtime's `DEFAULT_FORBIDDEN_HEADERS`, and
44
+ /// `content-length` and `te`, since the seam frames the body and its encoding
45
+ /// itself.
46
+ const FORBIDDEN_HEADERS: [&str; 11] = [
47
+ "connection",
48
+ "content-length",
49
+ "host",
50
+ "http2-settings",
51
+ "keep-alive",
52
+ "proxy-authenticate",
53
+ "proxy-authorization",
54
+ "proxy-connection",
55
+ "te",
56
+ "transfer-encoding",
57
+ "upgrade",
58
+ ];
59
+
60
+ /// Why a header the guest names is not one it may set.
61
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
62
+ #[non_exhaustive]
63
+ pub enum FieldError {
64
+ InvalidSyntax,
65
+ Forbidden,
66
+ /// The list would outgrow `MAX_FIELD_SIZE`.
67
+ TooLarge,
68
+ }
69
+
70
+ /// The most room one header list the guest builds may take, as wasmtime's
71
+ /// `DEFAULT_FIELD_SIZE_LIMIT`; each entry counts its name, its value, and its
72
+ /// own place, so even an empty value counts.
73
+ pub const MAX_FIELD_SIZE: usize = 128 * 1024;
74
+
75
+ /// The most a response's head, or one read of its body, takes in the seam's
76
+ /// read buffer, as hyper's `max_buf_size` bounds it, so a head the guest could
77
+ /// read as a header list fits and a longer one answers a protocol error.
78
+ const MAX_READ_BUFFER: usize = MAX_FIELD_SIZE;
79
+
80
+ /// A header list the guest builds or reads. What the guest appends stays
81
+ /// within `MAX_FIELD_SIZE`, and a response's head within the read buffer, so
82
+ /// a list holds a fixed most.
83
+ pub struct Fields {
84
+ list: Mutex<List>,
85
+ }
86
+
87
+ /// A list's entries and the room they take.
88
+ struct List {
89
+ entries: Vec<(String, Vec<u8>)>,
90
+ room: usize,
91
+ }
92
+
93
+ /// The room `name` and `value` take in a list.
94
+ fn room_of(name: &str, value: &[u8]) -> usize {
95
+ name.len() + value.len() + std::mem::size_of::<(String, Vec<u8>)>()
96
+ }
97
+
98
+ /// The room every entry of `entries` takes in a list.
99
+ fn total_room_of(entries: &[(String, Vec<u8>)]) -> usize {
100
+ entries
101
+ .iter()
102
+ .map(|(name, value)| room_of(name, value))
103
+ .sum()
104
+ }
105
+
106
+ impl Fields {
107
+ /// An empty list.
108
+ pub fn new() -> Arc<Self> {
109
+ Self::with_entries(Vec::new())
110
+ }
111
+
112
+ /// A list holding `entries`, as a response's headers are handed out; it
113
+ /// may outgrow `MAX_FIELD_SIZE`, which only bounds what the guest appends.
114
+ pub fn with_entries(entries: Vec<(String, Vec<u8>)>) -> Arc<Self> {
115
+ let room = total_room_of(&entries);
116
+ Arc::new(Self {
117
+ list: Mutex::new(List { entries, room }),
118
+ })
119
+ }
120
+
121
+ fn list(&self) -> MutexGuard<'_, List> {
122
+ self.list.lock().unwrap_or_else(PoisonError::into_inner)
123
+ }
124
+
125
+ /// The room the entries take, as a request's own parts share it.
126
+ pub fn room(&self) -> usize {
127
+ self.list().room
128
+ }
129
+
130
+ /// Append the header `name` with `value`, once `to_field_name` and
131
+ /// `to_field_value` take them and the list keeps within `MAX_FIELD_SIZE`.
132
+ pub fn append(&self, name: &str, value: Vec<u8>) -> Result<(), FieldError> {
133
+ let name = to_field_name(name)?;
134
+ let value = to_field_value(value)?;
135
+ let mut list = self.list();
136
+ let grown = list.room + room_of(&name, &value);
137
+ if grown > MAX_FIELD_SIZE {
138
+ return Err(FieldError::TooLarge);
139
+ }
140
+ list.room = grown;
141
+ list.entries.push((name, value));
142
+ Ok(())
143
+ }
144
+
145
+ /// Every entry, in the order appended.
146
+ pub fn entries(&self) -> Vec<(String, Vec<u8>)> {
147
+ self.list().entries.clone()
148
+ }
149
+ }
150
+
151
+ /// Whether `text` is an HTTP token, as a method or a header name must be.
152
+ pub fn is_token(text: &str) -> bool {
153
+ !text.is_empty()
154
+ && text
155
+ .chars()
156
+ .all(|c| c.is_ascii_alphanumeric() || "!#$%&'*+-.^_`|~".contains(c))
157
+ }
158
+
159
+ /// Whether `text` is a URI scheme, as hyper's `Scheme` parses one.
160
+ pub fn is_scheme(text: &str) -> bool {
161
+ text.parse::<hyper::http::uri::Scheme>().is_ok()
162
+ }
163
+
164
+ /// The header name a guest may set, lowercase: a token, and none the seam
165
+ /// writes itself.
166
+ pub fn to_field_name(name: &str) -> Result<String, FieldError> {
167
+ if !is_token(name) {
168
+ return Err(FieldError::InvalidSyntax);
169
+ }
170
+ let name = name.to_ascii_lowercase();
171
+ match FORBIDDEN_HEADERS.contains(&name.as_str()) {
172
+ true => Err(FieldError::Forbidden),
173
+ false => Ok(name),
174
+ }
175
+ }
176
+
177
+ /// The header value a guest may set: one an HTTP field value holds, with no
178
+ /// control byte but a tab, as hyper's `HeaderValue` and wasmtime take one.
179
+ pub fn to_field_value(value: Vec<u8>) -> Result<Vec<u8>, FieldError> {
180
+ match hyper::header::HeaderValue::from_bytes(&value) {
181
+ Ok(_) => Ok(value),
182
+ Err(_) => Err(FieldError::InvalidSyntax),
183
+ }
184
+ }
185
+
186
+ /// Whether `authority` names a host alone, with no path or user part, and a
187
+ /// port, when it names one, as a number that fits, as wasmtime's
188
+ /// `parse_authority` asks.
189
+ pub fn is_authority(authority: &str) -> bool {
190
+ if authority.contains('@') {
191
+ return false;
192
+ }
193
+ let has_port = match authority.rfind(']') {
194
+ Some(at) => authority[at..].contains(':'),
195
+ None => authority.contains(':'),
196
+ };
197
+ hyper::http::uri::Authority::try_from(authority)
198
+ .is_ok_and(|parsed| !has_port || parsed.port_u16().is_some())
199
+ }
200
+
201
+ /// The host and port an authority names, the port defaulting by `scheme`;
202
+ /// `None` for one `is_authority` refuses. One parser reads every authority,
203
+ /// so the authority a request is judged by is the one it reaches.
204
+ pub(crate) fn split_authority(authority: &str, scheme: Scheme) -> Option<(String, u16)> {
205
+ if !is_authority(authority) {
206
+ return None;
207
+ }
208
+ let parsed = hyper::http::uri::Authority::try_from(authority).ok()?;
209
+ let host = parsed.host().trim_start_matches('[').trim_end_matches(']');
210
+ (!host.is_empty()).then(|| {
211
+ (
212
+ host.to_ascii_lowercase(),
213
+ parsed.port_u16().unwrap_or(default_port(scheme)),
214
+ )
215
+ })
216
+ }
217
+
218
+ /// The authority a request names its server by, from the `host` and `port`
219
+ /// it was judged for: the port only when it is not `scheme`'s default, as
220
+ /// RFC 9110's `Host` field writes one.
221
+ pub(crate) fn join_authority(host: &str, port: u16, scheme: Scheme) -> String {
222
+ match port == default_port(scheme) {
223
+ true => host.to_string(),
224
+ false => format!("{host}:{port}"),
225
+ }
226
+ }
227
+
228
+ /// The port `scheme` reaches when an authority names none.
229
+ fn default_port(scheme: Scheme) -> u16 {
230
+ match scheme {
231
+ Scheme::Http => 80,
232
+ Scheme::Https => 443,
233
+ }
234
+ }
235
+
236
+ /// `path` as the request target sent in origin form, as wasmtime takes one:
237
+ /// `""` is `/` and a query alone sits on `/`; anything else not starting with
238
+ /// `/`, or no URI path holds, is none. A fragment is cut, as the target sent
239
+ /// carries none, so every rule judges what the server reads.
240
+ pub fn to_origin_form(path: &str) -> Option<String> {
241
+ let target = match path.chars().next() {
242
+ None => "/".to_string(),
243
+ Some('?') => format!("/{path}"),
244
+ Some('/') => path.to_string(),
245
+ Some(_) => return None,
246
+ };
247
+ hyper::http::uri::PathAndQuery::try_from(target)
248
+ .ok()
249
+ .map(|target| target.as_str().to_string())
250
+ }
251
+
252
+ /// One request the guest sends: its method, scheme, authority, path with its
253
+ /// query, headers, and body.
254
+ #[derive(Clone, Debug, PartialEq, Eq)]
255
+ #[non_exhaustive]
256
+ pub struct OutgoingRequest {
257
+ pub method: String,
258
+ pub scheme: Scheme,
259
+ pub authority: String,
260
+ pub path_with_query: String,
261
+ pub headers: Vec<(String, Vec<u8>)>,
262
+ pub body: Arc<RequestBody>,
263
+ pub timeouts: Timeouts,
264
+ /// The credentials bound to this request, swapped in only by the default
265
+ /// outbound seam and only on the way out, so no other seam reads a secret.
266
+ pub(crate) swaps: Vec<Swap>,
267
+ }
268
+
269
+ /// How long a request waits at each step, as `wasi:http`'s `request-options`
270
+ /// names them; `None` waits `DEFAULT_TIMEOUT`. Each bounds its own wait, as
271
+ /// wasmtime-wasi-http's does.
272
+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
273
+ #[non_exhaustive]
274
+ pub struct Timeouts {
275
+ /// For the connect to the server, answered as `ConnectionTimeout`.
276
+ pub connect: Option<Duration>,
277
+ /// For the response's head once connected, answered as
278
+ /// `ConnectionReadTimeout`.
279
+ pub first_byte: Option<Duration>,
280
+ /// For each part of the body after the last, failing the body's read as
281
+ /// `ETIMEDOUT`.
282
+ pub between_bytes: Option<Duration>,
283
+ }
284
+
285
+ /// How long a wait the request sets no timeout for lasts, as
286
+ /// wasmtime-wasi-http's `default_send_request` bounds each, so a server that
287
+ /// never answers ends the wait even where the run itself has no deadline.
288
+ const DEFAULT_TIMEOUT: Duration = Duration::from_secs(600);
289
+
290
+ /// The bound a wait takes from its timeout, `DEFAULT_TIMEOUT` where none is
291
+ /// set.
292
+ fn bound(timeout: Option<Duration>) -> Duration {
293
+ timeout.unwrap_or(DEFAULT_TIMEOUT)
294
+ }
295
+
296
+ impl OutgoingRequest {
297
+ pub fn new(method: impl Into<String>, scheme: Scheme, authority: impl Into<String>) -> Self {
298
+ Self {
299
+ method: method.into(),
300
+ scheme,
301
+ authority: authority.into(),
302
+ path_with_query: "/".to_string(),
303
+ headers: Vec::new(),
304
+ body: RequestBody::finished(&[]),
305
+ timeouts: Timeouts::default(),
306
+ swaps: Vec::new(),
307
+ }
308
+ }
309
+ }
310
+
311
+ /// The body a guest writes for a request, streamed to the seam as it is
312
+ /// written, as a pipe holds what its reader has not taken. The host holds at
313
+ /// most one socket buffer of it, so a server slow to take the body stops the
314
+ /// guest's writes and the TCP window pushes back, as wasi-http's
315
+ /// backpressure does.
316
+ pub struct RequestBody {
317
+ pipe: Mutex<Pipe>,
318
+ /// Writers waiting for room, as a pipe's `wr_wait`.
319
+ wait: Arc<WaitQueueHead>,
320
+ /// The exchange sending the body, which only the guest moves, so its
321
+ /// writes and polls move it too.
322
+ exchange: OnceLock<Weak<Exchange>>,
323
+ }
324
+
325
+ struct Pipe {
326
+ queued: BytesMut,
327
+ end: BodyEnd,
328
+ /// The seam's task waiting for what is written next.
329
+ reader: Option<Waker>,
330
+ /// A TRACE carries no content, so a write with any is refused.
331
+ refuses_content: bool,
332
+ }
333
+
334
+ /// How far a request body got.
335
+ #[derive(Clone, Copy, PartialEq, Eq)]
336
+ enum BodyEnd {
337
+ Open,
338
+ Finished,
339
+ /// It ended without finishing, which fails its request as the code names.
340
+ Failed(HttpError),
341
+ }
342
+
343
+ impl RequestBody {
344
+ /// A body the guest has written nothing to yet.
345
+ pub fn new() -> Arc<Self> {
346
+ Arc::new(Self {
347
+ pipe: Mutex::new(Pipe {
348
+ queued: BytesMut::new(),
349
+ end: BodyEnd::Open,
350
+ reader: None,
351
+ refuses_content: false,
352
+ }),
353
+ wait: Arc::default(),
354
+ exchange: OnceLock::new(),
355
+ })
356
+ }
357
+
358
+ /// Move the exchange sending the body as far as it goes, so the seam
359
+ /// takes what was written.
360
+ fn move_exchange(&self) -> Option<Arc<Exchange>> {
361
+ let exchange = self.exchange.get()?.upgrade()?;
362
+ exchange.poll_task();
363
+ Some(exchange)
364
+ }
365
+
366
+ /// A body already finished with `bytes`, as a request built whole sends.
367
+ pub(crate) fn finished(bytes: &[u8]) -> Arc<Self> {
368
+ let body = Self::new();
369
+ {
370
+ let mut pipe = body.pipe();
371
+ pipe.queued.extend_from_slice(bytes);
372
+ pipe.end = BodyEnd::Finished;
373
+ }
374
+ body
375
+ }
376
+
377
+ fn pipe(&self) -> MutexGuard<'_, Pipe> {
378
+ self.pipe.lock().unwrap_or_else(PoisonError::into_inner)
379
+ }
380
+
381
+ /// Allocate the file the guest writes the body through as `cred`, as
382
+ /// `anon_inode_getfile` does; it polls writable while the buffer has room.
383
+ pub fn alloc_file(self: &Arc<Self>, cred: &Arc<Cred>) -> File {
384
+ let how = OpenHow {
385
+ write: true,
386
+ nonblock: true,
387
+ ..OpenHow::default()
388
+ };
389
+ anon_inode_getfile(Box::new(RequestBodyFile(self.clone())), &how, cred)
390
+ }
391
+
392
+ /// How many bytes a write takes now: what the buffer has left.
393
+ pub fn room(&self) -> usize {
394
+ MAX_SOCKET_BUFFER.saturating_sub(self.pipe().queued.len())
395
+ }
396
+
397
+ /// Whether the seam took everything written, so a flush is done.
398
+ pub fn is_drained(&self) -> bool {
399
+ self.pipe().queued.is_empty()
400
+ }
401
+
402
+ /// Append what of `buf` the buffer has room for: `EAGAIN` while it has
403
+ /// none, and `EPIPE` once the body ended or for a TRACE's content.
404
+ fn write(&self, buf: &[u8]) -> Result<usize, Errno> {
405
+ let mut pipe = self.pipe();
406
+ if pipe.end != BodyEnd::Open || (pipe.refuses_content && !buf.is_empty()) {
407
+ return Err(Errno::BrokenPipe);
408
+ }
409
+ let take = buf.len().min(MAX_SOCKET_BUFFER - pipe.queued.len());
410
+ if take == 0 && !buf.is_empty() {
411
+ return Err(Errno::WouldBlock);
412
+ }
413
+ pipe.queued.extend_from_slice(&buf[..take]);
414
+ let reader = pipe.reader.take();
415
+ drop(pipe);
416
+ if let Some(reader) = reader {
417
+ reader.wake();
418
+ }
419
+ self.move_exchange();
420
+ Ok(take)
421
+ }
422
+
423
+ /// End the body, so the seam sends what is left and finishes the request.
424
+ pub fn finish(&self) {
425
+ self.end(BodyEnd::Finished);
426
+ }
427
+
428
+ /// End the body unfinished, which fails its request with `code`.
429
+ pub fn fail(&self, code: HttpError) {
430
+ self.end(BodyEnd::Failed(code));
431
+ }
432
+
433
+ fn end(&self, end: BodyEnd) {
434
+ let mut pipe = self.pipe();
435
+ if pipe.end != BodyEnd::Open {
436
+ return;
437
+ }
438
+ pipe.end = end;
439
+ let reader = pipe.reader.take();
440
+ drop(pipe);
441
+ if let Some(reader) = reader {
442
+ reader.wake();
443
+ }
444
+ self.wait.wake_up();
445
+ }
446
+
447
+ /// Whether the guest finished the body before it was sent.
448
+ fn is_finished(&self) -> bool {
449
+ self.pipe().end == BodyEnd::Finished
450
+ }
451
+
452
+ /// Whether the guest wrote content the seam has not taken, as a request
453
+ /// policy judges before anything is sent.
454
+ pub(crate) fn has_content(&self) -> bool {
455
+ !self.pipe().queued.is_empty()
456
+ }
457
+
458
+ /// Refuse any content written from now on, as a TRACE carries none.
459
+ pub(crate) fn refuse_content(&self) {
460
+ self.pipe().refuses_content = true;
461
+ }
462
+
463
+ /// The next part of the body for the seam, waking writers the room it
464
+ /// frees.
465
+ fn poll_part(&self, cx: &mut Context<'_>) -> Poll<Option<Result<Bytes, BodyFailed>>> {
466
+ let mut pipe = self.pipe();
467
+ if !pipe.queued.is_empty() {
468
+ let part = pipe.queued.split().freeze();
469
+ drop(pipe);
470
+ self.wait.wake_up();
471
+ return Poll::Ready(Some(Ok(part)));
472
+ }
473
+ match pipe.end {
474
+ BodyEnd::Finished => Poll::Ready(None),
475
+ BodyEnd::Failed(code) => Poll::Ready(Some(Err(BodyFailed(code)))),
476
+ BodyEnd::Open => {
477
+ pipe.reader = Some(cx.waker().clone());
478
+ Poll::Pending
479
+ }
480
+ }
481
+ }
482
+ }
483
+
484
+ impl std::fmt::Debug for RequestBody {
485
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
486
+ f.debug_struct("RequestBody")
487
+ .field("queued", &self.pipe().queued.len())
488
+ .finish_non_exhaustive()
489
+ }
490
+ }
491
+
492
+ /// A body is one stream, the same only as itself.
493
+ impl PartialEq for RequestBody {
494
+ fn eq(&self, other: &Self) -> bool {
495
+ std::ptr::eq(self, other)
496
+ }
497
+ }
498
+
499
+ impl Eq for RequestBody {}
500
+
501
+ /// Why a request body ended unfinished, carried through hyper to the
502
+ /// exchange it fails.
503
+ #[derive(Debug)]
504
+ struct BodyFailed(HttpError);
505
+
506
+ impl std::fmt::Display for BodyFailed {
507
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
508
+ f.write_str("the request body ended unfinished")
509
+ }
510
+ }
511
+
512
+ impl std::error::Error for BodyFailed {}
513
+
514
+ /// A request body as hyper sends it, one part at a time.
515
+ struct StreamedBody(Arc<RequestBody>);
516
+
517
+ impl Body for StreamedBody {
518
+ type Data = Bytes;
519
+ type Error = BodyFailed;
520
+
521
+ fn poll_frame(
522
+ self: Pin<&mut Self>,
523
+ cx: &mut Context<'_>,
524
+ ) -> Poll<Option<Result<http_body::Frame<Bytes>, BodyFailed>>> {
525
+ self.0
526
+ .poll_part(cx)
527
+ .map(|part| part.map(|part| part.map(http_body::Frame::data)))
528
+ }
529
+
530
+ fn is_end_stream(&self) -> bool {
531
+ let pipe = self.0.pipe();
532
+ pipe.end == BodyEnd::Finished && pipe.queued.is_empty()
533
+ }
534
+
535
+ /// Exact once the guest finished the body, so hyper frames it by its
536
+ /// length, as CRuby's Net::HTTP does; chunked while it still streams.
537
+ fn size_hint(&self) -> http_body::SizeHint {
538
+ let pipe = self.0.pipe();
539
+ match pipe.end {
540
+ BodyEnd::Finished => http_body::SizeHint::with_exact(pipe.queued.len() as u64),
541
+ BodyEnd::Open | BodyEnd::Failed(_) => http_body::SizeHint::default(),
542
+ }
543
+ }
544
+ }
545
+
546
+ /// What answers for a request body's file.
547
+ struct RequestBodyFile(Arc<RequestBody>);
548
+
549
+ impl FileOperations for RequestBodyFile {
550
+ fn write_iter(&mut self, _iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, Errno> {
551
+ self.0.write(buf)
552
+ }
553
+
554
+ /// A wait on the body sleeps on the exchange too, whose socket's wake
555
+ /// moves the seam on to take what is written.
556
+ fn poll(&self, _mode: FMode, mut table: Option<&mut PollTable>) -> PollMask {
557
+ if let Some(exchange) = self.0.move_exchange() {
558
+ poll_wait(&exchange.wait, table.as_deref_mut());
559
+ }
560
+ poll_wait(&self.0.wait, table);
561
+ let pipe = self.0.pipe();
562
+ match pipe.end != BodyEnd::Open || pipe.queued.len() < MAX_SOCKET_BUFFER {
563
+ true => PollMask::OUT,
564
+ false => PollMask::default(),
565
+ }
566
+ }
567
+
568
+ fn is_stream(&self) -> bool {
569
+ true
570
+ }
571
+ }
572
+
573
+ /// Why a request has no response, as WASI's `wasi:http` error codes name each
574
+ /// a client may meet; none carries host text.
575
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
576
+ #[non_exhaustive]
577
+ pub enum HttpError {
578
+ /// No entry lets the guest send it.
579
+ Denied,
580
+ /// The authority's name has no address, or no local address could be
581
+ /// assigned to reach it, as wasmtime-wasi-http reads EADDRNOTAVAIL.
582
+ DnsError,
583
+ /// No route reaches the authority's address.
584
+ DestinationUnavailable,
585
+ /// The authority refused the connection.
586
+ ConnectionRefused,
587
+ /// The connection did not open in time.
588
+ ConnectionTimeout,
589
+ /// The response's head did not arrive in time.
590
+ ConnectionReadTimeout,
591
+ /// The connection ended before the response did.
592
+ ConnectionTerminated,
593
+ /// The response was not one HTTP can read.
594
+ ProtocolError,
595
+ /// The request cannot start now, as a full cap leaves it.
596
+ ConnectionLimitReached,
597
+ /// The server's certificate is not one the host's store trusts.
598
+ TlsCertificate,
599
+ /// The server ended TLS with the alert of this id.
600
+ TlsAlertReceived(u8),
601
+ /// TLS could not be agreed with the server.
602
+ TlsProtocol,
603
+ /// The seam failed in a way no other code names.
604
+ Internal,
605
+ }
606
+
607
+ /// A response's head: its status and headers.
608
+ #[derive(Clone, Debug, PartialEq, Eq)]
609
+ pub struct ResponseHead {
610
+ pub status: u16,
611
+ pub headers: Vec<(String, Vec<u8>)>,
612
+ }
613
+
614
+ /// A response's body as the seam streams it.
615
+ pub type ResponseBody = UnsyncBoxBody<Bytes, HttpError>;
616
+
617
+ /// What the outbound seam answers: the head, and the body to read.
618
+ pub struct Response {
619
+ pub head: ResponseHead,
620
+ pub body: ResponseBody,
621
+ }
622
+
623
+ /// What the outbound seam's send runs as, polled by the thread that waits
624
+ /// for the response.
625
+ pub type ResponseFuture = Pin<Box<dyn Future<Output = Result<Response, HttpError>> + Send>>;
626
+
627
+ /// The HTTP sender, as wasmtime's `send_request`. It dials only through the
628
+ /// connector it is handed, so every rule judges where it goes; one dialing
629
+ /// any other way would skip them, so no Host App hands one in. The future
630
+ /// runs on kobako's reactor, so it must never block.
631
+ pub(crate) trait Outbound: Send + Sync {
632
+ /// Send `request` through `connector`.
633
+ fn send_request(&self, request: OutgoingRequest, connector: Connector) -> ResponseFuture;
634
+ }
635
+
636
+ /// What a timeout ends: the request, failed as the error names, or the body's
637
+ /// next read.
638
+ #[derive(Clone, Copy)]
639
+ enum Expiry {
640
+ Fail(HttpError),
641
+ Body,
642
+ }
643
+
644
+ #[derive(Clone, Debug, PartialEq, Eq)]
645
+ enum Phase {
646
+ Sending,
647
+ Answered(ResponseHead),
648
+ Failed(HttpError),
649
+ }
650
+
651
+ struct State {
652
+ phase: Phase,
653
+ /// The body the guest reads, never past one socket buffer.
654
+ body: SkBuffHead,
655
+ /// The frame read from the seam that waits for room in the body, copied
656
+ /// out so the seam's own buffer goes free at once.
657
+ pending: Option<Vec<u8>>,
658
+ body_ended: bool,
659
+ body_failed: bool,
660
+ /// The body waited past its timeout for its next part.
661
+ body_timed_out: bool,
662
+ /// When the head or the body's last part arrived.
663
+ last_part: Option<Instant>,
664
+ /// The task waiting for room in the body's buffer.
665
+ filler: Option<Waker>,
666
+ }
667
+
668
+ impl State {
669
+ /// Whether the body holds nothing yet and may still bring a part: it
670
+ /// neither ended, failed, nor waited past its timeout.
671
+ fn is_awaiting_body(&self) -> bool {
672
+ self.body.is_empty() && !self.body_ended && !self.body_failed && !self.body_timed_out
673
+ }
674
+ }
675
+
676
+ /// One request in flight, then its response: the head once it arrives, and
677
+ /// the body as the task reads it.
678
+ pub struct Exchange {
679
+ state: Arc<Mutex<State>>,
680
+ wait: Arc<WaitQueueHead>,
681
+ task: Mutex<Option<Arc<Task>>>,
682
+ /// The request's place against its Sandbox's cap and the process's.
683
+ place: Mutex<Option<Arc<Place>>>,
684
+ timeouts: Timeouts,
685
+ started: Instant,
686
+ /// When the connector's connect opened, which starts the wait for the
687
+ /// head.
688
+ connected: Arc<OnceLock<Instant>>,
689
+ }
690
+
691
+ impl Exchange {
692
+ /// Send `request` through `seam` on the asking thread, dialing through the
693
+ /// connector `connector_for` makes with the request's place; it counts
694
+ /// against `open_connections` and the process until
695
+ /// released and its connection closed, and a full count answers
696
+ /// `ConnectionLimitReached`.
697
+ pub(crate) fn start(
698
+ seam: Arc<dyn Outbound>,
699
+ request: OutgoingRequest,
700
+ connector_for: impl FnOnce(Arc<Place>) -> Result<Connector, HttpError>,
701
+ open_connections: &Arc<OpenConnections>,
702
+ ) -> Result<Arc<Self>, HttpError> {
703
+ let place = Arc::new(open(open_connections).ok_or(HttpError::ConnectionLimitReached)?);
704
+ let mut connector = connector_for(place.clone())?;
705
+ let place = Some(place);
706
+ let exchange = Arc::new(Self {
707
+ state: Arc::new(Mutex::new(State {
708
+ phase: Phase::Sending,
709
+ body: SkBuffHead::default(),
710
+ pending: None,
711
+ body_ended: false,
712
+ body_failed: false,
713
+ body_timed_out: false,
714
+ last_part: None,
715
+ filler: None,
716
+ })),
717
+ wait: Arc::default(),
718
+ task: Mutex::new(None),
719
+ place: Mutex::new(place),
720
+ timeouts: request.timeouts,
721
+ started: Instant::now(),
722
+ connected: connector.connected.clone(),
723
+ });
724
+ // The task holds what it answers into, never the exchange, so the
725
+ // exchange's last hold, which cancels the task, is never the task's.
726
+ let (state, wait) = (exchange.state.clone(), exchange.wait.clone());
727
+ connector.wait = Some(wait.clone());
728
+ let budget = connector.poll_budget.clone();
729
+ let _ = request.body.exchange.set(Arc::downgrade(&exchange));
730
+ let sending = seam.send_request(request, connector);
731
+ let sent = async move {
732
+ match sending.await {
733
+ Ok(response) => {
734
+ {
735
+ let mut answered = lock(&state);
736
+ // A head arriving past its timeout finds the exchange
737
+ // failed already.
738
+ if answered.phase != Phase::Sending {
739
+ return;
740
+ }
741
+ answered.phase = Phase::Answered(response.head);
742
+ answered.last_part = Some(Instant::now());
743
+ }
744
+ wait.wake_up();
745
+ fill_body(&state, &wait, response.body).await;
746
+ }
747
+ Err(err) => {
748
+ lock(&state).phase = Phase::Failed(err);
749
+ wait.wake_up();
750
+ }
751
+ }
752
+ };
753
+ let task = Arc::new(Task::spending(sent, exchange.wait.clone(), budget));
754
+ *exchange.task.lock().unwrap_or_else(PoisonError::into_inner) = Some(task);
755
+ exchange.poll_task();
756
+ Ok(exchange)
757
+ }
758
+
759
+ /// The exchange's state, its request moved as far as it goes and any
760
+ /// timeout that passed having ended its wait, as a timeout read on its
761
+ /// next look rather than by a timer.
762
+ fn state(&self) -> MutexGuard<'_, State> {
763
+ self.poll_task();
764
+ let mut state = lock(&self.state);
765
+ if self.expire(&mut state) {
766
+ drop(state);
767
+ self.cancel_task();
768
+ state = lock(&self.state);
769
+ }
770
+ state
771
+ }
772
+
773
+ /// Move the request on, on the thread that looks at the exchange, as its
774
+ /// guest waits on or reads it; the task is let go of before it is polled,
775
+ /// so a cancel never waits on this lock.
776
+ fn poll_task(&self) {
777
+ let task = self
778
+ .task
779
+ .lock()
780
+ .unwrap_or_else(PoisonError::into_inner)
781
+ .clone();
782
+ if let Some(task) = task {
783
+ task.poll();
784
+ }
785
+ }
786
+
787
+ /// Drop the task sending the request, with the connection it holds.
788
+ fn cancel_task(&self) {
789
+ let task = self
790
+ .task
791
+ .lock()
792
+ .unwrap_or_else(PoisonError::into_inner)
793
+ .take();
794
+ if let Some(task) = task {
795
+ task.cancel();
796
+ }
797
+ }
798
+
799
+ /// The soonest a timeout ends the wait under way: the connect until it
800
+ /// opens, then the head, then each part of the body; `None` while nothing
801
+ /// is awaited.
802
+ pub fn deadline(&self) -> Option<Instant> {
803
+ self.deadline_of(&lock(&self.state)).map(|(at, _)| at)
804
+ }
805
+
806
+ fn deadline_of(&self, state: &State) -> Option<(Instant, Expiry)> {
807
+ match state.phase {
808
+ Phase::Sending => match self.connected.get() {
809
+ None => Some((
810
+ self.started + bound(self.timeouts.connect),
811
+ Expiry::Fail(HttpError::ConnectionTimeout),
812
+ )),
813
+ Some(at) => Some((
814
+ *at + bound(self.timeouts.first_byte),
815
+ Expiry::Fail(HttpError::ConnectionReadTimeout),
816
+ )),
817
+ },
818
+ Phase::Answered(_) if state.is_awaiting_body() => {
819
+ let after = bound(self.timeouts.between_bytes);
820
+ state.last_part.map(|at| (at + after, Expiry::Body))
821
+ }
822
+ Phase::Answered(_) | Phase::Failed(_) => None,
823
+ }
824
+ }
825
+
826
+ /// End the wait under way once its timeout passed, answering whether it
827
+ /// did, so the task sending the request can be let go.
828
+ fn expire(&self, state: &mut State) -> bool {
829
+ let Some((at, expiry)) = self.deadline_of(state) else {
830
+ return false;
831
+ };
832
+ if Instant::now() < at {
833
+ return false;
834
+ }
835
+ match expiry {
836
+ Expiry::Fail(err) => state.phase = Phase::Failed(err),
837
+ Expiry::Body => state.body_timed_out = true,
838
+ }
839
+ true
840
+ }
841
+
842
+ /// The response's head, or why it has none; `None` while the request is
843
+ /// under way.
844
+ pub fn response(&self) -> Option<Result<ResponseHead, HttpError>> {
845
+ match &self.state().phase {
846
+ Phase::Sending => None,
847
+ Phase::Answered(head) => Some(Ok(head.clone())),
848
+ Phase::Failed(err) => Some(Err(*err)),
849
+ }
850
+ }
851
+
852
+ /// Allocate the file a poll finds readable once the response's head
853
+ /// arrives or the request fails, as `anon_inode_getfile` does.
854
+ pub fn alloc_response_file(self: &Arc<Self>, cred: &Arc<Cred>) -> File {
855
+ let how = OpenHow {
856
+ read: true,
857
+ nonblock: true,
858
+ ..OpenHow::default()
859
+ };
860
+ anon_inode_getfile(Box::new(ResponseFile(self.clone())), &how, cred)
861
+ }
862
+
863
+ /// Allocate the file the response's body reads from, as
864
+ /// `anon_inode_getfile` does.
865
+ pub fn alloc_body_file(self: &Arc<Self>, cred: &Arc<Cred>) -> File {
866
+ let how = OpenHow {
867
+ read: true,
868
+ nonblock: true,
869
+ ..OpenHow::default()
870
+ };
871
+ anon_inode_getfile(Box::new(BodyFile(self.clone())), &how, cred)
872
+ }
873
+
874
+ /// Read what the body holds into `buf`: zero at its end, `WouldBlock`
875
+ /// while it holds nothing yet, `ConnectionReset` for a body cut short, and
876
+ /// `TimedOut` once its next part waited past its timeout.
877
+ fn read(&self, buf: &mut [u8]) -> Result<usize, Errno> {
878
+ let mut state = self.state();
879
+ if state.body.is_empty() {
880
+ return match (state.body_ended, state.body_failed, state.body_timed_out) {
881
+ (_, true, _) => Err(Errno::ConnectionReset),
882
+ (_, _, true) => Err(Errno::TimedOut),
883
+ (true, _, _) => Ok(0),
884
+ _ => Err(Errno::WouldBlock),
885
+ };
886
+ }
887
+ let n = state.body.read_into(buf);
888
+ let filler = state.filler.take();
889
+ drop(state);
890
+ if let Some(filler) = filler {
891
+ filler.wake();
892
+ }
893
+ Ok(n)
894
+ }
895
+
896
+ /// Let the exchange go, dropping its task with the connection it holds
897
+ /// and the body's buffer. The head stays readable while the guest keeps
898
+ /// the exchange.
899
+ pub fn release(&self) {
900
+ self.cancel_task();
901
+ let mut state = lock(&self.state);
902
+ state.body.purge();
903
+ state.pending = None;
904
+ drop(state);
905
+ *self.place.lock().unwrap_or_else(PoisonError::into_inner) = None;
906
+ }
907
+ }
908
+
909
+ /// The last hold on an exchange lets it go, as the last `fput` of a socket's
910
+ /// file releases it, so no exchange outlives what the guest holds of it.
911
+ impl Drop for Exchange {
912
+ fn drop(&mut self) {
913
+ self.release();
914
+ }
915
+ }
916
+
917
+ /// What answers for the file an exchange's response is awaited on.
918
+ struct ResponseFile(Arc<Exchange>);
919
+
920
+ impl FileOperations for ResponseFile {
921
+ fn poll(&self, _mode: FMode, table: Option<&mut PollTable>) -> PollMask {
922
+ poll_wait(&self.0.wait, table);
923
+ match self.0.state().phase {
924
+ Phase::Sending => PollMask::default(),
925
+ Phase::Answered(_) | Phase::Failed(_) => PollMask::IN,
926
+ }
927
+ }
928
+
929
+ fn is_stream(&self) -> bool {
930
+ true
931
+ }
932
+ }
933
+
934
+ /// What answers for the file an exchange's body is read from.
935
+ struct BodyFile(Arc<Exchange>);
936
+
937
+ impl FileOperations for BodyFile {
938
+ fn read_iter(&mut self, _iocb: &mut Kiocb, buf: &mut [u8]) -> Result<usize, Errno> {
939
+ self.0.read(buf)
940
+ }
941
+
942
+ fn poll(&self, _mode: FMode, table: Option<&mut PollTable>) -> PollMask {
943
+ poll_wait(&self.0.wait, table);
944
+ let state = self.0.state();
945
+ let settled = !matches!(state.phase, Phase::Sending);
946
+ match settled && !state.is_awaiting_body() {
947
+ true => PollMask::IN,
948
+ false => PollMask::default(),
949
+ }
950
+ }
951
+
952
+ fn is_stream(&self) -> bool {
953
+ true
954
+ }
955
+ }
956
+
957
+ fn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {
958
+ state.lock().unwrap_or_else(PoisonError::into_inner)
959
+ }
960
+
961
+ /// Move `body` into the exchange's buffer frame by frame, never past one
962
+ /// socket buffer, until the body ends or fails, or the exchange lets the task
963
+ /// go. A frame is copied out of the seam as it is read, then waits until the
964
+ /// body has room for it whole, or goes in at once while the body is empty;
965
+ /// the task takes no further frame while one waits.
966
+ async fn fill_body(state: &Mutex<State>, wait: &WaitQueueHead, mut body: ResponseBody) {
967
+ loop {
968
+ let moved = poll_fn(|cx| {
969
+ let mut state = lock(state);
970
+ if let Some(frame) = state.pending.take() {
971
+ if state.body.len() + frame.len() <= MAX_SOCKET_BUFFER || state.body.is_empty() {
972
+ state.body.push_buffer(frame);
973
+ state.last_part = Some(Instant::now());
974
+ return Poll::Ready(true);
975
+ }
976
+ state.pending = Some(frame);
977
+ } else if state.pending.is_none() {
978
+ return Poll::Ready(false);
979
+ }
980
+ state.filler = Some(cx.waker().clone());
981
+ Poll::Pending
982
+ })
983
+ .await;
984
+ if moved {
985
+ wait.wake_up();
986
+ continue;
987
+ }
988
+ match poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await {
989
+ Some(Ok(frame)) => {
990
+ let Ok(data) = frame.into_data() else {
991
+ continue;
992
+ };
993
+ let mut state = lock(state);
994
+ state.pending = Some(data.to_vec()).filter(|frame| !frame.is_empty());
995
+ continue;
996
+ }
997
+ Some(Err(_)) => lock(state).body_failed = true,
998
+ None => lock(state).body_ended = true,
999
+ }
1000
+ wait.wake_up();
1001
+ return;
1002
+ }
1003
+ }
1004
+
1005
+ /// The outbound seam: hyper's HTTP/1 client, with no redirect, proxy, or
1006
+ /// decompression, every connection opened by kobako's connector and TLS ended
1007
+ /// on the host. It holds its own TLS configuration, so its sessions end with
1008
+ /// the Invocation that holds it.
1009
+ pub struct HyperOutbound {
1010
+ tls: Option<Arc<rustls::ClientConfig>>,
1011
+ }
1012
+
1013
+ impl HyperOutbound {
1014
+ pub fn new() -> Self {
1015
+ Self {
1016
+ tls: new_platform_tls(),
1017
+ }
1018
+ }
1019
+ }
1020
+
1021
+ impl Default for HyperOutbound {
1022
+ fn default() -> Self {
1023
+ Self::new()
1024
+ }
1025
+ }
1026
+
1027
+ impl Outbound for HyperOutbound {
1028
+ fn send_request(&self, request: OutgoingRequest, connector: Connector) -> ResponseFuture {
1029
+ let tls = match request.scheme {
1030
+ Scheme::Http => None,
1031
+ Scheme::Https => match self.tls.clone() {
1032
+ Some(config) => Some(config),
1033
+ None => return Box::pin(async { Err(HttpError::TlsProtocol) }),
1034
+ },
1035
+ };
1036
+ Box::pin(async move {
1037
+ let http = to_hyper_request(request)?;
1038
+ let connection = connector.dial().await?;
1039
+ match tls {
1040
+ None => send_over(Wire(connection), http).await,
1041
+ Some(config) => {
1042
+ let name = rustls::pki_types::ServerName::try_from(connector.authority().0)
1043
+ .map_err(|_| HttpError::ProtocolError)?;
1044
+ let session = tokio_rustls::TlsConnector::from(config)
1045
+ .connect(name, connection)
1046
+ .await
1047
+ .map_err(|err| HttpError::from_tls(&err))?;
1048
+ send_over(Wire(session), http).await
1049
+ }
1050
+ }
1051
+ })
1052
+ }
1053
+ }
1054
+
1055
+ /// `request` as hyper sends it: the path with its query as the target, a
1056
+ /// `host` header naming the authority, the `close` option, and each header
1057
+ /// with its credentials swapped in. The seam reuses no connection, and says
1058
+ /// so as RFC 9112 § 9.3 asks, so a server runs nothing a body hid behind the
1059
+ /// request the rules judged.
1060
+ fn to_hyper_request(request: OutgoingRequest) -> Result<hyper::Request<StreamedBody>, HttpError> {
1061
+ let mut builder = hyper::Request::builder()
1062
+ .method(request.method.as_str())
1063
+ .uri(request.path_with_query.as_str())
1064
+ .header("host", request.authority.as_str())
1065
+ .header("connection", "close");
1066
+ for (name, value) in &request.headers {
1067
+ let value = request
1068
+ .swaps
1069
+ .iter()
1070
+ .fold(value.clone(), |value, swap| swap.apply(name, &value));
1071
+ builder = builder.header(name.as_str(), value);
1072
+ }
1073
+ // A body still streaming is chunked whatever the method, so hyper never
1074
+ // takes a GET's for empty and leaves what the guest writes unsent.
1075
+ if !request.body.is_finished() {
1076
+ builder = builder.header("transfer-encoding", "chunked");
1077
+ }
1078
+ builder
1079
+ .body(StreamedBody(request.body))
1080
+ .map_err(|_| HttpError::ProtocolError)
1081
+ }
1082
+
1083
+ /// Send `request` over `wire` as HTTP/1, driving the connection beside it, and
1084
+ /// answer its response, whose body drives the connection on until it ends.
1085
+ async fn send_over<T, B>(wire: Wire<T>, request: hyper::Request<B>) -> Result<Response, HttpError>
1086
+ where
1087
+ T: AsyncRead + AsyncWrite + Unpin + Send + 'static,
1088
+ B: Body<Data = Bytes> + Send + 'static,
1089
+ B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
1090
+ {
1091
+ let (mut sender, connection) = hyper::client::conn::http1::Builder::new()
1092
+ .max_buf_size(MAX_READ_BUFFER)
1093
+ .handshake(wire)
1094
+ .await
1095
+ .map_err(|err| HttpError::from_hyper(&err))?;
1096
+ let mut connection: ConnectionTask = Some(Box::pin(async move {
1097
+ let _ = connection.await;
1098
+ }));
1099
+ let mut sending = Box::pin(sender.send_request(request));
1100
+ let response = poll_fn(|cx| {
1101
+ drive(&mut connection, cx);
1102
+ sending.as_mut().poll(cx)
1103
+ })
1104
+ .await
1105
+ .map_err(|err| HttpError::from_hyper(&err))?;
1106
+ let head = ResponseHead {
1107
+ status: response.status().as_u16(),
1108
+ headers: response
1109
+ .headers()
1110
+ .iter()
1111
+ .map(|(name, value)| (name.as_str().to_string(), value.as_bytes().to_vec()))
1112
+ .collect(),
1113
+ };
1114
+ let body = DrivenBody {
1115
+ body: response.into_body(),
1116
+ connection,
1117
+ };
1118
+ Ok(Response {
1119
+ head,
1120
+ body: body.boxed_unsync(),
1121
+ })
1122
+ }
1123
+
1124
+ /// The connection's own future, until it ends.
1125
+ type ConnectionTask = Option<Pin<Box<dyn Future<Output = ()> + Send>>>;
1126
+
1127
+ fn drive(connection: &mut ConnectionTask, cx: &mut Context<'_>) {
1128
+ if let Some(running) = connection.as_mut() {
1129
+ if running.as_mut().poll(cx).is_ready() {
1130
+ *connection = None;
1131
+ }
1132
+ }
1133
+ }
1134
+
1135
+ /// A response's body, driving its connection as it is read.
1136
+ struct DrivenBody {
1137
+ body: hyper::body::Incoming,
1138
+ connection: ConnectionTask,
1139
+ }
1140
+
1141
+ impl Body for DrivenBody {
1142
+ type Data = Bytes;
1143
+ type Error = HttpError;
1144
+
1145
+ fn poll_frame(
1146
+ self: Pin<&mut Self>,
1147
+ cx: &mut Context<'_>,
1148
+ ) -> Poll<Option<Result<http_body::Frame<Bytes>, HttpError>>> {
1149
+ let this = self.get_mut();
1150
+ drive(&mut this.connection, cx);
1151
+ Pin::new(&mut this.body)
1152
+ .poll_frame(cx)
1153
+ .map_err(|_| HttpError::ConnectionTerminated)
1154
+ }
1155
+ }
1156
+
1157
+ /// A connection, plain or under TLS, as hyper reads and writes it.
1158
+ struct Wire<T: AsyncWrite + Unpin>(T);
1159
+
1160
+ /// A connection let go shuts down first, however far its exchange got, so TLS
1161
+ /// sends the closure alert RFC 8446 § 6.1 asks before a close. It waits for
1162
+ /// no answer, as CRuby's `SSLSocket#sysclose` waits for none.
1163
+ impl<T: AsyncWrite + Unpin> Drop for Wire<T> {
1164
+ fn drop(&mut self) {
1165
+ let mut cx = Context::from_waker(Waker::noop());
1166
+ let _ = Pin::new(&mut self.0).poll_shutdown(&mut cx);
1167
+ }
1168
+ }
1169
+
1170
+ impl<T: AsyncRead + AsyncWrite + Unpin> hyper::rt::Read for Wire<T> {
1171
+ fn poll_read(
1172
+ self: Pin<&mut Self>,
1173
+ cx: &mut Context<'_>,
1174
+ mut buf: hyper::rt::ReadBufCursor<'_>,
1175
+ ) -> Poll<io::Result<()>> {
1176
+ // SAFETY: `ReadBuf` only writes initialized bytes into the cursor's
1177
+ // spare capacity, and `advance` counts no more than it wrote.
1178
+ let filled = unsafe {
1179
+ let mut read = ReadBuf::uninit(buf.as_mut());
1180
+ match Pin::new(&mut self.get_mut().0).poll_read(cx, &mut read) {
1181
+ Poll::Ready(Ok(())) => read.filled().len(),
1182
+ other => return other,
1183
+ }
1184
+ };
1185
+ unsafe { buf.advance(filled) };
1186
+ Poll::Ready(Ok(()))
1187
+ }
1188
+ }
1189
+
1190
+ impl<T: AsyncWrite + Unpin> hyper::rt::Write for Wire<T> {
1191
+ fn poll_write(
1192
+ self: Pin<&mut Self>,
1193
+ cx: &mut Context<'_>,
1194
+ buf: &[u8],
1195
+ ) -> Poll<io::Result<usize>> {
1196
+ Pin::new(&mut self.get_mut().0).poll_write(cx, buf)
1197
+ }
1198
+
1199
+ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1200
+ Pin::new(&mut self.get_mut().0).poll_flush(cx)
1201
+ }
1202
+
1203
+ fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1204
+ Pin::new(&mut self.get_mut().0).poll_shutdown(cx)
1205
+ }
1206
+ }
1207
+
1208
+ impl HttpError {
1209
+ /// The code a failed TLS handshake answers, as wasmtime-wasi-http's
1210
+ /// `p2_error_from_tls` names each: the rustls error it carries, a
1211
+ /// connection the server ended as `connection-terminated`, and any other
1212
+ /// as `TLS-protocol-error`; a failure for want of memory is the seam's own
1213
+ /// failure.
1214
+ pub(crate) fn from_tls(err: &io::Error) -> Self {
1215
+ match err
1216
+ .get_ref()
1217
+ .and_then(|inner| inner.downcast_ref::<rustls::Error>())
1218
+ {
1219
+ Some(rustls::Error::InvalidCertificate(_)) => return Self::TlsCertificate,
1220
+ Some(rustls::Error::AlertReceived(alert)) => {
1221
+ return Self::TlsAlertReceived(u8::from(*alert))
1222
+ }
1223
+ Some(_) => return Self::TlsProtocol,
1224
+ None => {}
1225
+ }
1226
+ if err.kind() == io::ErrorKind::UnexpectedEof {
1227
+ return Self::ConnectionTerminated;
1228
+ }
1229
+ Self::from_open_connection(&Errno::from_io_error(err)).unwrap_or(Self::TlsProtocol)
1230
+ }
1231
+
1232
+ /// The code an open connection failing with `err` answers: one the peer or
1233
+ /// the Invocation's end cut as `connection-terminated`, and a failure for
1234
+ /// want of memory as the seam's own; `None` for a
1235
+ /// failure the protocol over it names.
1236
+ fn from_open_connection(err: &Errno) -> Option<Self> {
1237
+ match err {
1238
+ Errno::ConnectionReset | Errno::ConnectionAborted | Errno::BrokenPipe => {
1239
+ Some(Self::ConnectionTerminated)
1240
+ }
1241
+ Errno::OutOfMemory => Some(Self::Internal),
1242
+ _ => None,
1243
+ }
1244
+ }
1245
+
1246
+ /// The code a connection failing with `err` answers, as wasmtime-wasi-http
1247
+ /// names each; a failure for want of memory is the seam's own failure.
1248
+ pub(crate) fn from_errno(err: &Errno) -> Self {
1249
+ match err {
1250
+ Errno::OutOfMemory => Self::Internal,
1251
+ Errno::TimedOut => Self::ConnectionTimeout,
1252
+ Errno::HostUnreachable
1253
+ | Errno::NetworkUnreachable
1254
+ | Errno::NetworkDown
1255
+ | Errno::AddressFamilyNotSupported => Self::DestinationUnavailable,
1256
+ Errno::ConnectionReset | Errno::ConnectionAborted => Self::ConnectionTerminated,
1257
+ Errno::AddressNotAvailable => Self::DnsError,
1258
+ _ => Self::ConnectionRefused,
1259
+ }
1260
+ }
1261
+
1262
+ /// The code a failed exchange answers. Its connection failing under it
1263
+ /// answers as an open connection's failure does, as the TLS handshake's
1264
+ /// does, so a failure answers one code wherever in the exchange it lands.
1265
+ fn from_hyper(err: &hyper::Error) -> Self {
1266
+ if let Some(BodyFailed(code)) =
1267
+ std::error::Error::source(err).and_then(|source| source.downcast_ref::<BodyFailed>())
1268
+ {
1269
+ return *code;
1270
+ }
1271
+ let failed = std::error::Error::source(err)
1272
+ .and_then(|source| source.downcast_ref::<io::Error>())
1273
+ .and_then(io::Error::get_ref)
1274
+ .and_then(|inner| inner.downcast_ref::<CarriedErrno>());
1275
+ if let Some(code) = failed.and_then(|CarriedErrno(errno)| Self::from_open_connection(errno))
1276
+ {
1277
+ return code;
1278
+ }
1279
+ if err.is_parse() || err.is_parse_status() {
1280
+ Self::ProtocolError
1281
+ } else if err.is_timeout() {
1282
+ Self::ConnectionTimeout
1283
+ } else if err.is_incomplete_message() || err.is_closed() || err.is_canceled() {
1284
+ Self::ConnectionTerminated
1285
+ } else {
1286
+ Self::Internal
1287
+ }
1288
+ }
1289
+ }
1290
+
1291
+ #[cfg(test)]
1292
+ mod tests {
1293
+ use std::io::{BufRead, BufReader, Read, Write};
1294
+ use std::net::TcpListener;
1295
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
1296
+ use std::thread;
1297
+ use std::time::Duration;
1298
+
1299
+ use std::net::SocketAddr;
1300
+
1301
+ use super::super::family::testing::{CountsDials, StallsLookups};
1302
+ use super::*;
1303
+ use crate::net::{HostInet, Namespace, OpenConnections, ProtocolFamily};
1304
+ use crate::network::Protocol;
1305
+ use crate::network::{Builder, Endpoint, Network};
1306
+ use crate::security::prepare_creds;
1307
+
1308
+ // @behavior NW-225
1309
+ #[test]
1310
+ fn a_failed_dial_answers_the_code_its_host_error_names() {
1311
+ let dials = [
1312
+ io::ErrorKind::TimedOut,
1313
+ io::ErrorKind::ConnectionRefused,
1314
+ io::ErrorKind::ConnectionReset,
1315
+ io::ErrorKind::ConnectionAborted,
1316
+ io::ErrorKind::HostUnreachable,
1317
+ io::ErrorKind::NetworkUnreachable,
1318
+ io::ErrorKind::NetworkDown,
1319
+ io::ErrorKind::AddrNotAvailable,
1320
+ ]
1321
+ .map(|kind| HttpError::from_errno(&Errno::from_io_error(&io::Error::from(kind))));
1322
+ assert_eq!(
1323
+ dials,
1324
+ [
1325
+ HttpError::ConnectionTimeout,
1326
+ HttpError::ConnectionRefused,
1327
+ HttpError::ConnectionTerminated,
1328
+ HttpError::ConnectionTerminated,
1329
+ HttpError::DestinationUnavailable,
1330
+ HttpError::DestinationUnavailable,
1331
+ HttpError::DestinationUnavailable,
1332
+ HttpError::DnsError,
1333
+ ],
1334
+ "a dial that timed out, was refused, reset, aborted, found no route to its host or \
1335
+ network, or had no local address must answer connection-timeout, \
1336
+ connection-refused, connection-terminated twice, destination-unavailable three \
1337
+ times, and DNS-error, as wasmtime-wasi-http names each"
1338
+ );
1339
+ }
1340
+
1341
+ // @behavior NW-225
1342
+ #[test]
1343
+ fn a_dial_to_a_host_down_answers_connection_refused() {
1344
+ use rustix::io::Errno as HostErrno;
1345
+ #[cfg(target_os = "linux")]
1346
+ let downs = [
1347
+ ("EHOSTDOWN", HostErrno::HOSTDOWN),
1348
+ ("ENONET", HostErrno::NONET),
1349
+ ];
1350
+ #[cfg(not(target_os = "linux"))]
1351
+ let downs = [("EHOSTDOWN", HostErrno::HOSTDOWN)];
1352
+ for (name, errno) in downs {
1353
+ let err = io::Error::from_raw_os_error(errno.raw_os_error());
1354
+ assert_eq!(
1355
+ HttpError::from_errno(&Errno::from_io_error(&err)),
1356
+ HttpError::ConnectionRefused,
1357
+ "a dial failing with {name} must answer connection-refused, as \
1358
+ wasmtime-wasi-http answers an errno std names no kind for"
1359
+ );
1360
+ }
1361
+ }
1362
+
1363
+ // @behavior NW-225
1364
+ #[test]
1365
+ fn a_failed_tls_handshake_answers_the_code_wasmtime_wasi_http_gives_it() {
1366
+ let alert = io::Error::new(
1367
+ io::ErrorKind::InvalidData,
1368
+ rustls::Error::AlertReceived(rustls::AlertDescription::HandshakeFailure),
1369
+ );
1370
+ let handshakes = [
1371
+ io::ErrorKind::UnexpectedEof,
1372
+ io::ErrorKind::ConnectionReset,
1373
+ io::ErrorKind::BrokenPipe,
1374
+ io::ErrorKind::InvalidData,
1375
+ io::ErrorKind::TimedOut,
1376
+ ]
1377
+ .map(|kind| HttpError::from_tls(&io::Error::from(kind)));
1378
+ assert_eq!(
1379
+ (handshakes, HttpError::from_tls(&alert)),
1380
+ (
1381
+ [
1382
+ HttpError::ConnectionTerminated,
1383
+ HttpError::ConnectionTerminated,
1384
+ HttpError::ConnectionTerminated,
1385
+ HttpError::TlsProtocol,
1386
+ HttpError::TlsProtocol,
1387
+ ],
1388
+ HttpError::TlsAlertReceived(40)
1389
+ ),
1390
+ "a TLS handshake the server ended by EOF, reset, or a broken pipe must answer \
1391
+ connection-terminated, bytes TLS could not read or any other failure \
1392
+ TLS-protocol-error, and a handshake_failure alert TLS-alert-received with its id, as \
1393
+ wasmtime-wasi-http's p2_error_from_tls names each"
1394
+ );
1395
+ }
1396
+
1397
+ /// A loopback server answering one request with `hello`, handing back the
1398
+ /// request line and headers it read.
1399
+ fn serve_once() -> (u16, thread::JoinHandle<Vec<String>>) {
1400
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1401
+ let port = listener.local_addr().unwrap().port();
1402
+ let server = thread::spawn(move || {
1403
+ let (stream, _) = listener.accept().unwrap();
1404
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
1405
+ let mut head = Vec::new();
1406
+ loop {
1407
+ let mut line = String::new();
1408
+ reader.read_line(&mut line).unwrap();
1409
+ if line.trim_end().is_empty() {
1410
+ break;
1411
+ }
1412
+ head.push(line.trim_end().to_string());
1413
+ }
1414
+ (&stream)
1415
+ .write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\nx-kind: test\r\n\r\nhello")
1416
+ .unwrap();
1417
+ head
1418
+ });
1419
+ (port, server)
1420
+ }
1421
+
1422
+ /// A namespace whose one entry holds `endpoints`.
1423
+ fn namespace(endpoints: Vec<Endpoint>) -> Namespace {
1424
+ let mut entry = Builder::default();
1425
+ endpoints.into_iter().for_each(|endpoint| {
1426
+ entry.endpoint(endpoint);
1427
+ });
1428
+ let network = Network::new("web", Arc::new(entry)).unwrap();
1429
+ Namespace::for_network(&network, Arc::new(HostInet), Arc::new(HyperOutbound::new()))
1430
+ }
1431
+
1432
+ /// A namespace whose one entry holds `endpoints`, over a host that counts
1433
+ /// each dial it is asked for, so a request sending nothing dials nothing.
1434
+ fn counting_namespace(endpoints: Vec<Endpoint>) -> (Namespace, Arc<CountsDials>) {
1435
+ let mut entry = Builder::default();
1436
+ endpoints.into_iter().for_each(|endpoint| {
1437
+ entry.endpoint(endpoint);
1438
+ });
1439
+ let network = Network::new("web", Arc::new(entry)).unwrap();
1440
+ let family = Arc::new(CountsDials::default());
1441
+ let outbound = Arc::new(HyperOutbound::new());
1442
+ (
1443
+ Namespace::for_network(&network, family.clone(), outbound),
1444
+ family,
1445
+ )
1446
+ }
1447
+
1448
+ fn greeting_request(authority: &str) -> OutgoingRequest {
1449
+ let mut request = OutgoingRequest::new("GET", Scheme::Http, authority);
1450
+ request.path_with_query = "/greeting?lang=en".to_string();
1451
+ request
1452
+ }
1453
+
1454
+ /// The exchange's head, then its whole body.
1455
+ fn read_response(exchange: &Exchange) -> Result<(ResponseHead, Vec<u8>), HttpError> {
1456
+ let head = settled(exchange)?;
1457
+ let mut body = Vec::new();
1458
+ let mut buf = [0; 64];
1459
+ let mut ended = None;
1460
+ crate::sched::testing::wait_until(
1461
+ "the response's body ending, so its server never closed it or its read never woke",
1462
+ || match exchange.read(&mut buf) {
1463
+ Ok(0) => {
1464
+ ended = Some(Ok(()));
1465
+ true
1466
+ }
1467
+ Ok(n) => {
1468
+ body.extend_from_slice(&buf[..n]);
1469
+ false
1470
+ }
1471
+ Err(Errno::WouldBlock) => false,
1472
+ Err(_) => {
1473
+ ended = Some(Err(HttpError::ConnectionTerminated));
1474
+ true
1475
+ }
1476
+ },
1477
+ );
1478
+ ended.expect("the body ended").map(|()| (head, body))
1479
+ }
1480
+
1481
+ // @behavior NW-225
1482
+ #[test]
1483
+ fn a_request_to_a_name_with_no_address_answers_dns_error_undialed() {
1484
+ let mut entry = Builder::default();
1485
+ entry.endpoint(Endpoint::new("missing.test", 80).unwrap());
1486
+ let network = Network::new("web", Arc::new(entry)).unwrap();
1487
+ // A Mock answers a name it holds no route for with no address.
1488
+ let mock = Arc::new(crate::net::Mock::default());
1489
+ let namespace = Namespace::for_network(
1490
+ &network,
1491
+ mock.clone(),
1492
+ Arc::new(HyperOutbound { tls: None }),
1493
+ );
1494
+ let exchange = crate::net::send(
1495
+ &namespace,
1496
+ &prepare_creds(&[], None),
1497
+ greeting_request("missing.test"),
1498
+ )
1499
+ .expect("the endpoint admits it");
1500
+ assert_eq!(
1501
+ (read_response(&exchange).err(), mock.dialed_addresses()),
1502
+ (Some(HttpError::DnsError), Vec::new()),
1503
+ "a request to a name its resolver finds no address for must answer DNS-error, as \
1504
+ wasmtime-wasi-http answers a failed lookup, and dial nothing"
1505
+ );
1506
+ }
1507
+
1508
+ #[test]
1509
+ fn an_https_request_without_trust_roots_dials_nothing() {
1510
+ let mut entry = Builder::default();
1511
+ entry.endpoint(Endpoint::new("127.0.0.1", 443).unwrap());
1512
+ let network = Network::new("web", Arc::new(entry)).unwrap();
1513
+ let family = Arc::new(CountsDials::default());
1514
+ let namespace = Namespace::for_network(
1515
+ &network,
1516
+ family.clone(),
1517
+ Arc::new(HyperOutbound { tls: None }),
1518
+ );
1519
+ let cred = prepare_creds(&[], None);
1520
+ let mut request = OutgoingRequest::new("GET", Scheme::Https, "127.0.0.1:443");
1521
+ request.path_with_query = "/".to_string();
1522
+ let exchange =
1523
+ crate::net::send(&namespace, &cred, request).expect("the endpoint admits it");
1524
+ let answer = settled(&exchange);
1525
+ assert_eq!(
1526
+ (answer.err(), family.dials()),
1527
+ (Some(HttpError::TlsProtocol), 0),
1528
+ "an https request through a seam with no trust roots must answer TlsProtocol before \
1529
+ dialing the host"
1530
+ );
1531
+ }
1532
+
1533
+ // @behavior NW-022
1534
+ #[test]
1535
+ fn a_released_requests_upstream_still_sending_holds_its_place() {
1536
+ // A released connection's queue only shrinks, so one still holding
1537
+ // bytes after the second request was sent held them while it was
1538
+ // sent. A try whose queue drained first proves nothing and goes again.
1539
+ let attempt = || {
1540
+ // TCP fixes a connection's window scale in its handshake and never
1541
+ // shrinks a window it offered, so only a receive buffer set before
1542
+ // listening keeps what the peer takes to a few kilobytes.
1543
+ let listener = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None)
1544
+ .expect("a loopback socket");
1545
+ listener.set_recv_buffer_size(4096).unwrap();
1546
+ listener
1547
+ .bind(&SocketAddr::from(([127, 0, 0, 1], 0)).into())
1548
+ .expect("a loopback listener");
1549
+ listener.listen(1).unwrap();
1550
+ let listener = std::net::TcpListener::from(listener);
1551
+ let port = listener.local_addr().unwrap().port();
1552
+ let mut entry = Builder::default();
1553
+ entry.endpoint(Endpoint::new("127.0.0.1", port).unwrap());
1554
+ let network = Network::new("web", Arc::new(entry)).unwrap();
1555
+ let namespace = Namespace::new(
1556
+ [&network],
1557
+ &crate::net::Backends::new(Arc::new(HostInet), Arc::new(HostInet)),
1558
+ OpenConnections::new(Some(1)),
1559
+ None,
1560
+ )
1561
+ .expect("the endpoints compile")
1562
+ .with_outbound(Arc::new(HyperOutbound::new()));
1563
+ let cred = prepare_creds(&[], None);
1564
+ let authority = format!("127.0.0.1:{port}");
1565
+ let mut request = OutgoingRequest::new("POST", Scheme::Http, &authority);
1566
+ request.path_with_query = "/".to_string();
1567
+ // Linux sizes a send buffer as the connection opens, from its
1568
+ // MSS, up to `tcp_wmem`'s default most of 4 MiB, so a body past
1569
+ // that always leaves bytes in the upstream's queue.
1570
+ request.body = RequestBody::finished(&vec![b'b'; 8 * 1024 * 1024]);
1571
+ let exchange =
1572
+ crate::net::send(&namespace, &cred, request).expect("the endpoint admits it");
1573
+ // The peer accepts and never reads, so the request's bytes stay queued.
1574
+ let (peer, _) = listener.accept().expect("the listener accepts");
1575
+ // A send buffer set by hand stops growing, so once the peer's
1576
+ // window is full the host takes no more of the body.
1577
+ let upstreams = namespace.tcp_sockets().held();
1578
+ for upstream in &upstreams {
1579
+ upstream.lock_host_send_buffer(4096);
1580
+ }
1581
+ // Each look moves the request on, as its guest's poll does.
1582
+ crate::sched::testing::wait_until(
1583
+ "the request's body queueing on its upstream",
1584
+ || {
1585
+ exchange.response().is_some()
1586
+ || upstreams.iter().any(|upstream| !upstream.is_drained())
1587
+ },
1588
+ );
1589
+ exchange.release();
1590
+ let while_sending =
1591
+ crate::net::send(&namespace, &cred, greeting_request(&authority)).err();
1592
+ let still_sending = upstreams.iter().any(|upstream| !upstream.is_drained());
1593
+ drop(peer);
1594
+ let once_closed = crate::sched::testing::holds_within_max_wait(|| {
1595
+ crate::net::send(&namespace, &cred, greeting_request(&authority)).is_ok()
1596
+ });
1597
+ still_sending.then_some((while_sending, once_closed))
1598
+ };
1599
+ assert_eq!(
1600
+ (0..5).find_map(|_| attempt()),
1601
+ Some((Some(HttpError::ConnectionLimitReached), true)),
1602
+ "a request past an open_connection_limit of 1 must answer ConnectionLimitReached \
1603
+ while a released request's connection still sends its queued body, and send once \
1604
+ that connection closed"
1605
+ );
1606
+ }
1607
+
1608
+ /// A host refusing every dial, whose resolver records the thread each
1609
+ /// query starts on and never answers.
1610
+ #[derive(Default)]
1611
+ struct RecordsResolveThread(Mutex<Vec<thread::ThreadId>>);
1612
+
1613
+ impl ProtocolFamily for RecordsResolveThread {
1614
+ fn connect(&self, _addr: SocketAddr) -> io::Result<std::net::TcpStream> {
1615
+ Err(io::ErrorKind::ConnectionRefused.into())
1616
+ }
1617
+ }
1618
+
1619
+ impl crate::net::Resolver for RecordsResolveThread {
1620
+ fn resolve(&self, _name: &str) -> crate::net::Resolving {
1621
+ self.0.lock().unwrap().push(thread::current().id());
1622
+ Box::pin(std::future::pending())
1623
+ }
1624
+ }
1625
+
1626
+ // The reactor never makes the call a Resolver may block on: a request's
1627
+ // lookup starts on the thread that sends it.
1628
+ #[test]
1629
+ fn a_requests_lookup_starts_on_the_thread_that_sends_it() {
1630
+ let mut entry = Builder::default();
1631
+ entry.endpoint(Endpoint::new("api.example.com", 80).unwrap());
1632
+ let network = Network::new("web", Arc::new(entry)).unwrap();
1633
+ let family = Arc::new(RecordsResolveThread::default());
1634
+ let namespace = Namespace::new(
1635
+ [&network],
1636
+ &crate::net::Backends::new(family.clone(), family.clone()),
1637
+ OpenConnections::new(None),
1638
+ None,
1639
+ )
1640
+ .expect("the endpoints compile");
1641
+ let cred = prepare_creds(&[], None);
1642
+ let exchange = crate::net::send(&namespace, &cred, greeting_request("api.example.com"))
1643
+ .expect("the endpoint admits it");
1644
+ // The send polls its request once before it answers, so a lookup that
1645
+ // starts on its thread is recorded by now.
1646
+ let started_on = family.0.lock().unwrap().clone();
1647
+ exchange.release();
1648
+ assert_eq!(
1649
+ started_on,
1650
+ vec![thread::current().id()],
1651
+ "a request's lookup must start once, on the thread that sends the request, never \
1652
+ on the reactor"
1653
+ );
1654
+ }
1655
+
1656
+ // @behavior NW-085
1657
+ #[test]
1658
+ fn a_released_requests_lookup_is_cancelled_and_gives_its_place_back_at_once() {
1659
+ let (started, resolving) = std::sync::mpsc::channel();
1660
+ let mut entry = Builder::default();
1661
+ entry.endpoint(Endpoint::new("api.example.com", 80).unwrap());
1662
+ let network = Network::new("web", Arc::new(entry)).unwrap();
1663
+ let family = Arc::new(StallsLookups::new(started));
1664
+ let namespace = Namespace::new(
1665
+ [&network],
1666
+ &crate::net::Backends::new(family.clone(), family.clone()),
1667
+ OpenConnections::new(Some(1)),
1668
+ None,
1669
+ )
1670
+ .expect("the endpoints compile");
1671
+ let cred = prepare_creds(&[], None);
1672
+ let first = crate::net::send(&namespace, &cred, greeting_request("api.example.com"))
1673
+ .expect("the first request has a place");
1674
+ resolving
1675
+ .recv_timeout(Duration::from_secs(5))
1676
+ .expect("the request's lookup starts");
1677
+ first.release();
1678
+ let next = crate::net::send(&namespace, &cred, greeting_request("api.example.com"));
1679
+ assert_eq!(
1680
+ (next.is_ok(), family.cancelled()),
1681
+ (true, 1),
1682
+ "with an open_connection_limit of 1, a request sent after one released while its \
1683
+ authority still resolves must take the place at once, the released request's query \
1684
+ cancelled though the resolver never answered"
1685
+ );
1686
+ }
1687
+
1688
+ // @behavior NW-022
1689
+ #[test]
1690
+ fn a_lookup_or_a_request_holding_the_last_place_makes_a_connect_answer_eagain() {
1691
+ let (started, resolving) = std::sync::mpsc::channel();
1692
+ let mut entry = Builder::default();
1693
+ entry.endpoint(Endpoint::new("api.example.com", 80).unwrap());
1694
+ entry.endpoint(
1695
+ Endpoint::new("127.0.0.1", 4567)
1696
+ .unwrap()
1697
+ .with_protocol(Protocol::Tcp),
1698
+ );
1699
+ let network = Network::new("web", Arc::new(entry)).unwrap();
1700
+ let family = Arc::new(StallsLookups::new(started));
1701
+ let namespace = Namespace::new(
1702
+ [&network],
1703
+ &crate::net::Backends::new(family.clone(), family),
1704
+ OpenConnections::new(Some(1)),
1705
+ None,
1706
+ )
1707
+ .expect("the endpoints compile");
1708
+ let cred = prepare_creds(&[], None);
1709
+ let connect = || {
1710
+ let sock = crate::net::TcpSock::create(&namespace, crate::net::AddressFamily::Inet)?;
1711
+ let addr = "127.0.0.1:4567".parse().ok();
1712
+ crate::net::sys_connect(&namespace, &cred, sock.as_ref(), addr)
1713
+ };
1714
+ let lookup = crate::net::resolve(&namespace, "api.example.com").expect("a lookup starts");
1715
+ resolving
1716
+ .recv_timeout(Duration::from_secs(5))
1717
+ .expect("the guest's lookup reaches the resolver");
1718
+ let past_lookup = connect().err();
1719
+ drop(lookup);
1720
+ let mut request = None;
1721
+ crate::sched::testing::wait_until("the lookup's place coming back", || {
1722
+ request = crate::net::send(&namespace, &cred, greeting_request("api.example.com")).ok();
1723
+ request.is_some()
1724
+ });
1725
+ resolving
1726
+ .recv_timeout(Duration::from_secs(5))
1727
+ .expect("the request's lookup reaches the resolver");
1728
+ let past_request = connect().err();
1729
+ drop(request);
1730
+ assert_eq!(
1731
+ (past_lookup, past_request),
1732
+ (Some(Errno::WouldBlock), Some(Errno::WouldBlock)),
1733
+ "a socket's connect must answer EAGAIN while a guest's lookup, or a request's, holds \
1734
+ the last place of an open_connection_limit of 1"
1735
+ );
1736
+ }
1737
+
1738
+ // @behavior NW-196
1739
+ #[test]
1740
+ fn a_request_dials_through_a_socket_of_the_invocations_own() {
1741
+ let (port, server) = serve_once();
1742
+ let seen = Arc::new(Mutex::new(Vec::new()));
1743
+ let mut entry = Builder::default();
1744
+ entry.endpoint(
1745
+ Endpoint::new("localhost", port)
1746
+ .unwrap()
1747
+ .with_addresses(vec![crate::network::Addresses::Local]),
1748
+ );
1749
+ let recorded = seen.clone();
1750
+ entry.connect_policy(move |connection: &crate::network::Connection<'_>| {
1751
+ recorded.lock().unwrap().push(connection.host.to_string());
1752
+ true
1753
+ });
1754
+ let network = Network::new("web", Arc::new(entry)).unwrap();
1755
+ let namespace =
1756
+ Namespace::for_network(&network, Arc::new(HostInet), Arc::new(HyperOutbound::new()));
1757
+ let cred = crate::security::restrict_self(
1758
+ &prepare_creds(&[], None),
1759
+ [&crate::grant::Grant::Network(network.clone())],
1760
+ )
1761
+ .expect("every Mount stands");
1762
+ let exchange = crate::net::send(
1763
+ &namespace,
1764
+ &cred,
1765
+ greeting_request(&format!("localhost:{port}")),
1766
+ )
1767
+ .expect("an endpoint names the authority");
1768
+ let status = read_response(&exchange).map(|(head, _)| head.status);
1769
+ assert_eq!(
1770
+ (status, seen.lock().unwrap().clone()),
1771
+ (Ok(200), vec!["localhost".to_string()]),
1772
+ "a guest's request must reach the server, and show the connect policy only the host \
1773
+ the guest named, never an address it resolved to"
1774
+ );
1775
+ server.join().unwrap();
1776
+ }
1777
+
1778
+ // @behavior NW-037
1779
+ #[test]
1780
+ fn a_request_to_an_http_endpoint_reads_back_the_response() {
1781
+ let (port, server) = serve_once();
1782
+ let namespace = namespace(vec![Endpoint::new("localhost", port)
1783
+ .unwrap()
1784
+ .with_addresses(vec![crate::network::Addresses::Local])]);
1785
+ let cred = prepare_creds(&[], None);
1786
+ let exchange = crate::net::send(
1787
+ &namespace,
1788
+ &cred,
1789
+ greeting_request(&format!("LocalHost:{port}")),
1790
+ )
1791
+ .expect("the endpoint names the authority");
1792
+ let (head, body) = read_response(&exchange).expect("the server answers");
1793
+ let seen = server.join().unwrap();
1794
+ assert!(
1795
+ head.status == 200
1796
+ && head
1797
+ .headers
1798
+ .contains(&("x-kind".to_string(), b"test".to_vec()))
1799
+ && body == b"hello"
1800
+ && seen[0] == "GET /greeting?lang=en HTTP/1.1",
1801
+ "a guest's request to an http endpoint must send the request line and read back the \
1802
+ status, headers, and body, got {head:?} {body:?} after {seen:?}"
1803
+ );
1804
+ }
1805
+
1806
+ /// A loopback server that reads no request body, answering each head it
1807
+ /// reads with `hello` until one asks it to close, which it honours in
1808
+ /// stages as RFC 9112 § 9.6 has a server close; it hands back the heads.
1809
+ fn serve_ignoring_bodies() -> (u16, thread::JoinHandle<Vec<Vec<String>>>) {
1810
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1811
+ let port = listener.local_addr().unwrap().port();
1812
+ let server = thread::spawn(move || {
1813
+ let (stream, _) = listener.accept().unwrap();
1814
+ stream
1815
+ .set_read_timeout(Some(Duration::from_secs(5)))
1816
+ .unwrap();
1817
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
1818
+ let mut heads = Vec::new();
1819
+ loop {
1820
+ let mut head = Vec::new();
1821
+ let mut line = String::new();
1822
+ while matches!(reader.read_line(&mut line), Ok(read) if read > 0) {
1823
+ if line.trim_end().is_empty() {
1824
+ break;
1825
+ }
1826
+ head.push(line.trim_end().to_string());
1827
+ line.clear();
1828
+ }
1829
+ if head.is_empty() {
1830
+ return heads;
1831
+ }
1832
+ let closes = head
1833
+ .iter()
1834
+ .any(|line| line.eq_ignore_ascii_case("connection: close"));
1835
+ heads.push(head);
1836
+ let _ = (&stream).write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nhello");
1837
+ if closes {
1838
+ let _ = stream.shutdown(std::net::Shutdown::Write);
1839
+ let _ = io::copy(&mut reader, &mut io::sink());
1840
+ return heads;
1841
+ }
1842
+ }
1843
+ });
1844
+ (port, server)
1845
+ }
1846
+
1847
+ // @behavior NW-241
1848
+ #[test]
1849
+ fn a_request_declares_that_its_connection_carries_no_other() {
1850
+ let bodies = [
1851
+ b"GET /behind HTTP/1.1\r\nhost: api.example.com\r\n\r\n".to_vec(),
1852
+ vec![b'b'; 1 << 20],
1853
+ ];
1854
+ let answers = bodies.map(|body| {
1855
+ let (port, server) = serve_ignoring_bodies();
1856
+ let namespace = namespace(vec![Endpoint::new("127.0.0.1", port)
1857
+ .unwrap()
1858
+ .with_addresses(vec![crate::network::Addresses::Local])]);
1859
+ let mut request = greeting_request(&format!("127.0.0.1:{port}"));
1860
+ request.body = RequestBody::finished(&body);
1861
+ let exchange = crate::net::send(&namespace, &prepare_creds(&[], None), request)
1862
+ .expect("the endpoint names the authority");
1863
+ let read = read_response(&exchange).map(|(head, body)| (head.status, body));
1864
+ exchange.release();
1865
+ let heads = server.join().unwrap();
1866
+ let declarations = heads[0]
1867
+ .iter()
1868
+ .filter(|line| line.eq_ignore_ascii_case("connection: close"))
1869
+ .count();
1870
+ (read, declarations, heads.len())
1871
+ });
1872
+ let expected = (Ok((200, b"hello".to_vec())), 1, 1);
1873
+ assert_eq!(
1874
+ answers,
1875
+ [expected.clone(), expected],
1876
+ "a request to a server reading no body must carry connection: close once, have \
1877
+ nothing behind it run, and read the response whole, its body spelling another \
1878
+ request or past the socket's buffers alike"
1879
+ );
1880
+ }
1881
+
1882
+ /// A wire answering `response` once a request's head was written, then
1883
+ /// silent as an open connection is, recording whether it was shut down,
1884
+ /// which is where TLS sends its closure alert.
1885
+ struct RecordsShutdown {
1886
+ response: &'static [u8],
1887
+ written: bool,
1888
+ shut_down: Arc<AtomicBool>,
1889
+ }
1890
+
1891
+ impl AsyncRead for RecordsShutdown {
1892
+ fn poll_read(
1893
+ self: Pin<&mut Self>,
1894
+ _cx: &mut Context<'_>,
1895
+ buf: &mut ReadBuf<'_>,
1896
+ ) -> Poll<io::Result<()>> {
1897
+ let this = self.get_mut();
1898
+ if !this.written || this.response.is_empty() {
1899
+ return Poll::Pending;
1900
+ }
1901
+ let n = this.response.len().min(buf.remaining());
1902
+ buf.put_slice(&this.response[..n]);
1903
+ this.response = &this.response[n..];
1904
+ Poll::Ready(Ok(()))
1905
+ }
1906
+ }
1907
+
1908
+ impl AsyncWrite for RecordsShutdown {
1909
+ fn poll_write(
1910
+ self: Pin<&mut Self>,
1911
+ _cx: &mut Context<'_>,
1912
+ buf: &[u8],
1913
+ ) -> Poll<io::Result<usize>> {
1914
+ self.get_mut().written = true;
1915
+ Poll::Ready(Ok(buf.len()))
1916
+ }
1917
+
1918
+ fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1919
+ Poll::Ready(Ok(()))
1920
+ }
1921
+
1922
+ fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1923
+ self.shut_down.store(true, Ordering::SeqCst);
1924
+ Poll::Ready(Ok(()))
1925
+ }
1926
+ }
1927
+
1928
+ // @behavior NW-240
1929
+ #[test]
1930
+ fn an_exchange_let_go_shuts_its_connection_down() {
1931
+ let responses: [&'static [u8]; 3] = [
1932
+ b"",
1933
+ b"HTTP/1.1 200 OK\r\ncontent-length: 100\r\n\r\nhello",
1934
+ b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nhello",
1935
+ ];
1936
+ let shut_down = responses.map(|response| {
1937
+ let shut_down = Arc::new(AtomicBool::new(false));
1938
+ let wire = RecordsShutdown {
1939
+ response,
1940
+ written: false,
1941
+ shut_down: shut_down.clone(),
1942
+ };
1943
+ let request = to_hyper_request(greeting_request("api.example.com"))
1944
+ .expect("the request's headers are valid");
1945
+ let mut exchange = Box::pin(async move {
1946
+ let mut body = send_over(Wire(wire), request).await?.body;
1947
+ while poll_fn(|cx| Pin::new(&mut body).poll_frame(cx))
1948
+ .await
1949
+ .is_some()
1950
+ {}
1951
+ Ok::<_, HttpError>(())
1952
+ });
1953
+ let mut cx = Context::from_waker(Waker::noop());
1954
+ // The wire is ready at once, so a few polls take the exchange as
1955
+ // far as its response lets it go.
1956
+ for _ in 0..16 {
1957
+ if exchange.as_mut().poll(&mut cx).is_ready() {
1958
+ break;
1959
+ }
1960
+ }
1961
+ drop(exchange);
1962
+ shut_down.load(Ordering::SeqCst)
1963
+ });
1964
+ assert_eq!(
1965
+ shut_down, [true; 3],
1966
+ "an HTTP exchange let go before its response, midway through its body, or after its \
1967
+ end must shut its connection down before closing it, so TLS sends its closure alert"
1968
+ );
1969
+ }
1970
+
1971
+ /// A seam recording the authority each request it is handed names, and
1972
+ /// answering none.
1973
+ #[derive(Default)]
1974
+ struct RecordsAuthority(Mutex<Vec<String>>);
1975
+
1976
+ impl Outbound for RecordsAuthority {
1977
+ fn send_request(&self, request: OutgoingRequest, _connector: Connector) -> ResponseFuture {
1978
+ self.0.lock().unwrap().push(request.authority);
1979
+ Box::pin(async { Err(HttpError::Internal) })
1980
+ }
1981
+ }
1982
+
1983
+ // @behavior NW-199
1984
+ #[test]
1985
+ fn a_request_names_its_server_as_the_endpoint_judged_it() {
1986
+ let (port, server) = serve_once();
1987
+ let namespace = namespace(vec![Endpoint::new("localhost", port)
1988
+ .unwrap()
1989
+ .with_addresses(vec![crate::network::Addresses::Local])]);
1990
+ let cred = prepare_creds(&[], None);
1991
+ let exchange = crate::net::send(
1992
+ &namespace,
1993
+ &cred,
1994
+ greeting_request(&format!("LocalHost.:{port}")),
1995
+ )
1996
+ .expect("the endpoint names the authority");
1997
+ read_response(&exchange).expect("the server answers");
1998
+ let seen = server.join().unwrap();
1999
+ let mut entry = Builder::default();
2000
+ entry.endpoint(
2001
+ Endpoint::new("localhost", 80)
2002
+ .unwrap()
2003
+ .with_addresses(vec![crate::network::Addresses::Local]),
2004
+ );
2005
+ let network = Network::new("web", Arc::new(entry)).unwrap();
2006
+ let recorded = Arc::new(RecordsAuthority::default());
2007
+ let at_default = Namespace::for_network(&network, Arc::new(HostInet), recorded.clone());
2008
+ let _ = crate::net::send(&at_default, &cred, greeting_request("LOCALHOST:80"));
2009
+ assert_eq!(
2010
+ (
2011
+ seen.iter()
2012
+ .find(|line| line.to_ascii_lowercase().starts_with("host:"))
2013
+ .cloned(),
2014
+ recorded.0.lock().unwrap().clone()
2015
+ ),
2016
+ (
2017
+ Some(format!("host: localhost:{port}")),
2018
+ vec!["localhost".to_string()]
2019
+ ),
2020
+ "a guest's request to an authority spelled in another case, with a trailing dot, or \
2021
+ with its scheme's default port must name its server as the endpoint judged it: \
2022
+ lowercase, no trailing dot, and no default port"
2023
+ );
2024
+ }
2025
+
2026
+ // @behavior NW-204
2027
+ #[test]
2028
+ fn a_response_head_past_the_read_buffer_answers_a_protocol_error() {
2029
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2030
+ let port = listener.local_addr().unwrap().port();
2031
+ let server = thread::spawn(move || {
2032
+ let (stream, _) = listener.accept().unwrap();
2033
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
2034
+ let mut line = String::new();
2035
+ while reader.read_line(&mut line).unwrap() > 2 {
2036
+ line.clear();
2037
+ }
2038
+ let long = "v".repeat(MAX_FIELD_SIZE * 2);
2039
+ let _ =
2040
+ (&stream).write_all(format!("HTTP/1.1 200 OK\r\nx-long: {long}\r\n").as_bytes());
2041
+ });
2042
+ let namespace = namespace(vec![Endpoint::new("127.0.0.1", port)
2043
+ .unwrap()
2044
+ .with_addresses(vec![crate::network::Addresses::Local])]);
2045
+ let cred = prepare_creds(&[], None);
2046
+ let answer = crate::net::send(
2047
+ &namespace,
2048
+ &cred,
2049
+ greeting_request(&format!("127.0.0.1:{port}")),
2050
+ )
2051
+ .expect("the endpoint names the authority");
2052
+ assert_eq!(
2053
+ read_response(&answer).err(),
2054
+ Some(HttpError::ProtocolError),
2055
+ "a response whose head runs past 128 KiB must answer a protocol error"
2056
+ );
2057
+ server.join().unwrap();
2058
+ }
2059
+
2060
+ // @behavior NW-203
2061
+ #[test]
2062
+ fn a_requests_method_is_judged_as_it_is_sent() {
2063
+ use crate::network::{Action, HttpRule};
2064
+ let seen = Arc::new(Mutex::new(Vec::new()));
2065
+ let recorded = seen.clone();
2066
+ let mut entry = Builder::default();
2067
+ entry
2068
+ .endpoint(
2069
+ Endpoint::new("127.0.0.1", 80)
2070
+ .unwrap()
2071
+ .with_addresses(vec![crate::network::Addresses::Local])
2072
+ .with_rules(vec![
2073
+ HttpRule::new(Action::Allow, Some("GET"), "/greeting"),
2074
+ HttpRule::new(Action::Deny, Some("DELETE"), "/greeting"),
2075
+ HttpRule::new(Action::Allow, Some("delete"), "/greeting"),
2076
+ ]),
2077
+ )
2078
+ .endpoint(
2079
+ Endpoint::new("127.0.0.1", 81)
2080
+ .unwrap()
2081
+ .with_addresses(vec![crate::network::Addresses::Local]),
2082
+ )
2083
+ .request_policy(move |sent: &crate::network::Request<'_>| {
2084
+ recorded.lock().unwrap().push(sent.method.to_string());
2085
+ true
2086
+ });
2087
+ let network = Network::new("web", Arc::new(entry)).unwrap();
2088
+ let namespace = Namespace::for_network(
2089
+ &network,
2090
+ Arc::new(HostInet),
2091
+ Arc::new(RecordsAuthority::default()),
2092
+ );
2093
+ let cred = prepare_creds(&[], None);
2094
+ let send = |method: &str, authority: &str| {
2095
+ let mut request = greeting_request(authority);
2096
+ request.method = method.to_string();
2097
+ crate::net::send(&namespace, &cred, request).is_ok()
2098
+ };
2099
+ let sent = [
2100
+ send("GET", "127.0.0.1"),
2101
+ send("get", "127.0.0.1"),
2102
+ send("delete", "127.0.0.1"),
2103
+ send("get", "127.0.0.1:81"),
2104
+ ];
2105
+ assert_eq!(
2106
+ (sent, seen.lock().unwrap().clone()),
2107
+ (
2108
+ [true, false, false, true],
2109
+ vec!["GET".to_string(), "get".to_string()]
2110
+ ),
2111
+ "a request by get must match no rule allowing GET, a request by delete must stay \
2112
+ refused by a rule denying DELETE, and the request policy must see get as sent"
2113
+ );
2114
+ }
2115
+
2116
+ // @behavior NW-201
2117
+ #[test]
2118
+ fn an_authority_spelling_an_address_short_is_judged_and_named_as_that_address() {
2119
+ let mut entry = Builder::default();
2120
+ entry.endpoint(
2121
+ Endpoint::new("127.0.0.1", 80)
2122
+ .unwrap()
2123
+ .with_addresses(vec![crate::network::Addresses::Local]),
2124
+ );
2125
+ let network = Network::new("web", Arc::new(entry)).unwrap();
2126
+ let recorded = Arc::new(RecordsAuthority::default());
2127
+ let namespace = Namespace::for_network(&network, Arc::new(HostInet), recorded.clone());
2128
+ let cred = prepare_creds(&[], None);
2129
+ let sent = crate::net::send(&namespace, &cred, greeting_request("127.1")).is_ok();
2130
+ assert_eq!(
2131
+ (sent, recorded.0.lock().unwrap().clone()),
2132
+ (true, vec!["127.0.0.1".to_string()]),
2133
+ "a guest's request to the authority 127.1 must pass an endpoint naming 127.0.0.1, \
2134
+ and name its server as that address"
2135
+ );
2136
+ }
2137
+
2138
+ // @behavior NW-122
2139
+ #[test]
2140
+ fn an_http_connection_sends_without_nagles_delay() {
2141
+ /// The host's network, keeping a handle on each stream it dials.
2142
+ #[derive(Default)]
2143
+ struct KeepsStreams(Mutex<Vec<std::net::TcpStream>>);
2144
+ impl ProtocolFamily for KeepsStreams {
2145
+ fn connect(&self, addr: SocketAddr) -> io::Result<std::net::TcpStream> {
2146
+ let stream = HostInet.connect(addr)?;
2147
+ self.0.lock().unwrap().push(stream.try_clone()?);
2148
+ Ok(stream)
2149
+ }
2150
+ }
2151
+ impl crate::net::Resolver for KeepsStreams {
2152
+ fn resolve(&self, name: &str) -> crate::net::Resolving {
2153
+ crate::net::Resolver::resolve(&HostInet, name)
2154
+ }
2155
+ }
2156
+ let (port, server) = serve_once();
2157
+ let mut entry = Builder::default();
2158
+ entry.endpoint(
2159
+ Endpoint::new("127.0.0.1", port)
2160
+ .unwrap()
2161
+ .with_addresses(vec![crate::network::Addresses::Local]),
2162
+ );
2163
+ let network = Network::new("web", Arc::new(entry)).unwrap();
2164
+ let family = Arc::new(KeepsStreams::default());
2165
+ let namespace =
2166
+ Namespace::for_network(&network, family.clone(), Arc::new(HyperOutbound::new()));
2167
+ let cred = prepare_creds(&[], None);
2168
+ let exchange = crate::net::send(
2169
+ &namespace,
2170
+ &cred,
2171
+ greeting_request(&format!("127.0.0.1:{port}")),
2172
+ )
2173
+ .expect("the endpoint names the authority");
2174
+ read_response(&exchange).expect("the server answers");
2175
+ server.join().unwrap();
2176
+ let nodelay = family
2177
+ .0
2178
+ .lock()
2179
+ .unwrap()
2180
+ .iter()
2181
+ .map(|stream| stream.nodelay().unwrap())
2182
+ .collect::<Vec<_>>();
2183
+ assert_eq!(
2184
+ nodelay,
2185
+ [true],
2186
+ "an HTTP request sent through the Protocol Family must turn TCP_NODELAY on for the \
2187
+ stream it dialed, as an HTTP client writes each request whole"
2188
+ );
2189
+ }
2190
+
2191
+ // @behavior NW-058
2192
+ #[test]
2193
+ fn a_body_past_the_buffer_streams_as_it_is_read() {
2194
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2195
+ let port = listener.local_addr().unwrap().port();
2196
+ let size = MAX_SOCKET_BUFFER * 4;
2197
+ let server = thread::spawn(move || {
2198
+ let (mut stream, _) = listener.accept().unwrap();
2199
+ let mut head = [0; 1024];
2200
+ let _ = stream.read(&mut head);
2201
+ let header = format!("HTTP/1.1 200 OK\r\ncontent-length: {size}\r\n\r\n");
2202
+ stream.write_all(header.as_bytes()).unwrap();
2203
+ let body = (0..size).map(|i| (i % 251) as u8).collect::<Vec<_>>();
2204
+ stream.write_all(&body).unwrap();
2205
+ });
2206
+ let namespace = namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
2207
+ let cred = prepare_creds(&[], None);
2208
+ let exchange = crate::net::send(
2209
+ &namespace,
2210
+ &cred,
2211
+ greeting_request(&format!("127.0.0.1:{port}")),
2212
+ )
2213
+ .expect("an endpoint names the authority");
2214
+ let mut held = 0;
2215
+ let mut body = Vec::new();
2216
+ let mut buf = [0; 4096];
2217
+ let started = std::time::Instant::now();
2218
+ while body.len() < size && started.elapsed() < Duration::from_secs(10) {
2219
+ held = held.max(exchange.state().body.len());
2220
+ match exchange.read(&mut buf) {
2221
+ Ok(0) => break,
2222
+ Ok(n) => body.extend_from_slice(&buf[..n]),
2223
+ Err(_) => thread::sleep(Duration::from_millis(1)),
2224
+ }
2225
+ }
2226
+ server.join().unwrap();
2227
+ let expected = (0..size).map(|i| (i % 251) as u8).collect::<Vec<_>>();
2228
+ assert!(
2229
+ body == expected && held <= MAX_SOCKET_BUFFER,
2230
+ "a response body four buffers long must reach the guest whole and in order, the body \
2231
+ waiting for it never past one buffer, got {} bytes, holding up to {held}",
2232
+ body.len()
2233
+ );
2234
+ }
2235
+
2236
+ // @behavior NW-038
2237
+ #[test]
2238
+ fn a_request_no_http_endpoint_names_is_denied_unsent() {
2239
+ let port = 8080;
2240
+ let raw = Endpoint::new("127.0.0.1", port)
2241
+ .unwrap()
2242
+ .with_protocol(Protocol::Tcp);
2243
+ let (namespace, family) = counting_namespace(vec![raw]);
2244
+ let cred = prepare_creds(&[], None);
2245
+ let answers = [
2246
+ format!("127.0.0.1:{port}"),
2247
+ format!("elsewhere.example:{port}"),
2248
+ format!("198.18.0.0:{port}"),
2249
+ ]
2250
+ .map(|authority| crate::net::send(&namespace, &cred, greeting_request(&authority)).err());
2251
+ assert!(
2252
+ answers
2253
+ .iter()
2254
+ .all(|answer| *answer == Some(HttpError::Denied))
2255
+ && family.dials() == 0,
2256
+ "a guest's request to an authority only a tcp endpoint names, one no endpoint names, \
2257
+ or a virtual address must answer Denied, sending nothing, got {answers:?}"
2258
+ );
2259
+ }
2260
+
2261
+ // @behavior NW-041
2262
+ #[test]
2263
+ fn a_request_carrying_a_header_the_seam_frames_is_refused_unsent() {
2264
+ let port = 8080;
2265
+ let (namespace, family) =
2266
+ counting_namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
2267
+ let cred = prepare_creds(&[], None);
2268
+ let answers = ["Host", "content-length", "bad name"].map(|name| {
2269
+ let mut request = greeting_request(&format!("127.0.0.1:{port}"));
2270
+ request.headers.push((name.to_string(), b"x".to_vec()));
2271
+ crate::net::send(&namespace, &cred, request).err()
2272
+ });
2273
+ assert!(
2274
+ answers
2275
+ .iter()
2276
+ .all(|answer| *answer == Some(HttpError::Denied))
2277
+ && family.dials() == 0,
2278
+ "a guest's request carrying host, content-length, or a name that is no \
2279
+ token must answer Denied, sending nothing, got {answers:?}"
2280
+ );
2281
+ }
2282
+
2283
+ // @behavior NW-184
2284
+ #[test]
2285
+ fn a_request_whose_target_is_not_in_origin_form_is_refused_unsent() {
2286
+ let port = 8080;
2287
+ let (namespace, family) =
2288
+ counting_namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
2289
+ let cred = prepare_creds(&[], None);
2290
+ let answers = ["http://other.example/x", "*", "", "/a#b"].map(|target| {
2291
+ let mut request = greeting_request(&format!("127.0.0.1:{port}"));
2292
+ request.path_with_query = target.to_string();
2293
+ crate::net::send(&namespace, &cred, request).err()
2294
+ });
2295
+ assert!(
2296
+ answers
2297
+ .iter()
2298
+ .all(|answer| *answer == Some(HttpError::Denied))
2299
+ && family.dials() == 0,
2300
+ "a guest's request whose target is absolute-form, asterisk-form, empty, or \
2301
+ carries a fragment must answer Denied, sending nothing, got {answers:?}"
2302
+ );
2303
+ }
2304
+
2305
+ // @behavior NW-219
2306
+ #[test]
2307
+ fn a_request_whose_method_is_not_a_token_is_refused_unsent() {
2308
+ let port = 8080;
2309
+ let (namespace, family) =
2310
+ counting_namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
2311
+ let cred = prepare_creds(&[], None);
2312
+ let answers = ["", "GET X"].map(|method| {
2313
+ let mut request = greeting_request(&format!("127.0.0.1:{port}"));
2314
+ request.method = method.to_string();
2315
+ crate::net::send(&namespace, &cred, request).err()
2316
+ });
2317
+ assert!(
2318
+ answers
2319
+ .iter()
2320
+ .all(|answer| *answer == Some(HttpError::Denied))
2321
+ && family.dials() == 0,
2322
+ "a guest's request whose method is empty or holds a space must answer Denied, \
2323
+ sending nothing, got {answers:?}"
2324
+ );
2325
+ }
2326
+
2327
+ /// A bearer credential swapping `kobako-token` for `s3cret`, its source
2328
+ /// counting into `asked` each time it is asked.
2329
+ fn bearer_credential(asked: &Arc<AtomicUsize>) -> crate::network::Credential {
2330
+ let asked = asked.clone();
2331
+ crate::network::Credential::new(
2332
+ crate::network::Placement::Bearer,
2333
+ "kobako-token",
2334
+ Arc::new(move |_: &crate::network::Request<'_>| {
2335
+ asked.fetch_add(1, Ordering::SeqCst);
2336
+ Ok(Some(crate::network::Secret::new("s3cret")))
2337
+ }),
2338
+ )
2339
+ }
2340
+
2341
+ /// A namespace whose one endpoint, `api.example.com` at 443 with no
2342
+ /// rules, binds a bearer credential, beside how often its source was
2343
+ /// asked, the swaps its seam was handed, and the dials its host saw.
2344
+ struct BoundEndpoint {
2345
+ namespace: Namespace,
2346
+ asked: Arc<AtomicUsize>,
2347
+ seam: Arc<RecordsSwaps>,
2348
+ family: Arc<CountsDials>,
2349
+ }
2350
+
2351
+ impl BoundEndpoint {
2352
+ fn new() -> Self {
2353
+ let asked = Arc::new(AtomicUsize::new(0));
2354
+ let mut entry = Builder::default();
2355
+ entry
2356
+ .endpoint(Endpoint::new("api.example.com", 443).unwrap())
2357
+ .credential(bearer_credential(&asked));
2358
+ let network = Network::new("api", Arc::new(entry)).unwrap();
2359
+ let seam = Arc::new(RecordsSwaps::default());
2360
+ let family = Arc::new(CountsDials::default());
2361
+ let namespace = Namespace::for_network(&network, family.clone(), seam.clone());
2362
+ Self {
2363
+ namespace,
2364
+ asked,
2365
+ seam,
2366
+ family,
2367
+ }
2368
+ }
2369
+
2370
+ /// What `send` answers `method` carrying the placeholder and `body`.
2371
+ fn send(&self, method: &str, body: &[u8]) -> Option<HttpError> {
2372
+ let mut request = OutgoingRequest::new(method, Scheme::Https, "api.example.com:443");
2373
+ request.headers = vec![("authorization".to_string(), b"Bearer kobako-token".to_vec())];
2374
+ request.body = RequestBody::finished(body);
2375
+ match crate::net::send(&self.namespace, &prepare_creds(&[], None), request) {
2376
+ Ok(exchange) => {
2377
+ let _ = read_response(&exchange);
2378
+ None
2379
+ }
2380
+ Err(err) => Some(err),
2381
+ }
2382
+ }
2383
+
2384
+ /// How often the source was asked, how many swaps each request the
2385
+ /// seam was handed carried, and the dials the host saw.
2386
+ fn seen(&self) -> (usize, Vec<usize>, usize) {
2387
+ (
2388
+ self.asked.load(Ordering::SeqCst),
2389
+ self.seam.0.lock().unwrap().iter().map(Vec::len).collect(),
2390
+ self.family.dials(),
2391
+ )
2392
+ }
2393
+ }
2394
+
2395
+ // @behavior NW-242
2396
+ #[test]
2397
+ fn a_connect_request_is_refused_unsent() {
2398
+ let endpoint = BoundEndpoint::new();
2399
+ let answers = ["CONNECT", "connect"].map(|method| endpoint.send(method, b""));
2400
+ assert_eq!(
2401
+ (answers, endpoint.seen()),
2402
+ ([Some(HttpError::Denied); 2], (0, Vec::new(), 0)),
2403
+ "a request whose method is CONNECT, in any case, must answer Denied with no \
2404
+ credential asked and nothing sent, its target never being authority-form"
2405
+ );
2406
+ }
2407
+
2408
+ // @behavior NW-243
2409
+ #[test]
2410
+ fn a_credential_is_never_swapped_into_a_trace_request() {
2411
+ let endpoint = BoundEndpoint::new();
2412
+ let answers = ["TRACE", "trace", "GET"].map(|method| endpoint.send(method, b""));
2413
+ let (asked, swaps, _) = endpoint.seen();
2414
+ assert_eq!(
2415
+ (answers, asked, swaps),
2416
+ ([None; 3], 1, vec![0, 0, 1]),
2417
+ "a TRACE request over HTTPS, in any case, must go with the placeholder unchanged \
2418
+ and never ask the credential its value, where a GET beside it carries the secret"
2419
+ );
2420
+ }
2421
+
2422
+ // @behavior NW-244
2423
+ #[test]
2424
+ fn a_trace_request_carrying_content_is_refused_unsent() {
2425
+ let endpoint = BoundEndpoint::new();
2426
+ let answers = ["TRACE", "trace"].map(|method| endpoint.send(method, b"content"));
2427
+ assert_eq!(
2428
+ (answers, endpoint.seen()),
2429
+ ([Some(HttpError::Denied); 2], (0, Vec::new(), 0)),
2430
+ "a TRACE request carrying a body, in any case, must answer Denied with no \
2431
+ credential asked and nothing sent"
2432
+ );
2433
+ }
2434
+
2435
+ // @behavior NW-048
2436
+ #[test]
2437
+ fn an_https_request_opens_tls_before_any_byte_of_http() {
2438
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2439
+ let port = listener.local_addr().unwrap().port();
2440
+ // The server reads the whole first record before it answers in clear,
2441
+ // and drains the client before it closes: a close with bytes unread
2442
+ // resets the connection on Windows before the client parses a byte.
2443
+ let server = thread::spawn(move || {
2444
+ let (mut stream, _) = listener.accept().unwrap();
2445
+ let mut header = [0; 5];
2446
+ stream.read_exact(&mut header).unwrap();
2447
+ let length = u16::from_be_bytes([header[3], header[4]]);
2448
+ stream
2449
+ .read_exact(&mut vec![0; usize::from(length)])
2450
+ .unwrap();
2451
+ stream.write_all(b"HTTP/1.1 200 OK\r\n\r\n").unwrap();
2452
+ stream.shutdown(std::net::Shutdown::Write).unwrap();
2453
+ let _ = stream.read_to_end(&mut Vec::new());
2454
+ header[0]
2455
+ });
2456
+ let namespace = namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
2457
+ let cred = prepare_creds(&[], None);
2458
+ let mut request = greeting_request(&format!("127.0.0.1:{port}"));
2459
+ request.scheme = Scheme::Https;
2460
+ let exchange =
2461
+ crate::net::send(&namespace, &cred, request).expect("an endpoint names the authority");
2462
+ let answer = read_response(&exchange).map(|(head, _)| head.status);
2463
+ assert_eq!(
2464
+ (server.join().unwrap(), answer),
2465
+ (0x16, Err(HttpError::TlsProtocol)),
2466
+ "an https request must open TLS with a handshake record before any HTTP, and a server \
2467
+ answering in clear must fail it as a TLS protocol error"
2468
+ );
2469
+ }
2470
+
2471
+ // @behavior NW-045
2472
+ #[test]
2473
+ fn a_request_policy_sees_the_request_and_refuses_it_unsent() {
2474
+ let port = 8080;
2475
+ let seen = Arc::new(Mutex::new(Vec::new()));
2476
+ let recorded = seen.clone();
2477
+ let mut entry = Builder::default();
2478
+ entry
2479
+ .endpoint(Endpoint::new("127.0.0.1", port).unwrap())
2480
+ .request_policy(move |sent: &crate::network::Request<'_>| {
2481
+ recorded.lock().unwrap().push((
2482
+ sent.authority.0.to_string(),
2483
+ sent.method.to_string(),
2484
+ sent.scheme.to_string(),
2485
+ sent.path.to_string(),
2486
+ sent.header_names
2487
+ .iter()
2488
+ .map(|n| n.to_string())
2489
+ .collect::<Vec<_>>(),
2490
+ ));
2491
+ false
2492
+ });
2493
+ let network = Network::new("web", Arc::new(entry)).unwrap();
2494
+ let family = Arc::new(CountsDials::default());
2495
+ let namespace =
2496
+ Namespace::for_network(&network, family.clone(), Arc::new(HyperOutbound::new()));
2497
+ let mut request = greeting_request(&format!("127.0.0.1:{port}"));
2498
+ request
2499
+ .headers
2500
+ .push(("X-Probe".to_string(), b"secret".to_vec()));
2501
+ let cred = prepare_creds(&[], None);
2502
+ let answer = crate::net::send(&namespace, &cred, request).err();
2503
+ assert_eq!(
2504
+ (answer, seen.lock().unwrap().clone(), family.dials() == 0),
2505
+ (
2506
+ Some(HttpError::Denied),
2507
+ vec![(
2508
+ "127.0.0.1".to_string(),
2509
+ "GET".to_string(),
2510
+ "http".to_string(),
2511
+ "/greeting".to_string(),
2512
+ vec!["x-probe".to_string()]
2513
+ )],
2514
+ true
2515
+ ),
2516
+ "a request policy must see the authority, method, scheme, path with no query, and \
2517
+ header names in lower case however the request spelled them, and its refusal must \
2518
+ answer Denied, sending nothing"
2519
+ );
2520
+ }
2521
+
2522
+ /// A seam recording the credentials each request it is handed carries, and
2523
+ /// answering none.
2524
+ #[derive(Default)]
2525
+ struct RecordsSwaps(Mutex<Vec<Vec<Swap>>>);
2526
+
2527
+ impl Outbound for RecordsSwaps {
2528
+ fn send_request(&self, request: OutgoingRequest, _connector: Connector) -> ResponseFuture {
2529
+ self.0.lock().unwrap().push(request.swaps);
2530
+ Box::pin(async { Err(HttpError::Internal) })
2531
+ }
2532
+ }
2533
+
2534
+ /// The swaps a request with `header: value` carries once its entry binds a
2535
+ /// credential to `exact.example.com` and `*.example.com` on 443, allowing
2536
+ /// GET on `/api/**`.
2537
+ fn swaps_of(scheme: Scheme, host: &str, path: &str, header: &str, value: &[u8]) -> Vec<Swap> {
2538
+ send_bound(scheme, host, path, &[(header, value)])
2539
+ .expect("an endpoint names the authority")
2540
+ .unwrap_or_default()
2541
+ }
2542
+
2543
+ /// What `send` answers a request with `headers` under the entry `swaps_of`
2544
+ /// describes: the swaps the seam was handed, `None` when it was handed no
2545
+ /// request.
2546
+ fn send_bound(
2547
+ scheme: Scheme,
2548
+ host: &str,
2549
+ path: &str,
2550
+ headers: &[(&str, &[u8])],
2551
+ ) -> Result<Option<Vec<Swap>>, HttpError> {
2552
+ let mut entry = Builder::default();
2553
+ entry
2554
+ .endpoint(
2555
+ Endpoint::new("exact.example.com", 443)
2556
+ .unwrap()
2557
+ .with_rules(vec![crate::network::HttpRule::new(
2558
+ crate::network::Action::Allow,
2559
+ Some("GET"),
2560
+ "/api/**",
2561
+ )]),
2562
+ )
2563
+ .endpoint(Endpoint::new("*.example.com", 443).unwrap())
2564
+ .credential(bearer_credential(&Arc::default()));
2565
+ let network = Network::new("api", Arc::new(entry)).unwrap();
2566
+ let seam = Arc::new(RecordsSwaps::default());
2567
+ let family = Arc::new(CountsDials::default());
2568
+ let namespace = Namespace::for_network(&network, family, seam.clone());
2569
+ let mut request = OutgoingRequest::new("GET", scheme, format!("{host}:443"));
2570
+ request.path_with_query = path.to_string();
2571
+ request.headers = headers
2572
+ .iter()
2573
+ .map(|(name, value)| (name.to_string(), value.to_vec()))
2574
+ .collect();
2575
+ let sent = crate::net::send(&namespace, &prepare_creds(&[], None), request);
2576
+ if let Ok(exchange) = &sent {
2577
+ let _ = read_response(exchange);
2578
+ }
2579
+ let recorded = seam.0.lock().unwrap().pop();
2580
+ sent.map(|_| recorded)
2581
+ }
2582
+
2583
+ // @behavior NW-220
2584
+ #[test]
2585
+ fn a_request_carrying_a_credentials_placeholder_more_than_once_is_refused_unsent() {
2586
+ let answer = |scheme, headers: &[(&str, &[u8])]| {
2587
+ send_bound(scheme, "exact.example.com", "/api/repos", headers)
2588
+ .map(|handed| handed.map(|swaps| swaps.len()))
2589
+ };
2590
+ assert_eq!(
2591
+ [
2592
+ answer(
2593
+ Scheme::Https,
2594
+ &[("authorization", b"Bearer kobako-token kobako-token")]
2595
+ ),
2596
+ answer(
2597
+ Scheme::Https,
2598
+ &[
2599
+ ("authorization", b"Bearer kobako-token"),
2600
+ ("Authorization", b"Bearer kobako-token"),
2601
+ ]
2602
+ ),
2603
+ // `a:kobako-tokenkobako-token`, encoded.
2604
+ answer(
2605
+ Scheme::Https,
2606
+ &[(
2607
+ "authorization",
2608
+ b"Basic YTprb2Jha28tdG9rZW5rb2Jha28tdG9rZW4="
2609
+ )]
2610
+ ),
2611
+ answer(
2612
+ Scheme::Https,
2613
+ &[
2614
+ ("authorization", b"Bearer kobako-token"),
2615
+ ("x-echo", b"kobako-token kobako-token"),
2616
+ ]
2617
+ ),
2618
+ ],
2619
+ [
2620
+ Err(HttpError::Denied),
2621
+ Err(HttpError::Denied),
2622
+ Err(HttpError::Denied),
2623
+ Ok(Some(1)),
2624
+ ],
2625
+ "a request whose credential header carries the placeholder more than once, in one \
2626
+ value, across two, or inside a Basic pair, must answer Denied with nothing sent, \
2627
+ and one carrying it once must go with its one swap whatever another header holds"
2628
+ );
2629
+ }
2630
+
2631
+ // @behavior NW-050
2632
+ #[test]
2633
+ fn a_credential_binds_only_to_https_its_exact_host_and_an_allowed_path() {
2634
+ let bound = |scheme, host, path, header| {
2635
+ !swaps_of(scheme, host, path, header, b"Bearer kobako-token").is_empty()
2636
+ };
2637
+ assert_eq!(
2638
+ [
2639
+ bound(
2640
+ Scheme::Https,
2641
+ "exact.example.com",
2642
+ "/api/repos",
2643
+ "authorization"
2644
+ ),
2645
+ bound(
2646
+ Scheme::Http,
2647
+ "exact.example.com",
2648
+ "/api/repos",
2649
+ "authorization"
2650
+ ),
2651
+ bound(
2652
+ Scheme::Https,
2653
+ "other.example.com",
2654
+ "/api/repos",
2655
+ "authorization"
2656
+ ),
2657
+ bound(
2658
+ Scheme::Https,
2659
+ "exact.example.com",
2660
+ "/admin",
2661
+ "authorization"
2662
+ ),
2663
+ bound(
2664
+ Scheme::Https,
2665
+ "exact.example.com",
2666
+ "/api/a;b",
2667
+ "authorization"
2668
+ ),
2669
+ bound(Scheme::Https, "exact.example.com", "/api/repos", "x-other"),
2670
+ ],
2671
+ [true, false, false, false, false, false],
2672
+ "a credential must bind only to https, to its entry's exact host, on a path the \
2673
+ endpoint allows and every server reads alike, and only where its header carries the \
2674
+ placeholder"
2675
+ );
2676
+ }
2677
+
2678
+ // @behavior NW-051
2679
+ #[test]
2680
+ fn a_swap_replaces_the_placeholder_in_its_header_only() {
2681
+ let swap = Swap {
2682
+ header: "authorization".to_string(),
2683
+ placeholder: b"kobako-token".to_vec(),
2684
+ secret: crate::network::Secret::new("s3cret"),
2685
+ };
2686
+ let masked = format!("{:?}", swap.secret);
2687
+ let mut request = OutgoingRequest::new("GET", Scheme::Https, "api.example.com:443");
2688
+ request.path_with_query = "/".to_string();
2689
+ request.headers = vec![
2690
+ ("Authorization".to_string(), b"Bearer kobako-token".to_vec()),
2691
+ ("x-echo".to_string(), b"kobako-token".to_vec()),
2692
+ ];
2693
+ request.swaps = vec![swap];
2694
+ let sent = to_hyper_request(request).expect("the request's headers are valid");
2695
+ let header = |name| {
2696
+ sent.headers()
2697
+ .get(name)
2698
+ .map(|value| value.as_bytes().to_vec())
2699
+ };
2700
+ assert_eq!(
2701
+ (
2702
+ header("authorization"),
2703
+ header("x-echo"),
2704
+ sent.headers().len(),
2705
+ masked
2706
+ ),
2707
+ (
2708
+ Some(b"Bearer s3cret".to_vec()),
2709
+ Some(b"kobako-token".to_vec()),
2710
+ 4,
2711
+ "Secret(**)".to_string()
2712
+ ),
2713
+ "the outbound seam must send a request with its credential's placeholder \
2714
+ replaced in the header the credential names only, every other header as the guest \
2715
+ set it, and the secret must print as a mask"
2716
+ );
2717
+ }
2718
+
2719
+ // @behavior NW-076
2720
+ #[test]
2721
+ fn a_request_sends_its_secret_inside_a_basic_pair_carrying_the_placeholder() {
2722
+ let sent = |value: &[u8]| {
2723
+ swaps_of(
2724
+ Scheme::Https,
2725
+ "exact.example.com",
2726
+ "/api/repos",
2727
+ "authorization",
2728
+ value,
2729
+ )
2730
+ .iter()
2731
+ .fold(value.to_vec(), |value, swap| {
2732
+ swap.apply("authorization", &value)
2733
+ })
2734
+ };
2735
+ assert_eq!(
2736
+ [sent(b"Basic dXNlcjprb2Jha28tdG9rZW4="), sent(b"Basic YQ=="),],
2737
+ [b"Basic dXNlcjpzM2NyZXQ=".to_vec(), b"Basic YQ==".to_vec()],
2738
+ "a request whose Basic pair encodes the placeholder must go with the secret in the \
2739
+ pair, encoded again, as OpenShell's does, and a pair without it must go as sent"
2740
+ );
2741
+ }
2742
+
2743
+ // @behavior NW-116
2744
+ #[test]
2745
+ fn a_body_holds_one_socket_buffer_until_the_guest_reads() {
2746
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2747
+ let port = listener.local_addr().unwrap().port();
2748
+ let size = 1 << 20;
2749
+ let server = thread::spawn(move || {
2750
+ let (mut stream, _) = listener.accept().unwrap();
2751
+ let mut head = [0; 1024];
2752
+ let _ = stream.read(&mut head);
2753
+ let header = format!("HTTP/1.1 200 OK\r\ncontent-length: {size}\r\n\r\n");
2754
+ stream.write_all(header.as_bytes()).unwrap();
2755
+ let body = (0..size).map(|i| (i % 251) as u8).collect::<Vec<_>>();
2756
+ let _ = stream.write_all(&body);
2757
+ });
2758
+ let namespace = namespace(vec![Endpoint::new("127.0.0.1", port).unwrap()]);
2759
+ let exchange = crate::net::send(
2760
+ &namespace,
2761
+ &prepare_creds(&[], Some(16 * 1024)),
2762
+ greeting_request(&format!("127.0.0.1:{port}")),
2763
+ )
2764
+ .expect("an endpoint names the authority");
2765
+ // Each look moves the exchange on, as its guest's poll does, until a
2766
+ // frame waits for room in the body's full buffer.
2767
+ crate::sched::testing::wait_until("a frame waiting for room in the body's buffer", || {
2768
+ exchange.state().pending.is_some()
2769
+ });
2770
+ let held = {
2771
+ let state = exchange.state();
2772
+ state.body.len() + state.pending.as_ref().map_or(0, Vec::len)
2773
+ };
2774
+ let mut body = Vec::new();
2775
+ let mut buf = [0; 4096];
2776
+ let started = std::time::Instant::now();
2777
+ while body.len() < size && started.elapsed() < Duration::from_secs(10) {
2778
+ match exchange.read(&mut buf) {
2779
+ Ok(0) => break,
2780
+ Ok(n) => body.extend_from_slice(&buf[..n]),
2781
+ Err(_) => thread::sleep(Duration::from_millis(1)),
2782
+ }
2783
+ }
2784
+ server.join().unwrap();
2785
+ let expected = (0..size).map(|i| (i % 251) as u8).collect::<Vec<_>>();
2786
+ assert!(
2787
+ held <= MAX_SOCKET_BUFFER + MAX_READ_BUFFER && body == expected,
2788
+ "a 1 MiB body the guest has not read, under a 16 KiB memory_limit, must hold no \
2789
+ more than one socket buffer and one read, then reach the guest whole and in \
2790
+ order; held {held}, got {} bytes",
2791
+ body.len()
2792
+ );
2793
+ }
2794
+
2795
+ /// A seam that never answers, holding each request it is handed.
2796
+ struct NeverAnswers;
2797
+
2798
+ impl Outbound for NeverAnswers {
2799
+ fn send_request(&self, request: OutgoingRequest, _: Connector) -> ResponseFuture {
2800
+ Box::pin(async move {
2801
+ let _held = request;
2802
+ std::future::pending().await
2803
+ })
2804
+ }
2805
+ }
2806
+
2807
+ /// A seam that dials the request's authority, then never answers.
2808
+ struct DialsThenWaits;
2809
+
2810
+ impl Outbound for DialsThenWaits {
2811
+ fn send_request(&self, request: OutgoingRequest, connector: Connector) -> ResponseFuture {
2812
+ Box::pin(async move {
2813
+ let _held = request;
2814
+ let _connection = connector.dial().await?;
2815
+ std::future::pending().await
2816
+ })
2817
+ }
2818
+ }
2819
+
2820
+ /// A seam that dials the request's authority, then reads the connection a
2821
+ /// byte at a time, counting each, and never answers.
2822
+ struct ReadsEachByte(Arc<AtomicUsize>);
2823
+
2824
+ impl Outbound for ReadsEachByte {
2825
+ fn send_request(&self, request: OutgoingRequest, connector: Connector) -> ResponseFuture {
2826
+ let reads = self.0.clone();
2827
+ Box::pin(async move {
2828
+ let _held = request;
2829
+ let mut connection = connector.dial().await?;
2830
+ let mut byte = [0; 1];
2831
+ loop {
2832
+ let mut buf = tokio::io::ReadBuf::new(&mut byte);
2833
+ poll_fn(|cx| {
2834
+ tokio::io::AsyncRead::poll_read(Pin::new(&mut connection), cx, &mut buf)
2835
+ })
2836
+ .await
2837
+ .map_err(|_| HttpError::Internal)?;
2838
+ if buf.filled().is_empty() {
2839
+ std::future::pending::<()>().await;
2840
+ }
2841
+ reads.fetch_add(1, Ordering::SeqCst);
2842
+ }
2843
+ })
2844
+ }
2845
+ }
2846
+
2847
+ // A peer that keeps the connection readable, as one sending endless
2848
+ // informational responses, must not hold one look at the request: the
2849
+ // look returns after its budget, and the request wakes its own wait.
2850
+ // @behavior NW-256
2851
+ #[test]
2852
+ fn one_look_at_a_request_reads_its_connection_at_most_128_times() {
2853
+ const SENT: usize = 16 * 1024;
2854
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2855
+ let port = listener.local_addr().unwrap().port();
2856
+ let (go, gone) = std::sync::mpsc::channel::<()>();
2857
+ let (done, finished) = std::sync::mpsc::channel::<()>();
2858
+ let peer = thread::spawn(move || {
2859
+ let (mut stream, _) = listener.accept().unwrap();
2860
+ let informational = b"HTTP/1.1 102 Processing\r\n\r\n".repeat(SENT);
2861
+ // Sent once the request connected, so no look before the
2862
+ // measured ones reads it.
2863
+ let _ = gone.recv_timeout(Duration::from_secs(10));
2864
+ stream.write_all(&informational[..SENT]).unwrap();
2865
+ let _ = finished.recv_timeout(Duration::from_secs(10));
2866
+ });
2867
+ let mut entry = Builder::default();
2868
+ entry.endpoint(
2869
+ Endpoint::new("127.0.0.1", port)
2870
+ .unwrap()
2871
+ .with_addresses(vec![crate::network::Addresses::Local]),
2872
+ );
2873
+ let network = Network::new("web", Arc::new(entry)).unwrap();
2874
+ let reads = Arc::new(AtomicUsize::new(0));
2875
+ let seam = Arc::new(ReadsEachByte(reads.clone()));
2876
+ let namespace = Namespace::for_network(&network, Arc::new(HostInet), seam);
2877
+ let exchange = crate::net::send(
2878
+ &namespace,
2879
+ &prepare_creds(&[], None),
2880
+ greeting_request(&format!("127.0.0.1:{port}")),
2881
+ )
2882
+ .expect("the endpoint names the authority");
2883
+ // Each look moves the request on, as its guest's poll does.
2884
+ crate::sched::testing::wait_until("the request connecting to the peer", || {
2885
+ let _ = exchange.response();
2886
+ exchange.connected.get().is_some()
2887
+ });
2888
+ let _ = go.send(());
2889
+ // Once the reactor queued every byte the peer sent, the connection
2890
+ // stays readable for each look that follows.
2891
+ let upstreams = namespace.tcp_sockets().held();
2892
+ crate::sched::testing::wait_until("the reactor queueing every byte the peer sent", || {
2893
+ upstreams.iter().any(|upstream| upstream.unread() == SENT)
2894
+ });
2895
+ let (mut most, mut last) = (0, reads.load(Ordering::SeqCst));
2896
+ let give_up = Instant::now() + crate::sched::testing::MAX_WAIT;
2897
+ let answer = crate::wait::do_poll(
2898
+ || Some(give_up),
2899
+ |table| {
2900
+ crate::wait::poll_wait(&exchange.wait, table);
2901
+ let _ = exchange.response();
2902
+ let now = reads.load(Ordering::SeqCst);
2903
+ most = most.max(now - last);
2904
+ last = now;
2905
+ (now >= SENT).then_some(())
2906
+ },
2907
+ );
2908
+ let _ = done.send(());
2909
+ peer.join().unwrap();
2910
+ assert_eq!(
2911
+ (answer, most),
2912
+ (Ok(Some(())), 128),
2913
+ "a request whose connection holds 16 KiB read a byte at a time must read at most 128 \
2914
+ times in each look, and wake its own wait until every byte is read, got {} of \
2915
+ {SENT} bytes",
2916
+ reads.load(Ordering::SeqCst)
2917
+ );
2918
+ }
2919
+
2920
+ /// The answer `exchange` settles on, once it settles. Ten seconds is far
2921
+ /// past any timeout these tests set, so an exchange still unsettled then
2922
+ /// is one no timeout was left to end.
2923
+ fn settled(exchange: &Exchange) -> Result<ResponseHead, HttpError> {
2924
+ let give_up = std::time::Instant::now() + Duration::from_secs(10);
2925
+ loop {
2926
+ match exchange.response() {
2927
+ Some(answer) => break answer,
2928
+ None if std::time::Instant::now() < give_up => {
2929
+ thread::sleep(Duration::from_millis(1))
2930
+ }
2931
+ None => panic!(
2932
+ "the exchange never settled in ten seconds; its dial {}, so a connected one \
2933
+ lost its first-byte timeout and an unconnected one its socket's wake",
2934
+ match exchange.connected.get() {
2935
+ Some(_) => "connected",
2936
+ None => "never connected",
2937
+ }
2938
+ ),
2939
+ }
2940
+ }
2941
+ }
2942
+
2943
+ // @behavior NW-205
2944
+ #[test]
2945
+ fn a_request_past_its_connect_or_first_byte_timeout_answers_that_timeout() {
2946
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2947
+ let port = listener.local_addr().unwrap().port();
2948
+ // Each request's namespace lives as long as the test: the Invocation's
2949
+ // end aborts what it still holds.
2950
+ let namespaces = std::cell::RefCell::new(Vec::new());
2951
+ let timed = |seam: Arc<dyn Outbound>, timeouts: Timeouts| {
2952
+ let mut entry = Builder::default();
2953
+ entry.endpoint(
2954
+ Endpoint::new("127.0.0.1", port)
2955
+ .unwrap()
2956
+ .with_addresses(vec![crate::network::Addresses::Local]),
2957
+ );
2958
+ let network = Network::new("web", Arc::new(entry)).unwrap();
2959
+ let namespace = Namespace::for_network(&network, Arc::new(HostInet), seam);
2960
+ let mut request = greeting_request(&format!("127.0.0.1:{port}"));
2961
+ request.timeouts = timeouts;
2962
+ let exchange = crate::net::send(&namespace, &prepare_creds(&[], None), request)
2963
+ .expect("the endpoint names the authority");
2964
+ namespaces.borrow_mut().push(namespace);
2965
+ exchange
2966
+ };
2967
+ let at_once = Some(Duration::ZERO);
2968
+ let unconnected = timed(
2969
+ Arc::new(NeverAnswers),
2970
+ Timeouts {
2971
+ connect: at_once,
2972
+ ..Timeouts::default()
2973
+ },
2974
+ );
2975
+ let unanswered = timed(
2976
+ Arc::new(DialsThenWaits),
2977
+ Timeouts {
2978
+ first_byte: at_once,
2979
+ ..Timeouts::default()
2980
+ },
2981
+ );
2982
+ let sent = Instant::now();
2983
+ let unset = timed(Arc::new(NeverAnswers), Timeouts::default());
2984
+ let unset_bound = unset
2985
+ .deadline()
2986
+ .map(|at| at.saturating_duration_since(sent).as_secs());
2987
+ let unset_head = timed(Arc::new(DialsThenWaits), Timeouts::default());
2988
+ let give_up = Instant::now() + Duration::from_secs(10);
2989
+ let connected = loop {
2990
+ // Each look moves the request on, as its guest's poll does.
2991
+ let _ = unset_head.response();
2992
+ match unset_head.connected.get() {
2993
+ Some(at) => break *at,
2994
+ None if Instant::now() < give_up => thread::sleep(Duration::from_millis(1)),
2995
+ None => panic!(
2996
+ "the request never connected to the loopback listener in ten seconds and \
2997
+ answered {:?}: an answer names why its dial failed, none that its socket \
2998
+ was never woken",
2999
+ unset_head.response()
3000
+ ),
3001
+ }
3002
+ };
3003
+ let unset_head_bound = unset_head
3004
+ .deadline()
3005
+ .map(|at| at.saturating_duration_since(connected).as_secs());
3006
+ assert_eq!(
3007
+ (
3008
+ settled(&unconnected).err(),
3009
+ settled(&unanswered).err(),
3010
+ unset_bound,
3011
+ unset.response(),
3012
+ unset_head_bound,
3013
+ unset_head.response()
3014
+ ),
3015
+ (
3016
+ Some(HttpError::ConnectionTimeout),
3017
+ Some(HttpError::ConnectionReadTimeout),
3018
+ Some(600),
3019
+ None,
3020
+ Some(600),
3021
+ None
3022
+ ),
3023
+ "a request whose connect outlasts its connect timeout must answer connection-timeout, \
3024
+ one connected whose head outlasts its first-byte timeout connection-read-timeout, \
3025
+ and one setting no timeout must wait on, its connect bounded 600 seconds after it \
3026
+ was sent and its head 600 seconds after it connected"
3027
+ );
3028
+ }
3029
+
3030
+ // @behavior NW-205
3031
+ #[test]
3032
+ fn a_body_whose_next_part_outlasts_its_timeout_fails_its_read() {
3033
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
3034
+ let port = listener.local_addr().unwrap().port();
3035
+ let server = thread::spawn(move || {
3036
+ for _ in 0..2 {
3037
+ let (stream, _) = listener.accept().unwrap();
3038
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
3039
+ let mut line = String::new();
3040
+ while reader.read_line(&mut line).unwrap() > 2 {
3041
+ line.clear();
3042
+ }
3043
+ (&stream)
3044
+ .write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 10\r\n\r\n")
3045
+ .unwrap();
3046
+ // Hold the connection open with the body unsent until the
3047
+ // client lets it go.
3048
+ let _ = reader.read_line(&mut line);
3049
+ }
3050
+ });
3051
+ let namespace = namespace(vec![Endpoint::new("127.0.0.1", port)
3052
+ .unwrap()
3053
+ .with_addresses(vec![crate::network::Addresses::Local])]);
3054
+ let mut request = greeting_request(&format!("127.0.0.1:{port}"));
3055
+ request.timeouts.between_bytes = Some(Duration::ZERO);
3056
+ let cred = prepare_creds(&[], None);
3057
+ let exchange =
3058
+ crate::net::send(&namespace, &cred, request).expect("the endpoint names the authority");
3059
+ let head = settled(&exchange).map(|head| head.status);
3060
+ let mut buf = [0; 8];
3061
+ let read = exchange.read(&mut buf);
3062
+ let readable = exchange.alloc_body_file(&cred).poll(None) == PollMask::IN;
3063
+ exchange.release();
3064
+ let sent = Instant::now();
3065
+ let unset = crate::net::send(
3066
+ &namespace,
3067
+ &cred,
3068
+ greeting_request(&format!("127.0.0.1:{port}")),
3069
+ )
3070
+ .expect("the endpoint names the authority");
3071
+ let unset_head = settled(&unset).map(|head| head.status);
3072
+ let unset_bound = unset
3073
+ .deadline()
3074
+ .map(|at| at.saturating_duration_since(sent).as_secs());
3075
+ unset.release();
3076
+ server.join().unwrap();
3077
+ assert_eq!(
3078
+ (head, read, readable, unset_head, unset_bound),
3079
+ (Ok(200), Err(Errno::TimedOut), true, Ok(200), Some(600)),
3080
+ "a body whose next part outlasts its between-bytes timeout must fail its read as \
3081
+ ETIMEDOUT once its head arrived, and its file must poll readable so a waiting \
3082
+ reader meets that failure; a body setting no timeout must bound its wait 600 \
3083
+ seconds after its head"
3084
+ );
3085
+ }
3086
+
3087
+ mod stress {
3088
+ use std::task::Context;
3089
+
3090
+ use super::*;
3091
+
3092
+ /// A body that never ends, a frame ready at every poll.
3093
+ struct EndlessBody;
3094
+
3095
+ impl Body for EndlessBody {
3096
+ type Data = Bytes;
3097
+ type Error = HttpError;
3098
+
3099
+ fn poll_frame(
3100
+ self: Pin<&mut Self>,
3101
+ _cx: &mut Context<'_>,
3102
+ ) -> Poll<Option<Result<http_body::Frame<Bytes>, HttpError>>> {
3103
+ Poll::Ready(Some(Ok(http_body::Frame::data(Bytes::from_static(
3104
+ &[0; 1024],
3105
+ )))))
3106
+ }
3107
+ }
3108
+
3109
+ /// A seam answering each request at once with an endless body.
3110
+ struct StreamsEndlessly;
3111
+
3112
+ impl Outbound for StreamsEndlessly {
3113
+ fn send_request(&self, _: OutgoingRequest, _: Connector) -> ResponseFuture {
3114
+ Box::pin(async {
3115
+ Ok(Response {
3116
+ head: ResponseHead {
3117
+ status: 200,
3118
+ headers: Vec::new(),
3119
+ },
3120
+ body: EndlessBody.boxed_unsync(),
3121
+ })
3122
+ })
3123
+ }
3124
+ }
3125
+
3126
+ // Each look fills a body that never ends, and the guest lets the
3127
+ // exchange go with its body still filling. A request sent after every
3128
+ // one of them must still be answered.
3129
+ // @behavior NW-082
3130
+ #[test]
3131
+ #[ignore = "a stress witness; run by rake crates:stress"]
3132
+ fn an_exchange_let_go_while_its_body_fills_leaves_later_requests_answered() {
3133
+ let mut entry = Builder::default();
3134
+ entry.endpoint(Endpoint::new("api.example.com", 80).unwrap());
3135
+ let network = Network::new("api", Arc::new(entry)).unwrap();
3136
+ let namespace = Namespace::for_network(
3137
+ &network,
3138
+ Arc::new(CountsDials::default()),
3139
+ Arc::new(StreamsEndlessly),
3140
+ );
3141
+ let cred = prepare_creds(&[], None);
3142
+ let send = || {
3143
+ crate::net::send(
3144
+ &namespace,
3145
+ &cred,
3146
+ OutgoingRequest::new("GET", Scheme::Http, "api.example.com:80"),
3147
+ )
3148
+ .expect("an endpoint names the authority")
3149
+ };
3150
+ for _ in 0..20_000 {
3151
+ let exchange = send();
3152
+ while exchange.response().is_none() {
3153
+ std::hint::spin_loop();
3154
+ }
3155
+ let _ = exchange.read(&mut [0; 1]);
3156
+ }
3157
+ let last = send();
3158
+ assert!(
3159
+ crate::sched::testing::holds_within_max_wait(|| last.response().is_some()),
3160
+ "a request sent after 20,000 exchanges let go while their bodies fill must still \
3161
+ be answered, so no exchange's release leaves anything held"
3162
+ );
3163
+ }
3164
+ }
3165
+ }