From 55f04ffeb59da6075425c78dd1f8586fd09f64ad Mon Sep 17 00:00:00 2001 From: frankyj915 Date: Fri, 21 Mar 2025 16:27:42 +0800 Subject: [PATCH] ozonec: Eliminate lint warnings --- ozonec/oci_spec/src/state.rs | 4 ++-- ozonec/src/commands/exec.rs | 2 +- ozonec/src/container/launcher.rs | 2 +- ozonec/src/linux/container.rs | 31 ++++++++++++++---------------- ozonec/src/linux/device.rs | 15 +++++++-------- ozonec/src/linux/mount.rs | 32 +++++++++++++++---------------- ozonec/src/linux/notify_socket.rs | 2 +- ozonec/src/linux/process.rs | 7 +++---- ozonec/src/linux/rootfs.rs | 15 ++++++--------- ozonec/src/utils/channel.rs | 2 ++ ozonec/src/utils/logger.rs | 6 +++--- ozonec/src/utils/mod.rs | 3 +-- 12 files changed, 56 insertions(+), 65 deletions(-) diff --git a/ozonec/oci_spec/src/state.rs b/ozonec/oci_spec/src/state.rs index 960e3b0f..105f128e 100644 --- a/ozonec/oci_spec/src/state.rs +++ b/ozonec/oci_spec/src/state.rs @@ -15,7 +15,7 @@ use std::collections::HashMap; use serde::{Deserialize, Serialize}; /// Runtime state of the container. -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Copy, Default)] +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Copy, Default, Eq)] #[serde(rename_all = "lowercase")] pub enum ContainerStatus { Creating, @@ -38,7 +38,7 @@ impl ToString for ContainerStatus { /// The state of a container. #[allow(non_snake_case)] -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] pub struct State { /// Version of the Open Container Initiative Runtime Specification /// with which the state complies. diff --git a/ozonec/src/commands/exec.rs b/ozonec/src/commands/exec.rs index ce15f572..9ee4e521 100644 --- a/ozonec/src/commands/exec.rs +++ b/ozonec/src/commands/exec.rs @@ -62,7 +62,7 @@ where { let pos = s .find('=') - .ok_or(anyhow!("Invalid KEY=value: no '=' found in '{}'", s))?; + .ok_or_else(|| anyhow!("Invalid KEY=value: no '=' found in '{}'", s))?; Ok((s[..pos].parse()?, s[pos + 1..].parse()?)) } diff --git a/ozonec/src/container/launcher.rs b/ozonec/src/container/launcher.rs index ef68c392..b9dca85d 100644 --- a/ozonec/src/container/launcher.rs +++ b/ozonec/src/container/launcher.rs @@ -37,7 +37,7 @@ use anyhow::{Context, Result}; use super::{state::State, Container}; use crate::{linux::Process, utils::OzonecErr}; -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Action { Create, Start, diff --git a/ozonec/src/linux/container.rs b/ozonec/src/linux/container.rs index cb023a48..2b51d21b 100644 --- a/ozonec/src/linux/container.rs +++ b/ozonec/src/linux/container.rs @@ -95,11 +95,11 @@ impl LinuxContainer { } pub fn load_from_state(state: &State, console_socket: &Option) -> Result { - let root_path = format!("{}/{}", state.root.to_string_lossy().to_string(), &state.id); + let root_path = format!("{}/{}", state.root.to_string_lossy(), &state.id); let config = state .config .clone() - .ok_or(anyhow!("Can't find config in state"))?; + .ok_or_else(|| anyhow!("Can't find config in state"))?; Ok(Self { id: state.id.clone(), @@ -145,7 +145,7 @@ impl LinuxContainer { // Spawn a child process to perform the second stage to initialize container. let init_pid = clone_process("ozonec:[2:INIT]", || { - self.do_second_stage(process, parent_channel, ¬ify_listener) + self.do_second_stage(process, parent_channel, notify_listener) .with_context(|| "Second stage process encounters errors")?; Ok(0) })?; @@ -334,14 +334,13 @@ impl LinuxContainer { } fn ns_controller(&self) -> Result { - Ok(self - .config + self.config .linux .as_ref() .unwrap() .namespaces .clone() - .try_into()?) + .try_into() } fn set_user_namespace( @@ -502,19 +501,17 @@ impl LinuxContainer { sethostname(hostname).with_context(|| "Failed to set hostname")?; } if let Some(domainname) = &self.config.domainname { - let errno; - // SAFETY: FFI call with valid arguments. - match unsafe { + let errno = match unsafe { setdomainname( domainname.as_bytes().as_ptr() as *const c_char, domainname.len(), ) } { 0 => return Ok(()), - -1 => errno = nix::Error::last(), - _ => errno = nix::Error::UnknownErrno, - } + -1 => nix::Error::last(), + _ => nix::Error::UnknownErrno, + }; bail!("Failed to set domainname: {}", errno); } } @@ -560,7 +557,7 @@ impl LinuxContainer { } fn write_id_mapping(&self, mappings: &Vec, pid: &Pid, file: &str) -> Result<()> { - let path = format!("/proc/{}/{}", pid.as_raw().to_string(), file); + let path = format!("/proc/{}/{}", pid.as_raw(), file); let mut opened_file = OpenOptions::new() .write(true) .open(&path) @@ -572,14 +569,14 @@ impl LinuxContainer { id_mappings = id_mappings + &mapping; } opened_file - .write_all(&id_mappings.as_bytes()) + .write_all(id_mappings.as_bytes()) .with_context(|| "Failed to write id mappings")?; Ok(()) } fn set_groups(pid: &Pid, allow: bool) -> Result<()> { - let path = format!("/proc/{}/setgroups", pid.as_raw().to_string()); - if allow == true { + let path = format!("/proc/{}/setgroups", pid.as_raw()); + if allow { std::fs::write(&path, "allow")? } else { std::fs::write(&path, "deny")? @@ -626,7 +623,7 @@ impl Container for LinuxContainer { let bundle = match rootfs.parent() { Some(p) => p .to_str() - .ok_or(anyhow!("root path is not valid unicode"))? + .ok_or_else(|| anyhow!("root path is not valid unicode"))? .to_string(), None => bail!("Failed to get bundle directory"), }; diff --git a/ozonec/src/linux/device.rs b/ozonec/src/linux/device.rs index 8ecc568b..c483d2eb 100644 --- a/ozonec/src/linux/device.rs +++ b/ozonec/src/linux/device.rs @@ -94,10 +94,9 @@ impl Device { } fn create_device_dir(&self, path: &PathBuf) -> Result<()> { - let dir = Path::new(path).parent().ok_or(anyhow!( - "Failed to get parent directory: {}", - path.display() - ))?; + let dir = Path::new(path) + .parent() + .ok_or_else(|| anyhow!("Failed to get parent directory: {}", path.display()))?; if !dir.exists() { create_dir_all(dir) .with_context(|| OzonecErr::CreateDir(dir.to_string_lossy().to_string()))?; @@ -122,7 +121,7 @@ impl Device { let binding = dev.path.to_string_lossy().to_string(); let stripped_path = binding .strip_prefix(&self.rootfs.to_string_lossy().to_string()) - .ok_or(anyhow!("Invalid device path"))?; + .ok_or_else(|| anyhow!("Invalid device path"))?; let src_path = PathBuf::from(stripped_path); if !dev.path.exists() { @@ -186,7 +185,7 @@ impl Device { return true; } } - return false; + false } pub fn delete_device(&self, dev: &OciDevice) -> Result<()> { @@ -199,10 +198,10 @@ impl Device { let path = self.rootfs.join(&dev.path.clone()[1..]); let major = dev .major - .ok_or(anyhow!("major not set for device {}", dev.path))?; + .ok_or_else(|| anyhow!("major not set for device {}", dev.path))?; let minor = dev .minor - .ok_or(anyhow!("minor not set for device {}", dev.path))?; + .ok_or_else(|| anyhow!("minor not set for device {}", dev.path))?; let dev_info = DeviceInfo { path, dev_type: dev.dev_type.clone(), diff --git a/ozonec/src/linux/mount.rs b/ozonec/src/linux/mount.rs index af44bd3c..c01aa457 100644 --- a/ozonec/src/linux/mount.rs +++ b/ozonec/src/linux/mount.rs @@ -38,9 +38,9 @@ pub struct Mount { } impl Mount { - pub fn new(rootfs: &PathBuf) -> Self { + pub fn new(rootfs: &Path) -> Self { Self { - rootfs: rootfs.clone(), + rootfs: rootfs.to_path_buf(), } } @@ -114,7 +114,7 @@ impl Mount { let src_binding = mount .source .clone() - .ok_or(anyhow!("Mount source not set"))?; + .ok_or_else(|| anyhow!("Mount source not set"))?; let mut source = Path::new(&src_binding); let canonicalized; // Strip the first "/". @@ -126,10 +126,9 @@ impl Mount { .with_context(|| format!("Failed to canonicalize {}", source.display()))?; source = canonicalized.as_path(); let dir = if source.is_file() { - target.parent().ok_or(anyhow!( - "Failed to get parent directory: {}", - target.display() - ))? + target.parent().ok_or_else(|| { + anyhow!("Failed to get parent directory: {}", target.display()) + })? } else { target }; @@ -139,15 +138,15 @@ impl Mount { fs_type = Some("bind"); } else { // Sysfs doesn't support duplicate mounting to one directory. - if self.is_mounted_sysfs_dir(&target.to_string_lossy().to_string()) { + if self.is_mounted_sysfs_dir(&target.to_string_lossy()) { nix::mount::umount(target) .with_context(|| format!("Failed to umount {}", target.display()))?; } } let target_fd = openat2_in_root( - &Path::new(&self.rootfs), - &Path::new(&mount.destination[1..]), + Path::new(&self.rootfs), + Path::new(&mount.destination[1..]), !source.is_file(), )?; nix::mount::mount( @@ -196,7 +195,7 @@ impl Mount { fn do_cgroup_mount(&self, mount: &OciMount) -> Result<()> { // Strip the first "/". let rel_target = Path::new(&mount.destination[1..]); - let target_fd = openat2_in_root(&Path::new(&self.rootfs), rel_target, true)?; + let target_fd = openat2_in_root(Path::new(&self.rootfs), rel_target, true)?; nix::mount::mount( Some("tmpfs"), &proc_fd_path(target_fd), @@ -225,12 +224,11 @@ impl Mount { for cg_path in host_cgroups { let cg = cg_path .file_name() - .ok_or(anyhow!("Failed to get controller file"))? + .ok_or_else(|| anyhow!("Failed to get controller file"))? .to_str() - .ok_or(anyhow!( - "Convert {:?} to string error", - cg_path.file_name().unwrap() - ))?; + .ok_or_else(|| { + anyhow!("Convert {:?} to string error", cg_path.file_name().unwrap()) + })?; let proc_cg_key = if cg == "systemd" { String::from("systemd") } else { @@ -242,7 +240,7 @@ impl Mount { let rel_target = cg_path .strip_prefix("/") .with_context(|| format!("{} doesn't start with '/'", cg_path.display()))?; - let target_fd = openat2_in_root(&Path::new(&self.rootfs), rel_target, true)?; + let target_fd = openat2_in_root(Path::new(&self.rootfs), rel_target, true)?; nix::mount::mount( Some(&source), diff --git a/ozonec/src/linux/notify_socket.rs b/ozonec/src/linux/notify_socket.rs index 356be384..5db9c57d 100644 --- a/ozonec/src/linux/notify_socket.rs +++ b/ozonec/src/linux/notify_socket.rs @@ -77,7 +77,7 @@ impl NotifySocket { let root_path = self .path .parent() - .ok_or(anyhow!("Invalid notify socket path"))?; + .ok_or_else(|| anyhow!("Invalid notify socket path"))?; chdir(root_path).with_context(|| "Failed to chdir to root directory")?; let mut stream = diff --git a/ozonec/src/linux/process.rs b/ozonec/src/linux/process.rs index 6ce1b911..20bd35d6 100644 --- a/ozonec/src/linux/process.rs +++ b/ozonec/src/linux/process.rs @@ -170,9 +170,8 @@ impl Process { .with_context(|| OzonecErr::GetAllCaps("Bounding".to_string()))?; let caps_hash_set = to_cap_set(bounding)?; for cap in all_caps.difference(&caps_hash_set) { - caps::drop(None, CapSet::Bounding, *cap).with_context(|| { - format!("Failed to drop {} from bonding set", cap.to_string()) - })?; + caps::drop(None, CapSet::Bounding, *cap) + .with_context(|| format!("Failed to drop {} from bonding set", cap))?; } } if let Some(effective) = caps.effective.as_ref() { @@ -363,7 +362,7 @@ fn to_cap_set(caps: &Vec) -> Result { let mut caps_hash_set = CapsHashSet::new(); for c in caps { - let cap = to_cap(&c)?; + let cap = to_cap(c)?; caps_hash_set.insert(cap); } Ok(caps_hash_set) diff --git a/ozonec/src/linux/rootfs.rs b/ozonec/src/linux/rootfs.rs index b7854a3f..48e43366 100644 --- a/ozonec/src/linux/rootfs.rs +++ b/ozonec/src/linux/rootfs.rs @@ -103,17 +103,14 @@ impl Rootfs { let process = Process::myself().with_context(|| OzonecErr::AccessProcSelf)?; let mount_info = process.mountinfo().with_context(|| OzonecErr::GetMntInfo)?; - match mount_info + if let Some(m) = mount_info .into_iter() .filter(|m| self.path.starts_with(&m.mount_point) && m.mount_point != self.path) .map(|m| m.mount_point) .max_by_key(|m| m.len()) .as_ref() { - Some(m) => { - nix::mount::mount(Some(m), m, None::<&str>, MsFlags::MS_PRIVATE, None::<&str>)? - } - None => (), + nix::mount::mount(Some(m), m, None::<&str>, MsFlags::MS_PRIVATE, None::<&str>)?; } Ok(()) } @@ -126,10 +123,10 @@ impl Rootfs { // dev/stderr -> /proc/self/fd/2 fn set_default_symlinks(&self) -> Result<()> { let link_pairs = vec![ - ((&self.path).join("dev/fd"), "/proc/self/fd"), - ((&self.path).join("dev/stdin"), "/proc/self/fd/0"), - ((&self.path).join("dev/stdout"), "/proc/self/fd/1"), - ((&self.path).join("dev/stderr"), "/proc/self/fd/2"), + ((self.path).join("dev/fd"), "/proc/self/fd"), + ((self.path).join("dev/stdin"), "/proc/self/fd/0"), + ((self.path).join("dev/stdout"), "/proc/self/fd/1"), + ((self.path).join("dev/stderr"), "/proc/self/fd/2"), ]; for pair in link_pairs { diff --git a/ozonec/src/utils/channel.rs b/ozonec/src/utils/channel.rs index 41b2b08b..b5d850e3 100644 --- a/ozonec/src/utils/channel.rs +++ b/ozonec/src/utils/channel.rs @@ -59,6 +59,7 @@ where let msg_vec = serde_json::to_vec(&msg).with_context(|| "Failed to load message")?; let msg_len = msg_vec.len() as u64; let iov = [ + // SAFETY: FFI call with valid arguments. IoSlice::new(unsafe { slice::from_raw_parts((&msg_len as *const u64) as *const u8, mem::size_of::()) }), @@ -110,6 +111,7 @@ where let mut buf = vec![0u8; msg_len as usize]; let bytes = { let mut iov = [ + // SAFETY: FFI call with valid arguments. IoSliceMut::new(unsafe { slice::from_raw_parts_mut( (&mut received_len as *mut u64) as *mut u8, diff --git a/ozonec/src/utils/logger.rs b/ozonec/src/utils/logger.rs index 1251de8a..33ecd86b 100644 --- a/ozonec/src/utils/logger.rs +++ b/ozonec/src/utils/logger.rs @@ -99,8 +99,8 @@ fn open_log_file(path: &PathBuf) -> Result { fn formatted_time(seconds: i64) -> [i32; 6] { // SAFETY: an all-zero value is valid for libc::tm. let mut ti: libc::tm = unsafe { std::mem::zeroed() }; + // SAFETY: seconds and ti are both local variables and valid. unsafe { - // SAFETY: seconds and ti are both local variables and valid. libc::localtime_r(&seconds, &mut ti); } [ @@ -118,8 +118,8 @@ fn wall_time() -> (i64, i64) { tv_sec: 0, tv_nsec: 0, }; + // SAFETY: ts is a local variable and valid. unsafe { - // SAFETY: ts is a local variable and valid. libc::clock_gettime(libc::CLOCK_REALTIME, &mut ts); } (ts.tv_sec, ts.tv_nsec) @@ -150,7 +150,7 @@ impl Logger { fn new(path: &Option, level: Level) -> Result { let (log_file, log_size, created_day) = match path { Some(p) => { - let file = Box::new(open_log_file(&p)?); + let file = Box::new(open_log_file(p)?); let metadata = file.metadata().with_context(|| "Failed to get metadata")?; let mod_time = metadata .modified() diff --git a/ozonec/src/utils/mod.rs b/ozonec/src/utils/mod.rs index 59da672a..4e86fc35 100644 --- a/ozonec/src/utils/mod.rs +++ b/ozonec/src/utils/mod.rs @@ -95,9 +95,8 @@ pub fn openat2_in_root(root: &Path, target: &Path, is_dir: bool) -> Result