ostrya_sys/lib.rs
1#![deny(unsafe_code)]
2
3//! Wrappers for the Linux fs-verity ioctls, a read-only memory map, the loop
4//! device, a sealed memory file, namespace descriptors, ID-mapped mounts,
5//! and socket credentials.
6//!
7//! A caller seals a file with fs-verity and reads the digest and the
8//! parameters that the kernel holds for the sealed file. The seal has the
9//! parameters that ostree uses: SHA-256, 4096-byte blocks, and no salt. A
10//! caller can also map a file read-only. On Linux, a caller attaches a file
11//! to a loop device, and writes bytes to a memory file that it then seals.
12//! It reads the type and the owner of a namespace, gives a thread its own
13//! file system attributes, sets an ID mapping on a detached mount, reads the
14//! groups of the peer of a Unix socket, and takes the socket that systemd
15//! passes. The crate depends on `rustix`. On Linux it also depends on
16//! `libc`, for the two calls that `rustix` does not give: `mount_setattr`
17//! and `SO_PEERGROUPS`.
18//!
19//! # Entry points
20//!
21//! - [`enable_verity`] seals a file with fs-verity.
22//! - [`measure_verity`] returns the fs-verity digest of a sealed file.
23//! - [`read_verity_descriptor`] returns the parameters of a sealed file.
24//! - [`Mmap`] is a read-only memory map of a file.
25//! - [`LoopDevice::attach`] attaches a file to a free loop device with a
26//! [`LoopConfig`]. Linux only.
27//! - [`sealable_memfd`] creates a memory file that accepts seals, and
28//! [`seal_contents`] seals its bytes and its size. Linux only.
29//! - [`ns_type`] returns the type of a namespace, and [`ns_owner_userns`]
30//! returns the user namespace that owns it. Linux only.
31//! - [`unshare_fs`] gives the calling thread its own root directory,
32//! working directory, and umask, so that the thread can enter a mount
33//! namespace. Linux only.
34//! - [`mount_setattr_idmap`] sets an ID mapping on a detached mount. Linux
35//! only.
36//! - [`peer_groups`] returns the supplementary groups of the peer of a Unix
37//! socket. Linux only.
38//! - [`systemd_listen_fd`] takes the one socket that systemd passes. Linux
39//! only.
40//!
41//! # Examples
42//!
43//! The example seals a file and reads its parameters and its digest. The file
44//! system of the file must support fs-verity.
45//!
46//! ```no_run
47//! use std::fs::File;
48//!
49//! use ostrya_sys::{enable_verity, measure_verity, read_verity_descriptor};
50//!
51//! // A read-only descriptor, and no writable descriptor to the file.
52//! let file = File::open("object.file")?;
53//! enable_verity(&file)?;
54//! let desc = read_verity_descriptor(&file)?;
55//! // SHA-256, 4096-byte blocks (2 to the power 12), and no salt.
56//! assert_eq!((desc.hash_algorithm, desc.log_blocksize, desc.salt_size), (1, 12, 0));
57//! let digest: [u8; 32] = measure_verity(&file)?;
58//! # let _ = digest;
59//! # Ok::<(), std::io::Error>(())
60//! ```
61//!
62//! This crate holds all `unsafe` code of the ostrya library crates. A
63//! `SAFETY` comment on each `unsafe` block gives its reasoning.
64
65// All other library crates of ostrya are `#![forbid(unsafe_code)]`. This crate
66// holds the `rustix` calls that need `unsafe` and that no safe `rustix` wrapper
67// gives. The crate root is `#![deny(unsafe_code)]`. Each of the modules `imp`,
68// `mmap`, `loop_dev`, `ns`, and `sock` has a scoped `#![allow(unsafe_code)]`,
69// so the audited `unsafe` code stays in these five modules.
70
71mod imp {
72 #![allow(unsafe_code)]
73
74 use std::marker::PhantomData;
75 use std::os::fd::AsFd;
76
77 use rustix::io::{Errno, Result};
78 use rustix::ioctl::{Ioctl, IoctlOutput, Opcode, Setter, Updater, ioctl, opcode};
79
80 /// The SHA-256 fs-verity hash-algorithm identifier.
81 const FS_VERITY_HASH_ALG_SHA256: u32 = 1;
82 /// The fs-verity block size, in bytes.
83 const FS_VERITY_BLOCK_SIZE: u32 = 4096;
84
85 /// The `fsverity_enable_arg` argument of `FS_IOC_ENABLE_VERITY`.
86 ///
87 /// The struct has the layout of the 128-byte kernel UAPI struct. The
88 /// kernel reads each field through the raw pointer. No Rust code reads a
89 /// field, so the struct exists only for the kernel ABI.
90 #[repr(C)]
91 #[derive(Clone, Copy)]
92 #[allow(dead_code)]
93 struct FsverityEnableArg {
94 version: u32,
95 hash_algorithm: u32,
96 block_size: u32,
97 salt_size: u32,
98 salt_ptr: u64,
99 sig_size: u32,
100 reserved1: u32,
101 sig_ptr: u64,
102 reserved2: [u64; 11],
103 }
104
105 /// `FS_IOC_ENABLE_VERITY = _IOW('f', 133, struct fsverity_enable_arg)`. The
106 /// opcode encodes the 128-byte argument size.
107 const FS_IOC_ENABLE_VERITY: Opcode = opcode::write::<FsverityEnableArg>(b'f', 133);
108
109 /// The 4-byte header of the `fsverity_digest` request.
110 ///
111 /// The `FS_IOC_MEASURE_VERITY` request number encodes only the size of
112 /// this header, because the C struct ends in a flexible `digest[]` array.
113 #[repr(C)]
114 #[allow(dead_code)]
115 struct FsverityDigestHeader {
116 digest_algorithm: u16,
117 digest_size: u16,
118 }
119
120 /// `FS_IOC_MEASURE_VERITY = _IOWR('f', 134, struct fsverity_digest)`. The
121 /// request number comes from `FsverityDigestHeader`, the base header of the
122 /// flexible array. The buffer that the call passes is larger.
123 const FS_IOC_MEASURE_VERITY: Opcode = opcode::read_write::<FsverityDigestHeader>(b'f', 134);
124
125 /// A `fsverity_digest` with space for a 32-byte SHA-256 digest.
126 #[repr(C)]
127 #[allow(dead_code)]
128 struct FsverityDigestSha256 {
129 digest_algorithm: u16,
130 digest_size: u16,
131 digest: [u8; 32],
132 }
133
134 /// Enables fs-verity on `fd` with SHA-256, 4096-byte blocks, and no salt.
135 ///
136 /// `fd` must be a read-only descriptor. The kernel refuses the call while a
137 /// process has the file open for writing, also through a writable memory
138 /// map. Other read-only descriptors to the file can stay open. After the
139 /// call, an open of the file for writing fails with `EPERM`.
140 ///
141 /// # Errors
142 ///
143 /// The function returns the `Errno` of the `FS_IOC_ENABLE_VERITY` ioctl.
144 /// The Linux kernel documentation of fs-verity gives these values:
145 ///
146 /// - `ETXTBSY` if the file is open for writing through `fd`, another
147 /// descriptor, or a writable memory map.
148 /// - `EEXIST` if fs-verity is already enabled on the file.
149 /// - `EACCES` if the process has no write access to the file.
150 /// - `EPERM` if the file is append-only, or if the kernel requires a
151 /// built-in signature. This function gives no signature.
152 /// - `EROFS` if the file system is read-only.
153 /// - `EISDIR` if `fd` refers to a directory.
154 /// - `EINVAL` if the file system does not accept a 4096-byte block, or if
155 /// `fd` refers to neither a regular file nor a directory.
156 /// - `ENOTTY` or `EOPNOTSUPP` if the file system or the kernel has no
157 /// fs-verity support.
158 /// - `EINTR` if a fatal signal interrupts the call.
159 /// - Another `Errno` for other failures.
160 ///
161 /// If `fd` is open for writing only, Linux 6.18 on btrfs returns `EBADF`.
162 /// The kernel documentation does not state this value.
163 pub fn enable_verity(fd: impl AsFd) -> Result<()> {
164 enable(fd, &[])
165 }
166
167 /// Enables fs-verity on `fd` with SHA-256, 4096-byte blocks, and `salt`.
168 ///
169 /// The tests use this function to seal a file with parameters that are
170 /// not the parameters of ostree. The descriptor rules of [`enable_verity`]
171 /// apply.
172 ///
173 /// # Errors
174 ///
175 /// - `EINVAL` if the length of `salt` does not fit in a `u32`.
176 /// - `EMSGSIZE` from the kernel if `salt` is longer than 32 bytes.
177 /// - The `Errno` values of [`enable_verity`].
178 #[doc(hidden)]
179 pub fn enable_verity_with_salt(fd: impl AsFd, salt: &[u8]) -> Result<()> {
180 enable(fd, salt)
181 }
182
183 /// Enables fs-verity on `fd` with SHA-256, 4096-byte blocks, and `salt`.
184 /// An empty `salt` gives a null salt pointer.
185 fn enable(fd: impl AsFd, salt: &[u8]) -> Result<()> {
186 let salt_size = u32::try_from(salt.len()).map_err(|_| Errno::INVAL)?;
187 let arg = FsverityEnableArg {
188 version: 1,
189 hash_algorithm: FS_VERITY_HASH_ALG_SHA256,
190 block_size: FS_VERITY_BLOCK_SIZE,
191 salt_size,
192 salt_ptr: if salt.is_empty() {
193 0
194 } else {
195 salt.as_ptr() as u64
196 },
197 sig_size: 0,
198 reserved1: 0,
199 sig_ptr: 0,
200 reserved2: [0; 11],
201 };
202 // SAFETY: `FS_IOC_ENABLE_VERITY` expects a pointer to a
203 // `fsverity_enable_arg`. `FsverityEnableArg` is that 128-byte
204 // `#[repr(C)]` struct. The opcode comes from the same type, so the
205 // memory at the pointer has the size and the layout that the kernel
206 // reads. The kernel only reads the argument. This matches `Setter`, the
207 // rustix pattern for the read-only pointer of an `_IOW` ioctl. A
208 // nonzero `salt_ptr` points to `salt`, which is borrowed for this whole
209 // call. `salt_size` is the length of `salt`, so the kernel reads only
210 // live bytes. The ioctl is synchronous, so the kernel holds no pointer
211 // after it returns.
212 unsafe {
213 let call: Setter<{ FS_IOC_ENABLE_VERITY }, FsverityEnableArg> = Setter::new(arg);
214 ioctl(fd, call)
215 }
216 }
217
218 /// Returns the fs-verity SHA-256 digest that the kernel holds for `fd`.
219 ///
220 /// `fd` must refer to a file with fs-verity enabled, for example by
221 /// [`enable_verity`]. The function returns the digest of each file sealed
222 /// with SHA-256, also with a salt or another block size.
223 /// [`read_verity_descriptor`] returns these parameters.
224 ///
225 /// # Errors
226 ///
227 /// - `EINVAL` if the kernel reports a hash algorithm that is not SHA-256,
228 /// or a digest size that is not 32 bytes.
229 /// - `ENODATA` from the kernel if fs-verity is not enabled on the file.
230 /// - `EOVERFLOW` from the kernel if the digest of the file is longer than
231 /// 32 bytes. A file sealed with SHA-512 has a 64-byte digest.
232 /// - `ENOTTY` or `EOPNOTSUPP` from the kernel if the file system or the
233 /// kernel has no fs-verity support.
234 /// - Another `Errno` from the `FS_IOC_MEASURE_VERITY` ioctl.
235 pub fn measure_verity(fd: impl AsFd) -> Result<[u8; 32]> {
236 let mut digest = FsverityDigestSha256 {
237 digest_algorithm: 0,
238 // On input, `digest_size` is the capacity of the buffer.
239 digest_size: 32,
240 digest: [0u8; 32],
241 };
242 // SAFETY: `FS_IOC_MEASURE_VERITY` reads `digest_size` as the capacity
243 // of the buffer. It writes the algorithm, the size, and the digest
244 // bytes back into the same `fsverity_digest`. `FsverityDigestSha256`
245 // is that struct with space for a 32-byte digest, so the capacity of
246 // 32 bytes is correct. The opcode comes from the base header of the
247 // flexible array, which is the size that the kernel compares against.
248 // `Updater` is the rustix pattern for a read-write pointer.
249 unsafe {
250 let call: Updater<'_, { FS_IOC_MEASURE_VERITY }, FsverityDigestSha256> =
251 Updater::new(&mut digest);
252 ioctl(fd, call)?;
253 }
254 // The kernel reports the algorithm that sealed the file. The bytes are
255 // an ostree digest only for SHA-256 with 32 bytes.
256 if u32::from(digest.digest_algorithm) != FS_VERITY_HASH_ALG_SHA256
257 || digest.digest_size != 32
258 {
259 return Err(Errno::INVAL);
260 }
261 Ok(digest.digest)
262 }
263
264 /// The `FS_IOC_READ_VERITY_METADATA` metadata type that selects the
265 /// fs-verity descriptor.
266 const FS_VERITY_METADATA_TYPE_DESCRIPTOR: u64 = 2;
267 /// The size of `struct fsverity_descriptor`, in bytes.
268 const DESCRIPTOR_SIZE: usize = 256;
269
270 /// The `fsverity_read_metadata_arg` argument of
271 /// `FS_IOC_READ_VERITY_METADATA`.
272 ///
273 /// The struct has the layout of the 40-byte kernel UAPI struct. The kernel
274 /// reads each field and writes no field back.
275 #[repr(C)]
276 #[allow(dead_code)]
277 struct FsverityReadMetadataArg {
278 metadata_type: u64,
279 offset: u64,
280 length: u64,
281 buf_ptr: u64,
282 reserved: u64,
283 }
284
285 /// `FS_IOC_READ_VERITY_METADATA = _IOWR('f', 135, struct
286 /// fsverity_read_metadata_arg)`. The opcode encodes the 40-byte argument
287 /// size.
288 const FS_IOC_READ_VERITY_METADATA: Opcode =
289 opcode::read_write::<FsverityReadMetadataArg>(b'f', 135);
290
291 /// The `FS_IOC_READ_VERITY_METADATA` call.
292 ///
293 /// The kernel writes into the buffer at `buf_ptr` and returns the number of
294 /// bytes that it wrote. No rustix pattern returns this count. The lifetime
295 /// ties the call to the mutable borrow of the buffer, so the buffer lives
296 /// longer than the call.
297 struct ReadMetadata<'a> {
298 arg: FsverityReadMetadataArg,
299 buf: PhantomData<&'a mut [u8]>,
300 }
301
302 impl<'a> ReadMetadata<'a> {
303 /// Returns a request that reads the fs-verity descriptor into `buf`.
304 ///
305 /// The read starts at offset 0. The pointer and the length come from
306 /// the same slice, so the kernel obeys the length of the memory at the
307 /// pointer.
308 fn descriptor(buf: &'a mut [u8]) -> Self {
309 ReadMetadata {
310 arg: FsverityReadMetadataArg {
311 metadata_type: FS_VERITY_METADATA_TYPE_DESCRIPTOR,
312 offset: 0,
313 length: buf.len() as u64,
314 buf_ptr: buf.as_mut_ptr() as u64,
315 reserved: 0,
316 },
317 buf: PhantomData,
318 }
319 }
320 }
321
322 // SAFETY: the opcode is the `_IOWR` number that comes from the argument
323 // type that the kernel expects, and `as_ptr` points at that argument. The
324 // kernel writes into the user buffer that the argument names, so the call
325 // changes user memory and `IS_MUTATING` is true. `output_from_ptr` reads
326 // nothing through the pointer. It converts the non-negative byte count
327 // that a successful call returns.
328 unsafe impl Ioctl for ReadMetadata<'_> {
329 type Output = usize;
330
331 const IS_MUTATING: bool = true;
332
333 fn opcode(&self) -> Opcode {
334 FS_IOC_READ_VERITY_METADATA
335 }
336
337 fn as_ptr(&mut self) -> *mut core::ffi::c_void {
338 (&mut self.arg as *mut FsverityReadMetadataArg).cast()
339 }
340
341 unsafe fn output_from_ptr(
342 out: IoctlOutput,
343 _: *mut core::ffi::c_void,
344 ) -> Result<Self::Output> {
345 usize::try_from(out).map_err(|_| Errno::INVAL)
346 }
347 }
348
349 /// The fs-verity parameters of a sealed file, from its `fsverity_descriptor`.
350 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
351 pub struct VerityDescriptor {
352 /// The format version of the descriptor, which the kernel sets to 1.
353 pub version: u8,
354 /// The identifier of the hash algorithm, 1 for SHA-256.
355 pub hash_algorithm: u8,
356 /// The base-2 logarithm of the Merkle-tree block size, 12 for 4096 bytes.
357 pub log_blocksize: u8,
358 /// The length of the salt in bytes, 0 if the file has no salt.
359 pub salt_size: u8,
360 /// The size of the file data in bytes at the time of the seal.
361 pub data_size: u64,
362 }
363
364 /// Returns the fs-verity parameters that the kernel holds for `fd`.
365 ///
366 /// `fd` must refer to a file with fs-verity enabled. A caller can use the
367 /// result to accept the digest of [`measure_verity`] only for a file
368 /// sealed with the parameters of ostree: SHA-256, 4096-byte blocks, and no
369 /// salt.
370 ///
371 /// # Errors
372 ///
373 /// - `ENODATA` from the kernel if fs-verity is not enabled on the file.
374 /// - `ENOTTY` from the kernel if the file system does not implement
375 /// fs-verity or the `FS_IOC_READ_VERITY_METADATA` ioctl. The ioctl is
376 /// available since Linux 5.12.
377 /// - `EOPNOTSUPP` from the kernel if the kernel or the file system has no
378 /// fs-verity support.
379 /// - `EINTR` from the kernel if a signal interrupts the call before it
380 /// reads data.
381 /// - `EIO` if the kernel returns fewer than 256 bytes, the size of the
382 /// descriptor struct. An interrupt can give a short read.
383 /// - Another `Errno` from the `FS_IOC_READ_VERITY_METADATA` ioctl.
384 pub fn read_verity_descriptor(fd: impl AsFd) -> Result<VerityDescriptor> {
385 let mut buf = [0u8; DESCRIPTOR_SIZE];
386 // SAFETY: `ReadMetadata::descriptor` takes `buf_ptr` and `length` from
387 // the same mutable borrow of `buf`. `buf` is a local that lives longer
388 // than this call, so the kernel writes at most `buf.len()` bytes into
389 // memory that this function owns. The borrow ends when `ioctl`
390 // consumes the request. The ioctl is synchronous, so the kernel holds
391 // no pointer after it returns. The function reads `buf` only after the
392 // call.
393 let n = unsafe { ioctl(fd, ReadMetadata::descriptor(&mut buf))? };
394 if n < DESCRIPTOR_SIZE {
395 return Err(Errno::IO);
396 }
397 Ok(VerityDescriptor {
398 version: buf[0],
399 hash_algorithm: buf[1],
400 log_blocksize: buf[2],
401 salt_size: buf[3],
402 data_size: u64::from_le_bytes(buf[8..16].try_into().expect("8-byte field")),
403 })
404 }
405}
406
407pub use imp::{
408 VerityDescriptor, enable_verity, enable_verity_with_salt, measure_verity,
409 read_verity_descriptor,
410};
411pub use mmap::Mmap;
412
413mod mmap {
414 #![allow(unsafe_code)]
415
416 use std::os::fd::AsFd;
417 use std::ptr::NonNull;
418
419 use rustix::io::{Errno, Result};
420 use rustix::mm::{MapFlags, ProtFlags, mmap, munmap};
421
422 // The static-delta reader of the `ostrya` crate maps a decompressed part or
423 // a source object that it wrote to a temp file. Random access to these
424 // bytes (splice offsets, bspatch source seeks) then costs address space and
425 // demand-paged file cache, and no resident heap. The reader maps only
426 // anonymous temp files that it alone holds, so no other writer can make
427 // one shorter. The reader maps a blob only if the blob is larger than its
428 // heap threshold.
429
430 /// A read-only, private memory map of an open file.
431 ///
432 /// The map is never written. It keeps the mapped pages alive on its own,
433 /// so the caller can close the file descriptor after
434 /// [`Mmap::read_only`] returns.
435 ///
436 /// # Truncation
437 ///
438 /// A read of a mapped page with no file bytes behind it raises `SIGBUS`.
439 /// No safe API can expose this signal, so [`Mmap::read_only`] measures the
440 /// file and refuses a map longer than the file. [`Mmap::as_slice`] is
441 /// sound for the whole life of the map if no writer truncates the file.
442 /// The caller must map only a file that no other writer can truncate.
443 pub struct Mmap {
444 ptr: NonNull<u8>,
445 len: usize,
446 }
447
448 // SAFETY: the map is read-only and owns its region for its whole life.
449 // These two facts make it sound to send the immutable byte view to another
450 // thread, or to share it between threads.
451 unsafe impl Send for Mmap {}
452 unsafe impl Sync for Mmap {}
453
454 impl Mmap {
455 /// Maps the first `len` bytes of `fd` read-only.
456 ///
457 /// `len` must be larger than zero and not larger than the size of the
458 /// file. Because the function refuses a `len` larger than the file, a
459 /// read of the map cannot raise `SIGBUS` while the file keeps its size.
460 ///
461 /// # Errors
462 ///
463 /// - An `Errno` from `fstat` if the function cannot read the size of
464 /// the file.
465 /// - `EINVAL` if `len` is larger than the size of the file.
466 /// - `EINVAL` from `mmap` if `len` is zero.
467 /// - Another `Errno` from `mmap`, for example `EACCES` if `fd` is not
468 /// open for reading.
469 ///
470 /// # Examples
471 ///
472 /// ```
473 /// use std::fs::File;
474 ///
475 /// use ostrya_sys::Mmap;
476 ///
477 /// let path = std::env::temp_dir().join(format!("ostrya-sys-doc-{}", std::process::id()));
478 /// std::fs::write(&path, b"ostree")?;
479 /// let file = File::open(&path)?;
480 /// assert!(Mmap::read_only(&file, 7).is_err(), "longer than the file");
481 /// let map = Mmap::read_only(&file, 6)?;
482 /// // The map stays valid after the descriptor closes.
483 /// drop(file);
484 /// assert_eq!(map.as_slice(), b"ostree");
485 /// std::fs::remove_file(&path)?;
486 /// # Ok::<(), std::io::Error>(())
487 /// ```
488 pub fn read_only(fd: impl AsFd, len: usize) -> Result<Mmap> {
489 // A map longer than the file gives bytes with no file pages behind
490 // them, and a read of these bytes raises SIGBUS. The size check
491 // here prevents this for each caller of this safe function.
492 let size = rustix::fs::fstat(fd.as_fd())?.st_size;
493 match i64::try_from(len) {
494 Ok(len) if len <= size => {}
495 _ => return Err(Errno::INVAL),
496 }
497 // SAFETY: a null address lets the kernel select the place of the
498 // region. PROT_READ with MAP_PRIVATE maps `len` file bytes
499 // read-only. The returned pointer is valid for `len` bytes until
500 // `munmap`, which `Drop` calls exactly once.
501 let ptr = unsafe {
502 mmap(
503 core::ptr::null_mut(),
504 len,
505 ProtFlags::READ,
506 MapFlags::PRIVATE,
507 fd,
508 0,
509 )?
510 };
511 let ptr = NonNull::new(ptr.cast::<u8>()).expect("mmap returns non-null on success");
512 Ok(Mmap { ptr, len })
513 }
514
515 /// Returns the mapped bytes.
516 pub fn as_slice(&self) -> &[u8] {
517 // SAFETY: `ptr` addresses `len` readable, initialized bytes for the
518 // lifetime of `self`, and nothing mutates the region, so a shared
519 // slice over it is valid.
520 unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
521 }
522
523 /// Returns the length of the map in bytes.
524 pub fn len(&self) -> usize {
525 self.len
526 }
527
528 /// Returns `true` if the map covers zero bytes.
529 ///
530 /// The result is always `false`, because [`Mmap::read_only`] refuses a
531 /// length of zero.
532 pub fn is_empty(&self) -> bool {
533 self.len == 0
534 }
535 }
536
537 impl std::fmt::Debug for Mmap {
538 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
539 f.debug_struct("Mmap").field("len", &self.len).finish()
540 }
541 }
542
543 impl Drop for Mmap {
544 fn drop(&mut self) {
545 // SAFETY: `ptr` and `len` are exactly the address and the length
546 // of the region that `mmap` returned. This call unmaps the region
547 // once, at the end of the life of the map.
548 unsafe {
549 let _ = munmap(self.ptr.as_ptr().cast(), self.len);
550 }
551 }
552 }
553}
554
555#[cfg(target_os = "linux")]
556pub use loop_dev::{
557 LO_FLAGS_AUTOCLEAR, LO_FLAGS_DIRECT_IO, LO_FLAGS_READ_ONLY, LoopConfig, LoopDevice,
558};
559#[cfg(target_os = "linux")]
560pub use memfd::{seal_contents, sealable_memfd};
561#[cfg(target_os = "linux")]
562pub use ns::{mount_setattr_idmap, ns_owner_userns, ns_type, unshare_fs};
563#[cfg(target_os = "linux")]
564pub use sock::{peer_groups, systemd_listen_fd};
565
566#[cfg(target_os = "linux")]
567mod loop_dev {
568 #![allow(unsafe_code)]
569
570 use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
571
572 use rustix::fs::{CWD, Mode, OFlags, openat};
573 use rustix::io::{Errno, Result};
574 use rustix::ioctl::{Getter, Ioctl, IoctlOutput, Opcode, Setter, ioctl};
575
576 /// The loop device is read-only.
577 pub const LO_FLAGS_READ_ONLY: u32 = 1;
578 /// The kernel detaches the backing file at the last close of the device.
579 pub const LO_FLAGS_AUTOCLEAR: u32 = 4;
580 /// The loop device reads the backing file with direct I/O.
581 pub const LO_FLAGS_DIRECT_IO: u32 = 16;
582
583 /// `LOOP_GET_STATUS64`. The loop ioctls use fixed numbers, not the
584 /// `_IOC` encoding.
585 const LOOP_GET_STATUS64: Opcode = 0x4C05;
586 /// `LOOP_CONFIGURE`.
587 const LOOP_CONFIGURE: Opcode = 0x4C0A;
588 /// `LOOP_CTL_GET_FREE`, an ioctl of `/dev/loop-control`.
589 const LOOP_CTL_GET_FREE: Opcode = 0x4C82;
590 /// The number of attempts of [`LoopDevice::attach`] when another process
591 /// takes the free device first.
592 const ATTACH_ATTEMPTS: u32 = 10;
593
594 /// The `loop_info64` struct of the kernel UAPI, 232 bytes.
595 #[repr(C)]
596 #[derive(Clone, Copy)]
597 #[allow(dead_code)]
598 struct LoopInfo64 {
599 lo_device: u64,
600 lo_inode: u64,
601 lo_rdevice: u64,
602 lo_offset: u64,
603 lo_sizelimit: u64,
604 lo_number: u32,
605 lo_encrypt_type: u32,
606 lo_encrypt_key_size: u32,
607 lo_flags: u32,
608 lo_file_name: [u8; 64],
609 lo_crypt_name: [u8; 64],
610 lo_encrypt_key: [u8; 32],
611 lo_init: [u64; 2],
612 }
613
614 /// The `loop_config` struct of the kernel UAPI, 304 bytes. The kernel
615 /// reads each field through the raw pointer of `LOOP_CONFIGURE`.
616 #[repr(C)]
617 #[allow(dead_code)]
618 struct LoopConfigRaw {
619 fd: u32,
620 block_size: u32,
621 info: LoopInfo64,
622 reserved: [u64; 8],
623 }
624
625 const _: () = assert!(size_of::<LoopInfo64>() == 232);
626 const _: () = assert!(size_of::<LoopConfigRaw>() == 304);
627 const _: () = assert!(std::mem::offset_of!(LoopConfigRaw, info) == 8);
628 const _: () = assert!(std::mem::offset_of!(LoopInfo64, lo_flags) == 52);
629
630 /// The `LOOP_CTL_GET_FREE` call. The kernel returns the number of a free
631 /// loop device as the result of the ioctl. No rustix pattern returns this
632 /// value.
633 struct GetFree;
634
635 // SAFETY: `LOOP_CTL_GET_FREE` takes no argument and reads no user memory,
636 // so the null pointer of `as_ptr` is never read. The call changes no user
637 // memory, so `IS_MUTATING` is false. `output_from_ptr` reads nothing
638 // through the pointer. It converts the non-negative device number that a
639 // successful call returns.
640 unsafe impl Ioctl for GetFree {
641 type Output = u32;
642
643 const IS_MUTATING: bool = false;
644
645 fn opcode(&self) -> Opcode {
646 LOOP_CTL_GET_FREE
647 }
648
649 fn as_ptr(&mut self) -> *mut core::ffi::c_void {
650 core::ptr::null_mut()
651 }
652
653 unsafe fn output_from_ptr(
654 out: IoctlOutput,
655 _: *mut core::ffi::c_void,
656 ) -> Result<Self::Output> {
657 u32::try_from(out).map_err(|_| Errno::INVAL)
658 }
659 }
660
661 /// The configuration of a new loop device.
662 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
663 pub struct LoopConfig {
664 /// The logical block size of the device in bytes. The value 0 lets
665 /// the kernel choose the default.
666 pub block_size: u32,
667 /// The device is read-only.
668 pub read_only: bool,
669 /// The kernel detaches the backing file at the last close of the
670 /// device.
671 pub autoclear: bool,
672 /// The device reads the backing file with direct I/O where the
673 /// kernel accepts it. [`LoopDevice::attach`] tells which.
674 pub direct_io: bool,
675 }
676
677 impl LoopConfig {
678 /// Returns the `lo_flags` value of the configuration.
679 fn flags(&self) -> u32 {
680 let mut flags = 0;
681 if self.read_only {
682 flags |= LO_FLAGS_READ_ONLY;
683 }
684 if self.autoclear {
685 flags |= LO_FLAGS_AUTOCLEAR;
686 }
687 if self.direct_io {
688 flags |= LO_FLAGS_DIRECT_IO;
689 }
690 flags
691 }
692 }
693
694 /// An open loop device with a backing file.
695 ///
696 /// The value holds an open descriptor of `/dev/loopN`. With
697 /// [`LoopConfig::autoclear`], the kernel detaches the backing file at the
698 /// last close of the device. A file system that the device holds keeps
699 /// the device open until its unmount.
700 #[derive(Debug)]
701 pub struct LoopDevice {
702 fd: OwnedFd,
703 number: u32,
704 }
705
706 impl LoopDevice {
707 /// Attaches `backing` to a free loop device with `cfg`.
708 ///
709 /// The call asks `/dev/loop-control` for a free device, opens
710 /// `/dev/loopN`, and configures it with `LOOP_CONFIGURE` in one step.
711 /// The open is read-only for [`LoopConfig::read_only`], and for
712 /// reading and writing otherwise. If another process configures the
713 /// same device first, the kernel returns `EBUSY`, and the call tries
714 /// the next free device, up to 10 times.
715 ///
716 /// If the kernel refuses [`LoopConfig::direct_io`] with `EINVAL`, the
717 /// call configures the same device again without direct I/O. A
718 /// backing file that does not accept direct I/O gives this refusal.
719 ///
720 /// `LOOP_CONFIGURE` is available since Linux 5.8.
721 ///
722 /// # Errors
723 ///
724 /// - An `Errno` from the open of `/dev/loop-control` or of
725 /// `/dev/loopN`, for example `EACCES` or `EPERM` for a process with
726 /// no access to the loop devices.
727 /// - An `Errno` from `LOOP_CTL_GET_FREE`.
728 /// - `EBUSY` if 10 attempts find the device taken.
729 /// - `EINVAL` from `LOOP_CONFIGURE` if the kernel refuses a value of
730 /// `cfg` other than [`LoopConfig::direct_io`].
731 /// - Another `Errno` from `LOOP_CONFIGURE`.
732 pub fn attach(backing: impl AsFd, cfg: &LoopConfig) -> Result<LoopDevice> {
733 let control = openat(
734 CWD,
735 "/dev/loop-control",
736 OFlags::RDWR | OFlags::CLOEXEC,
737 Mode::empty(),
738 )?;
739 let backing_fd = u32::try_from(backing.as_fd().as_raw_fd()).map_err(|_| Errno::BADF)?;
740 let access = if cfg.read_only {
741 OFlags::RDONLY
742 } else {
743 OFlags::RDWR
744 };
745 let mut attempts = 0;
746 loop {
747 attempts += 1;
748 // SAFETY: `GetFree` is the `LOOP_CTL_GET_FREE` request, which
749 // takes no argument. The kernel reads and writes no user
750 // memory.
751 let number = unsafe { ioctl(&control, GetFree)? };
752 let fd = openat(
753 CWD,
754 format!("/dev/loop{number}"),
755 access | OFlags::CLOEXEC,
756 Mode::empty(),
757 )?;
758 let mut result = configure(&fd, backing_fd, cfg.block_size, cfg.flags());
759 if result == Err(Errno::INVAL) && cfg.direct_io {
760 let flags = cfg.flags() & !LO_FLAGS_DIRECT_IO;
761 result = configure(&fd, backing_fd, cfg.block_size, flags);
762 }
763 match result {
764 Ok(()) => return Ok(LoopDevice { fd, number }),
765 Err(Errno::BUSY) if attempts < ATTACH_ATTEMPTS => continue,
766 Err(e) => return Err(e),
767 }
768 }
769 }
770
771 /// Returns the number `N` of the device `/dev/loopN`.
772 pub fn number(&self) -> u32 {
773 self.number
774 }
775
776 /// Returns the `lo_flags` value that the kernel holds for the device.
777 ///
778 /// The value is a combination of [`LO_FLAGS_READ_ONLY`],
779 /// [`LO_FLAGS_AUTOCLEAR`], [`LO_FLAGS_DIRECT_IO`], and other flags of
780 /// the kernel. A kernel can clear [`LO_FLAGS_DIRECT_IO`] when the
781 /// backing file does not accept direct I/O.
782 ///
783 /// # Errors
784 ///
785 /// - `ENXIO` if the device has no backing file.
786 /// - Another `Errno` from `LOOP_GET_STATUS64`.
787 pub fn flags(&self) -> Result<u32> {
788 // SAFETY: `LOOP_GET_STATUS64` writes one `loop_info64` to the
789 // pointer. `LoopInfo64` is that 232-byte `#[repr(C)]` struct, so
790 // the kernel writes inside the buffer of `Getter`. Each field is
791 // an integer or an integer array, so each bit pattern that the
792 // kernel writes is a valid value.
793 let info = unsafe {
794 let call: Getter<{ LOOP_GET_STATUS64 }, LoopInfo64> = Getter::new();
795 ioctl(&self.fd, call)?
796 };
797 Ok(info.lo_flags)
798 }
799 }
800
801 /// Runs `LOOP_CONFIGURE` on the loop device `fd` with the backing file
802 /// `backing_fd`, the block size `block_size`, and the flags `flags`.
803 fn configure(fd: &OwnedFd, backing_fd: u32, block_size: u32, flags: u32) -> Result<()> {
804 let raw = LoopConfigRaw {
805 fd: backing_fd,
806 block_size,
807 info: LoopInfo64 {
808 lo_device: 0,
809 lo_inode: 0,
810 lo_rdevice: 0,
811 lo_offset: 0,
812 lo_sizelimit: 0,
813 lo_number: 0,
814 lo_encrypt_type: 0,
815 lo_encrypt_key_size: 0,
816 lo_flags: flags,
817 lo_file_name: [0; 64],
818 lo_crypt_name: [0; 64],
819 lo_encrypt_key: [0; 32],
820 lo_init: [0; 2],
821 },
822 reserved: [0; 8],
823 };
824 // SAFETY: `LOOP_CONFIGURE` expects a pointer to a `loop_config`.
825 // `LoopConfigRaw` is that 304-byte `#[repr(C)]` struct, and the
826 // compile-time asserts pin its size and its field offsets. The kernel
827 // only reads the argument, which matches `Setter`. `backing_fd` names
828 // a descriptor that the caller of `LoopDevice::attach` keeps open for
829 // the whole call. The kernel takes its own reference to the backing
830 // file, so the caller can close it after the call. The ioctl is
831 // synchronous, so the kernel holds no pointer after it returns.
832 unsafe {
833 let call: Setter<{ LOOP_CONFIGURE }, LoopConfigRaw> = Setter::new(raw);
834 ioctl(fd, call)
835 }
836 }
837
838 impl AsFd for LoopDevice {
839 fn as_fd(&self) -> BorrowedFd<'_> {
840 self.fd.as_fd()
841 }
842 }
843}
844
845#[cfg(target_os = "linux")]
846mod memfd {
847 use std::os::fd::{AsFd, OwnedFd};
848
849 use rustix::fs::{MemfdFlags, SealFlags, fcntl_add_seals, memfd_create};
850 use rustix::io::Result;
851
852 /// Creates an anonymous memory file that accepts seals.
853 ///
854 /// The file has the flags `MFD_CLOEXEC`, `MFD_ALLOW_SEALING`, and
855 /// `MFD_NOEXEC_SEAL`, so no process can execute it. `name` shows in
856 /// `/proc/<pid>/fd` as `/memfd:<name>`. The memory of the file counts
857 /// against the memory cgroup of the process until the last reference to
858 /// the file closes.
859 ///
860 /// # Errors
861 ///
862 /// - `EINVAL` if `name` is longer than 249 bytes, or if the kernel does
863 /// not know `MFD_NOEXEC_SEAL`, which Linux 6.3 adds.
864 /// - Another `Errno` from `memfd_create`.
865 pub fn sealable_memfd(name: &str) -> Result<OwnedFd> {
866 memfd_create(
867 name,
868 MemfdFlags::CLOEXEC | MemfdFlags::ALLOW_SEALING | MemfdFlags::NOEXEC_SEAL,
869 )
870 }
871
872 /// Seals the content of a memory file from [`sealable_memfd`].
873 ///
874 /// The call adds `F_SEAL_WRITE`, `F_SEAL_GROW`, `F_SEAL_SHRINK`, and
875 /// `F_SEAL_SEAL`. After the call, no process can change the bytes or the
876 /// size of the file, and no process can remove a seal.
877 ///
878 /// # Errors
879 ///
880 /// - `EBUSY` if a writable shared memory map of the file exists.
881 /// - `EPERM` if the file has `F_SEAL_SEAL` already.
882 /// - Another `Errno` from `fcntl(F_ADD_SEALS)`.
883 pub fn seal_contents(fd: impl AsFd) -> Result<()> {
884 fcntl_add_seals(
885 fd,
886 SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL,
887 )
888 }
889}
890
891#[cfg(target_os = "linux")]
892mod ns {
893 #![allow(unsafe_code)]
894
895 use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd, RawFd};
896
897 use rustix::io::{Errno, Result};
898 use rustix::ioctl::{Ioctl, IoctlOutput, Opcode, ioctl, opcode};
899 use rustix::thread::LinkNameSpaceType;
900
901 /// The ioctl group of the namespace file descriptors.
902 const NSIO: u8 = 0xb7;
903 /// `NS_GET_USERNS = _IO(0xb7, 0x1)`: the owner user namespace.
904 const NS_GET_USERNS: Opcode = opcode::none(NSIO, 0x1);
905 /// `NS_GET_NSTYPE = _IO(0xb7, 0x3)`: the `CLONE_NEW*` type.
906 const NS_GET_NSTYPE: Opcode = opcode::none(NSIO, 0x3);
907
908 /// A namespace ioctl that takes no argument and returns an integer as
909 /// the result of the call.
910 struct NoArg {
911 opcode: Opcode,
912 }
913
914 // SAFETY: the two namespace requests that use this type take no argument
915 // and read no user memory, so the null pointer of `as_ptr` is never read.
916 // The calls change no user memory, so `IS_MUTATING` is false.
917 // `output_from_ptr` reads nothing through the pointer. It returns the
918 // non-negative integer that a successful call returns.
919 unsafe impl Ioctl for NoArg {
920 type Output = IoctlOutput;
921
922 const IS_MUTATING: bool = false;
923
924 fn opcode(&self) -> Opcode {
925 self.opcode
926 }
927
928 fn as_ptr(&mut self) -> *mut core::ffi::c_void {
929 core::ptr::null_mut()
930 }
931
932 unsafe fn output_from_ptr(
933 out: IoctlOutput,
934 _: *mut core::ffi::c_void,
935 ) -> Result<Self::Output> {
936 Ok(out)
937 }
938 }
939
940 /// Returns the type of the namespace that `fd` refers to.
941 ///
942 /// `fd` is a descriptor of a namespace file, for example an open
943 /// `/proc/<pid>/ns/user`.
944 ///
945 /// # Errors
946 ///
947 /// - `ENOTTY` if `fd` does not refer to a namespace.
948 /// - `EOPNOTSUPP` if the kernel returns a type that rustix does not
949 /// name.
950 /// - Another `Errno` from `NS_GET_NSTYPE`.
951 pub fn ns_type(fd: impl AsFd) -> Result<LinkNameSpaceType> {
952 // SAFETY: `NS_GET_NSTYPE` takes no argument. The kernel reads and
953 // writes no user memory and returns the type as the result.
954 let raw = unsafe {
955 ioctl(
956 fd,
957 NoArg {
958 opcode: NS_GET_NSTYPE,
959 },
960 )?
961 };
962 let raw = u32::try_from(raw).map_err(|_| Errno::INVAL)?;
963 [
964 LinkNameSpaceType::Time,
965 LinkNameSpaceType::Mount,
966 LinkNameSpaceType::ControlGroup,
967 LinkNameSpaceType::HostNameAndNISDomainName,
968 LinkNameSpaceType::InterProcessCommunication,
969 LinkNameSpaceType::User,
970 LinkNameSpaceType::ProcessID,
971 LinkNameSpaceType::Network,
972 ]
973 .into_iter()
974 .find(|ty| *ty as u32 == raw)
975 .ok_or(Errno::OPNOTSUPP)
976 }
977
978 /// Returns a descriptor of the user namespace that owns the namespace
979 /// `fd`.
980 ///
981 /// The new descriptor has the close-on-exec flag.
982 ///
983 /// # Errors
984 ///
985 /// - `ENOTTY` if `fd` does not refer to a namespace.
986 /// - `EINVAL` if `fd` refers to a user namespace with no parent, the
987 /// initial user namespace.
988 /// - `EPERM` if the owner is outside the user namespace of the process.
989 /// - Another `Errno` from `NS_GET_USERNS`.
990 pub fn ns_owner_userns(fd: impl AsFd) -> Result<OwnedFd> {
991 // SAFETY: `NS_GET_USERNS` takes no argument. The kernel reads and
992 // writes no user memory. A successful call returns a new descriptor
993 // that no other value owns, so `OwnedFd` takes ownership of it.
994 unsafe {
995 let raw = ioctl(
996 fd,
997 NoArg {
998 opcode: NS_GET_USERNS,
999 },
1000 )?;
1001 Ok(OwnedFd::from_raw_fd(raw as RawFd))
1002 }
1003 }
1004
1005 /// Gives the calling thread its own copy of its file system attributes:
1006 /// the root directory, the working directory, and the umask.
1007 ///
1008 /// The call is `unshare(CLONE_FS)`. The kernel refuses `setns` into a
1009 /// mount namespace with `EINVAL` for a thread that shares these
1010 /// attributes with another thread or process. Each thread of a process
1011 /// shares them, so a process with more than one thread calls this
1012 /// function in the thread that then calls `setns`. After the call, a
1013 /// change of the root or of the working directory in the calling thread,
1014 /// `setns` included, does not change the other threads.
1015 ///
1016 /// # Errors
1017 ///
1018 /// The `Errno` of `unshare`, for example `ENOMEM`.
1019 pub fn unshare_fs() -> Result<()> {
1020 // SAFETY: rustix makes `unshare_unsafe` unsafe because of
1021 // `CLONE_FILES`: a thread with its own descriptor table can hold a
1022 // descriptor number that another thread then uses for another file.
1023 // The call gives `UnshareFlags::FS` alone. It copies the root, the
1024 // working directory, and the umask of the thread, and does not change
1025 // the descriptor table, so each descriptor stays valid in each thread.
1026 unsafe { rustix::thread::unshare_unsafe(rustix::thread::UnshareFlags::FS) }
1027 }
1028
1029 /// Sets an ID mapping on the detached mount `mount`, with the user
1030 /// namespace `userns`.
1031 ///
1032 /// The call is `mount_setattr(2)` with `AT_EMPTY_PATH` and
1033 /// `MOUNT_ATTR_IDMAP`. After the call, the mount shows each file owner
1034 /// through the mapping of `userns`: the owner `0` in the file system
1035 /// shows as the user that `0` in `userns` maps to. rustix has no
1036 /// `mount_setattr`, so the call goes through the `syscall` function of
1037 /// libc.
1038 ///
1039 /// # Errors
1040 ///
1041 /// - `EPERM` if the process has no `CAP_SYS_ADMIN` in the user namespace
1042 /// that owns the mount, or none in `userns`.
1043 /// - `EINVAL` if `mount` is not a detached mount that was never attached,
1044 /// if it has a mapping already, if `userns` is the initial user
1045 /// namespace, or if the file system does not support ID-mapped mounts.
1046 /// - `EBADF` if `userns` is not a descriptor of a user namespace.
1047 /// - `ENOSYS` before Linux 5.12.
1048 /// - Another `Errno` from `mount_setattr`.
1049 pub fn mount_setattr_idmap(mount: impl AsFd, userns: impl AsFd) -> Result<()> {
1050 let attr = libc::mount_attr {
1051 attr_set: libc::MOUNT_ATTR_IDMAP,
1052 attr_clr: 0,
1053 propagation: 0,
1054 userns_fd: u64::try_from(userns.as_fd().as_raw_fd()).map_err(|_| Errno::BADF)?,
1055 };
1056 // SAFETY: the arguments are the descriptor of the mount, a pointer to
1057 // an empty C string that lives for the call, the flags, a pointer to
1058 // a `mount_attr` that lives for the call, and its size. The kernel
1059 // only reads the path and the struct, and holds no pointer after the
1060 // call returns. `libc::mount_attr` is the 32-byte UAPI struct. The
1061 // call creates and closes no descriptor.
1062 let ret = unsafe {
1063 libc::syscall(
1064 libc::SYS_mount_setattr,
1065 mount.as_fd().as_raw_fd(),
1066 c"".as_ptr(),
1067 libc::AT_EMPTY_PATH as libc::c_uint,
1068 &raw const attr,
1069 size_of::<libc::mount_attr>(),
1070 )
1071 };
1072 if ret < 0 {
1073 return Err(Errno::from_io_error(&std::io::Error::last_os_error()).unwrap_or(Errno::IO));
1074 }
1075 Ok(())
1076 }
1077
1078 const _: () = assert!(size_of::<libc::mount_attr>() == 32);
1079}
1080
1081#[cfg(target_os = "linux")]
1082mod sock {
1083 #![allow(unsafe_code)]
1084
1085 use std::ffi::OsStr;
1086 use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
1087 use std::sync::atomic::{AtomicBool, Ordering};
1088
1089 use rustix::io::{Errno, FdFlags, Result, fcntl_setfd};
1090
1091 /// The descriptor of the first socket that systemd passes,
1092 /// `SD_LISTEN_FDS_START`.
1093 const LISTEN_FD: i32 = 3;
1094
1095 /// The number of groups that the first `SO_PEERGROUPS` call has space
1096 /// for.
1097 const FIRST_GROUPS: usize = 64;
1098
1099 /// Returns the raw ids of the supplementary groups of the peer of the
1100 /// Unix socket `sock`. The peer must have at most `max` groups.
1101 ///
1102 /// The kernel records the groups when the peer connects, or when it
1103 /// creates the socket pair. The list is in the order of the kernel.
1104 ///
1105 /// # Errors
1106 ///
1107 /// - `ERANGE` if the peer has more than `max` groups.
1108 /// - `ENODATA` if the socket has no peer credentials, for example a
1109 /// listening socket.
1110 /// - `ENOTSOCK` if `sock` is not a socket, and `ENOPROTOOPT` if it is not
1111 /// a Unix socket.
1112 /// - Another `Errno` from `getsockopt(SO_PEERGROUPS)`.
1113 pub fn peer_groups(sock: impl AsFd, max: usize) -> Result<Vec<u32>> {
1114 let fd = sock.as_fd().as_raw_fd();
1115 let mut groups: Vec<libc::gid_t> = vec![0; FIRST_GROUPS.min(max)];
1116 loop {
1117 let mut len = libc::socklen_t::try_from(groups.len() * size_of::<libc::gid_t>())
1118 .map_err(|_| Errno::RANGE)?;
1119 // SAFETY: the buffer holds `len` bytes and lives for the call.
1120 // The kernel writes at most `len` bytes to it, and writes the
1121 // length of its data or the length that it needs to `len`.
1122 let ret = unsafe {
1123 libc::getsockopt(
1124 fd,
1125 libc::SOL_SOCKET,
1126 libc::SO_PEERGROUPS,
1127 groups.as_mut_ptr().cast(),
1128 &raw mut len,
1129 )
1130 };
1131 let need = len as usize / size_of::<libc::gid_t>();
1132 if ret == 0 {
1133 groups.truncate(need);
1134 return Ok(groups);
1135 }
1136 let errno = Errno::from_io_error(&std::io::Error::last_os_error()).unwrap_or(Errno::IO);
1137 if errno != Errno::RANGE || need <= groups.len() || need > max {
1138 return Err(errno);
1139 }
1140 groups.resize(need, 0);
1141 }
1142 }
1143
1144 /// Set when [`systemd_listen_fd`] takes the descriptor.
1145 static TAKEN: AtomicBool = AtomicBool::new(false);
1146
1147 /// Returns the one socket that systemd passes to the process, and sets
1148 /// its close-on-exec flag.
1149 ///
1150 /// systemd passes the socket as descriptor 3 and sets the environment
1151 /// variables `LISTEN_PID` and `LISTEN_FDS`. The call accepts them only
1152 /// when `LISTEN_PID` is the process id of this process and `LISTEN_FDS`
1153 /// is `1`. It returns `None` if neither variable is set. The call takes
1154 /// the descriptor once in the life of the process. It leaves the
1155 /// environment as it is, so a child process that the caller starts must
1156 /// not inherit the two variables.
1157 ///
1158 /// # Errors
1159 ///
1160 /// - `EINVAL` if only one of the two variables is set, if `LISTEN_PID`
1161 /// is not the process id of this process, or if `LISTEN_FDS` is not
1162 /// `1`.
1163 /// - `EALREADY` if an earlier call took the descriptor.
1164 /// - `EBADF` if descriptor 3 is not open.
1165 pub fn systemd_listen_fd() -> Result<Option<OwnedFd>> {
1166 let pid = std::env::var_os("LISTEN_PID");
1167 let fds = std::env::var_os("LISTEN_FDS");
1168 if !listen_vars_match(pid.as_deref(), fds.as_deref(), std::process::id())? {
1169 return Ok(None);
1170 }
1171 if TAKEN.swap(true, Ordering::SeqCst) {
1172 return Err(Errno::ALREADY);
1173 }
1174 // SAFETY: `fcntl(F_GETFD)` takes a raw descriptor number and reads no
1175 // memory of the process. A closed descriptor 3 gives `EBADF` and no
1176 // other effect. No Rust value holds the descriptor during the call.
1177 let flags = unsafe { libc::fcntl(LISTEN_FD, libc::F_GETFD) };
1178 if flags < 0 {
1179 return Err(Errno::from_io_error(&std::io::Error::last_os_error()).unwrap_or(Errno::IO));
1180 }
1181 // SAFETY: the probe shows that descriptor 3 is open. systemd passed
1182 // it to this process for its own use, and `TAKEN` makes sure that one
1183 // `OwnedFd` alone takes it.
1184 let fd = unsafe { OwnedFd::from_raw_fd(LISTEN_FD) };
1185 fcntl_setfd(
1186 &fd,
1187 FdFlags::from_bits_retain(flags as u32) | FdFlags::CLOEXEC,
1188 )?;
1189 Ok(Some(fd))
1190 }
1191
1192 /// Checks the values of `LISTEN_PID` and `LISTEN_FDS` for the process
1193 /// `own_pid`. Returns `false` if neither is set.
1194 pub(crate) fn listen_vars_match(
1195 pid: Option<&OsStr>,
1196 fds: Option<&OsStr>,
1197 own_pid: u32,
1198 ) -> Result<bool> {
1199 match (pid, fds) {
1200 (None, None) => Ok(false),
1201 (Some(pid), Some(fds)) => {
1202 let pid_ok = pid.to_str().and_then(|s| s.parse::<u32>().ok()) == Some(own_pid);
1203 if pid_ok && fds == "1" {
1204 Ok(true)
1205 } else {
1206 Err(Errno::INVAL)
1207 }
1208 }
1209 _ => Err(Errno::INVAL),
1210 }
1211 }
1212}
1213
1214#[cfg(test)]
1215mod tests {
1216 use super::{
1217 Mmap, enable_verity, enable_verity_with_salt, measure_verity, read_verity_descriptor,
1218 };
1219 use std::fs::{File, OpenOptions};
1220 use std::io::Write;
1221 use std::os::fd::AsFd;
1222
1223 /// A map of the whole file gives its bytes back. `Mmap::read_only` refuses
1224 /// a map longer than the file, because a read past the last file page
1225 /// raises `SIGBUS`.
1226 #[test]
1227 fn maps_the_file_and_refuses_a_longer_map() {
1228 let path = std::env::temp_dir().join(format!("ostrya-sys-mmap-{}", std::process::id()));
1229 let _ = std::fs::remove_file(&path);
1230 let body = b"ostrya mmap bounds";
1231 {
1232 let mut f = File::create(&path).unwrap();
1233 f.write_all(body).unwrap();
1234 f.sync_all().unwrap();
1235 }
1236 let ro = File::open(&path).unwrap();
1237
1238 let map = Mmap::read_only(ro.as_fd(), body.len()).unwrap();
1239 assert_eq!(map.as_slice(), body);
1240 assert_eq!(map.len(), body.len());
1241 assert!(!map.is_empty());
1242
1243 // One byte past the end is still inside the mapped page, so only the
1244 // explicit size check can refuse it.
1245 assert!(
1246 Mmap::read_only(ro.as_fd(), body.len() + 1).is_err(),
1247 "a map longer than the file must be refused"
1248 );
1249 // A page past the end, and an empty map.
1250 assert!(Mmap::read_only(ro.as_fd(), 8192).is_err());
1251 assert!(Mmap::read_only(ro.as_fd(), 0).is_err());
1252
1253 drop(map);
1254 let _ = std::fs::remove_file(&path);
1255 }
1256
1257 /// On a file system with fs-verity support, `enable_verity` seals the file,
1258 /// and a later open for writing fails. The measured digest is nonzero and
1259 /// stable. If the file system has no fs-verity support, the enable fails
1260 /// and the test skips.
1261 #[test]
1262 fn enable_then_measure_roundtrips() {
1263 let path = std::env::temp_dir().join(format!("ostrya-sys-verity-{}", std::process::id()));
1264 let _ = std::fs::remove_file(&path);
1265 {
1266 let mut f = File::create(&path).unwrap();
1267 f.write_all(b"hello ostrya verity").unwrap();
1268 f.sync_all().unwrap();
1269 }
1270 // The enable ioctl needs a read-only descriptor and no writable one.
1271 let ro = File::open(&path).unwrap();
1272 if enable_verity(ro.as_fd()).is_err() {
1273 let _ = std::fs::remove_file(&path);
1274 return;
1275 }
1276
1277 let measured = measure_verity(ro.as_fd()).unwrap();
1278 assert_ne!(measured, [0u8; 32], "a sealed file has a non-zero digest");
1279 assert_eq!(
1280 measured,
1281 measure_verity(ro.as_fd()).unwrap(),
1282 "the measured digest is stable"
1283 );
1284 assert!(
1285 OpenOptions::new().write(true).open(&path).is_err(),
1286 "a verity-sealed file rejects write-open"
1287 );
1288 let _ = std::fs::remove_file(&path);
1289 }
1290
1291 /// Writes `body` to a new file named for `tag` and opens it read-only, as
1292 /// the enable ioctl needs.
1293 fn read_only_file(tag: &str, body: &[u8]) -> (std::path::PathBuf, File) {
1294 let path = std::env::temp_dir().join(format!("ostrya-sys-{tag}-{}", std::process::id()));
1295 let _ = std::fs::remove_file(&path);
1296 {
1297 let mut f = File::create(&path).unwrap();
1298 f.write_all(body).unwrap();
1299 f.sync_all().unwrap();
1300 }
1301 let ro = File::open(&path).unwrap();
1302 (path, ro)
1303 }
1304
1305 /// The descriptor of a file that `enable_verity` sealed names SHA-256,
1306 /// 4096-byte blocks, no salt, and the size of the file. The test skips if
1307 /// the file system has no fs-verity support.
1308 #[test]
1309 fn descriptor_reports_the_ostree_parameters() {
1310 let body = b"ostrya verity descriptor".repeat(300);
1311 let (path, ro) = read_only_file("verity-descriptor", &body);
1312 if let Err(e) = enable_verity(ro.as_fd()) {
1313 eprintln!("skipping descriptor check: filesystem lacks fs-verity ({e})");
1314 let _ = std::fs::remove_file(&path);
1315 return;
1316 }
1317
1318 let desc = read_verity_descriptor(ro.as_fd()).unwrap();
1319 assert_eq!(desc.version, 1);
1320 assert_eq!(desc.hash_algorithm, 1, "SHA-256");
1321 assert_eq!(desc.log_blocksize, 12, "4096-byte blocks");
1322 assert_eq!(desc.salt_size, 0);
1323 assert_eq!(desc.data_size, body.len() as u64);
1324 let _ = std::fs::remove_file(&path);
1325 }
1326
1327 /// A file sealed with a salt reports the length of the salt. Its digest is
1328 /// not the digest of the same bytes sealed with no salt. The test skips if
1329 /// the file system has no fs-verity support.
1330 #[test]
1331 fn descriptor_reports_a_salt() {
1332 let body = b"ostrya salted verity";
1333 let (plain_path, plain) = read_only_file("verity-unsalted", body);
1334 if let Err(e) = enable_verity(plain.as_fd()) {
1335 eprintln!("skipping salt check: filesystem lacks fs-verity ({e})");
1336 let _ = std::fs::remove_file(&plain_path);
1337 return;
1338 }
1339 let (path, ro) = read_only_file("verity-salted", body);
1340 enable_verity_with_salt(ro.as_fd(), &[0x5a; 8]).unwrap();
1341
1342 let desc = read_verity_descriptor(ro.as_fd()).unwrap();
1343 assert_eq!(desc.hash_algorithm, 1);
1344 assert_eq!(desc.log_blocksize, 12);
1345 assert_eq!(desc.salt_size, 8);
1346 assert_ne!(
1347 measure_verity(ro.as_fd()).unwrap(),
1348 measure_verity(plain.as_fd()).unwrap(),
1349 "the salt changes the digest"
1350 );
1351 let _ = std::fs::remove_file(&path);
1352 let _ = std::fs::remove_file(&plain_path);
1353 }
1354
1355 /// A file without fs-verity has no descriptor to read.
1356 #[test]
1357 fn descriptor_of_an_unsealed_file_is_an_error() {
1358 let (path, ro) = read_only_file("verity-unsealed", b"not sealed");
1359 assert!(read_verity_descriptor(ro.as_fd()).is_err());
1360 assert!(measure_verity(ro.as_fd()).is_err());
1361 let _ = std::fs::remove_file(&path);
1362 }
1363}
1364
1365/// Tests of the loop device and the memory-file helpers.
1366///
1367/// The tests of the loop device need access to `/dev/loop-control`, which a
1368/// root process has. Without access, they skip. If `OSTRYA_REQUIRE_MOUNT` is
1369/// set, a missing access fails them.
1370#[cfg(all(test, target_os = "linux"))]
1371mod linux_tests {
1372 use super::{
1373 LO_FLAGS_AUTOCLEAR, LO_FLAGS_DIRECT_IO, LO_FLAGS_READ_ONLY, LoopConfig, LoopDevice,
1374 seal_contents, sealable_memfd,
1375 };
1376 use std::fs::File;
1377 use std::io::{Read, Seek, SeekFrom, Write};
1378 use std::os::fd::{AsFd, OwnedFd};
1379 use std::time::{Duration, Instant};
1380
1381 use rustix::fs::SealFlags;
1382 use rustix::io::Errno;
1383
1384 /// The environment variable that turns the skip of a test with no access
1385 /// to the loop devices into a failure.
1386 const REQUIRE_MOUNT: &str = "OSTRYA_REQUIRE_MOUNT";
1387
1388 /// The read-only, auto-clearing configuration with 4096-byte blocks.
1389 const BASE: LoopConfig = LoopConfig {
1390 block_size: 4096,
1391 read_only: true,
1392 autoclear: true,
1393 direct_io: false,
1394 };
1395
1396 /// Attaches `backing` with `cfg`. Returns `None` and prints a message if
1397 /// the process has no access to the loop devices and
1398 /// [`REQUIRE_MOUNT`] is not set.
1399 fn attach_or_skip(backing: impl AsFd, cfg: &LoopConfig) -> Option<LoopDevice> {
1400 match LoopDevice::attach(backing, cfg) {
1401 Ok(dev) => Some(dev),
1402 Err(e @ (Errno::ACCESS | Errno::PERM | Errno::NOENT)) => {
1403 assert!(
1404 std::env::var_os(REQUIRE_MOUNT).is_none(),
1405 "{REQUIRE_MOUNT} is set and the process has no access to the loop devices ({e})"
1406 );
1407 eprintln!("skipped: no access to the loop devices ({e})");
1408 None
1409 }
1410 Err(e) => panic!("attach failed: {e}"),
1411 }
1412 }
1413
1414 /// Returns the backing file that the kernel names for device `number`,
1415 /// or `None` if the device has no backing file.
1416 fn backing_file(number: u32) -> Option<String> {
1417 std::fs::read_to_string(format!("/sys/block/loop{number}/loop/backing_file"))
1418 .ok()
1419 .map(|s| s.trim_end().to_owned())
1420 }
1421
1422 /// Waits up to 5 seconds until device `number` no longer has the backing
1423 /// file `backing`. The release of an auto-clearing device can finish
1424 /// after the last close returns. Another test can take the same device
1425 /// after the release, with another backing file.
1426 fn wait_detached(number: u32, backing: &str) {
1427 let deadline = Instant::now() + Duration::from_secs(5);
1428 while backing_file(number).as_deref() == Some(backing) {
1429 assert!(Instant::now() < deadline, "loop{number} stays attached");
1430 std::thread::sleep(Duration::from_millis(20));
1431 }
1432 }
1433
1434 /// Returns a sealed memory file that holds 16 KiB.
1435 fn sealed_image() -> OwnedFd {
1436 let fd = sealable_memfd("ostrya-sys-loop").unwrap();
1437 let mut file = File::from(fd);
1438 file.write_all(&[0x5a; 16384]).unwrap();
1439 seal_contents(&file).unwrap();
1440 file.into()
1441 }
1442
1443 /// A sealed memory file refuses a write, a larger size, a smaller size,
1444 /// and a removal of the seal, and still reads.
1445 #[test]
1446 fn a_sealed_memfd_refuses_each_change() {
1447 let fd = sealable_memfd("ostrya-sys-seal").unwrap();
1448 let mut file = File::from(fd);
1449 file.write_all(b"sealed bytes").unwrap();
1450 seal_contents(&file).unwrap();
1451
1452 let seals = rustix::fs::fcntl_get_seals(&file).unwrap();
1453 assert!(
1454 seals
1455 .contains(SealFlags::WRITE | SealFlags::GROW | SealFlags::SHRINK | SealFlags::SEAL)
1456 );
1457 file.seek(SeekFrom::Start(0)).unwrap();
1458 assert!(file.write_all(b"x").is_err(), "a write is refused");
1459 assert_eq!(
1460 rustix::fs::ftruncate(&file, 64).unwrap_err(),
1461 Errno::PERM,
1462 "a larger size is refused"
1463 );
1464 assert_eq!(
1465 rustix::fs::ftruncate(&file, 1).unwrap_err(),
1466 Errno::PERM,
1467 "a smaller size is refused"
1468 );
1469 assert_eq!(seal_contents(&file).unwrap_err(), Errno::PERM);
1470
1471 let mut back = String::new();
1472 file.seek(SeekFrom::Start(0)).unwrap();
1473 file.read_to_string(&mut back).unwrap();
1474 assert_eq!(back, "sealed bytes");
1475 }
1476
1477 /// A loop device on a regular file holds the flags of its configuration
1478 /// and names the file. At the last close, the kernel detaches it.
1479 #[test]
1480 fn an_auto_clearing_device_detaches_at_the_last_close() {
1481 let path = std::env::temp_dir().join(format!("ostrya-sys-loop-{}", std::process::id()));
1482 std::fs::write(&path, vec![0u8; 16384]).unwrap();
1483 let file = File::open(&path).unwrap();
1484 let Some(dev) = attach_or_skip(&file, &BASE) else {
1485 let _ = std::fs::remove_file(&path);
1486 return;
1487 };
1488 let flags = dev.flags().unwrap();
1489 assert_eq!(
1490 flags & (LO_FLAGS_READ_ONLY | LO_FLAGS_AUTOCLEAR),
1491 LO_FLAGS_READ_ONLY | LO_FLAGS_AUTOCLEAR
1492 );
1493 let number = dev.number();
1494 let backing = backing_file(number).unwrap();
1495 assert_eq!(backing, path.to_str().unwrap());
1496
1497 drop(file);
1498 drop(dev);
1499 wait_detached(number, &backing);
1500 let _ = std::fs::remove_file(&path);
1501 }
1502
1503 /// A sealed memory file backs a loop device with a request for direct
1504 /// I/O. If the kernel refuses direct I/O on it, the device attaches
1505 /// without direct I/O. The test prints the flags that the kernel holds.
1506 #[test]
1507 fn a_sealed_memfd_backs_a_loop_device() {
1508 let image = sealed_image();
1509 let cfg = LoopConfig {
1510 direct_io: true,
1511 ..BASE
1512 };
1513 let Some(dev) = attach_or_skip(&image, &cfg) else {
1514 return;
1515 };
1516 let flags = dev.flags().unwrap();
1517 eprintln!(
1518 "loop{} flags {flags:#x}, direct I/O {}",
1519 dev.number(),
1520 flags & LO_FLAGS_DIRECT_IO != 0
1521 );
1522 assert_ne!(flags & LO_FLAGS_READ_ONLY, 0);
1523 let number = dev.number();
1524 let backing = backing_file(number).unwrap();
1525 drop(image);
1526 drop(dev);
1527 wait_detached(number, &backing);
1528 }
1529}
1530
1531/// Tests of the namespace, ID-mapping, and socket helpers. They run as any
1532/// user.
1533#[cfg(all(test, target_os = "linux"))]
1534mod ns_sock_tests {
1535 use super::{
1536 mount_setattr_idmap, ns_owner_userns, ns_type, peer_groups, sock::listen_vars_match,
1537 systemd_listen_fd, unshare_fs,
1538 };
1539 use std::ffi::OsStr;
1540 use std::os::fd::{AsFd, AsRawFd, OwnedFd};
1541 use std::process::Command;
1542
1543 use rustix::fs::{CWD, Mode, OFlags, fstat, openat};
1544 use rustix::io::{Errno, FdFlags};
1545 use rustix::thread::LinkNameSpaceType;
1546
1547 /// The name of the ignored test that the descriptor test runs in a child
1548 /// process.
1549 const LISTEN_CHILD: &str = "ns_sock_tests::listen_fd_child";
1550
1551 /// Opens `/proc/thread-self/ns/<name>`.
1552 fn own_ns(name: &str) -> OwnedFd {
1553 openat(
1554 CWD,
1555 format!("/proc/thread-self/ns/{name}"),
1556 OFlags::RDONLY | OFlags::CLOEXEC,
1557 Mode::empty(),
1558 )
1559 .unwrap()
1560 }
1561
1562 /// Returns the device and the inode of `fd`.
1563 fn dev_ino(fd: impl AsFd) -> (u64, u64) {
1564 let st = fstat(fd).unwrap();
1565 (st.st_dev, st.st_ino)
1566 }
1567
1568 #[test]
1569 fn a_namespace_has_its_type() {
1570 assert_eq!(ns_type(own_ns("user")).unwrap(), LinkNameSpaceType::User);
1571 assert_eq!(ns_type(own_ns("mnt")).unwrap(), LinkNameSpaceType::Mount);
1572 assert_eq!(ns_type(own_ns("net")).unwrap(), LinkNameSpaceType::Network);
1573 let file = std::fs::File::open("/proc/self/status").unwrap();
1574 assert_eq!(ns_type(&file).unwrap_err(), Errno::NOTTY);
1575 }
1576
1577 #[test]
1578 fn the_user_namespace_of_the_process_owns_its_mount_namespace() {
1579 let owner = ns_owner_userns(own_ns("mnt")).unwrap();
1580 assert_eq!(dev_ino(&owner), dev_ino(own_ns("user")));
1581 assert_eq!(ns_type(&owner).unwrap(), LinkNameSpaceType::User);
1582 let flags = rustix::io::fcntl_getfd(&owner).unwrap();
1583 assert!(flags.contains(FdFlags::CLOEXEC));
1584 }
1585
1586 /// After the call, a change of the working directory in the calling
1587 /// thread does not change the working directory of the main thread.
1588 #[test]
1589 fn a_thread_with_its_own_attributes_changes_its_directory_alone() {
1590 let before = std::fs::read_link("/proc/self/cwd").unwrap();
1591 assert_ne!(before, std::path::Path::new("/"));
1592 std::thread::spawn(move || {
1593 unshare_fs().unwrap();
1594 std::env::set_current_dir("/").unwrap();
1595 let own = std::fs::read_link("/proc/thread-self/cwd").unwrap();
1596 assert_eq!(own, std::path::Path::new("/"));
1597 assert_eq!(std::fs::read_link("/proc/self/cwd").unwrap(), before);
1598 })
1599 .join()
1600 .unwrap();
1601 }
1602
1603 /// A directory descriptor is not a detached mount. Without the privilege
1604 /// the kernel refuses the call with `EPERM`. With it, the kernel refuses
1605 /// the descriptor or the initial user namespace with `EINVAL`.
1606 #[test]
1607 fn an_idmap_of_a_plain_directory_is_refused() {
1608 let dir = openat(
1609 CWD,
1610 "/",
1611 OFlags::DIRECTORY | OFlags::RDONLY | OFlags::CLOEXEC,
1612 Mode::empty(),
1613 )
1614 .unwrap();
1615 let err = mount_setattr_idmap(&dir, own_ns("user")).unwrap_err();
1616 assert!(matches!(err, Errno::PERM | Errno::INVAL), "{err}");
1617 }
1618
1619 #[test]
1620 fn the_peer_groups_of_a_socket_pair_are_the_groups_of_the_process() {
1621 let (a, _b) = std::os::unix::net::UnixStream::pair().unwrap();
1622 let mut got: Vec<u32> = peer_groups(&a, 4096).unwrap();
1623 got.sort_unstable();
1624 let status = std::fs::read_to_string("/proc/self/status").unwrap();
1625 let mut want: Vec<u32> = status
1626 .lines()
1627 .find_map(|line| line.strip_prefix("Groups:"))
1628 .unwrap()
1629 .split_whitespace()
1630 .map(|g| g.parse().unwrap())
1631 .collect();
1632 want.sort_unstable();
1633 assert_eq!(got, want);
1634 if !want.is_empty() {
1635 assert_eq!(peer_groups(&a, want.len() - 1).unwrap_err(), Errno::RANGE);
1636 }
1637
1638 let file = std::fs::File::open("/proc/self/status").unwrap();
1639 assert_eq!(peer_groups(&file, 4096).unwrap_err(), Errno::NOTSOCK);
1640 }
1641
1642 #[test]
1643 fn the_listen_variables_must_name_this_process_and_one_socket() {
1644 let s = |v: &'static str| Some(OsStr::new(v));
1645 assert_eq!(listen_vars_match(None, None, 42), Ok(false));
1646 assert_eq!(listen_vars_match(s("42"), s("1"), 42), Ok(true));
1647 assert_eq!(listen_vars_match(s("41"), s("1"), 42), Err(Errno::INVAL));
1648 assert_eq!(listen_vars_match(s("42"), s("2"), 42), Err(Errno::INVAL));
1649 assert_eq!(listen_vars_match(s("42"), s("0"), 42), Err(Errno::INVAL));
1650 assert_eq!(listen_vars_match(s("x"), s("1"), 42), Err(Errno::INVAL));
1651 assert_eq!(listen_vars_match(s("42"), None, 42), Err(Errno::INVAL));
1652 assert_eq!(listen_vars_match(None, s("1"), 42), Err(Errno::INVAL));
1653 }
1654
1655 /// A child process with the systemd variables and an open descriptor 3
1656 /// takes the descriptor once.
1657 #[test]
1658 fn a_passed_descriptor_is_taken_once() {
1659 let exe = std::env::current_exe().unwrap();
1660 let out = Command::new("/bin/sh")
1661 .arg("-c")
1662 .arg(r#"export LISTEN_PID=$$ LISTEN_FDS=1; exec "$0" "$@" 3</dev/null"#)
1663 .arg(&exe)
1664 .args([LISTEN_CHILD, "--exact", "--ignored", "--nocapture"])
1665 .output()
1666 .unwrap();
1667 let stdout = String::from_utf8_lossy(&out.stdout);
1668 assert!(
1669 out.status.success() && stdout.contains("1 passed"),
1670 "{}\n{stdout}\n{}",
1671 out.status,
1672 String::from_utf8_lossy(&out.stderr)
1673 );
1674 }
1675
1676 /// The body of the child process of [`a_passed_descriptor_is_taken_once`].
1677 /// Outside that child, the test does nothing.
1678 #[test]
1679 #[ignore = "runs in a child process with LISTEN_PID and LISTEN_FDS"]
1680 fn listen_fd_child() {
1681 if std::env::var_os("LISTEN_PID").is_none() {
1682 return;
1683 }
1684 let fd = systemd_listen_fd().unwrap().unwrap();
1685 assert_eq!(fd.as_raw_fd(), 3);
1686 let flags = rustix::io::fcntl_getfd(&fd).unwrap();
1687 assert!(flags.contains(FdFlags::CLOEXEC));
1688 assert_eq!(systemd_listen_fd().unwrap_err(), Errno::ALREADY);
1689 }
1690}