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
//! inotify support for working with inotify objects.
//!
//! # Examples
//!
//! ```
//! use rustix::fs::inotify;
//! use rustix::io;
//! use std::mem::MaybeUninit;
//!
//! # fn test() -> io::Result<()> {
//! // Create an inotify object. In this example, we use `NONBLOCK` so that the
//! // reader fails with `WOULDBLOCK` when no events are ready. Otherwise it
//! // will block until at least one event is ready.
//! let inotify = inotify::init(inotify::CreateFlags::NONBLOCK)?;
//!
//! // Add a directory to watch.
//! inotify::add_watch(
//!     &inotify,
//!     "/path/to/some/directory/to/watch",
//!     inotify::WatchFlags::ALL_EVENTS,
//! )?;
//!
//! // Generate some events in the watched directory…
//!
//! // Loop over pending events.
//! let mut buf = [MaybeUninit::uninit(); 512];
//! let mut iter = inotify::Reader::new(inotify, &mut buf);
//! loop {
//!     let entry = match iter.next() {
//!         // Stop iterating if there are no more events for now.
//!         Err(io::Errno::WOULDBLOCK) => break,
//!         Err(e) => return Err(e),
//!         Ok(entry) => entry,
//!     };
//!
//!     // Use `entry`…
//! }
//!
//! # Ok(())
//! # }

#![allow(unused_qualifications)]

use super::inotify;
pub use crate::backend::fs::inotify::{CreateFlags, ReadFlags, WatchFlags};
use crate::backend::fs::syscalls;
use crate::fd::{AsFd, OwnedFd};
use crate::ffi::CStr;
use crate::io;
use crate::io::{read_uninit, Errno};
use core::mem::{align_of, size_of, MaybeUninit};
use linux_raw_sys::general::inotify_event;

#[deprecated(note = "Use `inotify::add_watch`.")]
#[doc(hidden)]
pub use add_watch as inotify_add_watch;
#[deprecated(note = "Use `inotify::init`.")]
#[doc(hidden)]
pub use init as inotify_init;
#[deprecated(note = "Use `inotify::remove_watch`.")]
#[doc(hidden)]
pub use remove_watch as inotify_remove_watch;

/// `inotify_init1(flags)`—Creates a new inotify object.
///
/// Use the [`CreateFlags::CLOEXEC`] flag to prevent the resulting file
/// descriptor from being implicitly passed across `exec` boundaries.
#[doc(alias = "inotify_init1")]
#[inline]
pub fn init(flags: inotify::CreateFlags) -> io::Result<OwnedFd> {
    syscalls::inotify_init1(flags)
}

/// `inotify_add_watch(self, path, flags)`—Adds a watch to inotify.
///
/// This registers or updates a watch for the filesystem path `path` and
/// returns a watch descriptor corresponding to this watch.
///
/// Note: Due to the existence of hardlinks, providing two different paths to
/// this method may result in it returning the same watch descriptor. An
/// application should keep track of this externally to avoid logic errors.
#[doc(alias = "inotify_add_watch")]
#[inline]
pub fn add_watch<P: crate::path::Arg>(
    inot: impl AsFd,
    path: P,
    flags: inotify::WatchFlags,
) -> io::Result<i32> {
    path.into_with_c_str(|path| syscalls::inotify_add_watch(inot.as_fd(), path, flags))
}

/// `inotify_rm_watch(self, wd)`—Removes a watch from this inotify.
///
/// The watch descriptor provided should have previously been returned by
/// [`inotify::add_watch`] and not previously have been removed.
#[doc(alias = "inotify_rm_watch")]
#[inline]
pub fn remove_watch(inot: impl AsFd, wd: i32) -> io::Result<()> {
    syscalls::inotify_rm_watch(inot.as_fd(), wd)
}

/// An inotify event iterator implemented with the read syscall.
///
/// See the [`RawDir`] API for more details and usage examples as this API is
/// based on it.
///
/// [`RawDir`]: crate::fs::raw_dir::RawDir
pub struct Reader<'buf, Fd: AsFd> {
    fd: Fd,
    buf: &'buf mut [MaybeUninit<u8>],
    initialized: usize,
    offset: usize,
}

impl<'buf, Fd: AsFd> Reader<'buf, Fd> {
    /// Create a new iterator from the given file descriptor and buffer.
    pub fn new(fd: Fd, buf: &'buf mut [MaybeUninit<u8>]) -> Self {
        Self {
            fd,
            buf: {
                let offset = buf.as_ptr().align_offset(align_of::<inotify_event>());
                if offset < buf.len() {
                    &mut buf[offset..]
                } else {
                    &mut []
                }
            },
            initialized: 0,
            offset: 0,
        }
    }
}

/// An inotify event.
#[derive(Debug)]
pub struct InotifyEvent<'a> {
    wd: i32,
    events: ReadFlags,
    cookie: u32,
    file_name: Option<&'a CStr>,
}

impl<'a> InotifyEvent<'a> {
    /// Returns the watch for which this event occurs.
    #[inline]
    pub fn wd(&self) -> i32 {
        self.wd
    }

    /// Returns a description of the events.
    #[inline]
    #[doc(alias = "mask")]
    pub fn events(&self) -> ReadFlags {
        self.events
    }

    /// Returns the unique cookie associating related events.
    #[inline]
    pub fn cookie(&self) -> u32 {
        self.cookie
    }

    /// Returns the file name of this event, if any.
    #[inline]
    pub fn file_name(&self) -> Option<&CStr> {
        self.file_name
    }
}

impl<'buf, Fd: AsFd> Reader<'buf, Fd> {
    /// Read the next inotify event.
    ///
    /// This is similar to `[Iterator::next`] except that it doesn't return an
    /// `Option`, because the stream doesn't have an ending. It always returns
    /// events or errors.
    ///
    /// If there are no events in the buffer and none ready to be read:
    ///  - If the file descriptor was opened with
    ///    [`inotify::CreateFlags::NONBLOCK`], this will fail with
    ///    [`Errno::AGAIN`].
    ///  - Otherwise this will block until at least one event is ready or an
    ///    error occurs.
    #[allow(unsafe_code)]
    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> io::Result<InotifyEvent<'_>> {
        if self.is_buffer_empty() {
            match read_uninit(self.fd.as_fd(), self.buf).map(|(init, _)| init.len()) {
                Ok(0) => return Err(Errno::INVAL),
                Ok(bytes_read) => {
                    self.initialized = bytes_read;
                    self.offset = 0;
                }
                Err(e) => return Err(e),
            }
        }

        let ptr = self.buf[self.offset..].as_ptr();

        // SAFETY:
        // - This data is initialized by the check above.
        //   - Assumption: the kernel will not give us partial structs.
        // - Assumption: the kernel uses proper alignment between structs.
        // - The starting pointer is aligned (performed in `Reader::new`).
        let event = unsafe { &*ptr.cast::<inotify_event>() };

        self.offset += size_of::<inotify_event>() + usize::try_from(event.len).unwrap();

        Ok(InotifyEvent {
            wd: event.wd,
            events: ReadFlags::from_bits_retain(event.mask),
            cookie: event.cookie,
            file_name: if event.len > 0 {
                // SAFETY: The kernel guarantees a NUL-terminated string.
                Some(unsafe { CStr::from_ptr(event.name.as_ptr().cast()) })
            } else {
                None
            },
        })
    }

    /// Returns true if the internal buffer is empty and will be refilled when
    /// calling [`next`]. This is useful to avoid further blocking reads.
    ///
    /// [`next`]: Self::next
    pub fn is_buffer_empty(&self) -> bool {
        self.offset >= self.initialized
    }
}