cloudfox-coreshift-core 2.0.0

Low-level Linux and Android systems primitives for CoreShift (CloudFox)
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/

//! Filesystem-oriented low-level helpers.
//!
//! This module contains lightweight Linux and Android file probes and helpers
//! that are useful near the OS boundary, including path existence checks,
//! page-cache read-ahead hints, and symlink-safe read/write primitives.

use crate::CoreError;
use std::ffi::CString;
use std::fs;
use std::io::{Read, Write};
use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::path::Path;
use std::time::UNIX_EPOCH;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PathFingerprint {
    pub len: u64,
    pub modified_ns: u128,
}

/// Return a fingerprint of the file metadata at the specified path.
///
/// ### Errors
/// - `EACCES`: Permission denied.
/// - `ENOENT`: The path does not exist.
pub fn path_fingerprint(path: &Path) -> Result<PathFingerprint, CoreError> {
    let metadata = std::fs::metadata(path).map_err(|err| {
        CoreError::sys(err.raw_os_error().unwrap_or(libc::EIO), "path_fingerprint")
    })?;
    let modified_ns = metadata
        .modified()
        .ok()
        .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
        .map(|duration| duration.as_nanos())
        .unwrap_or_default();
    Ok(PathFingerprint {
        len: metadata.len(),
        modified_ns,
    })
}

/// Probe whether a filesystem path is accessible and exists.
///
/// NOTE: This follows symbolic links. It uses `libc::access` with `F_OK`
/// so the check is a single syscall with no Rust allocator involvement.
/// Returns `true` if the path is accessible or visible, `false` on any error
/// (including `ENOENT`, `EACCES`, or invalid path bytes).
pub fn path_exists(path: &str) -> bool {
    match std::ffi::CString::new(path) {
        Ok(c) => unsafe { libc::access(c.as_ptr(), libc::F_OK) == 0 },
        Err(_) => false,
    }
}

/// Probe whether a path exists without following symbolic links.
///
/// Returns `true` if the path exists, including a dangling symlink.
pub fn path_lstat_exists(path: &str) -> bool {
    match std::ffi::CString::new(path) {
        Ok(c) => unsafe {
            let mut stat = std::mem::zeroed();
            libc::lstat(c.as_ptr(), &mut stat) == 0
        },
        Err(_) => false,
    }
}

/// Read a file into a string.
///
/// This stays as a small convenience helper for low-level modules that treat
/// blocking filesystem or procfs reads as an acceptable boundary cost.
/// Read the entire contents of a file into a string.
///
/// ### Errors
/// - `EACCES`: Permission denied.
/// - `ENOENT`: The path does not exist.
/// - `EIO`: Low-level I/O error.
pub fn read_to_string(path: &str) -> Result<String, CoreError> {
    std::fs::read_to_string(path)
        .map_err(|err| CoreError::sys(err.raw_os_error().unwrap_or(libc::EIO), "read_to_string"))
}

/// Advise the kernel to begin reading file data into the page cache.
///
/// This is an advisory hint only. It can help warm likely-needed file ranges,
/// but the kernel may ignore the request, perform only part of it, or return
/// before the data is fully resident in memory.
///
/// The `offset` and `len` identify the byte range to prefetch for `fd`.
/// Success means the kernel accepted the request, not that subsequent reads
/// are guaranteed to be cache hits.
/// Advise the kernel to begin reading file data into the page cache.
///
/// ### Errors
/// - `EBADF`: The file descriptor is invalid.
/// - `EINVAL`: The offset or length is invalid.
pub fn readahead(fd: impl AsRawFd, offset: u64, len: usize) -> Result<(), CoreError> {
    readahead_raw(fd.as_raw_fd(), offset, len)
}

// ── fadvise ──────────────────────────────────────────────────────────────────

pub const FADV_NORMAL: i32 = libc::POSIX_FADV_NORMAL;
pub const FADV_RANDOM: i32 = libc::POSIX_FADV_RANDOM;
pub const FADV_SEQUENTIAL: i32 = libc::POSIX_FADV_SEQUENTIAL;
pub const FADV_WILLNEED: i32 = libc::POSIX_FADV_WILLNEED;
pub const FADV_DONTNEED: i32 = libc::POSIX_FADV_DONTNEED;
pub const FADV_NOREUSE: i32 = libc::POSIX_FADV_NOREUSE;

