Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add option to open a directory #1210

Merged
merged 1 commit into from
May 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/fd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ bitflags! {
const O_TRUNC = 0o1000;
const O_APPEND = 0o2000;
const O_DIRECT = 0o40000;
const O_DIRECTORY = 0o200000;
}
}

Expand Down
191 changes: 156 additions & 35 deletions src/fs/fuse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,103 @@ impl Clone for FuseFileHandle {
}
}

#[derive(Debug, Clone)]
pub struct FuseDirectoryHandle {
name: Option<String>,
}

impl FuseDirectoryHandle {
pub fn new(name: Option<String>) -> Self {
Self { name }
}
}

#[async_trait]
impl ObjectInterface for FuseDirectoryHandle {
fn readdir(&self) -> Result<Vec<DirectoryEntry>, IoError> {
let path: String = if let Some(name) = &self.name {
"/".to_string() + name
} else {
"/".to_string()
};

debug!("FUSE opendir: {}", path);

let fuse_nid = lookup(&path).ok_or(IoError::ENOENT)?;

// Opendir
// Flag 0x10000 for O_DIRECTORY might not be necessary
let (mut cmd, mut rsp) = ops::Open::create(fuse_nid, 0x10000);
cmd.in_header.opcode = fuse_abi::Opcode::Opendir as u32;
get_filesystem_driver()
.ok_or(IoError::ENOSYS)?
.lock()
.send_command(cmd.as_ref(), rsp.as_mut())?;
let fuse_fh = unsafe { rsp.op_header.assume_init_ref().fh };

debug!("FUSE readdir: {}", path);

// Linux seems to allocate a single page to store the dirfile
let len = MAX_READ_LEN as u32;
let mut offset: usize = 0;

// read content of the directory
let (mut cmd, mut rsp) = ops::Read::create(fuse_nid, fuse_fh, len, 0);
cmd.in_header.opcode = fuse_abi::Opcode::Readdir as u32;
get_filesystem_driver()
.ok_or(IoError::ENOSYS)?
.lock()
.send_command(cmd.as_ref(), rsp.as_mut())?;

let len: usize = if unsafe { rsp.out_header.assume_init_ref().len } as usize
- ::core::mem::size_of::<fuse_abi::OutHeader>()
- ::core::mem::size_of::<fuse_abi::ReadOut>()
>= len.try_into().unwrap()
{
len.try_into().unwrap()
} else {
(unsafe { rsp.out_header.assume_init_ref().len } as usize)
- ::core::mem::size_of::<fuse_abi::OutHeader>()
- ::core::mem::size_of::<fuse_abi::ReadOut>()
};

if len <= core::mem::size_of::<fuse_abi::Dirent>() {
debug!("FUSE no new dirs");
return Err(IoError::ENOENT);
}

let mut entries: Vec<DirectoryEntry> = Vec::new();
while (unsafe { rsp.out_header.assume_init_ref().len } as usize) - offset
> core::mem::size_of::<fuse_abi::Dirent>()
{
let dirent =
unsafe { &*(rsp.payload.as_ptr().byte_add(offset) as *const fuse_abi::Dirent) };

offset += core::mem::size_of::<fuse_abi::Dirent>() + dirent.d_namelen as usize;
// Align to dirent struct
offset = ((offset) + U64_SIZE - 1) & (!(U64_SIZE - 1));

let name: &'static [u8] = unsafe {
core::slice::from_raw_parts(
dirent.d_name.as_ptr(),
dirent.d_namelen.try_into().unwrap(),
)
};
entries.push(DirectoryEntry::new(unsafe {
core::str::from_utf8_unchecked(name).to_string()
}));
}

let (cmd, mut rsp) = ops::Release::create(fuse_nid, fuse_fh);
get_filesystem_driver()
.unwrap()
.lock()
.send_command(cmd.as_ref(), rsp.as_mut())?;

Ok(entries)
}
}

