subc-os 0.1.57

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! File-object identity taken from the same handle that supplied captured bytes.

use std::{fs::File, io};
#[cfg(windows)]
use windows_sys::Win32::Storage::FileSystem::BY_HANDLE_FILE_INFORMATION;

#[derive(Debug)]
pub enum OpenRegularError {
    Io(io::Error),
    Symlink,
    NotRegularFile,
}
impl std::fmt::Display for OpenRegularError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(error) => write!(f, "input open failed: {error}"),
            Self::Symlink => f.write_str("input leaf is a symlink or reparse point"),
            Self::NotRegularFile => f.write_str("input handle is not a regular file"),
        }
    }
}
impl std::error::Error for OpenRegularError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(error) => Some(error),
            _ => None,
        }
    }
}
impl From<io::Error> for OpenRegularError {
    fn from(error: io::Error) -> Self {
        Self::Io(error)
    }
}

/// Open a regular input without following its leaf. Parent directories remain
/// the caller's responsibility. Nonblocking open prevents a FIFO substitution
/// from hanging before the descriptor's type can be checked.
#[cfg(unix)]
pub fn open_regular_nofollow(path: &std::path::Path) -> Result<File, OpenRegularError> {
    use std::os::unix::fs::OpenOptionsExt;
    let file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
        .open(path)
        .map_err(|error| {
            if error.raw_os_error() == Some(libc::ELOOP) {
                OpenRegularError::Symlink
            } else {
                OpenRegularError::Io(error)
            }
        })?;
    // File::metadata uses fstat on this descriptor, not a fresh path lookup.
    if !file.metadata()?.is_file() {
        return Err(OpenRegularError::NotRegularFile);
    }
    Ok(file)
}

/// Open an absolute regular file without following a symlink in any component.
/// Directory descriptors anchor each lookup even if an ancestor is renamed.
#[cfg(unix)]
pub fn open_regular_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
    open_nofollow_all(path, false)
}

/// Open an absolute directory without following symlinks in any component.
pub fn open_directory_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
    open_nofollow_all(path, true)
}

#[cfg(unix)]
fn open_nofollow_all(
    path: &std::path::Path,
    want_directory: bool,
) -> Result<File, OpenRegularError> {
    use rustix::fs::{open, openat, statat, AtFlags, FileType, Mode, OFlags};
    use std::path::Component;
    if !path.is_absolute() {
        return Err(io::Error::new(io::ErrorKind::InvalidInput, "absolute path required").into());
    }
    let mut directory = open(
        "/",
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
    )
    .map_err(io::Error::from)?;
    let parts = path
        .components()
        .filter(|part| !matches!(part, Component::RootDir | Component::CurDir))
        .collect::<Vec<_>>();
    for (index, part) in parts.iter().enumerate() {
        let name = part.as_os_str();
        let leaf = index + 1 == parts.len();
        let flags = OFlags::RDONLY
            | OFlags::CLOEXEC
            | OFlags::NOFOLLOW
            | OFlags::NONBLOCK
            | if leaf && !want_directory {
                OFlags::empty()
            } else {
                OFlags::DIRECTORY
            };
        directory = openat(&directory, name, flags, Mode::empty()).map_err(|error| {
            if error == rustix::io::Errno::LOOP
                || (error == rustix::io::Errno::NOTDIR
                    && statat(&directory, name, AtFlags::SYMLINK_NOFOLLOW).is_ok_and(|stat| {
                        FileType::from_raw_mode(stat.st_mode) == FileType::Symlink
                    }))
            {
                OpenRegularError::Symlink
            } else if error == rustix::io::Errno::NOTDIR {
                OpenRegularError::NotRegularFile
            } else {
                OpenRegularError::Io(error.into())
            }
        })?;
    }
    let file = File::from(directory);
    if if want_directory {
        !file.metadata()?.is_dir()
    } else {
        !file.metadata()?.is_file()
    } {
        return Err(OpenRegularError::NotRegularFile);
    }
    Ok(file)
}