/// Advise the kernel on the expected access pattern for a file range.
///
/// `offset` and `len` define the byte range; `len = 0` means "to end of file".
/// `advice` is one of the `FADV_*` constants.
///
/// Unlike most syscalls, `posix_fadvise` returns the error code directly
/// rather than setting `errno`.
///
/// ### Errors
/// - `EBADF`: invalid file descriptor.
/// - `EINVAL`: invalid advice value or unsupported `len`.
/// - `ESPIPE`: the fd refers to a pipe.
pub fn fadvise(fd: impl AsRawFd, offset: u64, len: usize, advice: i32) -> Result<(), CoreError> {
    let ret = unsafe {
        libc::posix_fadvise(
            fd.as_raw_fd(),
            offset as libc::off_t,
            len as libc::off_t,
            advice,
        )
    };
    if ret == 0 {
        Ok(())
    } else {
        Err(CoreError::sys(ret, "posix_fadvise"))
    }
}

/// Map a file range, advise the kernel that it will be needed, then unmap it.
///
/// `offset` must be page-aligned. This low-level primitive rejects unaligned
/// offsets with `EINVAL` instead of silently widening the requested range.
/// Map a file range and advise the kernel with `MADV_WILLNEED`.
///
/// ### Errors
/// - `EBADF`: The file descriptor is invalid.
/// - `EINVAL`: The offset is not page-aligned or the range is invalid.
/// - `ENOMEM`: Insufficient kernel memory.
pub fn mmap_madvise(
    fd: impl AsRawFd,
    offset: u64,
    len: usize,
    touch: bool,
) -> Result<(), CoreError> {
    mmap_madvise_raw(fd.as_raw_fd(), offset, len, touch)
}

#[cfg(any(target_os = "linux", target_os = "android"))]
fn mmap_madvise_raw(
    fd: libc::c_int,
    offset: u64,
    len: usize,
    touch: bool,
) -> Result<(), CoreError> {
    if len == 0 {
        return Ok(());
    }

    let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
    if page_size <= 0 {
        return Err(CoreError::sys(libc::EINVAL, "sysconf(_SC_PAGESIZE)"));
    }
    let page_size = page_size as u64;
    if offset % page_size != 0 || offset > libc::off_t::MAX as u64 {
        return Err(CoreError::sys(libc::EINVAL, "mmap"));
    }

    let ptr = unsafe {
        libc::mmap(
            std::ptr::null_mut(),
            len,
            libc::PROT_READ,
            libc::MAP_PRIVATE,
            fd,
            offset as libc::off_t,
        )
    };
    if ptr == libc::MAP_FAILED {
        let code = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
        return Err(CoreError::sys(code, "mmap"));
    }

    let result = if unsafe { libc::madvise(ptr, len, libc::MADV_WILLNEED) } == -1 {
        let code = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
        Err(CoreError::sys(code, "madvise"))
    } else {
        if touch {
            let mut pos = 0usize;
            let page_size = page_size as usize;
            while pos < len {
                unsafe {
                    std::ptr::read_volatile((ptr as *const u8).add(pos));
                }
                pos = pos.saturating_add(page_size);
            }
        }
        Ok(())
    };

    if unsafe { libc::munmap(ptr, len) } == -1 {
        let code = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
        return Err(CoreError::sys(code, "munmap"));
    }
    result
}

#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn mmap_madvise_raw(
    _fd: libc::c_int,
    _offset: u64,
    _len: usize,
    _touch: bool,
) -> Result<(), CoreError> {
    Err(CoreError::sys(libc::ENOSYS, "mmap"))
}

#[cfg(any(target_os = "linux", target_os = "android"))]
fn readahead_raw(fd: libc::c_int, offset: u64, len: usize) -> Result<(), CoreError> {
    if offset > libc::off64_t::MAX as u64 {
        return Err(CoreError::sys(libc::EINVAL, "readahead"));
    }

    let count = len as libc::size_t;
    let offset = offset as libc::off64_t;

    loop {
        let ret = unsafe { libc::syscall(readahead_syscall_number(), fd, offset, count) };
        if ret == -1 {
            let code = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
            if code == libc::EINTR {
                continue;
            }
            return Err(CoreError::sys(code, "readahead"));
        }
        return Ok(());
    }
}

