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