Skip to content

Commit

Permalink
Merge pull request #16 from tanveerraza789/master
Browse files Browse the repository at this point in the history
Version 0.2.0
  • Loading branch information
atamakahere-git authored Apr 20, 2023
2 parents 9905cfd + bd6dd17 commit bda90da
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 84 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ license = "AGPL-3.0-only"
repository = "https://github.com/SubconsciousCompute/naughtyfy.git"
documentation = "https://docs.rs/naughtyfy"
authors = ["Tanveer Raza <[email protected]>"]
version = "0.1.1"
version = "0.2.0"
edition = "2021"


Expand Down
8 changes: 3 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

A modern fanotify wrapper.

~~Note: This is still under development.~~ <br>
I guess it's in usable state, Open issue
for any feature/bug.
Open issue for any feature/bug.

## Example

Expand Down Expand Up @@ -48,10 +46,10 @@ fn main() {
- Documented
- Desciptive errors
- Only 1 dependency (libc)

Even though it's not designed to be blazzingly fast but is comparable. Will get better with further updates.
- and, Fast ofc.

## TODO

- [ ] Add more example
- [ ] Higher level API maybe?

Expand Down
1 change: 1 addition & 0 deletions examples/dir_events.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use naughtyfy::api::*;
use naughtyfy::flags::*;
use naughtyfy::types::Fd;
use naughtyfy::types::FdToPath;

/// Using naughtyfy to report(print) all
/// file access, modify, close, open events (for files)
Expand Down
22 changes: 13 additions & 9 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ use std::{
ffi::CString,
io::Error,
mem,
os::{fd::RawFd, unix::ffi::OsStrExt},
os::{
fd::{AsRawFd, FromRawFd, OwnedFd as Fd},
unix::ffi::OsStrExt,
},
};

// Used for docs test
Expand Down Expand Up @@ -96,6 +99,7 @@ pub static mut FAN_EVENT_BUFFER_LEN: std::sync::Mutex<usize> = std::sync::Mutex:
/// ```rust
/// # use naughtyfy::flags::*;
/// # use naughtyfy::api::*;
/// # use naughtyfy::types::*;
/// let fd = init(FAN_CLASS_NOTIF | FAN_NONBLOCK, O_RDONLY);
/// match fd {
/// Ok(fd) => {
Expand All @@ -114,7 +118,7 @@ pub fn init(flags: u32, event_f_flags: u32) -> Result<Fd, FanotifyError> {
-1 => Err(FanotifyError::Init(
Error::last_os_error().raw_os_error().unwrap_or_default(),
)),
fd => Ok(fd.into()),
fd => Ok(Fd::from_raw_fd(fd)),
}
}
}
Expand Down Expand Up @@ -214,7 +218,7 @@ pub fn mark<P: ?Sized + Path>(
) -> Result<(), FanotifyError> {
let path = CString::new(path.as_os_str().as_bytes()).unwrap_or_default();
unsafe {
match libc::fanotify_mark(fd.into(), flags, mask, dirfd, path.as_ptr()) {
match libc::fanotify_mark(fd.as_raw_fd(), flags, mask, dirfd, path.as_ptr()) {
0 => Ok(()),
_ => Err(FanotifyError::Mark(
Error::last_os_error().raw_os_error().unwrap_or_default(),
Expand Down Expand Up @@ -274,7 +278,7 @@ pub fn read(fd: &Fd) -> Result<Vec<fanotify_event_metadata>, FanotifyError> {
unsafe {
// `libc::read()` is unsafe
sizeof = libc::read(
fd.into(),
fd.as_raw_fd(),
buff.as_mut_ptr() as *mut c_void,
FAN_EVENT_METADATA_LEN * len,
);
Expand Down Expand Up @@ -351,7 +355,7 @@ pub fn read_do(
unsafe {
// `libc::read()` is unsafe
sizeof = libc::read(
fd.into(),
fd.as_raw_fd(),
buff.as_mut_ptr() as *mut c_void,
FAN_EVENT_METADATA_LEN * len,
);
Expand Down Expand Up @@ -400,7 +404,7 @@ pub fn read_with_fid(fd: &Fd) -> Result<Vec<fanotify_event_with_fid>, FanotifyEr
let sizeof;
unsafe {
sizeof = libc::read(
fd.into(),
fd.as_raw_fd(),
buff.as_mut_ptr() as *mut c_void,
FAN_EVENT_METADATA_FID_LEN * len,
);
Expand Down Expand Up @@ -447,7 +451,7 @@ pub fn read_with_fid_do(
unsafe {
// `libc::read()` is unsafe
sizeof = libc::read(
fd.into(),
fd.as_raw_fd(),
buff.as_mut_ptr() as *mut c_void,
FAN_EVENT_METADATA_FID_LEN * len,
);
Expand Down Expand Up @@ -542,7 +546,7 @@ pub fn read_with_fid_do(
pub fn write(fd: &Fd, response: &fanotify_response) -> Result<isize, FanotifyError> {
unsafe {
match libc::write(
fd.into(),
fd.as_raw_fd(),
response as *const fanotify_response as *const libc::c_void,
FAN_WRITE_RESPONSE_LEN,
) {
Expand All @@ -558,7 +562,7 @@ pub fn write(fd: &Fd, response: &fanotify_response) -> Result<isize, FanotifyErr
///
/// # Argument
/// * `fd` - file descriptor in raw form ([`RawFd`])`
pub fn close(fd: RawFd) -> Result<(), FanotifyError> {
pub fn close(fd: std::os::fd::RawFd) -> Result<(), FanotifyError> {
unsafe {
match libc::close(fd) {
0 => Ok(()),
Expand Down
101 changes: 32 additions & 69 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,83 +3,18 @@
use libc::{__s32, __u16, __u32, __u64, __u8, c_int};
use std::ffi::OsStr;
use std::os::fd::RawFd;
use std::os::fd::AsRawFd;
pub use std::os::fd::OwnedFd as Fd;

// For documentaton linking
#[allow(unused_imports)]
use crate::api::*;
#[allow(unused_imports)]
use crate::flags::*;

/// An inter convertable between [`RawFd`] struct that hold fd and provides
/// fd-related functionality with auto-close using drop trait
#[derive(Debug, Clone)]
pub struct Fd {
/// [`RawFd`] type that holds the file descriptors.
inner: RawFd,
}

impl Fd {
/// Constructs a new [`Fd`] using [`RawFd`]
#[inline]
pub fn new(fd: RawFd) -> Self {
Self { inner: fd }
}

/// Get the [`std::path::PathBuf`] related to the fd.
#[inline]
pub fn path(&self) -> Result<std::path::PathBuf, std::io::Error> {
std::fs::read_link(format!("/proc/self/fd/{}", self.inner))
}

/// Get the [`std::path::PathBuf`] related to the [`RawFd`] provided.
#[inline]
pub fn path_from_rawfd(fd: RawFd) -> Result<std::path::PathBuf, std::io::Error> {
std::fs::read_link(format!("/proc/self/fd/{}", fd))
}

/// Check if the fd is valid or not
#[inline]
pub fn is_valid(&self) -> bool {
self.inner >= 0
}
}

/// Closing file desriptor
impl Drop for Fd {
fn drop(&mut self) {
if let Err(e) = close(self.inner) {
eprintln!("(fd dropper)Fd :: {}\nErr :: {}", self.inner, e);
}
}
}

/// [`RawFd`] -> [`Fd`] convertion
impl From<RawFd> for Fd {
/// Construct [`Fd`] from [`RawFd`]
fn from(fd: RawFd) -> Self {
Self { inner: fd }
}
}

/// [`RawFd`] -> &[`Fd`] convertion
impl From<&Fd> for RawFd {
/// Converts [`RawFd`] to [`Fd`]
fn from(val: &Fd) -> Self {
val.inner
}
}

/// [`Fd`] -> [`RawFd`] conversion
impl From<Fd> for RawFd {
/// Converts [`RawFd`] to [`Fd`]
fn from(fd: Fd) -> Self {
fd.inner
}
}

/// After a successful read(2), the read buffer contains the following structure
#[derive(Debug, Clone)]
#[allow(non_camel_case_types)]
#[repr(C)]
pub struct fanotify_event_metadata {
/// This is the length of the data for the current event and
Expand Down Expand Up @@ -257,7 +192,7 @@ impl fanotify_response {
/// type from flags
pub fn new(fd: &Fd, response: __u32) -> Self {
fanotify_response {
fd: fd.inner,
fd: fd.as_raw_fd(),
response,
}
}
Expand Down Expand Up @@ -303,3 +238,31 @@ impl Path for String {
OsStr::new(self.as_str())
}
}

/// Trait that adds path conversion to [`Fd`] type
pub trait FdToPath {
fn path(&self) -> Result<std::path::PathBuf, std::io::Error>;
fn path_from_rawfd(fd: std::os::fd::RawFd) -> Result<std::path::PathBuf, std::io::Error>;
fn is_valid(&self) -> bool;
}

/// Adding path conversion ability to [`Fd`] type
impl FdToPath for Fd {
/// Get the [`std::path::PathBuf`] related to the fd.
#[inline]
fn path(&self) -> Result<std::path::PathBuf, std::io::Error> {
std::fs::read_link(format!("/proc/self/fd/{}", self.as_raw_fd()))
}

/// Get the [`std::path::PathBuf`] related to the [`RawFd`] provided.
#[inline]
fn path_from_rawfd(fd: std::os::fd::RawFd) -> Result<std::path::PathBuf, std::io::Error> {
std::fs::read_link(format!("/proc/self/fd/{}", fd))
}

/// Check if the fd is valid or not
#[inline]
fn is_valid(&self) -> bool {
self.as_raw_fd() >= 0
}
}

0 comments on commit bda90da

Please sign in to comment.