#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn readahead_raw(_fd: libc::c_int, _offset: u64, _len: usize) -> Result<(), CoreError> {
    Err(CoreError::sys(libc::ENOSYS, "readahead"))
}

#[cfg(target_os = "linux")]
#[inline(always)]
const fn readahead_syscall_number() -> libc::c_long {
    libc::SYS_readahead
}

#[cfg(all(target_os = "android", target_arch = "aarch64"))]
#[inline(always)]
const fn readahead_syscall_number() -> libc::c_long {
    213
}

#[cfg(all(target_os = "android", target_arch = "arm"))]
#[inline(always)]
const fn readahead_syscall_number() -> libc::c_long {
    225
}

#[cfg(all(target_os = "android", target_arch = "x86_64"))]
#[inline(always)]
const fn readahead_syscall_number() -> libc::c_long {
    187
}

#[cfg(all(target_os = "android", target_arch = "x86"))]
#[inline(always)]
const fn readahead_syscall_number() -> libc::c_long {
    225
}

const TEMP_ATTEMPTS: usize = 32;

fn cstr(s: &str) -> Result<CString, CoreError> {
    CString::new(s).map_err(|_| CoreError::sys(libc::EINVAL, "path:nul_byte"))
}

fn openat_raw(dirfd: RawFd, name: &str, flags: i32, mode: u32) -> Result<RawFd, CoreError> {
    let c = cstr(name)?;
    // SAFETY: `name` is a single path component (no `/`) converted to a
    // NUL-terminated string, and `dirfd` is a valid open directory fd.
    let fd = unsafe { libc::openat(dirfd, c.as_ptr(), flags, mode as libc::c_uint) };
    if fd < 0 {
        Err(std::io::Error::last_os_error().into())
    } else {
        Ok(fd)
    }
}

fn openat_dir(dirfd: RawFd, name: &str) -> Result<OwnedFd, CoreError> {
    let fd = openat_raw(
        dirfd,
        name,
        libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
        0,
    )?;
    // SAFETY: `fd` came from openat and is uniquely owned here.
    Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}

/// Resolve `path` from the root down to a directory fd, refusing to traverse
/// Walk `path` from the root down to a directory fd, refusing to traverse any
/// symlink component (ELOOP) or non-directory (ENOTDIR). When `create_mode` is
/// `Some(mode)`, missing components are created via `mkdirat` relative to the
/// previously held fd — never by re-resolving a path, so an attacker link can
/// never make root create a directory at an attacker-chosen location (N5).
fn walk_dir(path: &Path, create_mode: Option<u32>) -> Result<OwnedFd, CoreError> {
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()?.join(path)
    };
    let mut dir = openat_dir(libc::AT_FDCWD, "/")?;
    for comp in abs.components() {
        use std::path::Component;
        match comp {
            Component::RootDir | Component::CurDir => {}
            Component::Normal(name) => {
                let name = name
                    .to_str()
                    .ok_or_else(|| CoreError::sys(libc::EINVAL, "path:non_utf8"))?;
                let next = match openat_dir(dir.as_raw_fd(), name) {
                    Ok(fd) => fd,
                    Err(e) if e.raw_os_error() == Some(libc::ENOENT) && create_mode.is_some() => {
                        let c = cstr(name)?;
                        // SAFETY: mkdirat creates a single directory entry
                        // relative to the held fd; no pathname resolution of
                        // attacker components.
                        if unsafe {
                            libc::mkdirat(
                                dir.as_raw_fd(),
                                c.as_ptr(),
                                create_mode.unwrap() as libc::mode_t,
                            )
                        } != 0
                        {
                            // Raced with another creator; if it now exists as a
                            // real directory, use it. A symlink raced into place
                            // still fails O_NOFOLLOW below.
                            if std::io::Error::last_os_error().raw_os_error() == Some(libc::EEXIST)
                            {
                                openat_dir(dir.as_raw_fd(), name)?
                            } else {
                                return Err(std::io::Error::last_os_error().into());
                            }
                        } else {
                            openat_dir(dir.as_raw_fd(), name)?
                        }
                    }
                    Err(e) => return Err(e),
                };
                dir = next;
            }
            Component::ParentDir => {
                return Err(CoreError::sys(libc::EINVAL, "path:parent_component"));
            }
            Component::Prefix(_) => unreachable!("non-Windows path"),
        }
    }
    Ok(dir)
}