#[derive(Debug)]
pub(crate) struct FuseDirectory {
prefix: Option<String>,
Expand Down Expand Up @@ -888,6 +985,10 @@ impl VfsNode for FuseDirectory {
Ok(self.attr)
}

fn get_object(&self) -> Result<Arc<dyn ObjectInterface>, IoError> {
Ok(Arc::new(FuseDirectoryHandle::new(self.prefix.clone())))
}

fn traverse_readdir(&self, components: &mut Vec<&str>) -> Result<Vec<DirectoryEntry>, IoError> {
let path: String = if components.is_empty() {
if let Some(prefix) = &self.prefix {
Expand Down Expand Up @@ -1071,7 +1172,7 @@ impl VfsNode for FuseDirectory {
opt: OpenOption,
mode: AccessPermission,
) -> Result<Arc<dyn ObjectInterface>, IoError> {
let path: String = if components.is_empty() {
let mut path: String = if components.is_empty() {
if let Some(prefix) = &self.prefix {
"/".to_string() + prefix
} else {
Expand All @@ -1091,49 +1192,69 @@ impl VfsNode for FuseDirectory {
}
};

debug!("FUSE open: {}, {:?} {:?}", path, opt, mode);
debug!("FUSE lstat: {}", path);

let file = FuseFileHandle::new();
let (cmd, mut rsp) = ops::Lookup::create(&path);
get_filesystem_driver()
.unwrap()
.lock()
.send_command(cmd.as_ref(), rsp.as_mut())?;

// 1.FUSE_INIT to create session
// Already done
let mut file_guard = block_on(async { Ok(file.0.lock().await) }, None)?;
let attr = unsafe { FileAttr::from(rsp.op_header.assume_init().attr) };
let is_dir = attr.st_mode.contains(AccessPermission::S_IFDIR);

// Differentiate between opening and creating new file, since fuse does not support O_CREAT on open.
if !opt.contains(OpenOption::O_CREAT) {
// 2.FUSE_LOOKUP(FUSE_ROOT_ID, “foo”) -> nodeid
file_guard.fuse_nid = lookup(&path);
debug!("FUSE open: {}, {:?} {:?}", path, opt, mode);

if file_guard.fuse_nid.is_none() {
warn!("Fuse lookup seems to have failed!");
return Err(IoError::ENOENT);
if is_dir {
path.remove(0);
Ok(Arc::new(FuseDirectoryHandle::new(Some(path))))
} else {
if opt.contains(OpenOption::O_DIRECTORY) {
return Err(IoError::ENOTDIR);
}

// 3.FUSE_OPEN(nodeid, O_RDONLY) -> fh
let (cmd, mut rsp) =
ops::Open::create(file_guard.fuse_nid.unwrap(), opt.bits().try_into().unwrap());
get_filesystem_driver()
.ok_or(IoError::ENOSYS)?
.lock()
.send_command(cmd.as_ref(), rsp.as_mut())?;
file_guard.fuse_fh = Some(unsafe { rsp.op_header.assume_init_ref().fh });
} else {
// Create file (opens implicitly, returns results from both lookup and open calls)
let (cmd, mut rsp) =
ops::Create::create(&path, opt.bits().try_into().unwrap(), mode.bits());
get_filesystem_driver()
.ok_or(IoError::ENOSYS)?
.lock()
.send_command(cmd.as_ref(), rsp.as_mut())?;
let file = FuseFileHandle::new();

let inner = unsafe { rsp.op_header.assume_init() };
file_guard.fuse_nid = Some(inner.entry.nodeid);
file_guard.fuse_fh = Some(inner.open.fh);
}
// 1.FUSE_INIT to create session
// Already done
let mut file_guard = block_on(async { Ok(file.0.lock().await) }, None)?;

drop(file_guard);
// Differentiate between opening and creating new file, since fuse does not support O_CREAT on open.
if !opt.contains(OpenOption::O_CREAT) {
// 2.FUSE_LOOKUP(FUSE_ROOT_ID, “foo”) -> nodeid
file_guard.fuse_nid = lookup(&path);

Ok(Arc::new(file))
if file_guard.fuse_nid.is_none() {
warn!("Fuse lookup seems to have failed!");
return Err(IoError::ENOENT);
}

// 3.FUSE_OPEN(nodeid, O_RDONLY) -> fh
let (cmd, mut rsp) =
ops::Open::create(file_guard.fuse_nid.unwrap(), opt.bits().try_into().unwrap());
get_filesystem_driver()
.ok_or(IoError::ENOSYS)?
.lock()
.send_command(cmd.as_ref(), rsp.as_mut())?;
file_guard.fuse_fh = Some(unsafe { rsp.op_header.assume_init_ref().fh });
} else {
// Create file (opens implicitly, returns results from both lookup and open calls)
let (cmd, mut rsp) =
ops::Create::create(&path, opt.bits().try_into().unwrap(), mode.bits());
get_filesystem_driver()
.ok_or(IoError::ENOSYS)?
.lock()
.send_command(cmd.as_ref(), rsp.as_mut())?;

let inner = unsafe { rsp.op_header.assume_init() };
file_guard.fuse_nid = Some(inner.entry.nodeid);
file_guard.fuse_fh = Some(inner.open.fh);
}

drop(file_guard);

Ok(Arc::new(file))
}
}

fn traverse_unlink(&self, components: &mut Vec<&str>) -> core::result::Result<(), IoError> {
Expand Down
46 changes: 45 additions & 1 deletion src/fs/mem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,40 @@ impl RamFile {
}
}

#[derive(Debug, Clone)]
pub struct MemDirectoryInterface {
/// Directory entries
inner:
Arc<RwLock<BTreeMap<String, Box<dyn VfsNode + core::marker::Send + core::marker::Sync>>>>,
}

impl MemDirectoryInterface {
pub fn new(
inner: Arc<
RwLock<BTreeMap<String, Box<dyn VfsNode + core::marker::Send + core::marker::Sync>>>,
>,
) -> Self {
Self { inner }
}
}

#[async_trait]
impl ObjectInterface for MemDirectoryInterface {
fn readdir(&self) -> Result<Vec<DirectoryEntry>, IoError> {
block_on(
async {
let mut entries: Vec<DirectoryEntry> = Vec::new();
for name in self.inner.read().await.keys() {
entries.push(DirectoryEntry::new(name.to_string()));
}

Ok(entries)
},
None,
)
}
}

#[derive(Debug)]
pub(crate) struct MemDirectory {
inner:
Expand Down Expand Up @@ -358,7 +392,13 @@ impl MemDirectory {
return Ok(Arc::new(RamFileInterface::new(file.data.clone())));
}
} else if let Some(file) = guard.get(&node_name) {
if file.get_kind() == NodeKind::File {
if opt.contains(OpenOption::O_DIRECTORY)
&& file.get_kind() != NodeKind::Directory
{
return Err(IoError::ENOTDIR);
}

if file.get_kind() == NodeKind::File || file.get_kind() == NodeKind::Directory {
return file.get_object();
} else {
return Err(IoError::ENOENT);
Expand All @@ -382,6 +422,10 @@ impl VfsNode for MemDirectory {
NodeKind::Directory
}

fn get_object(&self) -> Result<Arc<dyn ObjectInterface>, IoError> {
Ok(Arc::new(MemDirectoryInterface::new(self.inner.clone())))
}

fn get_file_attributes(&self) -> Result<FileAttr, IoError> {
Ok(self.attr)
}
Expand Down