Skip to main content

dope_uring/watch/
raw.rs

1use std::{ffi::CStr, mem, num::NonZero, os::fd};
2
3use dope_sys::{Errno, kernel};
4
5use super::{Event, Watch};
6
7pub(super) fn create(path: &CStr) -> Result<fd::OwnedFd, Errno> {
8    use fd::AsRawFd as _;
9
10    // SAFETY: init transfers one descriptor or leaves this thread's errno.
11    let file = unsafe {
12        <fd::OwnedFd as dope_sys::io::fd::raw::Adopt>::try_adopt::<crate::Uring, Errno>(
13            libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC),
14        )
15    }?;
16    // SAFETY: the descriptor and terminated path stay live for this one registration.
17    let raw = unsafe {
18        libc::inotify_add_watch(
19            file.as_raw_fd(),
20            path.as_ptr(),
21            libc::IN_MOVED_TO
22                | libc::IN_MOVE_SELF
23                | libc::IN_DELETE_SELF
24                | libc::IN_ONLYDIR
25                | libc::IN_DONT_FOLLOW,
26        )
27    };
28    // SAFETY: add_watch returns a nonnegative watch id or -1 with unchanged errno.
29    unsafe { kernel::raw::Status::new(raw).try_value::<crate::Uring, Errno>() }?;
30    Ok(file)
31}
32
33pub struct Events<'a>(&'a [u8]);
34
35/// # Safety
36/// Bytes contain complete initialized inotify records with nonzero event masks.
37pub unsafe fn events<'a>(_: &Watch, bytes: &'a [u8]) -> Events<'a> {
38    Events(bytes)
39}
40
41impl<'a> Iterator for Events<'a> {
42    type Item = Event<'a>;
43
44    fn next(&mut self) -> Option<Self::Item> {
45        if self.0.is_empty() {
46            return None;
47        }
48        const HEADER: usize = mem::size_of::<libc::inotify_event>();
49        // SAFETY: the retained native prefix consists of complete initialized records.
50        let event = unsafe {
51            self.0
52                .as_ptr()
53                .cast::<libc::inotify_event>()
54                .read_unaligned()
55        };
56        // SAFETY: the native length bounds this complete record within the admitted read.
57        let (record, rest) = unsafe { self.0.split_at_unchecked(HEADER + event.len as usize) };
58        self.0 = rest;
59        Some(match event.mask & !libc::IN_ISDIR {
60            libc::IN_MOVED_TO => Event::MovedIn(&record[HEADER..]),
61            libc::IN_Q_OVERFLOW => Event::Overflow,
62            // SAFETY: every admitted native record carries a nonzero event mask.
63            _ => Event::Invalidated(unsafe { NonZero::new_unchecked(event.mask) }),
64        })
65    }
66}