/// Resolve `path` from the root down to a directory fd, refusing to traverse
/// any symlink component (ELOOP) or non-directory (ENOTDIR).
fn open_dir_nofollow(path: &Path) -> Result<OwnedFd, CoreError> {
    walk_dir(path, None)
}

fn fstat(fd: RawFd) -> Result<libc::stat, CoreError> {
    let mut st: libc::stat = unsafe { std::mem::zeroed() };
    // SAFETY: `fd` is valid and `st` remains alive for the call.
    if unsafe { libc::fstat(fd, &mut st) } != 0 {
        Err(std::io::Error::last_os_error().into())
    } else {
        Ok(st)
    }
}

fn unlink_name(dirfd: RawFd, name: &str) -> Result<(), CoreError> {
    let c = cstr(name)?;
    // SAFETY: unlinkat without AT_SYMLINK_FOLLOW removes the directory entry
    // itself and never follows a final symlink.
    if unsafe { libc::unlinkat(dirfd, c.as_ptr(), 0) } != 0 {
        Err(std::io::Error::last_os_error().into())
    } else {
        Ok(())
    }
}

fn basename(target: &Path) -> Result<String, CoreError> {
    target
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .ok_or_else(|| CoreError::sys(libc::EINVAL, "path:no_file_name"))
}

fn parent_dir(target: &Path) -> &Path {
    target
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."))
}

/// Open the parent directory of `target` fd-anchored (O_NOFOLLOW walk) and
/// verify it is owned by the current effective uid.
///
/// Requiring ownership on every operation closes the directory-swap vector:
/// an attacker who renames the state dir and substitutes their own can never
/// make the daemon read from or write into the substituted directory, because
/// the substituted dir fails the ownership check regardless of the path.
fn open_parent_nofollow(target: &Path) -> Result<OwnedFd, CoreError> {
    let dir = open_dir_nofollow(parent_dir(target))?;
    let st = fstat(dir.as_raw_fd())?;
    let euid = unsafe { libc::geteuid() };
    if st.st_uid != euid {
        return Err(CoreError::sys(libc::EACCES, "parent_dir_owner"));
    }
    Ok(dir)
}

struct TmpGuard {
    dirfd: RawFd,
    name: String,
}

impl Drop for TmpGuard {
    fn drop(&mut self) {
        let _ = unlink_name(self.dirfd, &self.name);
    }
}

/// Atomically replace `path` with `content`.
///
/// The parent directory is opened `O_NOFOLLOW` component-by-component and held
/// as a directory fd; the content is written to a fresh `O_CREAT|O_EXCL`
/// temp file via `openat` and then `renameat`d over the destination. A symlink
/// anywhere in the parent path fails the open; a symlink at the destination is
/// replaced by the rename, never followed (N5).
pub fn write_atomic(path: impl AsRef<Path>, content: &[u8]) -> Result<(), CoreError> {
    let target = path.as_ref();
    let file_name = basename(target)?;
    let dir = open_parent_nofollow(target)?;
    let dirfd = dir.as_raw_fd();

    for attempt in 0..TEMP_ATTEMPTS {
        let tmp_name = format!(".{file_name}.{}.{attempt}", std::process::id());
        match openat_raw(
            dirfd,
            &tmp_name,
            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_CLOEXEC,
            0o600,
        ) {
            Ok(raw) => {
                // SAFETY: `raw` came from openat with O_EXCL and is uniquely
                // owned; it becomes an owned File for the write.
                let mut file = unsafe { fs::File::from_raw_fd(raw) };
                let _guard = TmpGuard {
                    dirfd,
                    name: tmp_name.clone(),
                };
                file.write_all(content)?;
                file.sync_all()?;
                drop(file);
                let c_tmp = cstr(&tmp_name)?;
                let c_final = cstr(&file_name)?;
                // SAFETY: renameat replaces the destination entry and never
                // follows a final symlink; both names are single components
                // relative to the anchored directory fd.
                if unsafe { libc::renameat(dirfd, c_tmp.as_ptr(), dirfd, c_final.as_ptr()) } != 0 {
                    return Err(std::io::Error::last_os_error().into());
                }
                // rename succeeded; the temp entry no longer exists.
                std::mem::forget(_guard);
                return Ok(());
            }
            Err(e) if e.raw_os_error() == Some(libc::EEXIST) => continue,
            Err(e) => return Err(e),
        }
    }

    Err(CoreError::sys(libc::EEXIST, "temp:exhausted"))
}

