Skip to content

Commit ee66d23

Browse files
Jbansal2ppenna
authored andcommitted
lxutil: close the descriptor when fdopendir fails in DirectoryEnumerator::new
fdopendir takes ownership of the descriptor only on success. Converting the OwnedFd to a raw fd before the call leaked it whenever fdopendir failed, e.g. with ENOTDIR for a virtio-fs FUSE_READDIR on a regular file handle, letting a guest exhaust the host process descriptors. Keep the OwnedFd until fdopendir succeeds so failures close it. (cherry picked from commit 7417a03)
1 parent 5f4a47b commit ee66d23

1 file changed

Lines changed: 30 additions & 3 deletions

File tree

  • vm/devices/support/fs/lxutil/src/unix

‎vm/devices/support/fs/lxutil/src/unix/util.rs‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,12 @@ unsafe impl Sync for DirectoryEnumerator {}
2828
impl DirectoryEnumerator {
2929
// Create a new enumerator by taking ownership of a file descriptor.
3030
pub fn new(fd: impl Into<OwnedFd>) -> lx::Result<Self> {
31-
// SAFETY: By requiring an OwnedFd we take ownership of the fd and give it away to fdopendir, as per its
32-
// documented requirements.
33-
let dir = check_lx_ptr(unsafe { libc::fdopendir(fd.into().into_raw_fd()) })?;
31+
let fd = fd.into();
32+
// SAFETY: fd is a valid, owned descriptor. fdopendir takes ownership only on success; on failure the
33+
// OwnedFd is dropped here and closes it, so a non-directory fd (ENOTDIR) does not leak.
34+
let dir = check_lx_ptr(unsafe { libc::fdopendir(fd.as_raw_fd()) })?;
35+
// fdopendir succeeded and now owns the descriptor; closedir in Drop will close it.
36+
let _ = fd.into_raw_fd();
3437
Ok(Self { dir })
3538
}
3639

@@ -448,4 +451,28 @@ mod tests {
448451
0o640
449452
);
450453
}
454+
455+
fn open_fds() -> usize {
456+
std::fs::read_dir("/proc/self/fd").unwrap().count()
457+
}
458+
459+
#[test]
460+
fn directory_enumerator_on_non_directory_does_not_leak_fd() {
461+
let root = tempfile::tempdir().unwrap();
462+
let file = root.path().join("file");
463+
std::fs::write(&file, b"data").unwrap();
464+
let before = open_fds();
465+
for _ in 0..200 {
466+
let fd = std::fs::File::open(&file).unwrap();
467+
assert_eq!(
468+
DirectoryEnumerator::new(fd).err().unwrap(),
469+
lx::Error::ENOTDIR
470+
);
471+
}
472+
let after = open_fds();
473+
assert!(
474+
after < before + 100,
475+
"200 failed enumerations: {before} -> {after} descriptors open"
476+
);
477+
}
451478
}

0 commit comments

Comments
 (0)