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
use std::ffi;
use std::io;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::io::{AsRawFd, RawFd};
use std::path::Path;

use bitflags::bitflags;

use super::constants;

bitflags! {
    pub struct Events: u32 {
        const OPEN = libc::IN_OPEN;
        const ATTRIB = libc::IN_ATTRIB;
        const ACCESS = libc::IN_ACCESS;
        const MODIFY = libc::IN_MODIFY;

        const CLOSE_WRITE = libc::IN_CLOSE_WRITE;
        const CLOSE_NOWRITE = libc::IN_CLOSE_NOWRITE;

        const CREATE = libc::IN_CREATE;
        const DELETE = libc::IN_DELETE;

        const DELETE_SELF = libc::IN_DELETE_SELF;
        const MOVE_SELF = libc::IN_MOVE_SELF;

        const MOVED_FROM = libc::IN_MOVED_FROM;
        const MOVED_TO = libc::IN_MOVED_TO;

        const MOVE = libc::IN_MOVE;
        const CLOSE = libc::IN_CLOSE;
        const ALL_EVENTS = libc::IN_ALL_EVENTS;
    }
}

bitflags! {
    pub struct WatchFlags: u32 {
        const DONT_FOLLOW = libc::IN_DONT_FOLLOW;
        const ONESHOT = libc::IN_ONESHOT;
        const ONLYDIR = libc::IN_ONLYDIR;

        const EXCL_UNLINK = constants::IN_EXCL_UNLINK;
    }
}

bitflags! {
    pub struct EventFlags: u32 {
        const IGNORED = libc::IN_IGNORED;
        const ISDIR = libc::IN_ISDIR;
        const Q_OVERFLOW = libc::IN_Q_OVERFLOW;
        const UNMOUNT = libc::IN_UNMOUNT;
    }
}

#[derive(Clone, Debug)]
pub struct Event {
    pub watch: Watch,
    pub events: Events,
    pub flags: EventFlags,
    pub cookie: u32,
    pub name: ffi::OsString,
}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct Watch {
    wd: i32,
}

bitflags! {
    #[derive(Default)]
    pub struct InotifyFlags: i32 {
        const NONBLOCK = libc::IN_NONBLOCK;
        const CLOEXEC = libc::IN_CLOEXEC;
    }
}

#[derive(Debug)]
pub struct Inotify {
    fd: i32,
}

const RAW_EVENT_SIZE: usize = std::mem::size_of::<libc::inotify_event>();

impl Inotify {
    /// Construct a new inotify file descriptor with the given options.
    pub fn new(flags: InotifyFlags) -> io::Result<Self> {
        super::error::convert_neg_ret(unsafe { libc::inotify_init1(flags.bits) })
            .map(|fd| Self { fd })
    }

    fn add_watch_impl<P: AsRef<Path>>(&mut self, path: P, flags: u32) -> io::Result<Watch> {
        let c_path = ffi::CString::new(path.as_ref().as_os_str().as_bytes())?;

        super::error::convert_neg_ret(unsafe {
            libc::inotify_add_watch(self.fd, c_path.as_ptr(), flags)
        })
        .map(|wd| Watch { wd })
    }

    /// Add a new watch (or modify an existing watch) for the given file.
    #[inline]
    pub fn add_watch<P: AsRef<Path>>(
        &mut self,
        path: P,
        events: Events,
        flags: WatchFlags,
    ) -> io::Result<Watch> {
        self.add_watch_impl(path, events.bits | flags.bits)
    }

    /// Add a new watch for the given file, or extend the watch mask if the watch already exists.
    #[inline]
    pub fn extend_watch<P: AsRef<Path>>(
        &mut self,
        path: P,
        events: Events,
        flags: WatchFlags,
    ) -> io::Result<Watch> {
        self.add_watch_impl(path, events.bits | flags.bits | constants::IN_MASK_ADD)
    }

    /// Add a new watch for the given file, failing with an error if the event already exists
    #[inline]
    pub fn create_watch<P: AsRef<Path>>(
        &mut self,
        path: P,
        events: Events,
        flags: WatchFlags,
    ) -> io::Result<Watch> {
        self.add_watch_impl(path, events.bits | flags.bits | constants::IN_MASK_CREATE)
    }

