From 2d25ea7eb25f4c6480cf0b1b53cab0cfe1e0c87d Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Mon, 30 Jan 2023 20:37:26 +0000 Subject: Switch to rustix --- src/lib.rs | 53 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 33 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index 42a9c1b..0b5fff9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,31 +5,38 @@ mod pam; mod passwd; mod syslog; -use cap_std::fs::{Dir, OpenOptions}; use pam::PAMHandle; +use rustix::fd::{AsFd, OwnedFd}; +use rustix::fs::{self, Mode, OFlags}; +use rustix::io::{self, Errno}; +use rustix::path::Arg; use std::ffi::{c_char, c_int, CStr, CString}; -use std::io::{ErrorKind, Write}; use std::panic; -use std::path::Path; use std::process; use syslog::{Facility, Level, Priority}; -fn create_and_open_dir + ?Sized>( - d: &Dir, - path: &P, -) -> std::io::Result { - if let Err(e) = d.create_dir(path) { - if e.kind() != ErrorKind::AlreadyExists { +fn create_and_open_dir( + d: &D, + path: P, +) -> rustix::io::Result { + if let Err(e) = fs::mkdirat(d, path, Mode::RWXU | Mode::RWXG | Mode::RWXO) { + if e != Errno::EXIST { return Err(e); } } - d.open_dir(path) + fs::openat(d, path, OFlags::DIRECTORY | OFlags::PATH, Mode::empty()) } struct SessionError; -impl From for SessionError { - fn from(_: std::io::Error) -> Self { +impl From for SessionError { + fn from(_: rustix::io::Errno) -> Self { + SessionError + } +} + +impl From for SessionError { + fn from(_: std::ffi::NulError) -> Self { SessionError } } @@ -52,7 +59,7 @@ fn open_session(h: &PAMHandle, mountpoint: &str) -> Result<(), SessionError> { } }; let uid = match passwd::get_uid_by_name(&user) { - Some(uid) => uid.to_string(), + Some(uid) => CString::new(uid.to_string())?, None => { if let Ok(message) = CString::new(format!("Failure to map user {user:?} to passwd entry")) @@ -62,16 +69,22 @@ fn open_session(h: &PAMHandle, mountpoint: &str) -> Result<(), SessionError> { return Err(SessionError); } }; - let d = Dir::open_ambient_dir(mountpoint, cap_std::ambient_authority())?; + let d = fs::openat( + fs::cwd(), + mountpoint, + OFlags::DIRECTORY | OFlags::PATH, + Mode::empty(), + )?; let d = create_and_open_dir(&d, "user")?; let d = create_and_open_dir(&d, &uid)?; let d = create_and_open_dir(&d, "leaf")?; - let pid = process::id().to_string(); - let mut options = OpenOptions::new(); - options.write(true); - let mut procs = d.open_with("cgroup.procs", &options)?; - procs.write_all(pid.as_bytes())?; - Ok(()) + let pid = CString::new(process::id().to_string())?; + let pid = pid.as_bytes(); + let procs = fs::openat(d, "cgroup.procs", OFlags::WRONLY, Mode::empty())?; + match io::write(procs, pid) { + Ok(n) if n == pid.len() => Ok(()), + _ => Err(SessionError), + } } const CG_MOUNT: &str = "/sys/fs/cgroup"; -- cgit v1.2.3-54-g00ecf