/// Read a file to a string, refusing to follow a symlink at the final or any
/// parent component.
///
/// Fails with `ELOOP` if `path` is a symlink or passes through one. Used for
/// reading attacker-placed state files so their contents can never be injected
/// through a link.
pub fn read_nofollow(path: impl AsRef<Path>) -> Result<String, CoreError> {
    let target = path.as_ref();
    let file_name = basename(target)?;
    let dir = open_parent_nofollow(target)?;
    let fd = openat_raw(
        dir.as_raw_fd(),
        &file_name,
        libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
        0,
    )?;
    // SAFETY: `fd` is uniquely owned; it becomes an owned File.
    let mut file = unsafe { fs::File::from_raw_fd(fd) };
    let mut content = String::new();
    file.read_to_string(&mut content)?;
    Ok(content)
}

/// Open an existing-or-create append stream that refuses to follow symlinks.
///
/// Appends to a regular file at `path`. If `path` is a symlink — or sits under
/// a symlinked parent — the open fails with `ELOOP` rather than writing
/// through it.
pub fn open_append_nofollow(path: impl AsRef<Path>) -> Result<fs::File, CoreError> {
    let target = path.as_ref();
    let file_name = basename(target)?;
    let dir = open_parent_nofollow(target)?;
    let fd = openat_raw(
        dir.as_raw_fd(),
        &file_name,
        libc::O_WRONLY | libc::O_CREAT | libc::O_APPEND | libc::O_NOFOLLOW | libc::O_CLOEXEC,
        0o644,
    )?;
    // SAFETY: `fd` is uniquely owned; it becomes an owned File.
    Ok(unsafe { fs::File::from_raw_fd(fd) })
}

/// Remove a directory entry without following a final symlink, anchored to its
/// (symlink-free) parent. The entry itself is removed even if it is a symlink;
/// its target is never touched.
pub fn remove_nofollow(path: impl AsRef<Path>) -> Result<(), CoreError> {
    let target = path.as_ref();
    let file_name = basename(target)?;
    let dir = open_parent_nofollow(target)?;
    unlink_name(dir.as_raw_fd(), &file_name)
}

/// Create `dir` if needed, then verify it is a real directory with no symlink
/// component and that it is owned by the current effective uid. Returning the
/// anchored fd lets callers refuse to operate inside an attacker-pre-created
/// or attacker-redirected state directory.
pub fn ensure_state_dir(dir: impl AsRef<Path>) -> Result<OwnedFd, CoreError> {
    let dir = dir.as_ref();
    // Anchored create-then-verify: missing components are made with mkdirat
    // relative to the held fd; a symlink at any component ELOOPs rather than
    // being followed, and the opened fd below is the authority for ownership.
    let fd = walk_dir(dir, Some(0o700))?;
    let st = fstat(fd.as_raw_fd())?;
    let euid = unsafe { libc::geteuid() };
    if st.st_uid != euid {
        return Err(CoreError::sys(libc::EACCES, "state_dir_owner"));
    }
    Ok(fd)
}

#[cfg(test)]
mod tests {
    #[cfg(target_os = "linux")]
    #[test]
    fn test_readahead_syscall_number_linux_matches_libc() {
        assert_eq!(super::readahead_syscall_number(), libc::SYS_readahead);
    }

    #[cfg(all(target_os = "android", target_arch = "aarch64"))]
    #[test]
    fn test_readahead_syscall_number_android_aarch64() {
        assert_eq!(super::readahead_syscall_number(), 213);
    }