    /// Remove a previously added watch.
    pub fn rm_watch(&mut self, watch: Watch) -> io::Result<()> {
        super::error::convert_nzero(unsafe { libc::inotify_rm_watch(self.fd, watch.wd) }, ())
    }

    /// Read a list of events from the inotify file descriptor, or return an
    /// empty vector if no events are pending.
    pub fn read_nowait(&mut self) -> io::Result<Vec<Event>> {
        // See how much data is ready for reading
        let mut nbytes: i32 = 0;
        super::error::convert_nzero(
            unsafe { libc::ioctl(self.fd, libc::FIONREAD, &mut nbytes) },
            (),
        )?;

        // No data? Return an empty vector.
        if nbytes == 0 {
            return Ok(Vec::new());
        }

        // Prepare a buffer
        let mut buf: Vec<u8> = Vec::new();
        buf.resize(nbytes as usize, 0);

        // Read the data
        let nbytes: isize = super::error::convert_neg_ret(unsafe {
            libc::read(
                self.fd,
                buf.as_mut_ptr() as *mut libc::c_void,
                nbytes as usize,
            )
        })?;

        // Trim down if we read less data
        buf.resize(nbytes as usize, 0);

        Ok(Self::parse_multi(&buf))
    }

    /// Read a list of events from the inotify file descriptor, waiting for
    /// an event to occur if none are pending.
    ///
    /// Note: The current implementation of this function may not read *all* of the
    /// events from the the inotify file descriptor. If that is necessary for whatever
    /// reason, it is recommended to immediately follow a call to `read_wait()` with a
    /// call to `read_nowait()` and combine the two resulting vectors.
    pub fn read_wait(&mut self) -> io::Result<Vec<Event>> {
        let mut buf: Vec<u8> = Vec::new();

        // In the extremely rare event that this isn't enough to read a single event, we'll expand it later.
        // In practice, it'll usually be enough to read at least a few dozen events.
        buf.resize(4096, 0);

        let mut i = 0;
        loop {
            match super::error::convert_neg_ret(unsafe {
                libc::read(self.fd, buf.as_mut_ptr() as *mut libc::c_void, buf.len())
            }) {
                Ok(nbytes) => {
                    // Trim down to size
                    buf.resize(nbytes as usize, 0);

                    // And parse the events
                    return Ok(Self::parse_multi(&buf));
                }
                Err(e) => {
                    if i < 10 && super::error::is_einval(&e) {
                        buf.resize(buf.len() * 2, 0);
                    } else {
                        return Err(e);
                    }
                }
            }

            i += 1;
        }
    }

    fn parse_multi(data: &[u8]) -> Vec<Event> {
        let mut events: Vec<Event> = Vec::new();
        let mut offset: usize = 0;
        while offset < data.len() {
            let (event, inc) = Self::parse_one(&data[offset..]);
            events.push(event);
            offset += inc;
        }

        events
    }

    fn parse_one(data: &[u8]) -> (Event, usize) {
        debug_assert!(data.len() >= RAW_EVENT_SIZE);

        // Extract the raw event
        #[allow(clippy::transmute_ptr_to_ref)]
        let raw_event =
            unsafe { std::mem::transmute::<*const u8, &libc::inotify_event>(data.as_ptr()) };

        // Extract the name.
        //
        // We skip over the initial structure,
        // limit our traversal to the length we were given,
        // stop at the first null byte,
        // clone the elements so we don't have to mess with references,
        // collect into a vector,
        // and convert that into an OsString.
        let name = ffi::OsString::from_vec(
            data.iter()
                .skip(RAW_EVENT_SIZE)
                .take(raw_event.len as usize)
                .take_while(|x| **x != 0)
                .cloned()
                .collect(),
        );

        // Now return the events and the number of bytes we consumed.
        (
            Event {
                watch: Watch { wd: raw_event.wd },
                events: Events::from_bits_truncate(raw_event.mask),
                flags: EventFlags::from_bits_truncate(raw_event.mask),
                cookie: raw_event.cookie,
                name,
            },
            RAW_EVENT_SIZE + raw_event.len as usize,
        )
    }
}

impl AsRawFd for Inotify {
    #[inline]
    fn as_raw_fd(&self) -> RawFd {
        self.fd
    }
}

impl Drop for Inotify {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            libc::close(self.fd);
        }
    }
}