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,869 @@
1
+ //! A socket is a file, as Linux's `net/socket.c` makes one: every socket
2
+ //! stands on sockfs, and its file hands each call to the protocol's operations,
3
+ //! as `socket_file_ops` hands them to `proto_ops`.
4
+
5
+ use std::collections::HashSet;
6
+ use std::io;
7
+ use std::net::{IpAddr, Ipv4Addr, Shutdown, SocketAddr};
8
+ use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError};
9
+
10
+ use socket2::SockRef;
11
+
12
+ use crate::cred::Cred;
13
+ use crate::vfs::{
14
+ alloc_file_pseudo, Dentry, FMode, File, FileOperations, FileSystemType, FileType, Inode,
15
+ InodeOperations, Kiocb, Kstat, OpenHow, PollMask, SuperBlock, VfsMount,
16
+ };
17
+ use crate::wait::PollTable;
18
+ use crate::Errno;
19
+
20
+ use super::connections::{open, OpenConnections, Place};
21
+ use super::namespace::TcpSockets;
22
+ use super::{Namespace, ProtocolFamily, TcpSock, UdpSock};
23
+ use crate::network::{Connection, Protocol, Ruleset};
24
+
25
+ /// How much a socket holds each way before it stops reading and refuses
26
+ /// more, as `sk_rcvbuf` and `sk_sndbuf` bound a Linux socket and net core's
27
+ /// `rmem_max` and `wmem_max` bound what either may be set to, so a full
28
+ /// buffer pushes back on the peer.
29
+ pub const MAX_SOCKET_BUFFER: usize = 64 * 1024;
30
+
31
+ /// What one protocol answers for its socket, as Linux's `struct proto_ops`:
32
+ /// its bind, the file's reads and writes, what a poll finds, its shutdown,
33
+ /// names, and options, and the release once every view is gone, whichever
34
+ /// protocol stands behind.
35
+ pub trait ProtoOps: Send + Sync {
36
+ /// Take `addr` as the socket's own end once the socket hooks passed it,
37
+ /// its port from `net`'s ports for the protocol, as `->bind` runs after
38
+ /// `__sys_bind` asks `security_socket_bind`: an IPv6 address answers
39
+ /// `AddressFamilyNotSupported`, a socket bound or connected already
40
+ /// `InvalidInput`, and a port held elsewhere `AddressInUse`, as
41
+ /// `__inet_bind` refuses one.
42
+ fn bind(&self, net: &Namespace, addr: SocketAddr) -> Result<(), Errno>;
43
+ /// Connect to `addr`, the address the guest named, once the socket hooks
44
+ /// passed it, as `->connect` runs after `__sys_connect` asks
45
+ /// `security_socket_connect`: the socket's own state is checked first,
46
+ /// then `net` translates `addr` as cgroup `connect4` does and its ruleset
47
+ /// judges the real destination.
48
+ fn connect(&self, net: &Namespace, addr: SocketAddr) -> Result<(), Errno>;
49
+ /// Read what the socket holds and who sent it, as `->recvmsg` fills
50
+ /// `msg_name`: a datagram's peer as the guest named it, none for a
51
+ /// stream; `WouldBlock` while it holds nothing yet.
52
+ fn recvmsg(&self, buf: &mut [u8]) -> Result<(usize, Option<SocketAddr>), Errno>;
53
+ /// Write what the socket takes now; `WouldBlock` while it takes nothing.
54
+ fn sendmsg(&self, buf: &[u8]) -> Result<usize, Errno>;
55
+ /// What a call would find ready, the socket's wait queue registered on
56
+ /// `table`, as a protocol's `->poll` calls `sock_poll_wait`.
57
+ fn poll(&self, table: Option<&mut PollTable>) -> PollMask;
58
+ /// Shut the reading side, the writing side, or both down, as
59
+ /// `inet_shutdown` marks `sk_shutdown`; a socket connected to nothing
60
+ /// answers `ENOTCONN`.
61
+ fn shutdown(&self, how: Shutdown) -> Result<(), Errno>;
62
+ /// The `peer` end, or the guest's own, as `->getname` answers each. The
63
+ /// peer is the address the guest named, mapped back from the real one
64
+ /// through cgroup `getpeername4`; a socket connected to nothing answers
65
+ /// `ENOTCONN`. The own end passes cgroup `getsockname4`: the guest's own
66
+ /// virtual address and the port its namespace gave as the connect began,
67
+ /// or the unspecified address before then, as Linux answers an unbound
68
+ /// socket.
69
+ fn getname(&self, peer: bool) -> Result<SocketAddr, Errno>;
70
+ /// The protocol the socket speaks, as `sk_protocol` names it, which the
71
+ /// socket hooks judge a connect by.
72
+ fn protocol(&self) -> Protocol;
73
+ /// The value `opt` holds on this socket, never the host's; one the
74
+ /// protocol has not answers `ProtocolNotAvailable`.
75
+ fn getsockopt(&self, opt: SockOpt) -> Result<u32, Errno>;
76
+ /// Set `opt` to `value`, as `setsockopt` does, refusing what Linux
77
+ /// refuses; a host socket already dialed takes it at once.
78
+ fn setsockopt(&self, opt: SockOpt, value: u32) -> Result<(), Errno>;
79
+ /// Close the socket once every view is gone, as `sock_close` runs on the
80
+ /// last `fput`; a protocol may finish sending before its host socket goes.
81
+ fn release(&self);
82
+ }
83
+
84
+ /// A socket option a protocol may answer, as `setsockopt`'s level and name
85
+ /// pick one. Sizes are bytes, times are seconds, and a flag is 0 or 1.
86
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
87
+ #[non_exhaustive]
88
+ pub enum SockOpt {
89
+ /// `SO_RCVBUF`, which reads twice what was set.
90
+ RcvBuf,
91
+ /// `SO_SNDBUF`, which reads twice what was set.
92
+ SndBuf,
93
+ /// `IP_TTL`.
94
+ Ttl,
95
+ /// `SO_KEEPALIVE`.
96
+ KeepAlive,
97
+ /// `TCP_KEEPIDLE`.
98
+ KeepIdle,
99
+ /// `TCP_KEEPINTVL`.
100
+ KeepIntvl,
101
+ /// `TCP_KEEPCNT`.
102
+ KeepCnt,
103
+ /// `TCP_NODELAY`, which sends each write without Nagle's delay.
104
+ NoDelay,
105
+ }
106
+
107
+ /// The bottom of the virtual range, `198.18.0.0/15`, inside the reserved set,
108
+ /// so no real destination is ever in it.
109
+ pub(crate) const VIRTUAL_BASE: u32 = u32::from_be_bytes([198, 18, 0, 0]);
110
+
111
+ /// How many virtual addresses the range holds.
112
+ pub(crate) const VIRTUAL_SIZE: u32 = 1 << 17;
113
+
114
+ /// The guest's own end of every socket it connects, `198.19.255.254`, kept
115
+ /// out of what a lookup hands out, as a container in its own network
116
+ /// namespace reads its veth's address while the host translates. It sits
117
+ /// below the virtual range's last address, the one a broadcast would take.
118
+ pub(crate) const LOCAL_ADDRESS: Ipv4Addr = Ipv4Addr::from_bits(VIRTUAL_BASE + VIRTUAL_SIZE - 2);
119
+
120
+ /// The ports a bind to port 0 or a connect gives the guest for its own end,
121
+ /// Linux's default `ip_local_port_range`, taken in turn from the bottom and
122
+ /// around again, so no host port reaches the guest and a script reads the
123
+ /// same ports each run.
124
+ const VIRTUAL_PORTS: std::ops::RangeInclusive<u16> = 32768..=60999;
125
+
126
+ /// The ports one protocol's sockets hold in a namespace, as TCP's `bhash`
127
+ /// and UDP's `udp_table` keep each bound port: a port is held by one socket
128
+ /// at a time, and goes back as that socket puts it.
129
+ pub(crate) struct BindHash {
130
+ ports: Mutex<Ports>,
131
+ }
132
+
133
+ /// The ports held, and where the next search for a free one starts.
134
+ struct Ports {
135
+ held: HashSet<u16>,
136
+ next: u16,
137
+ }
138
+
139
+ impl BindHash {
140
+ pub(crate) fn new() -> Arc<Self> {
141
+ Arc::new(Self {
142
+ ports: Mutex::new(Ports {
143
+ held: HashSet::new(),
144
+ next: *VIRTUAL_PORTS.start(),
145
+ }),
146
+ })
147
+ }
148
+
149
+ fn ports(&self) -> MutexGuard<'_, Ports> {
150
+ self.ports.lock().unwrap_or_else(PoisonError::into_inner)
151
+ }
152
+
153
+ /// `port` held for one socket, or `EADDRINUSE` while another holds it,
154
+ /// as `inet_csk_get_port` and `udp_lib_get_port` find it taken.
155
+ fn get_port(self: &Arc<Self>, port: u16) -> Result<BoundPort, Errno> {
156
+ match self.ports().held.insert(port) {
157
+ true => Ok(BoundPort {
158
+ hash: self.clone(),
159
+ port,
160
+ }),
161
+ false => Err(Errno::AddressInUse),
162
+ }
163
+ }
164
+
165
+ /// The first free port of `VIRTUAL_PORTS` from where the last search
166
+ /// left off, as `inet_csk_find_open_port`, `inet_hash_connect`, and
167
+ /// `udp_lib_get_port` walk `ip_local_port_range` past each port held;
168
+ /// `None` once every one is held.
169
+ fn find_open_port(self: &Arc<Self>) -> Option<BoundPort> {
170
+ let mut ports = self.ports();
171
+ let start = ports.next;
172
+ let mut port = start;
173
+ loop {
174
+ let after = match port == *VIRTUAL_PORTS.end() {
175
+ true => *VIRTUAL_PORTS.start(),
176
+ false => port + 1,
177
+ };
178
+ if ports.held.insert(port) {
179
+ ports.next = after;
180
+ return Some(BoundPort {
181
+ hash: self.clone(),
182
+ port,
183
+ });
184
+ }
185
+ if after == start {
186
+ return None;
187
+ }
188
+ port = after;
189
+ }
190
+ }
191
+ }
192
+
193
+ /// One port a socket holds in its protocol's `BindHash`, given back as it is
194
+ /// dropped, as `__inet_put_port` takes a socket off its bucket.
195
+ pub(crate) struct BoundPort {
196
+ hash: Arc<BindHash>,
197
+ port: u16,
198
+ }
199
+
200
+ impl Drop for BoundPort {
201
+ fn drop(&mut self) {
202
+ self.hash.ports().held.remove(&self.port);
203
+ }
204
+ }
205
+
206
+ /// Where a socket stands as the calls TCP and UDP share read Linux's
207
+ /// `sk_state`: a UDP socket naming a peer is `TCP_ESTABLISHED`, as
208
+ /// `__ip4_datagram_connect` sets it.
209
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
210
+ pub(crate) enum SkState {
211
+ /// `TCP_CLOSE`: connected to nothing, or back from a failure.
212
+ Close,
213
+ /// `TCP_SYN_SENT`: a connect under way.
214
+ SynSent,
215
+ /// `TCP_ESTABLISHED`.
216
+ Established,
217
+ }
218
+
219
+ /// What every inet socket holds beside its protocol's own state, as Linux's
220
+ /// `inet_sock` sits beneath `tcp_sock` and `udp_sock`.
221
+ pub(crate) struct InetSock {
222
+ /// The port the socket holds, as `inet_num`, which a bind or a connect
223
+ /// takes and closing puts back.
224
+ num: Option<BoundPort>,
225
+ /// The port the guest reads for its own end, as `inet_sport`, kept after
226
+ /// the port goes back until another is taken.
227
+ sport: Option<u16>,
228
+ /// The address a bind named, as `inet_rcv_saddr`.
229
+ rcv_saddr: Ipv4Addr,
230
+ /// The peer as the guest named it, a virtual address standing for its
231
+ /// name, as cgroup `getpeername4` maps a real peer back.
232
+ pub(crate) peer: Option<SocketAddr>,
233
+ /// How much each queue holds, as `sk_rcvbuf` and `sk_sndbuf`.
234
+ pub(crate) buffers: Buffers,
235
+ /// The hop limit sent with, as `inet_sock` keeps `uc_ttl`.
236
+ pub(crate) uc_ttl: u8,
237
+ /// The socket's pending failure, as `sk_err`: answered once, then
238
+ /// cleared, as `sock_error` swaps it with zero.
239
+ pub(crate) err: Option<Errno>,
240
+ /// The guest shut its reading side down, as `sk_shutdown`'s
241
+ /// `RCV_SHUTDOWN`.
242
+ pub(crate) rcv_shutdown: bool,
243
+ /// The guest shut its writing side down, as `SEND_SHUTDOWN`.
244
+ pub(crate) send_shutdown: bool,
245
+ /// The socket's place against its Sandbox's cap and the process's, given
246
+ /// back as it is released; an upstream socket shares its request's.
247
+ pub(crate) place: Option<Arc<Place>>,
248
+ /// Whether the bind named its port, which the socket then keeps once it
249
+ /// closes, as `SOCK_BINDPORT_LOCK` does.
250
+ bindport_locked: bool,
251
+ }
252
+
253
+ impl InetSock {
254
+ /// A socket whose queues start at `buffers`.
255
+ pub(crate) fn new(buffers: Buffers) -> Self {
256
+ Self {
257
+ num: None,
258
+ sport: None,
259
+ rcv_saddr: Ipv4Addr::UNSPECIFIED,
260
+ peer: None,
261
+ buffers,
262
+ uc_ttl: IPDEFTTL,
263
+ err: None,
264
+ rcv_shutdown: false,
265
+ send_shutdown: false,
266
+ place: None,
267
+ bindport_locked: false,
268
+ }
269
+ }
270
+
271
+ /// Take `addr` as the socket's own end, its port from `hash`, as
272
+ /// `__inet_bind` does: an IPv6 address answers `EAFNOSUPPORT`, and a
273
+ /// socket holding a port, or past `TCP_CLOSE` and so bound by its connect,
274
+ /// `EINVAL`. Port 0 takes a free virtual port, and a named port one no
275
+ /// other socket holds, either answering `EADDRINUSE` once none is left,
276
+ /// as the protocol's `get_port` does.
277
+ pub(crate) fn bind(
278
+ &mut self,
279
+ addr: SocketAddr,
280
+ state: SkState,
281
+ hash: &Arc<BindHash>,
282
+ ) -> Result<(), Errno> {
283
+ let IpAddr::V4(ip) = addr.ip() else {
284
+ return Err(Errno::AddressFamilyNotSupported);
285
+ };
286
+ if self.num.is_some() || state != SkState::Close {
287
+ return Err(Errno::InvalidInput);
288
+ }
289
+ let bound = match addr.port() {
290
+ 0 => hash.find_open_port().ok_or(Errno::AddressInUse)?,
291
+ port => hash.get_port(port)?,
292
+ };
293
+ self.sport = Some(bound.port);
294
+ self.num = Some(bound);
295
+ self.bindport_locked = addr.port() != 0;
296
+ self.rcv_saddr = ip;
297
+ Ok(())
298
+ }
299
+
300
+ /// Give back the port the socket holds once it closes, unless a bind
301
+ /// named it, as `tcp_set_state` puts the port on entering `TCP_CLOSE`
302
+ /// without `SOCK_BINDPORT_LOCK`.
303
+ pub(crate) fn put_port(&mut self) {
304
+ if !self.bindport_locked {
305
+ self.num = None;
306
+ }
307
+ }
308
+
309
+ /// The peer as the guest named it, or the guest's own end, as
310
+ /// `inet_getname` answers TCP and UDP alike. A peer answers `ENOTCONN`
311
+ /// unless one is named and the socket is past `TCP_SYN_SENT`. The own end
312
+ /// reads `inet_rcv_saddr`, or the guest's own virtual address once it
313
+ /// names a peer, and `inet_sport`.
314
+ pub(crate) fn getname(&self, peer: bool, state: SkState) -> Result<SocketAddr, Errno> {
315
+ if peer {
316
+ return match state {
317
+ SkState::Established => self.peer.ok_or(Errno::NotConnected),
318
+ SkState::Close | SkState::SynSent => Err(Errno::NotConnected),
319
+ };
320
+ }
321
+ let ip = match (self.rcv_saddr.is_unspecified(), self.peer) {
322
+ (true, Some(_)) => LOCAL_ADDRESS,
323
+ _ => self.rcv_saddr,
324
+ };
325
+ Ok(SocketAddr::from((ip, self.sport.unwrap_or(0))))
326
+ }
327
+
328
+ /// Hold a free port from `hash` as a connect begins, unless the socket
329
+ /// holds one, as `inet_hash_connect` picks a port only when `inet_num` is
330
+ /// zero, answering `EADDRNOTAVAIL` once none is left. A port put back once
331
+ /// the socket closed is then replaced, while reading the socket's own end
332
+ /// still answers the old one until then, as `inet_sport` keeps it.
333
+ pub(crate) fn hash_connect(&mut self, hash: &Arc<BindHash>) -> Result<(), Errno> {
334
+ if self.num.is_none() {
335
+ let bound = hash.find_open_port().ok_or(Errno::AddressNotAvailable)?;
336
+ self.sport = Some(bound.port);
337
+ self.num = Some(bound);
338
+ }
339
+ Ok(())
340
+ }
341
+
342
+ /// A new place against `open_connections` and the process, or `None`
343
+ /// when the socket holds one already, so a socket connecting again
344
+ /// counts once; either cap full answers `EAGAIN`.
345
+ pub(crate) fn open_place(
346
+ &self,
347
+ open_connections: &Arc<OpenConnections>,
348
+ ) -> Result<Option<Arc<Place>>, Errno> {
349
+ match self.place {
350
+ Some(_) => Ok(None),
351
+ None => open(open_connections)
352
+ .map(|place| Some(Arc::new(place)))
353
+ .ok_or(Errno::WouldBlock),
354
+ }
355
+ }
356
+
357
+ /// Mark the sides `how` names shut, as `inet_shutdown` sets
358
+ /// `sk_shutdown`.
359
+ pub(crate) fn mark_shutdown(&mut self, how: Shutdown) {
360
+ self.rcv_shutdown |= matches!(how, Shutdown::Read | Shutdown::Both);
361
+ self.send_shutdown |= matches!(how, Shutdown::Write | Shutdown::Both);
362
+ }
363
+
364
+ /// Shut the sides `how` names, as `inet_shutdown` does for TCP and UDP
365
+ /// alike: a socket in `TCP_CLOSE` marks them still and answers
366
+ /// `ENOTCONN`. A protocol disconnects one in `TCP_SYN_SENT` itself.
367
+ pub(crate) fn shutdown(&mut self, how: Shutdown, state: SkState) -> Result<(), Errno> {
368
+ self.mark_shutdown(how);
369
+ match state {
370
+ SkState::Close => Err(Errno::NotConnected),
371
+ SkState::SynSent | SkState::Established => Ok(()),
372
+ }
373
+ }
374
+
375
+ /// Give back the socket's place, as `sk_free` does once the socket is
376
+ /// released.
377
+ pub(crate) fn release(&mut self) {
378
+ self.place = None;
379
+ }
380
+
381
+ /// What `opt` reads at the socket and IP levels, as `sk_getsockopt` and
382
+ /// `do_ip_getsockopt` answer; a TCP option answers `ProtocolNotAvailable`.
383
+ pub(crate) fn getsockopt(&self, opt: SockOpt) -> Result<u32, Errno> {
384
+ let value = match opt {
385
+ SockOpt::RcvBuf => self.buffers.rcvbuf,
386
+ SockOpt::SndBuf => self.buffers.sndbuf,
387
+ SockOpt::Ttl => usize::from(self.uc_ttl),
388
+ _ => return Err(Errno::ProtocolNotAvailable),
389
+ };
390
+ Ok(u32::try_from(value).unwrap_or(u32::MAX))
391
+ }
392
+
393
+ /// Set `opt` at the socket and IP levels, as `sk_setsockopt` and
394
+ /// `do_ip_setsockopt` do for every inet protocol: a buffer to twice
395
+ /// `value`, and the hop limit, which reaches `host`, a host socket
396
+ /// already dialed, at once; a host refusing it leaves the old value, as a
397
+ /// failed `setsockopt` changes nothing. A TCP option answers
398
+ /// `ProtocolNotAvailable`.
399
+ pub(crate) fn setsockopt(
400
+ &mut self,
401
+ opt: SockOpt,
402
+ value: u32,
403
+ host: Option<SockRef<'_>>,
404
+ ) -> Result<(), Errno> {
405
+ let bytes = usize::try_from(value).unwrap_or(usize::MAX);
406
+ match opt {
407
+ SockOpt::RcvBuf => self.buffers.set_rcvbuf(bytes),
408
+ SockOpt::SndBuf => self.buffers.set_sndbuf(bytes),
409
+ SockOpt::Ttl => {
410
+ let ttl = to_ttl(value)?;
411
+ if let Some(host) = host {
412
+ set_hop_limit(host, ttl).map_err(|err| Errno::from_io_error(&err))?;
413
+ }
414
+ self.uc_ttl = ttl;
415
+ }
416
+ _ => return Err(Errno::ProtocolNotAvailable),
417
+ }
418
+ Ok(())
419
+ }
420
+ }
421
+
422
+ /// The least `SO_RCVBUF` and `SO_SNDBUF` leave a queue, Linux's
423
+ /// `SOCK_MIN_RCVBUF` and `SOCK_MIN_SNDBUF`.
424
+ const SOCK_MIN_RCVBUF: usize = 2304;
425
+ const SOCK_MIN_SNDBUF: usize = 4608;
426
+
427
+ /// What a TCP socket's queues hold until it connects, Linux's `tcp_wmem[1]`
428
+ /// and `tcp_rmem[1]`.
429
+ const TCP_WMEM_DEFAULT: usize = 16 * 1024;
430
+ const TCP_RMEM_DEFAULT: usize = 128 * 1024;
431
+
432
+ /// How much a socket's queues hold, as `sk_rcvbuf` and `sk_sndbuf`. Each
433
+ /// starts at Linux's default and never passes `MAX_SOCKET_BUFFER`, which
434
+ /// plays `rmem_max` and `wmem_max` as twice the most a set takes.
435
+ pub(crate) struct Buffers {
436
+ pub(crate) rcvbuf: usize,
437
+ pub(crate) sndbuf: usize,
438
+ /// Whether the guest set `SO_SNDBUF`, which Linux's `SOCK_SNDBUF_LOCK`
439
+ /// keeps from growing.
440
+ sndbuf_locked: bool,
441
+ }
442
+
443
+ impl Default for Buffers {
444
+ /// A datagram socket's, Linux's `rmem_default` and `wmem_default`, both
445
+ /// past the cap.
446
+ fn default() -> Self {
447
+ Self::new(MAX_SOCKET_BUFFER, MAX_SOCKET_BUFFER)
448
+ }
449
+ }
450
+
451
+ impl Buffers {
452
+ /// A TCP socket's, until it connects.
453
+ pub(crate) fn tcp() -> Self {
454
+ Self::new(TCP_RMEM_DEFAULT, TCP_WMEM_DEFAULT)
455
+ }
456
+
457
+ /// Ones of `rcvbuf` and `sndbuf` bytes, each held to the cap.
458
+ fn new(rcvbuf: usize, sndbuf: usize) -> Self {
459
+ Self {
460
+ rcvbuf: rcvbuf.min(MAX_SOCKET_BUFFER),
461
+ sndbuf: sndbuf.min(MAX_SOCKET_BUFFER),
462
+ sndbuf_locked: false,
463
+ }
464
+ }
465
+
466
+ /// Grow a connected TCP socket's send buffer, as `tcp_sndbuf_expand` makes
467
+ /// room for its window: two of `TCP_INIT_CWND` segments, which pass the
468
+ /// cap at any MSS. One the guest set stays.
469
+ pub(crate) fn sndbuf_expand(&mut self) {
470
+ if !self.sndbuf_locked {
471
+ self.sndbuf = MAX_SOCKET_BUFFER;
472
+ }
473
+ }
474
+
475
+ /// Twice `bytes`, within the cap, as `sock_setsockopt` doubles a value to
476
+ /// leave room for its bookkeeping.
477
+ fn to_buffer_room(bytes: usize, least: usize) -> usize {
478
+ (bytes.min(MAX_SOCKET_BUFFER / 2) * 2).max(least)
479
+ }
480
+
481
+ pub(crate) fn set_rcvbuf(&mut self, bytes: usize) {
482
+ self.rcvbuf = Self::to_buffer_room(bytes, SOCK_MIN_RCVBUF);
483
+ }
484
+
485
+ pub(crate) fn set_sndbuf(&mut self, bytes: usize) {
486
+ self.sndbuf = Self::to_buffer_room(bytes, SOCK_MIN_SNDBUF);
487
+ self.sndbuf_locked = true;
488
+ }
489
+ }
490
+
491
+ /// The hop limit a socket sends with until the guest sets one, Linux's
492
+ /// `IPDEFTTL`; the host's own default never reaches the guest.
493
+ pub(crate) const IPDEFTTL: u8 = 64;
494
+
495
+ /// `ttl` as a hop limit Linux takes, 1 to 255, refusing the rest with EINVAL
496
+ /// as `do_ip_setsockopt` does.
497
+ pub(crate) fn to_ttl(ttl: u32) -> Result<u8, Errno> {
498
+ match u8::try_from(ttl) {
499
+ Ok(0) | Err(_) => Err(Errno::InvalidInput),
500
+ Ok(ttl) => Ok(ttl),
501
+ }
502
+ }
503
+
504
+ /// Give the host socket `socket` the hop limit `ttl`, as `IP_TTL` on an IPv4
505
+ /// one and `IPV6_UNICAST_HOPS` on an IPv6 one, since the guest's IPv4 socket
506
+ /// may reach the host over IPv6 and each family keeps its own.
507
+ pub(crate) fn set_hop_limit(socket: SockRef<'_>, ttl: u8) -> io::Result<()> {
508
+ match socket.local_addr()?.is_ipv6() {
509
+ true => socket.set_unicast_hops_v6(ttl.into()),
510
+ false => socket.set_ttl_v4(ttl.into()),
511
+ }
512
+ }
513
+
514
+ /// `value` within 1 to `max`, else EINVAL, as Linux bounds a TCP option.
515
+ pub(crate) fn ensure_within(value: u32, max: u32) -> Result<(), Errno> {
516
+ match (1..=max).contains(&value) {
517
+ true => Ok(()),
518
+ false => Err(Errno::InvalidInput),
519
+ }
520
+ }
521
+
522
+ /// Take how a non-blocking connect on `stream` stands, as reading `SO_ERROR`
523
+ /// clears it and then the peer's name tells: `None` while it is under way, and
524
+ /// its outcome once it settled. Every dialer of a host stream reads it the same
525
+ /// way.
526
+ pub(crate) fn take_connect_outcome(stream: &mio::net::TcpStream) -> Option<io::Result<()>> {
527
+ match (stream.take_error(), stream.peer_addr()) {
528
+ (Ok(Some(err)), _) | (Err(err), _) => Some(Err(err)),
529
+ (Ok(None), Ok(_)) => Some(Ok(())),
530
+ (Ok(None), Err(err)) if err.kind() == io::ErrorKind::NotConnected => None,
531
+ (Ok(None), Err(err)) => Some(Err(err)),
532
+ }
533
+ }
534
+
535
+ /// The one Filesystem every socket stands on, as Linux's `sock_mnt`. No path
536
+ /// reaches it: a socket is only ever open.
537
+ static SOCK_MNT: LazyLock<Arc<VfsMount>> = LazyLock::new(|| {
538
+ let sb = SuperBlock::new(SockFs).expect("sockfs fills in nothing that can fail");
539
+ VfsMount::kern_mount(sb)
540
+ });
541
+
542
+ /// A socket reports what it is and no length, as `sock_alloc` makes one.
543
+ struct SockFs;
544
+
545
+ impl FileSystemType for SockFs {
546
+ fn fill_super(self: Arc<Self>, sb: &mut SuperBlock) -> Result<(), Errno> {
547
+ sb.d_make_root(Inode::new(&Kstat::new(FileType::Dir, 0), self));
548
+ Ok(())
549
+ }
550
+ }
551
+
552
+ impl InodeOperations for SockFs {
553
+ fn getattr(&self, _dentry: &Dentry) -> Result<Kstat, Errno> {
554
+ Ok(Kstat::new(FileType::Sock, 0))
555
+ }
556
+ }
557
+
558
+ /// What answers for a socket file, as `socket_file_ops` hands each call to the
559
+ /// socket's protocol operations. The file never waits: a read or write that
560
+ /// would wait answers EAGAIN and the guest polls, since WASI's sockets never
561
+ /// block and no encoding clears the file's `O_NONBLOCK`.
562
+ struct SocketFile {
563
+ ops: Arc<dyn ProtoOps>,
564
+ }
565
+
566
+ impl FileOperations for SocketFile {
567
+ /// A read of nothing answers zero before the socket is asked, as
568
+ /// `sock_read_iter` does, so it takes no datagram.
569
+ fn read_iter(&mut self, _iocb: &mut Kiocb, buf: &mut [u8]) -> Result<usize, Errno> {
570
+ if buf.is_empty() {
571
+ return Ok(0);
572
+ }
573
+ self.ops.recvmsg(buf).map(|(n, _)| n)
574
+ }
575
+
576
+ fn write_iter(&mut self, _iocb: &mut Kiocb, buf: &[u8]) -> Result<usize, Errno> {
577
+ self.ops.sendmsg(buf)
578
+ }
579
+
580
+ fn poll(&self, _mode: FMode, table: Option<&mut PollTable>) -> PollMask {
581
+ self.ops.poll(table)
582
+ }
583
+
584
+ fn is_stream(&self) -> bool {
585
+ true
586
+ }
587
+ }
588
+
589
+ impl Drop for SocketFile {
590
+ fn drop(&mut self) {
591
+ self.ops.release();
592
+ }
593
+ }
594
+
595
+ /// The socket file of `sock`, opened as `cred` for reading and writing, as
596
+ /// Linux's `sock_alloc_file` makes one; dropping it releases the socket.
597
+ pub fn sock_alloc_file(sock: Arc<dyn ProtoOps>, cred: &Arc<Cred>) -> File {
598
+ let inode = Inode::new(&Kstat::new(FileType::Sock, 0), Arc::new(SockFs));
599
+ alloc_file_pseudo(
600
+ inode,
601
+ &SOCK_MNT,
602
+ &OpenHow {
603
+ read: true,
604
+ write: true,
605
+ nonblock: true,
606
+ ..OpenHow::default()
607
+ },
608
+ Box::new(SocketFile { ops: sock }),
609
+ cred,
610
+ )
611
+ }
612
+
613
+ /// The address family a socket is made in, as `socket()`'s `domain`.
614
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
615
+ #[non_exhaustive]
616
+ pub enum AddressFamily {
617
+ /// `AF_INET`.
618
+ Inet,
619
+ /// `AF_INET6`, which the guest has none of.
620
+ Inet6,
621
+ }
622
+
623
+ impl AddressFamily {
624
+ /// The family `ip` is an address of, as an address's `sa_family` names it.
625
+ pub(crate) fn of(ip: IpAddr) -> Self {
626
+ match ip {
627
+ IpAddr::V4(_) => Self::Inet,
628
+ IpAddr::V6(_) => Self::Inet6,
629
+ }
630
+ }
631
+ }
632
+
633
+ /// Refuse a family the guest has no socket of, as `__sock_create` answers
634
+ /// `EAFNOSUPPORT` for a family no `net_proto_family` registered; an address of
635
+ /// such a family reaches no socket, so a connect to one answers the same.
636
+ pub(crate) fn check_family(family: AddressFamily) -> Result<(), Errno> {
637
+ match family {
638
+ AddressFamily::Inet => Ok(()),
639
+ AddressFamily::Inet6 => Err(Errno::AddressFamilyNotSupported),
640
+ }
641
+ }
642
+
643
+ impl TcpSock {
644
+ /// A TCP socket of `family`, connected to nothing, in `net`, as
645
+ /// `__sock_create` makes one; it connects through `net`'s Protocol
646
+ /// Family.
647
+ pub fn create(net: &Namespace, family: AddressFamily) -> Result<Arc<Self>, Errno> {
648
+ check_family(family)?;
649
+ Ok(Self::create_kern(net.family(), net.tcp_sockets()))
650
+ }
651
+
652
+ /// A TCP socket the runtime makes for itself, as `sock_create_kern` does:
653
+ /// it connects through `family`, and `sockets` holds it until the
654
+ /// Invocation ends.
655
+ pub(crate) fn create_kern(family: &Arc<dyn ProtocolFamily>, sockets: &TcpSockets) -> Arc<Self> {
656
+ let sock = Self::new(family.clone());
657
+ sockets.hold(&sock);
658
+ sock
659
+ }
660
+ }
661
+
662
+ impl UdpSock {
663
+ /// A UDP socket of `family`, connected to nothing, in `net`, as
664
+ /// `__sock_create` makes one.
665
+ pub fn create(_net: &Namespace, family: AddressFamily) -> Result<Arc<Self>, Errno> {
666
+ check_family(family)?;
667
+ Ok(Self::new())
668
+ }
669
+ }
670
+
671
+ /// Bind `sock` to `addr` in `net` as `cred`, as `__sys_bind` asks
672
+ /// `security_socket_bind` before the protocol's `->bind`; the host socket
673
+ /// takes its own address as it connects.
674
+ pub fn sys_bind(
675
+ net: &Namespace,
676
+ cred: &Cred,
677
+ sock: &dyn ProtoOps,
678
+ addr: SocketAddr,
679
+ ) -> Result<(), Errno> {
680
+ cred.security_socket_bind(addr)?;
681
+ sock.bind(net, addr)
682
+ }
683
+
684
+ /// Connect `sock` in `net` to `addr`, the address the guest named, as `cred`,
685
+ /// as `__sys_connect` does: the socket hooks judge what the guest named
686
+ /// first, then the socket's `->connect` takes it. `None` stands for
687
+ /// `AF_UNSPEC`, which Linux takes as a disconnect; a socket naming no peer
688
+ /// would send each datagram anywhere, so it is refused.
689
+ pub fn sys_connect(
690
+ net: &Namespace,
691
+ cred: &Cred,
692
+ sock: &dyn ProtoOps,
693
+ addr: Option<SocketAddr>,
694
+ ) -> Result<(), Errno> {
695
+ let addr = addr.ok_or(Errno::PermissionDenied)?;
696
+ security_socket_connect(net, cred, addr, sock.protocol())?;
697
+ sock.connect(net, addr)
698
+ }
699
+
700
+ /// Judge a `protocol` connection to `addr` through the socket hooks `cred`
701
+ /// holds, the name a virtual address in `net` stands for in place of the
702
+ /// address, as `security_socket_connect` runs before the protocol's
703
+ /// `connect`.
704
+ fn security_socket_connect(
705
+ net: &Namespace,
706
+ cred: &Cred,
707
+ addr: SocketAddr,
708
+ protocol: Protocol,
709
+ ) -> Result<(), Errno> {
710
+ let host = match net.translation_of(addr) {
711
+ Some(Some((name, _))) => name,
712
+ _ => addr.ip().to_string(),
713
+ };
714
+ cred.security_socket_connect(&Connection::new(&host, addr.port(), protocol))
715
+ }
716
+
717
+ /// Where a socket's connect leads once cgroup `connect4` ran: the literal
718
+ /// address the guest named, or the name a virtual address stands for, the
719
+ /// real address it stands for, and the port.
720
+ pub(crate) enum Destination {
721
+ Literal(SocketAddr),
722
+ Named {
723
+ name: String,
724
+ real: IpAddr,
725
+ port: u16,
726
+ },
727
+ }
728
+
729
+ /// What a socket's connect to `addr` reaches in `net` once its state check
730
+ /// passed, as cgroup `connect4` runs inside the protocol's `connect`: an IPv6
731
+ /// address answers `EAFNOSUPPORT`, as `tcp_v4_connect` and
732
+ /// `__ip4_datagram_connect` refuse one; a
733
+ /// virtual address turns into the name it stands for and the one real
734
+ /// address it stands for, one no name holds answering `EACCES`; any other
735
+ /// stands as itself.
736
+ pub(crate) fn connect4(net: &Namespace, addr: SocketAddr) -> Result<Destination, Errno> {
737
+ check_family(AddressFamily::of(addr.ip()))?;
738
+ match net.translation_of(addr) {
739
+ None => Ok(Destination::Literal(addr)),
740
+ Some(None) => Err(Errno::PermissionDenied),
741
+ Some(Some((name, real))) => Ok(Destination::Named {
742
+ name,
743
+ real,
744
+ port: addr.port(),
745
+ }),
746
+ }
747
+ }
748
+
749
+ /// The real address a `protocol` connection to `dest` dials, once `net`'s
750
+ /// ruleset lets it, as the filter judges what leaves after the socket took
751
+ /// its port; `EACCES` when it does not.
752
+ pub(crate) fn filter(
753
+ net: &Namespace,
754
+ dest: &Destination,
755
+ protocol: Protocol,
756
+ ) -> Result<SocketAddr, Errno> {
757
+ filter_with(net.ruleset(), &**net.family(), dest, protocol)
758
+ }
759
+
760
+ /// The real address a `protocol` connection to `dest` dials once `ruleset`
761
+ /// lets it, judged against the host's own addresses as `family` reads them;
762
+ /// `EACCES` when it does not.
763
+ pub(crate) fn filter_with(
764
+ ruleset: &Ruleset,
765
+ family: &dyn ProtocolFamily,
766
+ dest: &Destination,
767
+ protocol: Protocol,
768
+ ) -> Result<SocketAddr, Errno> {
769
+ match dest {
770
+ Destination::Literal(addr) => {
771
+ ruleset.admit_literal(*addr, protocol)?;
772
+ Ok(*addr)
773
+ }
774
+ Destination::Named { name, real, port } => {
775
+ admitted_addresses_of(family, ruleset, name, &[*real], *port, protocol)
776
+ .pop()
777
+ .ok_or(Errno::PermissionDenied)
778
+ }
779
+ }
780
+ }
781
+
782
+ /// The addresses `real`, resolved from `name`, the ruleset admits to `port`
783
+ /// over `protocol`, judged against the host's own addresses as `family` reads
784
+ /// them. A host whose addresses cannot be read admits none, so an unreadable
785
+ /// interface list refuses a connect rather than judging as if the host had
786
+ /// none. Every path that dials a name passes through here.
787
+ fn admitted_addresses_of(
788
+ family: &dyn ProtocolFamily,
789
+ ruleset: &Ruleset,
790
+ name: &str,
791
+ real: &[IpAddr],
792
+ port: u16,
793
+ protocol: Protocol,
794
+ ) -> Vec<SocketAddr> {
795
+ match family.local_addresses() {
796
+ Ok(local) => ruleset.admitted_addresses_of(name, real, port, protocol, &local),
797
+ Err(_) => Vec::new(),
798
+ }
799
+ }
800
+
801
+ /// What the socket tests share.
802
+ #[cfg(test)]
803
+ pub(crate) mod testing {
804
+ use crate::sched::testing::within_max_wait;
805
+ use crate::vfs::PollMask;
806
+ use crate::wait::{do_poll, PollTable};
807
+
808
+ /// Wait on `poll`, a socket's or its file's, until it finds `mask`; past
809
+ /// the longest a test waits, the test fails.
810
+ pub(crate) fn wait_for(poll: impl Fn(Option<&mut PollTable>) -> PollMask, mask: PollMask) {
811
+ let found =
812
+ within_max_wait(|| do_poll(|| None, |table| poll(table).contains(mask).then_some(())));
813
+ assert_eq!(found, Ok(Some(())), "the socket's poll must find {mask:?}");
814
+ }
815
+
816
+ /// How many times a wait on `poll` to read woke over `quiet`, and whether
817
+ /// it found something: each wake asks `poll` again, so a wait nothing
818
+ /// woke asks it once as it starts and once as it ends.
819
+ pub(crate) fn looks_waiting_to_read(
820
+ poll: impl Fn(Option<&mut PollTable>) -> PollMask,
821
+ quiet: std::time::Duration,
822
+ ) -> (usize, bool) {
823
+ let end = std::time::Instant::now() + quiet;
824
+ let mut looks = 0;
825
+ let found = within_max_wait(|| {
826
+ do_poll(
827
+ || Some(end),
828
+ |table| {
829
+ looks += 1;
830
+ poll(table).contains(PollMask::IN).then_some(())
831
+ },
832
+ )
833
+ });
834
+ (looks, found == Ok(Some(())))
835
+ }
836
+ }
837
+
838
+ #[cfg(test)]
839
+ mod tests {
840
+ use super::*;
841
+
842
+ // @behavior NW-066
843
+ #[test]
844
+ fn a_socket_of_an_ipv6_family_answers_eafnosupport() {
845
+ let network =
846
+ crate::network::Network::new("api", Arc::new(crate::network::Builder::default()))
847
+ .unwrap();
848
+ let net = Namespace::for_network(
849
+ &network,
850
+ Arc::new(super::super::family::testing::CountsDials::default()),
851
+ Arc::new(super::super::HyperOutbound::new()),
852
+ );
853
+ let answers = (
854
+ TcpSock::create(&net, AddressFamily::Inet6).err(),
855
+ UdpSock::create(&net, AddressFamily::Inet6).err(),
856
+ TcpSock::create(&net, AddressFamily::Inet).is_ok(),
857
+ );
858
+ assert_eq!(
859
+ answers,
860
+ (
861
+ Some(Errno::AddressFamilyNotSupported),
862
+ Some(Errno::AddressFamilyNotSupported),
863
+ true
864
+ ),
865
+ "a TCP or UDP socket asked for in the IPv6 family must answer EAFNOSUPPORT, as the \
866
+ guest carries IPv4 alone, while one in the IPv4 family is made"
867
+ );
868
+ }
869
+ }