/// Pin each Windows directory against rename while rejecting symlinks and
/// junctions (reparse points). Holding all ancestors until the leaf is open
/// prevents another process from replacing a checked directory with a redirect.
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn open_regular_nofollow_all(path: &std::path::Path) -> Result<File, OpenRegularError> {
    open_nofollow_all(path, false)
}

#[cfg(windows)]
#[allow(unsafe_code)]
fn open_nofollow_all(
    path: &std::path::Path,
    want_directory: bool,
) -> Result<File, OpenRegularError> {
    use std::os::windows::{fs::OpenOptionsExt, io::AsRawHandle};
    use windows_sys::Win32::Storage::FileSystem::{
        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT,
        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES,
        FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_TRAVERSE,
    };
    if !path.is_absolute() {
        return Err(io::Error::new(io::ErrorKind::InvalidInput, "absolute path required").into());
    }
    let mut ancestors = Vec::new();
    // Use slices of the original path. Rebuilding it with PathBuf::push can
    // lose the root separator on verbatim drive paths such as \\?\C:\.
    let prefixes: Vec<_> = path
        .ancestors()
        .take_while(|prefix| prefix.is_absolute())
        .collect();
    for prefix in prefixes.into_iter().rev() {
        // Directory writers need not exclude traversal. Still deny delete
        // sharing to pin each checked name, and leave regular leaves read-only.
        let mut options = std::fs::OpenOptions::new();
        if want_directory || prefix != path {
            options
                .access_mode(FILE_READ_ATTRIBUTES | FILE_TRAVERSE)
                .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE);
        } else {
            options.read(true).share_mode(FILE_SHARE_READ);
        }
        let file = options
            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
            .open(prefix)?;
        let mut information: BY_HANDLE_FILE_INFORMATION = Default::default();
        // SAFETY: file owns the queried handle and information is writable.
        if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
            return Err(io::Error::last_os_error().into());
        }
        if information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            return Err(OpenRegularError::Symlink);
        }
        ancestors.push(file);
    }
    let file = ancestors.pop().ok_or(OpenRegularError::NotRegularFile)?;
    if if want_directory {
        !file.metadata()?.is_dir()
    } else {
        !file.metadata()?.is_file()
    } {
        return Err(OpenRegularError::NotRegularFile);
    }
    Ok(file)
}

/// Windows equivalent of the regular-input opener. Reparse-point and type
/// checks use the opened handle, never a second lookup through the pathname.
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn open_regular_nofollow(path: &std::path::Path) -> Result<File, OpenRegularError> {
    use std::os::windows::{fs::OpenOptionsExt, io::AsRawHandle};
    use windows_sys::Win32::Storage::FileSystem::{
        GetFileInformationByHandle, GetFileType, BY_HANDLE_FILE_INFORMATION,
        FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
        FILE_FLAG_OPEN_REPARSE_POINT, FILE_TYPE_DISK,
    };
    let file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
        .open(path)?;
    // SAFETY: file owns the live handle for the entire query.
    if unsafe { GetFileType(file.as_raw_handle()) } != FILE_TYPE_DISK {
        return Err(OpenRegularError::NotRegularFile);
    }
    let mut information: BY_HANDLE_FILE_INFORMATION = Default::default();
    // SAFETY: file owns the handle; information is a correctly sized writable
    // output buffer and both remain live throughout the synchronous query.
    if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) } == 0 {
        return Err(io::Error::last_os_error().into());
    }
    if information.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
        return Err(OpenRegularError::Symlink);
    }
    if information.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0 {
        return Err(OpenRegularError::NotRegularFile);
    }
    Ok(file)
}

#[cfg(test)]
#[path = "regular_open_tests.rs"]
mod open_tests;

#[cfg(unix)]
pub type RetainedFileIdentity = crate::FileIdentity;
#[cfg(windows)]
pub type RetainedFileIdentity = crate::WindowsFileIdentity;