    #[cfg(all(target_os = "android", target_arch = "arm"))]
    #[test]
    fn test_readahead_syscall_number_android_arm() {
        assert_eq!(super::readahead_syscall_number(), 225);
    }

    #[cfg(all(target_os = "android", target_arch = "x86_64"))]
    #[test]
    fn test_readahead_syscall_number_android_x86_64() {
        assert_eq!(super::readahead_syscall_number(), 187);
    }

    #[cfg(all(target_os = "android", target_arch = "x86"))]
    #[test]
    fn test_readahead_syscall_number_android_x86() {
        assert_eq!(super::readahead_syscall_number(), 225);
    }
}

#[cfg(test)]
mod safe_fs_tests {

    use super::*;
    use std::os::unix::fs::symlink;
    use std::path::PathBuf;

    fn tmpdir(name: &str) -> PathBuf {
        let d = std::env::temp_dir().join(format!(
            "coreshift_safe_fs_dir_{}_{name}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&d);
        fs::create_dir_all(&d).unwrap();
        d
    }

    #[test]
    fn test_write_atomic_creates_regular_file() {
        let dir = tmpdir("w");
        let p = dir.join("out.txt");

        write_atomic(&p, b"hello").unwrap();
        assert_eq!(fs::read_to_string(&p).unwrap(), "hello");
        assert!(fs::symlink_metadata(&p).unwrap().file_type().is_file());
    }

    #[test]
    fn test_write_atomic_replaces_existing_symlink_not_target() {
        let dir = tmpdir("s1");
        let target = dir.join("victim");
        let link = dir.join("link");

        fs::write(&target, b"precious").unwrap();
        symlink(&target, &link).unwrap();

        // Write through the symlink: the victim must stay untouched and the
        // path must become a regular file (the symlink is replaced).
        write_atomic(&link, b"new").unwrap();

        assert_eq!(fs::read_to_string(&target).unwrap(), "precious");
        assert_eq!(fs::read_to_string(&link).unwrap(), "new");
        assert!(fs::symlink_metadata(&link).unwrap().file_type().is_file());
    }

    #[test]
    fn test_read_nofollow_refuses_symlink() {
        let dir = tmpdir("r");
        let target = dir.join("victim2");
        let link = dir.join("link2");

        fs::write(&target, b"secret").unwrap();
        symlink(&target, &link).unwrap();

        assert_eq!(read_nofollow(&target).unwrap(), "secret");
        assert!(read_nofollow(&link).is_err());
    }

    #[test]
    fn test_open_append_nofollow_refuses_symlink() {
        let dir = tmpdir("a");
        let target = dir.join("target3");
        let link = dir.join("link3");

        fs::write(&target, b"x").unwrap();
        symlink(&target, &link).unwrap();

        // Append to the regular file is fine.
        assert!(open_append_nofollow(&target).is_ok());
        // Appending through a symlink must fail.
        assert!(open_append_nofollow(&link).is_err());

        let _ = fs::remove_file(&target);
        let _ = fs::remove_file(&link);
    }

    #[test]
    fn test_write_atomic_refuses_symlinked_parent() {
        // An intermediate directory replaced by a symlink must make the
        // anchored open fail, and nothing may be written through to the
        // linked directory.
        let dir = tmpdir("parent_symlink");
        let elsewhere = tmpdir("parent_dest");
        let link = dir.join("coreshift");
        symlink(&elsewhere, &link).unwrap();

        assert!(write_atomic(link.join("payload.txt"), b"boom").is_err());
        assert!(!elsewhere.join("payload.txt").exists());
        assert!(!link.join("payload.txt").exists());
    }

    #[test]
    fn test_read_nofollow_refuses_symlinked_parent() {
        let dir = tmpdir("read_parent_symlink");
        let elsewhere = tmpdir("read_parent_dest");
        fs::write(elsewhere.join("conf"), b"injected").unwrap();
        let link = dir.join("coreshift");
        symlink(&elsewhere, &link).unwrap();

        assert!(read_nofollow(link.join("conf")).is_err());
    }

    #[test]
    fn test_open_append_nofollow_refuses_symlinked_parent() {
        let dir = tmpdir("append_parent_symlink");
        let elsewhere = tmpdir("append_parent_dest");
        let link = dir.join("coreshift");
        symlink(&elsewhere, &link).unwrap();

        assert!(open_append_nofollow(link.join("daemon.log")).is_err());
        assert!(!elsewhere.join("daemon.log").exists());
    }

    #[test]
    fn test_ensure_state_dir_refuses_symlink() {
        let dir = tmpdir("state_symlink");
        let elsewhere = tmpdir("state_dest");
        let link = dir.join("state");
        symlink(&elsewhere, &link).unwrap();

        assert!(ensure_state_dir(&link).is_err());
        // A real directory is accepted (owned by the current euid).
        let real = tmpdir("state_real");
        assert!(ensure_state_dir(&real).is_ok());
    }

    #[test]
    fn test_remove_nofollow_removes_entry_not_target() {
        let dir = tmpdir("unlink");
        let target = dir.join("victim4");
        let link = dir.join("link4");
        fs::write(&target, b"keep").unwrap();
        symlink(&target, &link).unwrap();

        remove_nofollow(&link).unwrap();
        assert!(!link.exists());
        assert_eq!(fs::read_to_string(&target).unwrap(), "keep");
    }

    #[test]
    fn test_write_atomic_requires_parent_to_exist() {
        let dir = tmpdir("missing_parent");
        let p = dir.join("nope").join("file.txt");

        assert!(write_atomic(&p, b"x").is_err());
        assert!(!p.exists());
    }

    #[test]
    fn test_ops_refuse_foreign_owned_parent() {
        // Simulates an attacker who renames the root-owned state dir and
        // substitutes their own: the real (non-symlink) substituted dir must
        // fail every operation because it is not owned by the effective uid.
        // Only exercisable as root (chown); otherwise skipped.
        if unsafe { libc::geteuid() } != 0 {
            return;
        }
        let dir = tmpdir("foreign_owner");
        let path = dir.join("f");
        let owned = cstr(&dir.to_string_lossy()).unwrap();
        // SAFETY: chown to 65534 (nobody) while running as root.
        assert_eq!(unsafe { libc::chown(owned.as_ptr(), 65534, 65534) }, 0);

        assert!(write_atomic(&path, b"x").is_err());
        assert!(read_nofollow(&path).is_err());
        assert!(open_append_nofollow(&path).is_err());
        assert!(remove_nofollow(&path).is_err());
        assert!(ensure_state_dir(&dir).is_err());
        assert!(!path.exists());
    }

    fn temp_leftovers(dir: &Path, file_name: &str) -> Vec<String> {
        let prefix = format!(".{file_name}.");
        fs::read_dir(dir)
            .map(|rd| {
                rd.filter_map(|e| e.ok())
                    .filter_map(|e| e.file_name().to_str().map(str::to_owned))
                    .filter(|n| n.starts_with(&prefix))
                    .collect()
            })
            .unwrap_or_default()
    }

    #[test]
    fn test_write_atomic_cleans_temp_on_rename_failure() {
        // A non-empty directory at the destination forces renameat to fail
        // (EISDIR/ENOTEMPTY) after the temp file has been fully written; the
        // TmpGuard must remove the temp entry.
        let dir = tmpdir("rename_fail");
        let dest = dir.join("dest");
        fs::create_dir_all(&dest).unwrap();
        fs::write(dest.join("keep"), b"x").unwrap();

        assert!(write_atomic(&dest, b"boom").is_err());
        assert_eq!(fs::read_to_string(dest.join("keep")).unwrap(), "x");
        assert!(
            temp_leftovers(&dir, "dest").is_empty(),
            "temp file must be cleaned up"
        );
    }

    #[test]
    fn test_write_atomic_leaves_no_temp_on_success() {
        let dir = tmpdir("no_temp_success");
        let p = dir.join("out.txt");

        write_atomic(&p, b"hello").unwrap();
        assert_eq!(fs::read_to_string(&p).unwrap(), "hello");
        assert!(
            temp_leftovers(&dir, "out.txt").is_empty(),
            "no temp left behind"
        );
    }

    #[test]
    fn test_write_atomic_retries_when_temp_name_exists() {
        let dir = tmpdir("temp_collision");
        let p = dir.join("out.txt");
        let pid = std::process::id();
        let collided = dir.join(format!(".out.txt.{pid}.0"));
        fs::write(&collided, b"not mine").unwrap();

        write_atomic(&p, b"hello").unwrap();
        assert_eq!(fs::read_to_string(&p).unwrap(), "hello");
        // The pre-existing colliding temp is neither clobbered nor mistaken for
        // ours; a later attempt slot is used.
        assert_eq!(fs::read_to_string(&collided).unwrap(), "not mine");
        let leftovers = temp_leftovers(&dir, "out.txt");
        assert_eq!(
            leftovers.len(),
            1,
            "only the pre-existing colliding temp remains"
        );
        assert_eq!(leftovers[0], format!(".out.txt.{pid}.0"));
    }

    #[test]
    fn test_ops_refuse_foreign_owned_writable_parent() {
        // A world-writable directory owned by a uid != euid (e.g. /tmp owned by
        // root) is a privilege-free proxy for a swapped state dir: a vulnerable
        // implementation with no ownership check would happily write into it,
        // while the fixed one must refuse every operation. Runs whenever such a
        // directory is available; skips as root (root owns /tmp).
        use std::os::unix::fs::MetadataExt;
        let euid = unsafe { libc::geteuid() };
        if euid == 0 {
            return;
        }
        let tmp = std::env::temp_dir();
        let meta = match fs::symlink_metadata(&tmp) {
            Ok(m) => m,
            Err(_) => return,
        };
        if meta.uid() == euid {
            return; // no ownership mismatch available in this environment
        }
        if meta.mode() & 0o002 == 0 && meta.mode() & 0o020 == 0 {
            return; // not writable by us; the proxy doesn't apply
        }
        let p = tmp.join(format!(
            "coreshift_fs_foreign_{}_{}",
            std::process::id(),
            "out"
        ));
        let _ = fs::remove_file(&p);
        fs::write(&p, b"probe").unwrap();

        assert!(read_nofollow(&p).is_err());
        assert!(open_append_nofollow(&p).is_err());
        assert!(write_atomic(&p, b"boom").is_err());
        assert!(remove_nofollow(&p).is_err());
        assert!(ensure_state_dir(&tmp).is_err());
        assert_eq!(fs::read_to_string(&p).unwrap(), "probe");
        let _ = fs::remove_file(&p);
    }

    #[test]
    fn test_ensure_state_dir_creates_fresh_dir() {
        let base = tmpdir("fresh_base");
        let nested = base.join("a").join("b").join("state");

        let fd = ensure_state_dir(&nested).unwrap();
        assert!(nested.is_dir());
        drop(fd);
        assert!(ensure_state_dir(&nested).is_ok());
    }

    #[test]
    fn test_open_append_nofollow_refuses_dangling_symlink() {
        let dir = tmpdir("dangling_append");
        let missing = dir.join("not_there.txt");
        let link = dir.join("linkd");
        symlink(&missing, &link).unwrap();

        assert!(open_append_nofollow(&link).is_err());
        assert!(
            !missing.exists(),
            "must not create the target through a dangling link"
        );
    }

    #[test]
    fn test_read_nofollow_refuses_dangling_symlink() {
        let dir = tmpdir("dangling_read");
        let missing = dir.join("not_there2.txt");
        let link = dir.join("linkd2");
        symlink(&missing, &link).unwrap();

        assert!(read_nofollow(&link).is_err());
        assert!(!missing.exists());
    }

    #[test]
    fn test_ops_refuse_regular_file_parent() {
        // A parent component that is a regular file must yield ENOTDIR for
        // every anchored operation — no write-through, no creation.
        let dir = tmpdir("regfile_parent");
        let f = dir.join("notadir");
        fs::write(&f, b"x").unwrap();

        assert!(write_atomic(f.join("out"), b"y").is_err());
        assert!(read_nofollow(f.join("out")).is_err());
        assert!(open_append_nofollow(f.join("out")).is_err());
        assert!(remove_nofollow(f.join("out")).is_err());
        assert!(ensure_state_dir(&f).is_err());
        assert_eq!(fs::read_to_string(&f).unwrap(), "x");
    }
}