/// Identify an already-open file, without resolving its mutable pathname again.
/// Unix identities contain device and inode; Windows identities contain the
/// volume serial and all sixteen file-id bytes. Content hashes remain separate.
#[cfg(unix)]
pub fn retained_file_identity(file: &File) -> io::Result<RetainedFileIdentity> {
    use std::os::unix::fs::MetadataExt;
    let metadata = file.metadata()?;
    Ok(RetainedFileIdentity {
        device: metadata.dev(),
        inode: metadata.ino(),
    })
}

/// The published registry's Windows identity uses the legacy 64-bit file index,
/// not FILE_ID_INFO's 128-bit identifier; neither is a padded form of the other.
#[cfg(windows)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WindowsFileIndexIdentity {
    pub volume_serial: u32,
    pub file_index: u64,
}

/// A snapshot of Windows file information from an open handle.
#[cfg(windows)]
pub struct WindowsFileInformation(BY_HANDLE_FILE_INFORMATION);

#[cfg(windows)]
impl WindowsFileInformation {
    /// The number of hard links reported for the file when queried.
    pub fn link_count(&self) -> u32 {
        self.0.nNumberOfLinks
    }

    pub(crate) fn attributes(&self) -> u32 {
        self.0.dwFileAttributes
    }
}

/// Query information about the opened object without resolving its path again.
/// This does not validate the file type or check for reparse points.
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn retained_file_information(file: &File) -> io::Result<WindowsFileInformation> {
    use std::os::windows::io::AsRawHandle;
    use windows_sys::Win32::Storage::FileSystem::GetFileInformationByHandle;
    let mut info = BY_HANDLE_FILE_INFORMATION::default();
    // SAFETY: file owns the live handle and info is a writable, correctly sized buffer.
    if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(WindowsFileInformation(info))
}

/// Read the legacy 64-bit file index and volume serial from the exact handle.
/// Registries publish this identity; FILE_ID_INFO's 128-bit identifier is a
/// different representation and cannot safely be inferred by padding this one.
#[cfg(windows)]
pub fn retained_file_index(file: &File) -> io::Result<WindowsFileIndexIdentity> {
    let info = retained_file_information(file)?.0;
    Ok(WindowsFileIndexIdentity {
        volume_serial: info.dwVolumeSerialNumber,
        file_index: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
    })
}

/// Identify an already-open file using the complete Windows file-object id.
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn retained_file_identity(file: &File) -> io::Result<RetainedFileIdentity> {
    use std::{mem::size_of, os::windows::io::AsRawHandle};
    use windows_sys::Win32::Storage::FileSystem::{
        FileIdInfo, GetFileInformationByHandleEx, FILE_ID_INFO,
    };
    let mut info: FILE_ID_INFO = Default::default();
    // SAFETY: file owns a live handle; the writable buffer has the FileIdInfo
    // layout and size, and neither the handle nor the buffer escapes this call.
    if unsafe {
        GetFileInformationByHandleEx(
            file.as_raw_handle(),
            FileIdInfo,
            (&mut info as *mut FILE_ID_INFO).cast(),
            size_of::<FILE_ID_INFO>() as u32,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    Ok(RetainedFileIdentity {
        volume_serial_number: info.VolumeSerialNumber,
        file_id: info.FileId.Identifier,
    })
}

#[cfg(all(test, any(unix, windows)))]
mod tests {
    use super::*;

    #[cfg(windows)]
    #[test]
    fn retained_file_information_reports_link_count_from_an_open_handle() {
        let scratch = cortexkit_test_support::ScratchDir::new("retained-link-count");
        let path = scratch.join("file");
        std::fs::write(&path, b"content").unwrap();
        let file = File::open(&path).unwrap();
        assert_eq!(retained_file_information(&file).unwrap().link_count(), 1);

        std::fs::hard_link(&path, scratch.join("second-link")).unwrap();
        assert_eq!(retained_file_information(&file).unwrap().link_count(), 2);
    }

    #[test]
    fn retained_directory_open_checks_type_and_identity() {
        let dir = cortexkit_test_support::ScratchDir::new("retained-directory");
        let opened = open_directory_nofollow_all(&dir).unwrap();
        assert!(opened.metadata().unwrap().is_dir());
        assert_eq!(
            retained_file_identity(&opened).unwrap(),
            retained_file_identity(&open_directory_nofollow_all(&dir).unwrap()).unwrap()
        );
        let path = dir.join("file");
        std::fs::write(&path, b"file").unwrap();
        assert!(open_directory_nofollow_all(&path).is_err());
        assert!(open_directory_nofollow_all(std::path::Path::new("relative")).is_err());
    }

    #[cfg(unix)]
    #[test]
    fn retained_directory_open_refuses_symlink_ancestors_and_leaf() {
        let dir = cortexkit_test_support::ScratchDir::new("retained-directory-symlink");
        std::fs::create_dir_all(dir.join("real/child")).unwrap();
        std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).unwrap();
        assert!(open_directory_nofollow_all(&dir.join("link")).is_err());
        assert!(open_directory_nofollow_all(&dir.join("link/child")).is_err());
    }

    #[cfg(windows)]
    #[test]
    fn retained_directory_open_can_publish_under_a_canonical_windows_path() {
        use std::{ffi::OsStr, io::Write};

        let root = cortexkit_test_support::ScratchDir::new("retained-canonical-directory");
        let canonical = std::fs::canonicalize(root.path()).unwrap();
        let parent = open_directory_nofollow_all(&canonical).unwrap();
        let mut file = crate::RetainedTempFile::create_for_publish(&parent).unwrap();
        file.file_mut().write_all(b"published").unwrap();
        file.publish(OsStr::new("published")).unwrap();
        assert_eq!(std::fs::read(root.join("published")).unwrap(), b"published");
    }

    #[cfg(windows)]
    #[test]
    fn retained_directory_open_coexists_with_an_existing_directory_writer() {
        use std::os::windows::fs::OpenOptionsExt;
        use windows_sys::Win32::Storage::FileSystem::{FILE_ADD_FILE, FILE_FLAG_BACKUP_SEMANTICS};

        let dir = cortexkit_test_support::ScratchDir::new("retained-directory-writer");
        let child = dir.join("child");
        std::fs::create_dir(&child).unwrap();
        // FILE_ADD_FILE requests the directory right corresponding to write
        // data on a file, so an opener that denies write sharing conflicts.
        let writer = std::fs::OpenOptions::new()
            .access_mode(FILE_ADD_FILE)
            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
            .open(&dir)
            .unwrap();

        let parent = open_directory_nofollow_all(&dir).unwrap();
        let reopened = open_directory_nofollow_all(&dir).unwrap();
        assert_eq!(
            retained_file_identity(&parent).unwrap(),
            retained_file_identity(&reopened).unwrap()
        );
        assert!(open_directory_nofollow_all(&child)
            .unwrap()
            .metadata()
            .unwrap()
            .is_dir());
        drop(writer);
    }

    #[cfg(windows)]
    #[test]
    fn retained_directory_open_still_blocks_rename_until_handle_closes() {
        let dir = cortexkit_test_support::ScratchDir::new("retained-directory-rename");
        let child = dir.join("child");
        let renamed = dir.join("renamed");
        std::fs::create_dir(&child).unwrap();
        let handle = open_directory_nofollow_all(&child).unwrap();

        assert!(std::fs::rename(&child, &renamed).is_err());
        assert!(!renamed.exists());
        drop(handle);
        std::fs::rename(&child, &renamed).unwrap();
        assert!(renamed.is_dir());
    }

    #[test]
    fn retained_file_identity_hard_links_share_identity_but_copies_do_not() {
        let root = cortexkit_test_support::ScratchDir::new("subc-retained-file");
        let first = root.join("first");
        let link = root.join("link");
        let copy = root.join("copy");
        std::fs::write(&first, b"same bytes").unwrap();
        std::fs::hard_link(&first, &link).unwrap();
        std::fs::copy(&first, &copy).unwrap();
        let id = |path| retained_file_identity(&File::open(path).unwrap()).unwrap();
        assert_eq!(id(&first), id(&link));
        assert_ne!(id(&first), id(&copy));
    }
}