diff --git a/core/coms/mount/src/manager.rs b/core/coms/mount/src/manager.rs index 6ea063c80d6432e4f00b0a256632b891839cd437..ab8f3039021ab5c6b3c57e31f7808a6478668d0c 100644 --- a/core/coms/mount/src/manager.rs +++ b/core/coms/mount/src/manager.rs @@ -12,13 +12,13 @@ #[cfg(feature = "plugin")] use crate::base::PLUGIN_NAME; -use basic::fs_util::is_path; +use basic::fs::is_path; #[cfg(feature = "plugin")] use constants::LOG_FILE_PATH; use super::comm::MountUmComm; use super::rentry::{MountRe, MountReFrame}; -use basic::mount_util::{mount_point_to_unit_name, MountInfoParser}; +use basic::mount::{mount_point_to_unit_name, MountInfoParser}; use core::error::*; use core::rel::{ReStation, ReliLastFrame, Reliability}; use core::unit::{unit_name_is_valid, UmIf, UnitManagerObj, UnitMngUtil, UnitNameFlags, UnitType}; diff --git a/core/coms/mount/src/mng.rs b/core/coms/mount/src/mng.rs index de00ea5229dfbbcde9fab5835023211e9eaeca03..9de72d0c962646757f7397e81deee05cbaecc455 100644 --- a/core/coms/mount/src/mng.rs +++ b/core/coms/mount/src/mng.rs @@ -11,9 +11,9 @@ // See the Mulan PSL v2 for more details. //! The core logic of the mount subclass -use basic::fs_util::{directory_is_empty, mkdir_p_label}; -use basic::mount_util::filter_options; -use basic::time_util::USEC_PER_SEC; +use basic::fs::{directory_is_empty, mkdir_p_label}; +use basic::mount::filter_options; +use basic::time::USEC_PER_SEC; use basic::{MOUNT_BIN, UMOUNT_BIN}; use event::{EventState, Events}; use event::{EventType, Source}; diff --git a/core/coms/mount/src/rentry.rs b/core/coms/mount/src/rentry.rs index db07447e787a1d318b799ea143967fc93e0db2f1..fa4508e78f6ab03c62a723b21846060450bf6c29 100644 --- a/core/coms/mount/src/rentry.rs +++ b/core/coms/mount/src/rentry.rs @@ -242,7 +242,7 @@ pub struct SectionMount { pub Group: String, #[entry(default = String::from("0022"))] pub UMask: String, - #[entry(parser = basic::fs_util::parse_pathbuf)] + #[entry(parser = basic::fs::parse_pathbuf)] pub RootDirectory: Option, #[entry(default = WorkingDirectory::default(), parser = core::exec::parse_working_directory)] pub WorkingDirectory: WorkingDirectory, diff --git a/core/coms/mount/src/unit.rs b/core/coms/mount/src/unit.rs index 86b1fc55c06f8bfbdb1cb4ce43b6cd2f944ce89b..f7d93a3981b2da254ee1723d457ce78d8c341fa7 100644 --- a/core/coms/mount/src/unit.rs +++ b/core/coms/mount/src/unit.rs @@ -18,7 +18,7 @@ use crate::rentry::{MountProcFlags, MountState}; use super::comm::MountUnitComm; use super::mng::MountMng; -use basic::mount_util::mount_point_to_unit_name; +use basic::mount::mount_point_to_unit_name; use core::error::*; use core::exec::ExecContext; use core::rel::{ReStation, Reliability}; diff --git a/core/coms/service/Cargo.toml b/core/coms/service/Cargo.toml index 408fa07589056299c5bbfe45c8cf1ed74f2512a7..bc5957d8f02eebe21a032489cbf04e0fd5446cad 100644 --- a/core/coms/service/Cargo.toml +++ b/core/coms/service/Cargo.toml @@ -15,7 +15,7 @@ basic = { path = "../../../libs/basic", default-features = false, features = [ "fs", "fd", "unit_name", - "time_util", + "time", ] } cgroup = { path = "../../../libs/cgroup", default-features = false } constants = { path = "../../../libs/constants" } diff --git a/core/coms/service/src/mng.rs b/core/coms/service/src/mng.rs index 39b0fd7864d75a7167d420011007f1392a4a1483..710507aeba30ee15ee38a01ca6844d6aece385e9 100644 --- a/core/coms/service/src/mng.rs +++ b/core/coms/service/src/mng.rs @@ -20,8 +20,8 @@ use super::rentry::{ }; use super::spawn::ServiceSpawn; use crate::rentry::{ExitStatus, NotifyAccess}; -use basic::{do_entry_log, fd_util, IN_SET}; -use basic::{fs_util, process}; +use basic::{do_entry_log, fd, IN_SET}; +use basic::{fs, process}; use core::error::*; use core::exec::{ExecCommand, ExecContext, ExecFlag, ExecFlags, PreserveMode}; use core::rel::ReStation; @@ -1049,7 +1049,7 @@ impl ServiceMng { }); } - let pid = match fs_util::read_first_line(pid_file_path) { + let pid = match fs::read_first_line(pid_file_path) { Ok(line) => line.trim().parse::(), Err(e) => { return Err(Error::Parse { @@ -2310,7 +2310,7 @@ impl PathInotify { } fn unwatch(&self) { - fd_util::close(*self.inotify.borrow()); + fd::close(*self.inotify.borrow()); *self.inotify.borrow_mut() = -1; } diff --git a/core/coms/service/src/rentry.rs b/core/coms/service/src/rentry.rs index 24d2d47473cef76ebc5e250a468db930e001303a..bc1acccc6ffa6feb58384a32e653426826bf9824 100644 --- a/core/coms/service/src/rentry.rs +++ b/core/coms/service/src/rentry.rs @@ -13,7 +13,7 @@ #![allow(non_snake_case)] use crate::monitor::ServiceMonitor; -use basic::fs_util::{path_is_abosolute, path_length_is_valid, path_name_is_safe, path_simplify}; +use basic::fs::{path_is_abosolute, path_length_is_valid, path_name_is_safe, path_simplify}; use core::exec::PreserveMode; use macros::{EnumDisplay, UnitSection}; use nix::sys::signal::Signal; @@ -32,8 +32,8 @@ use core::exec::{ExecCommand, Rlimit, RuntimeDirectory, StateDirectory, WorkingD use core::rel::{ReDb, ReDbRwTxn, ReDbTable, ReliSwitch, Reliability}; use core::unit::KillMode; -use basic::time_util::USEC_PER_MSEC; -use basic::time_util::USEC_PER_SEC; +use basic::time::USEC_PER_MSEC; +use basic::time::USEC_PER_SEC; use basic::EXEC_RUNTIME_PREFIX; struct ServiceReDb(ReDb); @@ -232,7 +232,7 @@ fn parse_pidfile(s: &str) -> Result { } fn parse_sec(s: &str) -> Result { - basic::time_util::parse_sec(s).context(NixSnafu) + basic::time::parse_sec(s).context(NixSnafu) } fn parse_timeout(s: &str) -> Result { @@ -292,7 +292,7 @@ pub struct SectionService { pub Group: String, #[entry(default = String::from("0022"))] pub UMask: String, - #[entry(parser = basic::fs_util::parse_pathbuf)] + #[entry(parser = basic::fs::parse_pathbuf)] pub RootDirectory: Option, #[entry(default = WorkingDirectory::default(), parser = core::exec::parse_working_directory)] pub WorkingDirectory: WorkingDirectory, diff --git a/core/coms/service/src/spawn.rs b/core/coms/service/src/spawn.rs index f28278b60140fbdecc30553baf0710e692aea67f..fce52942b47845d3ba28c851da84dfe2b6900788 100644 --- a/core/coms/service/src/spawn.rs +++ b/core/coms/service/src/spawn.rs @@ -16,7 +16,7 @@ use super::comm::ServiceUnitComm; use super::config::ServiceConfig; use super::pid::ServicePid; use super::rentry::ServiceType; -use basic::fd_util; +use basic::fd; use core::error::*; use core::exec::{ExecCommand, ExecContext, ExecFlags, ExecParameters}; use nix::unistd::Pid; @@ -141,7 +141,7 @@ impl ServiceSpawn { } pub(super) fn release_socket_fd(&self, fd: i32) { - fd_util::close(fd); + fd::close(fd); *self.socket_fd.borrow_mut() = -1; } } diff --git a/core/coms/socket/src/config.rs b/core/coms/socket/src/config.rs index c53e275aaf0c785521dd5352e636f8eae36af99a..011b5a5631177b1b68767a4363560db0ab00888f 100644 --- a/core/coms/socket/src/config.rs +++ b/core/coms/socket/src/config.rs @@ -16,7 +16,7 @@ use super::comm::SocketUnitComm; use super::rentry::{PortType, SectionSocket, SocketCommand}; use crate::base::NetlinkProtocol; -use basic::{fd_util, socket_util}; +use basic::fd; use core::error::*; use core::exec::ExecCommand; use core::rel::ReStation; @@ -427,7 +427,7 @@ impl SocketPortConf { Ok(v) => v, }; let st = fstat(fd)?; - if !fd_util::stat_is_reg(st.st_mode) && !fd_util::stat_is_char(st.st_mode) { + if !fd::stat_is_reg(st.st_mode) && !fd::stat_is_char(st.st_mode) { return Err(Errno::EEXIST); } Ok(fd) @@ -630,7 +630,7 @@ fn parse_socket_address(item: &str, socket_type: SockType) -> Result Result<()> { if let Ok(true) = socket::getsockopt(self.fd(), sockopt::AcceptConn) { for _i in 1..1024 { - let events = match io_util::wait_for_events(self.fd(), PollFlags::POLLIN, 0) { + let events = match io::wait_for_events(self.fd(), PollFlags::POLLIN, 0) { Err(e) => { if let basic::Error::Nix { source: Errno::EINTR, @@ -189,7 +189,7 @@ impl SocketPort { } Ok(v) => v, }; - fd_util::close(cfd); + fd::close(cfd); } } Ok(()) @@ -197,7 +197,7 @@ impl SocketPort { pub(super) fn flush_fd(&self) { loop { - let v = io_util::wait_for_events(self.fd(), PollFlags::POLLIN, 0).unwrap_or(0); + let v = io::wait_for_events(self.fd(), PollFlags::POLLIN, 0).unwrap_or(0); if v == 0 { return; }; @@ -214,37 +214,37 @@ impl SocketPort { pub(super) fn apply_sock_opt(&self, fd: RawFd) { if let Some(v) = self.config.config_data().borrow().Socket.PassPacketInfo { - if let Err(e) = socket_util::set_pkginfo(fd, self.family(), v) { + if let Err(e) = basic::socket::set_pkginfo(fd, self.family(), v) { log::warn!("set socket pkginfo errno: {}", e); } } if let Some(v) = self.config.config_data().borrow().Socket.PassCredentials { - if let Err(e) = socket_util::set_pass_cred(fd, v) { + if let Err(e) = basic::socket::set_pass_cred(fd, v) { log::warn!("set socket pass cred errno: {}", e); } } if let Some(v) = self.config.config_data().borrow().Socket.ReceiveBuffer { - if let Err(e) = socket_util::set_receive_buffer(fd, v as usize) { + if let Err(e) = basic::socket::set_receive_buffer(fd, v as usize) { log::warn!("set socket receive buffer errno: {}", e); } } if let Some(v) = self.config.config_data().borrow().Socket.SendBuffer { - if let Err(e) = socket_util::set_send_buffer(fd, v as usize) { + if let Err(e) = basic::socket::set_send_buffer(fd, v as usize) { log::warn!("set socket send buffer errno: {}", e); } } if let Some(v) = self.config.config_data().borrow().Socket.KeepAlive { - if let Err(e) = socket_util::set_keepalive_state(fd, v) { + if let Err(e) = basic::socket::set_keepalive_state(fd, v) { log::warn!("set keepalive state errno: {}", e); } } if let Some(v) = self.config.config_data().borrow().Socket.KeepAliveTimeSec { - if let Err(e) = socket_util::set_keepalive_timesec(fd, v) { + if let Err(e) = basic::socket::set_keepalive_timesec(fd, v) { log::warn!("set keepalive time errno: {}", e); } } @@ -256,19 +256,19 @@ impl SocketPort { .Socket .KeepAliveIntervalSec { - if let Err(e) = socket_util::set_keepalive_intervalsec(fd, v) { + if let Err(e) = basic::socket::set_keepalive_intervalsec(fd, v) { log::warn!("set keepalive interval errno: {}", e); } } if let Some(v) = self.config.config_data().borrow().Socket.KeepAliveProbes { - if let Err(e) = socket_util::set_keepalive_probes(fd, v) { + if let Err(e) = basic::socket::set_keepalive_probes(fd, v) { log::warn!("set keepalive probe count errno: {}", e); } } if let Some(v) = self.config.config_data().borrow().Socket.Broadcast { - if let Err(e) = socket_util::set_broadcast_state(fd, v) { + if let Err(e) = basic::socket::set_broadcast_state(fd, v) { log::warn!("set broadcast state errno: {}", e); } } @@ -299,7 +299,7 @@ impl SocketPort { let target = self.listen(); for symlink in &config.borrow().Socket.Symlinks { let symlink_str = symlink.to_str().unwrap(); - if let Err(e) = basic::fs_util::symlink(target, symlink_str, false) { + if let Err(e) = basic::fs::symlink(target, symlink_str, false) { let unit_name = match self.comm.owner() { None => "null".to_string(), Some(v) => v.id().to_string(), diff --git a/core/coms/socket/src/rentry.rs b/core/coms/socket/src/rentry.rs index 1886f97028819123e596a02e08041235b54cba1d..1de3231e9e369a1302969ee21313e05270bbae4a 100644 --- a/core/coms/socket/src/rentry.rs +++ b/core/coms/socket/src/rentry.rs @@ -32,11 +32,10 @@ const RELI_LAST_KEY: u32 = 0; // singleton fn parse_pathbuf_vec(s: &str) -> Result, core::error::Error> { let mut res = Vec::new(); for v in s.split_ascii_whitespace() { - let path = basic::fs_util::parse_absolute_path(v).map_err(|_| { - core::error::Error::ConfigureError { + let path = + basic::fs::parse_absolute_path(v).map_err(|_| core::error::Error::ConfigureError { msg: "Invalid PathBuf".to_string(), - } - })?; + })?; res.push(PathBuf::from(path)); } Ok(res) diff --git a/core/coms/timer/src/config.rs b/core/coms/timer/src/config.rs index c0340bb7880869c9c59331fc04f70b883aa9923b..ad0b42dd4495c9573fc6a287197218ea26fbcce9 100644 --- a/core/coms/timer/src/config.rs +++ b/core/coms/timer/src/config.rs @@ -14,7 +14,7 @@ use crate::{ comm::TimerUnitComm, rentry::{CalendarSpec, SectionTimer, TimerBase, TimerValue}, }; -use basic::time_util::USEC_INFINITY; +use basic::time::USEC_INFINITY; use core::error::*; use core::rel::ReStation; use std::{cell::RefCell, path::PathBuf, rc::Rc}; diff --git a/core/coms/timer/src/lib.rs b/core/coms/timer/src/lib.rs index ca683ce39b40c27ef5e542b4d956511f7c040c0b..f4fb969a07e9055dad7ac9c50c341eb7f60f997b 100644 --- a/core/coms/timer/src/lib.rs +++ b/core/coms/timer/src/lib.rs @@ -30,7 +30,7 @@ //! //! Set the trigger precision of the timer //! -//! OnActiveSec、 OnBootSec、 OnStartupSec、 OnUnitActiveSec、 OnUnitInactiveSec +//! OnActiveSec,OnBootSec,OnStartupSec,OnUnitActiveSec,OnUnitInactiveSec //! //! Defines a monotone timer relative to a period of time after a specific point in time //! diff --git a/core/coms/timer/src/mng.rs b/core/coms/timer/src/mng.rs index 6634158aa54f1affbc699b3db37950482ad491a9..cad0aeac9d51a33d1f5030f7bddf2559c54826ae 100644 --- a/core/coms/timer/src/mng.rs +++ b/core/coms/timer/src/mng.rs @@ -16,9 +16,9 @@ use crate::{ rentry::{TimerBase, TimerResult, TimerState}, }; use basic::{ - fs_util::touch_file, + fs::touch_file, machine::Machine, - time_util::{ + time::{ duml_timestamp_is_set, now_clockid, timespec_load, triple_timestamp_by_clock, usec_add, usec_shift_clock, DualTimestamp, TripleTimestamp, USEC_INFINITY, }, diff --git a/core/coms/timer/src/rentry.rs b/core/coms/timer/src/rentry.rs index 51509bd02c42382b9916e47aa3650904bb90e4ce..da0e368ea70ba79e0c089ce2d911ac520db834ed 100644 --- a/core/coms/timer/src/rentry.rs +++ b/core/coms/timer/src/rentry.rs @@ -10,7 +10,7 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. #![allow(non_snake_case)] -use basic::time_util::{parse_timer, USEC_INFINITY}; +use basic::time::{parse_timer, USEC_INFINITY}; use core::rel::{ReDb, ReDbRwTxn, ReDbTable, ReliSwitch, Reliability}; use macros::{EnumDisplay, UnitSection}; use serde::{Deserialize, Serialize}; diff --git a/core/libcore/src/exec/base.rs b/core/libcore/src/exec/base.rs index 134a8c047141b673e89671cd07a7dc3c7015d104..4f885663784b02cd729c56c8c60affeb18862fb6 100644 --- a/core/libcore/src/exec/base.rs +++ b/core/libcore/src/exec/base.rs @@ -11,7 +11,7 @@ // See the Mulan PSL v2 for more details. use crate::error::*; -use basic::fs_util::{path_is_abosolute, path_length_is_valid, path_name_is_safe, path_simplify}; +use basic::fs::{path_is_abosolute, path_length_is_valid, path_name_is_safe, path_simplify}; use basic::rlimit; use bitflags::bitflags; use libc::EPERM; diff --git a/core/libcore/src/exec/cmd.rs b/core/libcore/src/exec/cmd.rs index af1fb7d947131d1a524343caecd026609d050865..b5b808306126a52645f80e75c1fe98713fbb527c 100644 --- a/core/libcore/src/exec/cmd.rs +++ b/core/libcore/src/exec/cmd.rs @@ -14,8 +14,8 @@ use crate::serialize::DeserializeWith; use crate::specifier::{ unit_string_specifier_escape, unit_strings_specifier_escape, UnitSpecifierData, }; -use basic::fs_util::{path_is_abosolute, path_simplify}; -use basic::{fs_util::parse_absolute_path, Error, Result}; +use basic::fs::{path_is_abosolute, path_simplify}; +use basic::{fs::parse_absolute_path, Error, Result}; use bitflags::bitflags; use serde::{ de::{self, Unexpected}, diff --git a/core/libcore/src/rel/api_norecov.rs b/core/libcore/src/rel/api_norecov.rs index d4a3ebf2bff47e53a1cdcc251e552ec63d62c7c1..28a12beb4e65f5c24fa684d56273771dc79e39d9 100755 --- a/core/libcore/src/rel/api_norecov.rs +++ b/core/libcore/src/rel/api_norecov.rs @@ -25,7 +25,7 @@ use super::{ ReStationKind, }; use crate::error::*; -use crate::utils::fd as fd_util; +use crate::utils::fd; use heed::Env; use std::rc::Rc; use std::{cell::RefCell, fmt}; @@ -136,7 +136,7 @@ impl Reliability { /// set the fd's 'cloexec' flag and record it pub fn fd_cloexec(&self, fd: i32, cloexec: bool) -> Result<()> { // just set the fd's 'cloexec' flag - fd_util::fd_cloexec(fd, cloexec).context(NixSnafu)?; + basic::fd::fd_cloexec(fd, cloexec).context(NixSnafu)?; Ok(()) } diff --git a/core/libcore/src/rel/pending.rs b/core/libcore/src/rel/pending.rs index 12a3f1cc9b8b351ec0a42c39622dd42508060abe..b72b63c71bd68dc38b9eab19339b8e69ddc89e76 100644 --- a/core/libcore/src/rel/pending.rs +++ b/core/libcore/src/rel/pending.rs @@ -12,7 +12,7 @@ use super::base::RELI_INTERNAL_DB_PFD; use crate::error::*; -use crate::utils::fd as fd_util; +use crate::utils::fd; use heed::types::{OwnedType, SerdeBincode}; use heed::{Database, Env}; use serde::{Deserialize, Serialize}; @@ -68,7 +68,7 @@ impl ReliPending { let iter = db.iter(&rtxn).unwrap(); for entry in iter { let (fd, _) = entry.unwrap(); - fd_util::close(fd); + fd::close(fd); } // clear data @@ -100,7 +100,7 @@ impl ReliPending { self.fd_add(fd, ReliPState::Retaining); // action - let ret = fd_util::fd_cloexec(fd, false).context(NixSnafu); + let ret = fd::fd_cloexec(fd, false).context(NixSnafu); if ret.is_err() { self.fd_del(fd); return ret; @@ -115,7 +115,7 @@ impl ReliPending { fn fd_remove(&self, fd: i32) -> Result<()> { // close-on-exec - if fd_util::fd_is_cloexec(fd) { + if fd::fd_is_cloexec(fd) { // debug self.fd_del(fd); return Ok(()); @@ -125,7 +125,7 @@ impl ReliPending { self.fd_add(fd, ReliPState::Removing); // action - let ret = fd_util::fd_cloexec(fd, true).context(NixSnafu); + let ret = fd::fd_cloexec(fd, true).context(NixSnafu); if ret.is_err() { self.fd_del(fd); return ret; diff --git a/core/libcore/src/serialize.rs b/core/libcore/src/serialize.rs index 0fe407839d503181364843939ad6719b3473f949..7e5dfcedfe329f5c191e26b3f3790d69adfa00ae 100644 --- a/core/libcore/src/serialize.rs +++ b/core/libcore/src/serialize.rs @@ -13,7 +13,7 @@ //! use std::path::PathBuf; -use basic::fs_util::parse_absolute_path; +use basic::fs::parse_absolute_path; use serde::{ de::{self, Unexpected}, Deserialize, Deserializer, diff --git a/core/libcore/src/unit/base.rs b/core/libcore/src/unit/base.rs index d2e25e6f3787cfc5a549c16f552d6b460f18ea45..b62e29a5efe516f01fedddbe7ad04bf3b06e8009 100644 --- a/core/libcore/src/unit/base.rs +++ b/core/libcore/src/unit/base.rs @@ -16,7 +16,7 @@ use super::state::{UnitActiveState, UnitNotifyFlags}; use super::umif::UnitMngUtil; use super::UnitType; use crate::error::*; -use basic::time_util::UnitTimeStamp; +use basic::time::UnitTimeStamp; use bitflags::bitflags; use nix::sys::wait::WaitStatus; use nix::{sys::socket::UnixCredentials, unistd::Pid}; diff --git a/core/libcore/src/unit/umif.rs b/core/libcore/src/unit/umif.rs index 02efad2d4ae0f134d63e3e4adeccea1823520097..2e74caf3c39defa4f0483bb0e15d25c5ec8967e5 100644 --- a/core/libcore/src/unit/umif.rs +++ b/core/libcore/src/unit/umif.rs @@ -16,7 +16,7 @@ use crate::error::*; use crate::exec::{ExecCommand, ExecContext, ExecParameters}; use crate::rel::{ReStation, Reliability}; use crate::unit::{UnitActiveState, UnitType}; -use basic::time_util::UnitTimeStamp; +use basic::time::UnitTimeStamp; use event::Events; use nix::unistd::Pid; use std::cell::RefCell; diff --git a/core/sysmaster/Cargo.toml b/core/sysmaster/Cargo.toml index 790510fd000d70654c011b79c025cb2562bc47e9..d11d236d59c0bc6439b0f4d4a85485251ea368c9 100644 --- a/core/sysmaster/Cargo.toml +++ b/core/sysmaster/Cargo.toml @@ -22,7 +22,7 @@ features = [ "security", "mount", "machine", - "exec_util", + "exec", "unit_name", ] optional = false diff --git a/core/sysmaster/src/main.rs b/core/sysmaster/src/main.rs index 0bc6b9bf81ffbc94f20317e4ebe32da5d2ec1cc1..b4d3a55c557f56cba02801fff9dc948063248c64 100644 --- a/core/sysmaster/src/main.rs +++ b/core/sysmaster/src/main.rs @@ -40,7 +40,7 @@ use crate::manager::config::ManagerConfig; use crate::manager::signals::EVENT_SIGNALS; use crate::manager::{Action, Manager, Mode, MANAGER_ARGS_SIZE_MAX}; use crate::mount::setup; -use basic::{machine, machine::Machine, mount_util::read_lines, FSTAB_PATH, MOUNT_BIN}; +use basic::{machine, machine::Machine, mount::read_lines, FSTAB_PATH, MOUNT_BIN}; use clap::Parser; use constants::LOG_FILE_PATH; use core::error::*; diff --git a/core/sysmaster/src/manager/commands.rs b/core/sysmaster/src/manager/commands.rs index ee5f7e22b8c30c864e77d409c0533f1ede93c6bb..279eae58fe366f30a7ed23bb86f50ef1999e8c80 100644 --- a/core/sysmaster/src/manager/commands.rs +++ b/core/sysmaster/src/manager/commands.rs @@ -10,8 +10,8 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -use basic::fs_util::{self, is_symlink}; -use basic::{do_entry_log, socket_util}; +use basic::do_entry_log; +use basic::fs::{self, is_symlink}; use cmdproto::proto::execute::ExecuterAction; use cmdproto::proto::ProstServerStream; use core::rel::{ReliLastFrame, Reliability}; @@ -41,7 +41,7 @@ where let sctl_socket_path = Path::new(SCTL_SOCKET); let run_sysmaster = sctl_socket_path.parent().unwrap(); if run_sysmaster.exists() { - let _ = fs_util::chmod("/run/sysmaster", 0o755); + let _ = fs::chmod("/run/sysmaster", 0o755); } /* remove the old socket if it exists */ if sctl_socket_path.exists() && !is_symlink(sctl_socket_path) { @@ -56,7 +56,7 @@ where ) .unwrap(); /* set SO_PASSCRED, we need it to check whether sctl is running under root */ - socket_util::set_pass_cred(socket_fd, true).unwrap(); + basic::socket::set_pass_cred(socket_fd, true).unwrap(); /* create the socket with mode 666 */ let old_mask = stat::umask(stat::Mode::from_bits_truncate(!0o666)); match socket::bind(socket_fd, &sctl_socket_addr) { @@ -97,7 +97,7 @@ where Ok(_) => (), Err(e) => log::error!("Commands failed: {:?}", e), } - basic::fd_util::close(client); + basic::fd::close(client); 0 } } diff --git a/core/sysmaster/src/manager/mod.rs b/core/sysmaster/src/manager/mod.rs index 46228b77e99ac4e39b7f7c93247afae9b3df59ec..4483ba3617a69a0d0258d222be0d649d8c64515c 100644 --- a/core/sysmaster/src/manager/mod.rs +++ b/core/sysmaster/src/manager/mod.rs @@ -25,7 +25,7 @@ pub(crate) mod signals; use self::config::ManagerConfig; use crate::unit::UnitManagerX; use alive_timer::AliveTimer; -use basic::fs_util::LookupPaths; +use basic::fs::LookupPaths; use basic::process::{self}; use basic::{CGROUP_SYSMASTER, MULTI_USER_TARGET}; use cgroup::CgController; @@ -488,7 +488,7 @@ impl Manager { fn run_generators(&self) { let paths = vec!["/usr/lib/sysmaster/system-generators"]; - if let Err(err) = basic::exec_util::execute_directories(paths) { + if let Err(err) = basic::exec::execute_directories(paths) { log::error!("run generators err: {}", err); } } diff --git a/core/sysmaster/src/manager/pre_install.rs b/core/sysmaster/src/manager/pre_install.rs index ad0f17d781e4896140db74aac5cfcfabc7ad2a90..698234788f89318689082aff4663dfc7ab15e24d 100644 --- a/core/sysmaster/src/manager/pre_install.rs +++ b/core/sysmaster/src/manager/pre_install.rs @@ -12,8 +12,8 @@ // #![allow(non_snake_case)] use crate::unit::{unit_name_to_type, UeConfigInstall, UnitType}; -use basic::fs_util::is_symlink; -use basic::fs_util::LookupPaths; +use basic::fs::is_symlink; +use basic::fs::LookupPaths; use bitflags::bitflags; use core::error::*; use nix::unistd::UnlinkatFlags; @@ -311,7 +311,7 @@ impl InstallContext { let source = install.path(); for symlink in symlinks { let target = format!("{}/{}", target_path, symlink); - if let Err(e) = basic::fs_util::symlink(&source, &target, false) { + if let Err(e) = basic::fs::symlink(&source, &target, false) { log::warn!("Failed to create symlink {} -> {}: {}", &target, &source, e); continue; } @@ -346,7 +346,7 @@ impl InstallContext { } } - if let Err(e) = basic::fs_util::symlink(&source, &target, false) { + if let Err(e) = basic::fs::symlink(&source, &target, false) { log::warn!("Failed to create symlink {} -> {}: {}", &target, &source, e); continue; } @@ -731,7 +731,7 @@ impl Install { #[cfg(test)] mod test { use super::{Install, PresetAction, PresetMode, PresetRule, Presets}; - use basic::fs_util::LookupPaths; + use basic::fs::LookupPaths; use std::rc::Rc; #[test] diff --git a/core/sysmaster/src/mount/setup.rs b/core/sysmaster/src/mount/setup.rs index f191070f535596853ef3a946ebfd9f26c33eddb7..7dad6116894b0bdf1a592b0e1684a1a0cec140db 100644 --- a/core/sysmaster/src/mount/setup.rs +++ b/core/sysmaster/src/mount/setup.rs @@ -12,7 +12,7 @@ //! mount the cgroup systems use basic::machine::Machine; -use basic::{cmdline, machine, mount_util}; +use basic::{cmdline, machine, mount}; use bitflags::bitflags; use cgroup::{self, CgController, CgType, CG_BASE_DIR}; use core::error::*; @@ -377,7 +377,7 @@ impl MountPoint { } fn invalid_mount_point(&self, flags: AtFlags) -> Result { - if basic::fs_util::path_equal(&self.target, "/") { + if basic::fs::path_equal(&self.target, "/") { return Ok(true); } @@ -385,7 +385,7 @@ impl MountPoint { // symlink let path = Path::new(&self.target); - let file = basic::fs_util::open_parent( + let file = basic::fs::open_parent( path, OFlag::O_PATH | OFlag::O_CLOEXEC, Mode::from_bits(0).unwrap(), @@ -393,11 +393,8 @@ impl MountPoint { let last_file_name = path.file_name().unwrap_or_default(); - let ret = mount_util::mount_point_fd_valid( - file.as_raw_fd(), - last_file_name.to_str().unwrap(), - flags, - )?; + let ret = + mount::mount_point_fd_valid(file.as_raw_fd(), last_file_name.to_str().unwrap(), flags)?; Ok(ret) } @@ -521,7 +518,7 @@ fn pair_controller(controller: &str) -> Option { fn symlink_controller(source: String, alias: String) -> Result<()> { let target_path = Path::new(CG_BASE_DIR).join(alias); let target = target_path.to_str().unwrap(); - match basic::fs_util::symlink(&source, target, false) { + match basic::fs::symlink(&source, target, false) { Ok(()) => Ok(()), Err(basic::Error::Nix { source: Errno::EEXIST, @@ -539,22 +536,17 @@ fn symlink_controller(source: String, alias: String) -> Result<()> { } fn cg_unified_wanted() -> bool { - let cg_ver = cgroup::cg_type(); - - if let Ok(v) = cg_ver { + if let Ok(v) = cgroup::cg_type() { return v == CgType::UnifiedV2; } - let ret = cmdline::proc_cmdline_get_bool("sysmaster.unified_cgroup_hierarchy"); - if let Ok(v) = ret { - return v; + if basic::cmdline::Cmdline::default().has_param("systemd.unified_cgroup_hierarchy") { + return true; } - let ret = cmdline::cmdline_get_value("cgroup_no_v1"); - if let Ok(v) = ret { - if v.is_some() && v.unwrap() == "all" { - return true; - } + let v = cmdline::Cmdline::default().get_param("cgroup_no_v1"); + if v.is_some() && v.unwrap() == "all" { + return true; } false @@ -579,10 +571,5 @@ fn cg_unifiedv1_wanted() -> bool { } } - let ret = cmdline::proc_cmdline_get_bool("sysmaster.unified_v1_controller"); - if let Ok(v) = ret { - return v; - } - - false + cmdline::Cmdline::default().has_param("systemd.unified_v1_controller") } diff --git a/core/sysmaster/src/unit/entry/uentry.rs b/core/sysmaster/src/unit/entry/uentry.rs index ca995b15576262ba9b6d0f4b72eeb904fc156b68..1d3cc7ce1f5a05faeefa1527fbefbb8c91aea9ac 100644 --- a/core/sysmaster/src/unit/entry/uentry.rs +++ b/core/sysmaster/src/unit/entry/uentry.rs @@ -22,7 +22,7 @@ use crate::unit::data::{DataManager, UnitState}; use crate::unit::rentry::{UnitLoadState, UnitRe}; use crate::unit::util::UnitFile; use basic::process::{self, my_child}; -use basic::time_util::{now_clockid, UnitTimeStamp}; +use basic::time::{now_clockid, UnitTimeStamp}; use cgroup::{self, CgFlags}; use core::error::*; use core::rel::ReStation; @@ -861,7 +861,7 @@ mod tests { use crate::manager::RELI_HISTORY_MAX_DBS; use crate::unit::rentry::UnitRe; use crate::unit::test::test_utils::UmIfD; - use basic::fs_util::LookupPaths; + use basic::fs::LookupPaths; use core::rel::{ReliConf, Reliability}; use core::unit::UnitType; use std::rc::Rc; diff --git a/core/sysmaster/src/unit/execute/spawn.rs b/core/sysmaster/src/unit/execute/spawn.rs index 01651289dd5764d72c588e7c8f3bf02cebe8d73d..d603cac9e25fad95d47a9052abb8b7c979536271 100644 --- a/core/sysmaster/src/unit/execute/spawn.rs +++ b/core/sysmaster/src/unit/execute/spawn.rs @@ -11,7 +11,7 @@ // See the Mulan PSL v2 for more details. use super::super::entry::Unit; -use basic::fd_util; +use basic::fd; use core::error::*; use core::exec::{ExecCommand, ExecContext, ExecFlags, ExecParameters, WorkingDirectory}; use nix::fcntl::FcntlArg; @@ -369,7 +369,7 @@ fn close_all_fds(fds: &[i32]) -> bool { continue; } - fd_util::close(fd); + fd::close(fd); } true } @@ -389,7 +389,7 @@ fn shift_fds(fds: &mut [i32]) -> bool { Ok(v) => v, }; - fd_util::close(fds[i as usize]); + fd::close(fds[i as usize]); fds[i as usize] = nfd; @@ -411,11 +411,11 @@ fn shift_fds(fds: &mut [i32]) -> bool { fn flags_fds(fds: &mut Vec, nonblock: bool) -> bool { for fd in fds { - if fd_util::fd_nonblock(*fd, nonblock).is_err() { + if fd::fd_nonblock(*fd, nonblock).is_err() { return false; } - if fd_util::fd_cloexec(*fd, false).is_err() { + if fd::fd_cloexec(*fd, false).is_err() { return false; } } diff --git a/core/sysmaster/src/unit/manager.rs b/core/sysmaster/src/unit/manager.rs index 7eedc2f28180789f6b63326c4e5679d685cca7fd..245b929b0f1beb8a07a2410cdca8076165b5ea23 100644 --- a/core/sysmaster/src/unit/manager.rs +++ b/core/sysmaster/src/unit/manager.rs @@ -34,11 +34,10 @@ use crate::manager::pre_install::{Install, PresetMode}; use crate::manager::State; use crate::unit::data::{DataManager, UnitState}; use crate::utils::table::{TableOp, TableSubscribe}; -use basic::cmdline::get_process_cmdline; -use basic::fs_util::LookupPaths; +use basic::fs::LookupPaths; use basic::show_table::{CellColor, ShowTable}; -use basic::time_util::UnitTimeStamp; -use basic::{machine, process, rlimit, signal_util}; +use basic::time::UnitTimeStamp; +use basic::{machine, process, rlimit, signal}; use constants::SIG_SWITCH_ROOT_OFFSET; use core::error::*; use core::exec::ExecParameters; @@ -208,9 +207,9 @@ impl UnitManagerX { pub(crate) fn mask_unit(&self, unit_file: &str) -> Result<()> { log::info!("Masking unit {}.", unit_file); - let link_name_path = std::path::Path::new(basic::fs_util::ETC_SYSTEM_PATH).join(unit_file); + let link_name_path = std::path::Path::new(basic::fs::ETC_SYSTEM_PATH).join(unit_file); let target_path = std::path::Path::new("/dev/null"); - basic::fs_util::symlink( + basic::fs::symlink( target_path.to_str().unwrap(), link_name_path.to_str().unwrap(), false, @@ -220,7 +219,7 @@ impl UnitManagerX { pub(crate) fn unmask_unit(&self, unit_file: &str) -> Result<()> { log::info!("Unmasking unit {}.", unit_file); - let link_name_path = std::path::Path::new(basic::fs_util::ETC_SYSTEM_PATH).join(unit_file); + let link_name_path = std::path::Path::new(basic::fs::ETC_SYSTEM_PATH).join(unit_file); if !link_name_path.exists() { return Ok(()); } @@ -275,8 +274,8 @@ impl UnitManagerX { })?; } - signal_util::reset_all_signal_handlers(); - signal_util::reset_signal_mask(); + signal::reset_all_signal_handlers(); + signal::reset_signal_mask(); rlimit::rlimit_nofile_safe(); let res = unsafe { libc::kill(getppid(), libc::SIGRTMIN() + SIG_SWITCH_ROOT_OFFSET) }; if res == 0 { @@ -960,7 +959,7 @@ impl UnitManager { } res += &pid.to_string(); res += " "; - res += get_process_cmdline(pid).as_str(); + res += &basic::cmdline::Cmdline::new(*pid).get_cmdline(); } res } diff --git a/core/sysmaster/src/unit/notify.rs b/core/sysmaster/src/unit/notify.rs index e6cb6f10752882945132acd973e3098d3bf2e2a9..fff80ce46613ffcf782219fb99b6d635ebc7f8f0 100644 --- a/core/sysmaster/src/unit/notify.rs +++ b/core/sysmaster/src/unit/notify.rs @@ -14,7 +14,7 @@ use super::datastore::UnitDb; use super::entry::UnitX; use super::rentry::UnitRe; use crate::job::JobManager; -use basic::{fd_util, socket_util}; +use basic::fd; use core::error::*; use core::rel::{ReStation, ReliLastFrame, Reliability}; use event::{EventState, EventType, Events, Source}; @@ -181,7 +181,7 @@ impl Notify { return Err(e); } socket::setsockopt(fd, sockopt::PassCred, &true)?; - if let Err(e) = socket_util::set_receive_buffer(fd, 1024 * 1014 * 8) { + if let Err(e) = basic::socket::set_receive_buffer(fd, 1024 * 1014 * 8) { log::error!("Failed to set the notify socket receive buffer: {}", e); } @@ -294,7 +294,7 @@ fn notify_peek_pid(fd: RawFd, flags: MsgFlags) -> Result { // get message information let (received_cred, received_fds) = notify_trans_recvmsg(&msgs); for fd in received_fds.iter() { - fd_util::close(*fd); + fd::close(*fd); } // check diff --git a/core/sysmaster/src/unit/test/mod.rs b/core/sysmaster/src/unit/test/mod.rs index 70c5aa2f8d697143a059fc9bb855e5b09bcb16ee..0ddf0b25f11717de650d69063f92073cb83b3051 100644 --- a/core/sysmaster/src/unit/test/mod.rs +++ b/core/sysmaster/src/unit/test/mod.rs @@ -22,7 +22,7 @@ pub(crate) mod test_utils { util::{self, UnitFile}, }, }; - use basic::fs_util::LookupPaths; + use basic::fs::LookupPaths; use core::rel::Reliability; use core::unit::UmIf; pub(crate) struct UmIfD; diff --git a/core/sysmaster/src/unit/uload.rs b/core/sysmaster/src/unit/uload.rs index ff454dd480b1ffd54201a39bc922a11d26e15907..6ae470f9e433bd1bebcc4af815704b0e96a39fbf 100644 --- a/core/sysmaster/src/unit/uload.rs +++ b/core/sysmaster/src/unit/uload.rs @@ -19,7 +19,7 @@ use super::runtime::UnitRT; use super::util::UnitFile; use super::util::{self}; use crate::utils::table::{TableOp, TableSubscribe}; -use basic::fs_util::LookupPaths; +use basic::fs::LookupPaths; use core::unit::{unit_name_is_valid, UnitNameFlags, UnitType}; use std::cell::RefCell; use std::rc::{Rc, Weak}; diff --git a/core/sysmaster/src/unit/util/unit_file.rs b/core/sysmaster/src/unit/util/unit_file.rs index ef623edc62cc965f9fa89225e2ffc2664093e281..127cdeda92b3722dd025b2599f71696d08018b09 100644 --- a/core/sysmaster/src/unit/util/unit_file.rs +++ b/core/sysmaster/src/unit/util/unit_file.rs @@ -10,9 +10,8 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -use basic::fs_util; -use basic::fs_util::is_symlink; -use basic::fs_util::LookupPaths; +use basic::fs::is_symlink; +use basic::fs::LookupPaths; use core::unit::unit_name_is_valid; use core::unit::UnitNameFlags; use siphasher::sip::SipHasher24; @@ -177,7 +176,7 @@ impl UnitFileData { } let file_name = de.file_name().unwrap().to_string_lossy().to_string(); - let target_path = match fs_util::chase_symlink(&de) { + let target_path = match basic::fs::chase_symlink(&de) { Err(e) => { log::debug!("Failed to get the symlink of {:?}: {}, ignoring.", de, e); continue; diff --git a/exts/devmaster/Cargo.toml b/exts/devmaster/Cargo.toml index cb09ceee4f31306a9325174ad3ebc37183b0fc16..bcfc460c251bdb1b7e268a2ded0443d2f685326d 100644 --- a/exts/devmaster/Cargo.toml +++ b/exts/devmaster/Cargo.toml @@ -32,7 +32,7 @@ basic = { path = "../../libs/basic", default-features = false, features = [ "socket", "io", "argv", - "time_util", + "time", ] } blkid_rs = { path = "../../libs/blkid_rs" } device = { path = "../../libs/device", default-features = false } diff --git a/exts/devmaster/src/bin/devctl/main.rs b/exts/devmaster/src/bin/devctl/main.rs index a8a821f12e9ca1cbb3d63fb41bf538dca8e84c9e..a87f5bf726d992273971fa92ef79f18f46617ddb 100644 --- a/exts/devmaster/src/bin/devctl/main.rs +++ b/exts/devmaster/src/bin/devctl/main.rs @@ -15,7 +15,7 @@ #![allow(deprecated)] mod daemon; mod subcmds; -use basic::argv_util::invoked_as; +use basic::argv::invoked_as; use clap::Parser; use daemon::run_daemon; use libdevmaster::config::devmaster_conf::DEFAULT_CONFIG; diff --git a/exts/devmaster/src/bin/devctl/subcmds/info.rs b/exts/devmaster/src/bin/devctl/subcmds/info.rs index 1129fc6af4faa941b913882eb41a04365671b04f..4f9585cc4755aae88d85420b784235f80e4879c0 100644 --- a/exts/devmaster/src/bin/devctl/subcmds/info.rs +++ b/exts/devmaster/src/bin/devctl/subcmds/info.rs @@ -14,7 +14,7 @@ use crate::subcmds::utils; use crate::Result; -use basic::fd_util::{dot_or_dot_dot, xopendirat}; +use basic::fd::{dot_or_dot_dot, xopendirat}; use device::{device_enumerator::DeviceEnumerator, Device}; use nix::dir::Dir; use nix::fcntl::{AtFlags, OFlag}; diff --git a/exts/devmaster/src/bin/devctl/subcmds/monitor.rs b/exts/devmaster/src/bin/devctl/subcmds/monitor.rs index 50f310a22377108baff7106a8f262fd14739c563..81cad5fcc535de37bffd5603909d5fe48fe7fb1c 100644 --- a/exts/devmaster/src/bin/devctl/subcmds/monitor.rs +++ b/exts/devmaster/src/bin/devctl/subcmds/monitor.rs @@ -14,7 +14,7 @@ //! use crate::Result; -use basic::socket_util::set_receive_buffer; +use basic::socket::set_receive_buffer; use device::{device_monitor::DeviceMonitor, device_monitor::MonitorNetlinkGroup}; use event::{EventState, EventType, Events, Source}; use nix::errno::Errno; diff --git a/exts/devmaster/src/bin/devctl/subcmds/settle.rs b/exts/devmaster/src/bin/devctl/subcmds/settle.rs index 7bbe69fc6192646c4debef953cfce2fbe8e3cc22..4874ca7724aa824020249533d0b5fa484b98d236 100644 --- a/exts/devmaster/src/bin/devctl/subcmds/settle.rs +++ b/exts/devmaster/src/bin/devctl/subcmds/settle.rs @@ -15,7 +15,7 @@ use crate::subcmds::utils::devmaster_queue_is_empty; use crate::Result; -use basic::time_util::{parse_sec, USEC_INFINITY, USEC_PER_SEC}; +use basic::time::{parse_sec, USEC_INFINITY, USEC_PER_SEC}; use event::{EventState, EventType, Events, Source}; use libdevmaster::framework::control_manager::CONTROL_MANAGER_LISTEN_ADDR; use nix::sys::inotify::AddWatchFlags; diff --git a/exts/devmaster/src/lib/framework/job_queue.rs b/exts/devmaster/src/lib/framework/job_queue.rs index e488f4802662e98bb34df5c2efafa8e2946f32cf..9037df173fe606826620e5929525da064e6cfe47 100644 --- a/exts/devmaster/src/lib/framework/job_queue.rs +++ b/exts/devmaster/src/lib/framework/job_queue.rs @@ -13,7 +13,7 @@ //! job queue //! use crate::{error::*, framework::*}; -use basic::fs_util::touch_file; +use basic::fs::touch_file; use device::device::Device; use event::Events; use nix::unistd::unlink; diff --git a/exts/devmaster/src/lib/framework/uevent_monitor.rs b/exts/devmaster/src/lib/framework/uevent_monitor.rs index 0add91f6737a0ea276ff21c9850070791adfd962..c042d5a03a7a428b2d9da22cfc2c6b4ef9f56a83 100644 --- a/exts/devmaster/src/lib/framework/uevent_monitor.rs +++ b/exts/devmaster/src/lib/framework/uevent_monitor.rs @@ -39,7 +39,7 @@ impl UeventMonitor { /// forcely set the size of socket receive buffer pub fn set_receive_buffer(&self, v: usize) { - basic::socket_util::set_receive_buffer(self.device_monitor.fd(), v).unwrap(); + basic::socket::set_receive_buffer(self.device_monitor.fd(), v).unwrap(); } } diff --git a/exts/devmaster/src/lib/rules/exec_mgr.rs b/exts/devmaster/src/lib/rules/exec_mgr.rs index 3f6cd143f268e86d04257f5499518b1242c242e5..22b9a2ad64b132d4f30fac9da4b8ef3336309aeb 100644 --- a/exts/devmaster/src/lib/rules/exec_mgr.rs +++ b/exts/devmaster/src/lib/rules/exec_mgr.rs @@ -26,10 +26,7 @@ use crate::{ rules::*, utils::{commons::*, spawn::*}, }; -use basic::{ - cmdline::cmdline_get_item, fs_util::write_string_file, naming_scheme::*, parse::parse_mode, - unistd::*, -}; +use basic::{fs::write_string_file, naming_scheme::*, parse::parse_mode, unistd::*}; use device::{Device, DeviceAction}; use fnmatch_sys::fnmatch; use libc::{gid_t, mode_t, uid_t}; @@ -905,17 +902,8 @@ impl ExecuteManager { Ok(token.read().unwrap().as_ref().unwrap().op == OperatorType::Match) } MatchImportCmdline => { - let s = cmdline_get_item(&token_value).map_err(|e| { - log_rule_token!(error, token.read().unwrap().as_ref().unwrap(), e); - Error::RulesExecuteError { - msg: format!( - "Apply '{}' failed: {}", - token.read().unwrap().as_ref().unwrap(), - e - ), - errno: Errno::EINVAL, - } - })?; + let cmdline = basic::cmdline::Cmdline::default(); + let s = cmdline.get_param(&token_value); if s.is_none() { return Ok(token.read().unwrap().as_ref().unwrap().op == OperatorType::Nomatch); diff --git a/exts/devmaster/src/lib/rules/node.rs b/exts/devmaster/src/lib/rules/node.rs index 830801ad519b633897d81c689c0d237d079d04b5..a6ac9adc55403e5d6eab52c06958d30689dd1eb5 100644 --- a/exts/devmaster/src/lib/rules/node.rs +++ b/exts/devmaster/src/lib/rules/node.rs @@ -33,9 +33,9 @@ //! directory, the directory will be removed. use crate::{error::*, log_dev, log_dev_option}; -use basic::fs_util::{chmod, path_simplify}; -use basic::fs_util::{fchmod_and_chown, futimens_opath, symlink}; -use basic::{fd_util::xopendirat, fs_util::remove_dir_until}; +use basic::fs::{chmod, path_simplify}; +use basic::fs::{fchmod_and_chown, futimens_opath, symlink}; +use basic::{fd::xopendirat, fs::remove_dir_until}; use cluFlock::ExclusiveFlock; use device::Device; use libc::{mode_t, S_IFBLK, S_IFCHR, S_IFLNK, S_IFMT}; @@ -678,7 +678,7 @@ pub(crate) fn cleanup_prior_dir() -> Result<()> { #[cfg(test)] mod test { use super::*; - use basic::fs_util::{is_symlink, touch_file}; + use basic::fs::{is_symlink, touch_file}; use device::device_enumerator::*; use device::utils::LoopDev; use nix::unistd::unlink; diff --git a/exts/devmaster/src/lib/rules/rules_load.rs b/exts/devmaster/src/lib/rules/rules_load.rs index 49da2d63d6460613660131cd890e0953438ddac2..438e812f21ae965a054ddc797f3dfc57f611fa4f 100644 --- a/exts/devmaster/src/lib/rules/rules_load.rs +++ b/exts/devmaster/src/lib/rules/rules_load.rs @@ -1725,7 +1725,7 @@ impl RuleToken { #[cfg(test)] pub(crate) mod tests { - use basic::fs_util::touch_file; + use basic::fs::touch_file; use log::init_log; use log::Level; diff --git a/exts/fstab/src/fstab_item.rs b/exts/fstab/src/fstab_item.rs index a9238d56e6332685e849a32a37f73273a9a32de5..9bd92e6b279155315b3fe30edcd17b6aa4a3d67b 100644 --- a/exts/fstab/src/fstab_item.rs +++ b/exts/fstab/src/fstab_item.rs @@ -12,7 +12,7 @@ //! fstab_item encapsulates six fields and status of /etc/fstab. -use basic::mount_util::read_lines; +use basic::mount::read_lines; /// FSTabItem structure pub struct FSTabItem { diff --git a/exts/fstab/src/main.rs b/exts/fstab/src/main.rs index 4a8e06604800e2a298001823760c85e093daaddd..09d7dd3464606cb28c93098e9789103063e26ef5 100644 --- a/exts/fstab/src/main.rs +++ b/exts/fstab/src/main.rs @@ -19,7 +19,7 @@ //! # limit //! 1. The current device only supports configuration as full directory or UUID. -use basic::mount_util::{is_mount_point, is_swap}; +use basic::mount::{is_mount_point, is_swap}; use basic::{FSTAB_PATH, MOUNT_BIN, SWAP_BIN}; use inotify::{EventMask, Inotify, WatchMask}; use std::collections::HashSet; diff --git a/exts/getty-generator/src/main.rs b/exts/getty-generator/src/main.rs index dbb0ad13ba6217d17ee9eba3694698f877b954b9..e99bf6bfd300247a79660d30a7f894331f80c274 100644 --- a/exts/getty-generator/src/main.rs +++ b/exts/getty-generator/src/main.rs @@ -387,7 +387,7 @@ fn create_getty(tty_type: &str, tty: &str) -> io::Result<()> { } fn concat_from_symlink(file_name: &str) -> String { - basic::fs_util::LIB_SYSTEM_PATH.to_string() + "/" + file_name + basic::fs::LIB_SYSTEM_PATH.to_string() + "/" + file_name } fn concat_to_symlink(file_name: &str) -> String { diff --git a/exts/hostname_setup/src/main.rs b/exts/hostname_setup/src/main.rs index 80693a4c1b12de6f327ed2d30d7669bdf25974e8..fa2fb8e1fd1bc1e16887fd15e178b2d686f36fdb 100644 --- a/exts/hostname_setup/src/main.rs +++ b/exts/hostname_setup/src/main.rs @@ -38,32 +38,30 @@ impl Hostname { } fn from_cmdline() -> Option { - let systemd_hostname = match cmdline::cmdline_get_value(SYSTEMD_HOSTNAME_KEY) { - Err(e) => { + let mut hostname = match cmdline::Cmdline::default().get_param(SYSTEMD_HOSTNAME_KEY) { + None => { log::warn!( - "Failed to get proc cmdline by key {}: {}", - SYSTEMD_HOSTNAME_KEY, - e + "Failed to get proc cmdline by key {}.", + SYSTEMD_HOSTNAME_KEY ); - None + "".to_string() } - Ok(hostname) => hostname, + Some(h) => h, }; - systemd_hostname.map_or_else( - || match cmdline::cmdline_get_value(SYSMASTER_HOSTNAME_KEY) { - Err(e) => { + if hostname.is_empty() { + hostname = match cmdline::Cmdline::default().get_param(SYSMASTER_HOSTNAME_KEY) { + None => { log::warn!( - "Failed to get proc cmdline by key {}: {}", - SYSMASTER_HOSTNAME_KEY, - e + "Failed to get proc cmdline by key {}.", + SYSMASTER_HOSTNAME_KEY ); - None + "".to_string() } - Ok(hostname) => hostname.and_then(|hostname| Hostname::from_string(&hostname)), - }, - |hostname| Hostname::from_string(&hostname), - ) + Some(h) => h, + }; + } + Hostname::from_string(&hostname) } fn from_etc_hostname() -> Option { diff --git a/exts/machine-id-setup/src/main.rs b/exts/machine-id-setup/src/main.rs index 18605eed9107bedb84269c5b4a6b7c29acd2903c..8450566f298f09c0c28160473789c2609a9d7219 100644 --- a/exts/machine-id-setup/src/main.rs +++ b/exts/machine-id-setup/src/main.rs @@ -13,7 +13,7 @@ //! use basic::{ - id128_util, + id128, machine::{self, machine_id_setup}, }; use nix::{Error, Result}; @@ -48,9 +48,9 @@ fn main() -> Result<()> { if args.contains(&String::from("--commit")) { let etc_machine_id = "/etc/machine-id".to_string(); machine::machine_id_commit()?; - id = match id128_util::id128_read_by_path( + id = match id128::id128_read_by_path( Path::new(&etc_machine_id), - id128_util::Id128FormatFlag::ID128_FORMAT_PLAIN, + id128::Id128FormatFlag::ID128_FORMAT_PLAIN, ) { Ok(id) => id, Err(e) => { diff --git a/exts/random_seed/src/random_seed.rs b/exts/random_seed/src/random_seed.rs index 74846a6ff459e9ad9176b1249a272d2e6d1fc586..ee054a089d2bc895d4730bf9af7a3e35c728220d 100644 --- a/exts/random_seed/src/random_seed.rs +++ b/exts/random_seed/src/random_seed.rs @@ -10,7 +10,7 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -use basic::io_util::loop_read; +use basic::io::loop_read; use nix::ioctl_write_ptr; use std::alloc::{alloc, dealloc, Layout}; use std::ffi::CString; diff --git a/exts/switch_root/src/switch_root.rs b/exts/switch_root/src/switch_root.rs index 6c17c02f857049b85c7a35655e3dfb61746fcfed..86ba630ccc429642603acde517b872b5bc242b46 100644 --- a/exts/switch_root/src/switch_root.rs +++ b/exts/switch_root/src/switch_root.rs @@ -10,7 +10,7 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -use basic::{machine, mount_util::MountInfoParser, IN_SET}; +use basic::{machine, mount::MountInfoParser, IN_SET}; use nix::{ dir::Type, errno::Errno, diff --git a/libs/basic/Cargo.toml b/libs/basic/Cargo.toml index 965c305546fcc7c6cba28eb92994a0b38ab669a2..ccf7953ccf873e40673ff7115d8c175308017b59 100644 --- a/libs/basic/Cargo.toml +++ b/libs/basic/Cargo.toml @@ -64,12 +64,12 @@ full = [ "unit_name", "strbuf", "argv", - "exec_util", + "exec", "random", "id128", "namespace", - "time_util", - "path_util", + "time", + "path", ] capability = [] @@ -90,7 +90,7 @@ argv = [] config = [] cpu = [] disk = [] -exec_util = [] +exec = [] fd = ["stat", "nix/ioctl", "nix/socket"] file = [] fs = ["pathdiff", "rand", "nix/fs", "nix/user"] @@ -121,5 +121,5 @@ sysfs = ["nix/dir"] unistd = ["nix/user"] unit_name = [] uuid = ["bitflags", "random"] -time_util = [] -path_util = [] +time = [] +path = [] diff --git a/libs/basic/src/argv_util.rs b/libs/basic/src/argv.rs similarity index 70% rename from libs/basic/src/argv_util.rs rename to libs/basic/src/argv.rs index 69b2d30f7980005ab6494763921d502e7b4c6d0e..6bb51f23264f17139b94fd3e872cca333eb4985e 100644 --- a/libs/basic/src/argv_util.rs +++ b/libs/basic/src/argv.rs @@ -10,11 +10,21 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -//! - +//! Arguments functions use std::path::Path; +/// The function checks if the first argument in the command line contains a specific token. +/// +/// Arguments: +/// +/// * `argv`: A vector of strings representing command line arguments passed to the program. The first +/// element of the vector is expected to be the name of the executable file. +/// * `token`: The `token` parameter is a string that represents a token or keyword that we want to +/// check for in the file name. +/// +/// Returns: /// +/// a boolean value. pub fn invoked_as(argv: Vec, token: &str) -> bool { if argv.is_empty() || token.is_empty() { return false; @@ -31,7 +41,7 @@ pub fn invoked_as(argv: Vec, token: &str) -> bool { #[cfg(test)] mod tests { - use crate::argv_util::invoked_as; + use crate::argv::invoked_as; #[test] fn test_invoked_as() { let argv = vec!["/a/bb////aabbcc".to_string()]; diff --git a/libs/basic/src/capability.rs b/libs/basic/src/capability.rs index ad25ce9d2d7185036bb7443d11a7726c93756528..e1e6ee062012bec86f7f6baa754c956ef0fbc0b7 100644 --- a/libs/basic/src/capability.rs +++ b/libs/basic/src/capability.rs @@ -10,141 +10,141 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -//! +//! Capability functions /// from #[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)] #[allow(non_camel_case_types)] #[repr(u8)] pub enum Capability { - /// `CAP_CHOWN` (from POSIX) - CAP_CHOWN = 0, - /// `CAP_DAC_OVERRIDE` (from POSIX) - CAP_DAC_OVERRIDE = 1, - /// `CAP_DAC_READ_SEARCH` (from POSIX) - CAP_DAC_READ_SEARCH = 2, - /// `CAP_FOWNER` (from POSIX) - CAP_FOWNER = 3, - /// `CAP_FSETID` (from POSIX) - CAP_FSETID = 4, - /// `CAP_KILL` (from POSIX) - CAP_KILL = 5, - /// `CAP_SETGID` (from POSIX) - CAP_SETGID = 6, - /// `CAP_SETUID` (from POSIX) - CAP_SETUID = 7, - /// `CAP_SETPCAP` (from Linux) - CAP_SETPCAP = 8, - /// - CAP_LINUX_IMMUTABLE = 9, - /// - CAP_NET_BIND_SERVICE = 10, - /// - CAP_NET_BROADCAST = 11, - /// - CAP_NET_ADMIN = 12, - /// - CAP_NET_RAW = 13, - /// - CAP_IPC_LOCK = 14, - /// - CAP_IPC_OWNER = 15, - /// `CAP_SYS_MODULE` (from Linux) - CAP_SYS_MODULE = 16, - /// `CAP_SYS_RAWIO` (from Linux) - CAP_SYS_RAWIO = 17, - /// `CAP_SYS_CHROOT` (from Linux) - CAP_SYS_CHROOT = 18, - /// `CAP_SYS_PTRACE` (from Linux) - CAP_SYS_PTRACE = 19, - /// `CAP_SYS_PACCT` (from Linux) - CAP_SYS_PACCT = 20, - /// `CAP_SYS_ADMIN` (from Linux) - CAP_SYS_ADMIN = 21, - /// `CAP_SYS_BOOT` (from Linux) - CAP_SYS_BOOT = 22, - /// `CAP_SYS_NICE` (from Linux) - CAP_SYS_NICE = 23, - /// `CAP_SYS_RESOURCE` (from Linux) - CAP_SYS_RESOURCE = 24, - /// `CAP_SYS_TIME` (from Linux) - CAP_SYS_TIME = 25, - /// `CAP_SYS_TTY_CONFIG` (from Linux) - CAP_SYS_TTY_CONFIG = 26, - /// `CAP_SYS_MKNOD` (from Linux, >= 2.4) - CAP_MKNOD = 27, - /// `CAP_LEASE` (from Linux, >= 2.4) - CAP_LEASE = 28, - /// - CAP_AUDIT_WRITE = 29, - /// `CAP_AUDIT_CONTROL` (from Linux, >= 2.6.11) - CAP_AUDIT_CONTROL = 30, - /// - CAP_SETFCAP = 31, - /// - CAP_MAC_OVERRIDE = 32, - /// - CAP_MAC_ADMIN = 33, - /// `CAP_SYSLOG` (from Linux, >= 2.6.37) - CAP_SYSLOG = 34, - /// `CAP_WAKE_ALARM` (from Linux, >= 3.0) - CAP_WAKE_ALARM = 35, - /// - CAP_BLOCK_SUSPEND = 36, - /// `CAP_AUDIT_READ` (from Linux, >= 3.16). - CAP_AUDIT_READ = 37, - /// `CAP_PERFMON` (from Linux, >= 5.8). - CAP_PERFMON = 38, - /// `CAP_BPF` (from Linux, >= 5.8). - CAP_BPF = 39, - /// `CAP_CHECKPOINT_RESTORE` (from Linux, >= 5.9). - CAP_CHECKPOINT_RESTORE = 40, + /// `CHOWN` (from POSIX) + CHOWN = 0, + /// `DAC_OVERRIDE` (from POSIX) + DAC_OVERRIDE = 1, + /// `DAC_READ_SEARCH` (from POSIX) + DAC_READ_SEARCH = 2, + /// `FOWNER` (from POSIX) + FOWNER = 3, + /// `FSETID` (from POSIX) + FSETID = 4, + /// `KILL` (from POSIX) + KILL = 5, + /// `SETGID` (from POSIX) + SETGID = 6, + /// `SETUID` (from POSIX) + SETUID = 7, + /// `SETPCAP` (from Linux) + SETPCAP = 8, + /// + LINUX_IMMUTABLE = 9, + /// + NET_BIND_SERVICE = 10, + /// + NET_BROADCAST = 11, + /// + NET_ADMIN = 12, + /// + NET_RAW = 13, + /// + IPC_LOCK = 14, + /// + IPC_OWNER = 15, + /// `SYS_MODULE` (from Linux) + SYS_MODULE = 16, + /// `SYS_RAWIO` (from Linux) + SYS_RAWIO = 17, + /// `SYS_CHROOT` (from Linux) + SYS_CHROOT = 18, + /// `SYS_PTRACE` (from Linux) + SYS_PTRACE = 19, + /// `SYS_PACCT` (from Linux) + SYS_PACCT = 20, + /// `SYS_ADMIN` (from Linux) + SYS_ADMIN = 21, + /// `SYS_BOOT` (from Linux) + SYS_BOOT = 22, + /// `SYS_NICE` (from Linux) + SYS_NICE = 23, + /// `SYS_RESOURCE` (from Linux) + SYS_RESOURCE = 24, + /// `SYS_TIME` (from Linux) + SYS_TIME = 25, + /// `SYS_TTY_CONFIG` (from Linux) + SYS_TTY_CONFIG = 26, + /// `SYS_MKNOD` (from Linux, >= 2.4) + MKNOD = 27, + /// `LEASE` (from Linux, >= 2.4) + LEASE = 28, + /// + AUDIT_WRITE = 29, + /// `AUDIT_CONTROL` (from Linux, >= 2.6.11) + AUDIT_CONTROL = 30, + /// + SETFCAP = 31, + /// + MAC_OVERRIDE = 32, + /// + MAC_ADMIN = 33, + /// `SYSLOG` (from Linux, >= 2.6.37) + SYSLOG = 34, + /// `WAKE_ALARM` (from Linux, >= 3.0) + WAKE_ALARM = 35, + /// + BLOCK_SUSPEND = 36, + /// `AUDIT_READ` (from Linux, >= 3.16). + AUDIT_READ = 37, + /// `PERFMON` (from Linux, >= 5.8). + PERFMON = 38, + /// `BPF` (from Linux, >= 5.8). + BPF = 39, + /// `CHECKPOINT_RESTORE` (from Linux, >= 5.9). + CHECKPOINT_RESTORE = 40, } impl std::fmt::Display for Capability { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let name = match *self { - Capability::CAP_CHOWN => "CAP_CHOWN", - Capability::CAP_DAC_OVERRIDE => "CAP_DAC_OVERRIDE", - Capability::CAP_DAC_READ_SEARCH => "CAP_DAC_READ_SEARCH", - Capability::CAP_FOWNER => "CAP_FOWNER", - Capability::CAP_FSETID => "CAP_FSETID", - Capability::CAP_KILL => "CAP_KILL", - Capability::CAP_SETGID => "CAP_SETGID", - Capability::CAP_SETUID => "CAP_SETUID", - Capability::CAP_SETPCAP => "CAP_SETPCAP", - Capability::CAP_LINUX_IMMUTABLE => "CAP_LINUX_IMMUTABLE", - Capability::CAP_NET_BIND_SERVICE => "CAP_NET_BIND_SERVICE", - Capability::CAP_NET_BROADCAST => "CAP_NET_BROADCAST", - Capability::CAP_NET_ADMIN => "CAP_NET_ADMIN", - Capability::CAP_NET_RAW => "CAP_NET_RAW", - Capability::CAP_IPC_LOCK => "CAP_IPC_LOCK", - Capability::CAP_IPC_OWNER => "CAP_IPC_OWNER", - Capability::CAP_SYS_MODULE => "CAP_SYS_MODULE", - Capability::CAP_SYS_RAWIO => "CAP_SYS_RAWIO", - Capability::CAP_SYS_CHROOT => "CAP_SYS_CHROOT", - Capability::CAP_SYS_PTRACE => "CAP_SYS_PTRACE", - Capability::CAP_SYS_PACCT => "CAP_SYS_PACCT", - Capability::CAP_SYS_ADMIN => "CAP_SYS_ADMIN", - Capability::CAP_SYS_BOOT => "CAP_SYS_BOOT", - Capability::CAP_SYS_NICE => "CAP_SYS_NICE", - Capability::CAP_SYS_RESOURCE => "CAP_SYS_RESOURCE", - Capability::CAP_SYS_TIME => "CAP_SYS_TIME", - Capability::CAP_SYS_TTY_CONFIG => "CAP_SYS_TTY_CONFIG", - Capability::CAP_MKNOD => "CAP_MKNOD", - Capability::CAP_LEASE => "CAP_LEASE", - Capability::CAP_AUDIT_WRITE => "CAP_AUDIT_WRITE", - Capability::CAP_AUDIT_CONTROL => "CAP_AUDIT_CONTROL", - Capability::CAP_SETFCAP => "CAP_SETFCAP", - Capability::CAP_MAC_OVERRIDE => "CAP_MAC_OVERRIDE", - Capability::CAP_MAC_ADMIN => "CAP_MAC_ADMIN", - Capability::CAP_SYSLOG => "CAP_SYSLOG", - Capability::CAP_WAKE_ALARM => "CAP_WAKE_ALARM", - Capability::CAP_BLOCK_SUSPEND => "CAP_BLOCK_SUSPEND", - Capability::CAP_AUDIT_READ => "CAP_AUDIT_READ", - Capability::CAP_PERFMON => "CAP_PERFMON", - Capability::CAP_BPF => "CAP_BPF", - Capability::CAP_CHECKPOINT_RESTORE => "CAP_CHECKPOINT_RESTORE", + Capability::CHOWN => "CHOWN", + Capability::DAC_OVERRIDE => "DAC_OVERRIDE", + Capability::DAC_READ_SEARCH => "DAC_READ_SEARCH", + Capability::FOWNER => "FOWNER", + Capability::FSETID => "FSETID", + Capability::KILL => "KILL", + Capability::SETGID => "SETGID", + Capability::SETUID => "SETUID", + Capability::SETPCAP => "SETPCAP", + Capability::LINUX_IMMUTABLE => "LINUX_IMMUTABLE", + Capability::NET_BIND_SERVICE => "NET_BIND_SERVICE", + Capability::NET_BROADCAST => "NET_BROADCAST", + Capability::NET_ADMIN => "NET_ADMIN", + Capability::NET_RAW => "NET_RAW", + Capability::IPC_LOCK => "IPC_LOCK", + Capability::IPC_OWNER => "IPC_OWNER", + Capability::SYS_MODULE => "SYS_MODULE", + Capability::SYS_RAWIO => "SYS_RAWIO", + Capability::SYS_CHROOT => "SYS_CHROOT", + Capability::SYS_PTRACE => "SYS_PTRACE", + Capability::SYS_PACCT => "SYS_PACCT", + Capability::SYS_ADMIN => "SYS_ADMIN", + Capability::SYS_BOOT => "SYS_BOOT", + Capability::SYS_NICE => "SYS_NICE", + Capability::SYS_RESOURCE => "SYS_RESOURCE", + Capability::SYS_TIME => "SYS_TIME", + Capability::SYS_TTY_CONFIG => "SYS_TTY_CONFIG", + Capability::MKNOD => "MKNOD", + Capability::LEASE => "LEASE", + Capability::AUDIT_WRITE => "AUDIT_WRITE", + Capability::AUDIT_CONTROL => "AUDIT_CONTROL", + Capability::SETFCAP => "SETFCAP", + Capability::MAC_OVERRIDE => "MAC_OVERRIDE", + Capability::MAC_ADMIN => "MAC_ADMIN", + Capability::SYSLOG => "SYSLOG", + Capability::WAKE_ALARM => "WAKE_ALARM", + Capability::BLOCK_SUSPEND => "BLOCK_SUSPEND", + Capability::AUDIT_READ => "AUDIT_READ", + Capability::PERFMON => "PERFMON", + Capability::BPF => "BPF", + Capability::CHECKPOINT_RESTORE => "CHECKPOINT_RESTORE", }; write!(f, "{}", name) } @@ -155,47 +155,47 @@ impl std::str::FromStr for Capability { fn from_str(s: &str) -> std::result::Result { match s { - "CAP_CHOWN" => Ok(Capability::CAP_CHOWN), - "CAP_DAC_OVERRIDE" => Ok(Capability::CAP_DAC_OVERRIDE), - "CAP_DAC_READ_SEARCH" => Ok(Capability::CAP_DAC_READ_SEARCH), - "CAP_FOWNER" => Ok(Capability::CAP_FOWNER), - "CAP_FSETID" => Ok(Capability::CAP_FSETID), - "CAP_KILL" => Ok(Capability::CAP_KILL), - "CAP_SETGID" => Ok(Capability::CAP_SETGID), - "CAP_SETUID" => Ok(Capability::CAP_SETUID), - "CAP_SETPCAP" => Ok(Capability::CAP_SETPCAP), - "CAP_LINUX_IMMUTABLE" => Ok(Capability::CAP_LINUX_IMMUTABLE), - "CAP_NET_BIND_SERVICE" => Ok(Capability::CAP_NET_BIND_SERVICE), - "CAP_NET_BROADCAST" => Ok(Capability::CAP_NET_BROADCAST), - "CAP_NET_ADMIN" => Ok(Capability::CAP_NET_ADMIN), - "CAP_NET_RAW" => Ok(Capability::CAP_NET_RAW), - "CAP_IPC_LOCK" => Ok(Capability::CAP_IPC_LOCK), - "CAP_IPC_OWNER" => Ok(Capability::CAP_IPC_OWNER), - "CAP_SYS_MODULE" => Ok(Capability::CAP_SYS_MODULE), - "CAP_SYS_RAWIO" => Ok(Capability::CAP_SYS_RAWIO), - "CAP_SYS_CHROOT" => Ok(Capability::CAP_SYS_CHROOT), - "CAP_SYS_PTRACE" => Ok(Capability::CAP_SYS_PTRACE), - "CAP_SYS_PACCT" => Ok(Capability::CAP_SYS_PACCT), - "CAP_SYS_ADMIN" => Ok(Capability::CAP_SYS_ADMIN), - "CAP_SYS_BOOT" => Ok(Capability::CAP_SYS_BOOT), - "CAP_SYS_NICE" => Ok(Capability::CAP_SYS_NICE), - "CAP_SYS_RESOURCE" => Ok(Capability::CAP_SYS_RESOURCE), - "CAP_SYS_TIME" => Ok(Capability::CAP_SYS_TIME), - "CAP_SYS_TTY_CONFIG" => Ok(Capability::CAP_SYS_TTY_CONFIG), - "CAP_MKNOD" => Ok(Capability::CAP_MKNOD), - "CAP_LEASE" => Ok(Capability::CAP_LEASE), - "CAP_AUDIT_WRITE" => Ok(Capability::CAP_AUDIT_WRITE), - "CAP_AUDIT_CONTROL" => Ok(Capability::CAP_AUDIT_CONTROL), - "CAP_SETFCAP" => Ok(Capability::CAP_SETFCAP), - "CAP_MAC_OVERRIDE" => Ok(Capability::CAP_MAC_OVERRIDE), - "CAP_MAC_ADMIN" => Ok(Capability::CAP_MAC_ADMIN), - "CAP_SYSLOG" => Ok(Capability::CAP_SYSLOG), - "CAP_WAKE_ALARM" => Ok(Capability::CAP_WAKE_ALARM), - "CAP_BLOCK_SUSPEND" => Ok(Capability::CAP_BLOCK_SUSPEND), - "CAP_AUDIT_READ" => Ok(Capability::CAP_AUDIT_READ), - "CAP_PERFMON" => Ok(Capability::CAP_PERFMON), - "CAP_BPF" => Ok(Capability::CAP_BPF), - "CAP_CHECKPOINT_RESTORE" => Ok(Capability::CAP_CHECKPOINT_RESTORE), + "CHOWN" => Ok(Capability::CHOWN), + "DAC_OVERRIDE" => Ok(Capability::DAC_OVERRIDE), + "DAC_READ_SEARCH" => Ok(Capability::DAC_READ_SEARCH), + "FOWNER" => Ok(Capability::FOWNER), + "FSETID" => Ok(Capability::FSETID), + "KILL" => Ok(Capability::KILL), + "SETGID" => Ok(Capability::SETGID), + "SETUID" => Ok(Capability::SETUID), + "SETPCAP" => Ok(Capability::SETPCAP), + "LINUX_IMMUTABLE" => Ok(Capability::LINUX_IMMUTABLE), + "NET_BIND_SERVICE" => Ok(Capability::NET_BIND_SERVICE), + "NET_BROADCAST" => Ok(Capability::NET_BROADCAST), + "NET_ADMIN" => Ok(Capability::NET_ADMIN), + "NET_RAW" => Ok(Capability::NET_RAW), + "IPC_LOCK" => Ok(Capability::IPC_LOCK), + "IPC_OWNER" => Ok(Capability::IPC_OWNER), + "SYS_MODULE" => Ok(Capability::SYS_MODULE), + "SYS_RAWIO" => Ok(Capability::SYS_RAWIO), + "SYS_CHROOT" => Ok(Capability::SYS_CHROOT), + "SYS_PTRACE" => Ok(Capability::SYS_PTRACE), + "SYS_PACCT" => Ok(Capability::SYS_PACCT), + "SYS_ADMIN" => Ok(Capability::SYS_ADMIN), + "SYS_BOOT" => Ok(Capability::SYS_BOOT), + "SYS_NICE" => Ok(Capability::SYS_NICE), + "SYS_RESOURCE" => Ok(Capability::SYS_RESOURCE), + "SYS_TIME" => Ok(Capability::SYS_TIME), + "SYS_TTY_CONFIG" => Ok(Capability::SYS_TTY_CONFIG), + "MKNOD" => Ok(Capability::MKNOD), + "LEASE" => Ok(Capability::LEASE), + "AUDIT_WRITE" => Ok(Capability::AUDIT_WRITE), + "AUDIT_CONTROL" => Ok(Capability::AUDIT_CONTROL), + "SETFCAP" => Ok(Capability::SETFCAP), + "MAC_OVERRIDE" => Ok(Capability::MAC_OVERRIDE), + "MAC_ADMIN" => Ok(Capability::MAC_ADMIN), + "SYSLOG" => Ok(Capability::SYSLOG), + "WAKE_ALARM" => Ok(Capability::WAKE_ALARM), + "BLOCK_SUSPEND" => Ok(Capability::BLOCK_SUSPEND), + "AUDIT_READ" => Ok(Capability::AUDIT_READ), + "PERFMON" => Ok(Capability::PERFMON), + "BPF" => Ok(Capability::BPF), + "CHECKPOINT_RESTORE" => Ok(Capability::CHECKPOINT_RESTORE), _ => Err(crate::Error::Caps { what: format!("invalid capability: {}", s), }), @@ -204,13 +204,41 @@ impl std::str::FromStr for Capability { } impl Capability { + /// The `bitmask` function returns a bitmask where the bit at the position of `self` is set to 1 and + /// all other bits are set to 0. + /// + /// Returns: /// + /// The bitmask function returns a u64 value, which is the result of shifting 1u64 to the left by + /// the value of *self as u8. pub fn bitmask(&self) -> u64 { 1u64 << (*self as u8) } + /// The function returns the index of a value as an unsigned 8-bit integer. + /// + /// Returns: /// + /// The index of the object, converted to an unsigned 8-bit integer. pub fn index(&self) -> u8 { *self as u8 } } +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bitmask_test() { + let vec = Capability::WAKE_ALARM; + + assert_eq!(vec.bitmask(), 1 << 35); + } + + #[test] + fn index_test() { + let vec = Capability::WAKE_ALARM; + + assert_eq!(vec.index(), 35); + } +} diff --git a/libs/basic/src/cargo.rs b/libs/basic/src/cargo.rs index 4a4f66dfe1aa9b1f8a54213d57b9a6f26c0a0ae1..5ba443e258d242be4c4da72bd55397b9e1d58241 100644 --- a/libs/basic/src/cargo.rs +++ b/libs/basic/src/cargo.rs @@ -10,7 +10,7 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -//! +//! Cargo functions use crate::error::*; use std::env; @@ -80,4 +80,11 @@ mod tests { fn test_build_libblkid() { build_libblkid(); } + + #[test] + fn env_path_test() { + let result = env_path().unwrap(); + + println!("{:?}", result); + } } diff --git a/libs/basic/src/cmdline.rs b/libs/basic/src/cmdline.rs index 9a97ccea3275d5427948df0f3ad85703c9d9e6e2..52cdf5c391099cb6b74b74e355371836dd4a3016 100644 --- a/libs/basic/src/cmdline.rs +++ b/libs/basic/src/cmdline.rs @@ -10,140 +10,210 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -//! -use crate::config; -use crate::error::*; +//! Cmdline functions use nix::unistd::Pid; +use std::collections::HashMap; use std::collections::HashSet; use std::fs::File; -use std::io::{BufReader, Read}; -use std::path::Path; - -fn cmdline_content() -> Result { - let mut file = File::open("/proc/cmdline").context(IoSnafu)?; - - let mut buf = String::new(); - match file.read_to_string(&mut buf) { - Ok(s) => s, - Err(e) => { - return Err(Error::Io { source: e }); - } - }; - Ok(buf) +use std::io::Read; + +/// The `Cmdline` struct represents a command line with parameters and their corresponding values. +/// +/// Properties: +/// +/// * `params`: The `params` property is a `HashMap` that stores key-value pairs. The keys are of type +/// `String`, and the values are of type `Option`. The `Option` type allows for the possibility +/// of a value being present (`Some`) or absent (`None`). +#[derive(Debug)] +pub struct Cmdline { + params: HashMap>, + cmdline: String, } -/// read the content from /proc/cmdline and return the value depend the key -pub fn cmdline_get_value(key: &str) -> Result, Error> { - let buf = cmdline_content()?; - - let cmdline: Vec<&str> = buf.split_whitespace().collect(); - - for cmd in cmdline.iter() { - if let Some(k_val) = cmd.split_once('=') { - if k_val.0 == key { - return Ok(Some(k_val.1.to_string())); +impl Cmdline { + /// The function `read_cmdline` reads a file at a given path, extracts key-value pairs from its + /// contents, and returns them as a HashMap. + /// + /// Arguments: + /// + /// * `path`: A string representing the path to the file that needs to be read. + /// * `cmdline`: A mutable reference to a String that will be updated with the contents of the file + /// at the specified path. + /// + /// Returns: + /// + /// The function `read_cmdline` returns a `HashMap>`. + fn read_cmdline(path: String, cmdline: &mut String) -> HashMap> { + let mut params = HashMap::new(); + if let Ok(mut file) = File::open(path) { + let mut data = String::new(); + if file.read_to_string(&mut data).is_ok() { + *cmdline = data.clone(); + for item in data.split_whitespace() { + let mut parts = item.splitn(2, '='); + let key = parts.next().unwrap_or_default().to_string(); + let value = parts.next().map(|v| v.to_string()); + params.insert(key, value); + } } } + params } - Ok(None) -} - -/// read the content from /proc/cmdline and return specified item -///- -/// take `crashkernel=512M ro` for example, given `crashkernel` will -/// return `crashkernel=512M`, given `ro` will return `ro`, given -/// `foo` will return None. -pub fn cmdline_get_item(item: &str) -> Result, Error> { - let buf = cmdline_content()?; - let pair_item = item.to_string() + "="; - let cmdline: Vec<&str> = buf.split_whitespace().collect(); - - for cmd in cmdline.iter() { - if cmd.starts_with(&pair_item) || cmd.eq(&item) { - return Ok(Some(cmd.to_string())); - } + /// The function `get_cmdline` returns a clone of the `cmdline` string. + /// + /// Returns: + /// + /// A String is being returned. + pub fn get_cmdline(&self) -> String { + self.cmdline.clone() } - Ok(None) -} + /// The code defines a struct `Cmdline` with methods to read command line parameters from a process + /// and check if a parameter exists. + /// + /// Arguments: + /// + /// * `pid`: The `pid` parameter represents the process ID (PID) of a running process. It is used to + /// identify a specific process in the system. + /// + /// Returns: + /// + /// In the `new` function, a new instance of the `Cmdline` struct is being returned. + pub fn new(pid: Pid) -> Self { + let cmdfile = format!("/proc/{}/cmdline", pid); + let mut cmdline = String::new(); + let params = Self::read_cmdline(cmdfile, &mut cmdline); + + Cmdline { params, cmdline } + } -/// read the content from /proc/cmdline and return the bool value depend the key -pub fn proc_cmdline_get_bool(key: &str) -> Result { - let val = cmdline_get_value(key)?; + /// The `get_param` function retrieves a parameter value from a map and returns it as an + /// `Option`. + /// + /// Arguments: + /// + /// * `key`: The `key` parameter is a reference to a string that represents the key for which you + /// want to retrieve a value from the `params` map. + /// + /// Returns: + /// + /// The function `get_param` returns an `Option`. + pub fn get_param(&self, key: &str) -> Option { + self.params.get(key).map(|v| v.clone().unwrap_or_default()) + } - if val.is_none() { - return Ok(false); + /// The function `has_param` checks if a given key exists in a map called `params`. + /// + /// Arguments: + /// + /// * `key`: The `key` parameter is of type `&str`, which means it is a reference to a string slice. + /// + /// Returns: + /// + /// The `has_param` function returns a boolean value indicating whether the given `key` is present in + /// the `params` map. + pub fn has_param(&self, key: &str) -> bool { + self.params.contains_key(key) } - let r = config::parse_boolean(&val.unwrap())?; + /// The function `cmdline_item` parses a key-value pair and inserts the values into a + /// HashSet if the key is "module_blacklist". + /// + /// Arguments: + /// + /// * `key`: The key parameter is a String that represents the key of a key-value pair in a command + /// line item. + /// * `value`: The value parameter is a string that represents the value associated with the key in the + /// proc cmdline file. + /// * `data`: A mutable reference to a HashSet of strings. + pub fn cmdline_item(key: String, value: String, data: &mut HashSet) { + if key.eq("module_blacklist") { + if value.is_empty() { + return; + } - Ok(r) -} + let k: Vec<&str> = value.split(',').collect(); -/// parse cmdline item, insert module_blacklist's value to data -pub fn parse_proc_cmdline_item(key: String, value: String, data: &mut HashSet) { - if key.eq("module_blacklist") { - if value.is_empty() { - return; + for i in k { + data.insert(i.to_string()); + } } + } - let k: Vec<&str> = value.split(',').collect(); + /// The `parse` function reads the contents of the `/proc/cmdline` file, splits it into key-value + /// pairs, and calls a provided function to parse and store the values. + /// + /// Arguments: + /// + /// * `parse_item`: The `parse_item` parameter is a closure that takes three arguments: a `String` + /// representing a key, a `String` representing a value, and a mutable reference to `T` (the type of + /// `data`). The closure is responsible for parsing the key-value pair and updating the `data + /// * `data`: A mutable reference to the data structure that will be populated with the parsed + /// key-value pairs. + pub fn parse(parse_item: F, data: &mut T) + where + F: Fn(String, String, &mut T), + { + let mut cmdline = String::new(); + let line = Self::read_cmdline("/proc/cmdline".to_string(), &mut cmdline); + if line.is_empty() { + log::info!("/proc/cmdline is empty!"); + return; + } - for i in k { - data.insert(i.to_string()); + for i in cmdline.split(' ') { + let parts = i.split_once('='); + if let Some((key, value)) = parts { + parse_item(key.to_string(), value.to_string(), data); + } } } } -/// parse /proc/cmdline, Distinguish between key and value based on '=' -pub fn proc_cmdline_parse(parse_item: F, data: &mut T) -where - F: Fn(String, String, &mut T), -{ - let line = read_file(Path::new("/proc/cmdline")); - if line.is_empty() { - log::info!("/proc/1/cmdline is empty!"); - return; - } +impl Default for Cmdline { + fn default() -> Self { + let mut cmdline = String::new(); + let params = Self::read_cmdline("/proc/cmdline".to_string(), &mut cmdline); - let v: Vec<&str> = line.split(' ').collect(); - for i in &v { - let key = match i.to_string().split('=').next() { - None => continue, - Some(k) => k.to_string(), - }; - let value = match i.to_string().split('=').nth(1) { - None => continue, - Some(v) => v.to_string(), - }; - parse_item(key, value, data); + Cmdline { params, cmdline } } } -/// read /proc/PID/cmdline and return -pub fn get_process_cmdline(pid: &Pid) -> String { - let pid_str = pid.to_string(); - read_file(&Path::new("/proc").join(pid_str).join("cmdline")) -} +#[cfg(test)] +mod tests { + use super::*; -fn read_file(path: &Path) -> String { - let cmdline_path = path; - let file = match File::open(cmdline_path) { - Ok(file) => file, - Err(_) => { - return String::from(""); - } - }; - let buf_reader = BufReader::new(file); - let mut cmdline_content = String::new(); - for byte in buf_reader.bytes() { - let b = match byte { - Ok(b) => b, - Err(_) => break, - }; - let b = if b != 0 { b as char } else { ' ' }; - cmdline_content += &b.to_string(); + #[test] + fn test_cmdline_new() { + let cmdline = Cmdline::default(); + println!("{:?}", cmdline); + assert!(cmdline.has_param("root")); + assert!(cmdline.get_param("root").is_some()); + } + #[test] + fn test_get_cmdline() { + let mut cmdline = String::new(); + let params = Cmdline::read_cmdline("/proc/cmdline".to_string(), &mut cmdline); + let cmdline_str = cmdline.clone(); + let cmdline = Cmdline { params, cmdline }; + assert_eq!(cmdline.get_cmdline(), cmdline_str); + } + + #[test] + fn test_get_param() { + let mut cmdline = String::new(); + let params = Cmdline::read_cmdline("/proc/cmdline".to_string(), &mut cmdline); + let cmdline = Cmdline { params, cmdline }; + assert!(!cmdline.get_param("argv0").is_some()); + } + + #[test] + fn test_has_param() { + let mut cmdline = String::new(); + let params = Cmdline::read_cmdline("/proc/cmdline".to_string(), &mut cmdline); + let cmdline = Cmdline { params, cmdline }; + assert!(!cmdline.has_param("argv0")); + assert!(!cmdline.has_param("not_a_key")); } - cmdline_content } diff --git a/libs/basic/src/condition.rs b/libs/basic/src/condition.rs index 010a653f2f7f9fb947e48797974b926c8c8c213c..7bae2727b8a2d7b00b885e3582f57650305cae6e 100644 --- a/libs/basic/src/condition.rs +++ b/libs/basic/src/condition.rs @@ -22,12 +22,11 @@ use nix::{ use libc::{glob, glob_t, globfree, GLOB_NOSORT}; use crate::{ - cmdline, fd_util, fs_util::directory_is_not_empty, mount_util::is_mount_point, security, - sysfs::SysFs, unistd, + cmdline, fd, fs::directory_is_not_empty, mount::is_mount_point, security, sysfs::SysFs, unistd, }; #[cfg(target_env = "musl")] -use crate::mount_util::MountInfoParser; +use crate::mount::MountInfoParser; use std::{ ffi::CString, @@ -209,7 +208,7 @@ impl Condition { } Ok(v) => v, }; - (fd_util::stat_is_reg(s.st_mode) && (s.st_mode & 111 > 0)) as i8 + (fd::stat_is_reg(s.st_mode) && (s.st_mode & 111 > 0)) as i8 } fn test_file_not_empty(&self) -> i8 { @@ -222,10 +221,9 @@ impl Condition { } fn test_first_boot(&self) -> i8 { - if let Ok(ret) = cmdline::proc_cmdline_get_bool("sysmaster.condition-first-boot") { - if ret { - return ret as i8; - } + let ret = cmdline::Cmdline::default().has_param("sysmaster.condition-first-boot"); + if ret { + return ret as i8; } let result = self.params.eq("true"); @@ -241,20 +239,20 @@ impl Condition { } else { &self.params }; - let value = match cmdline::cmdline_get_item(search_value) { - Err(_) => { + let value = match cmdline::Cmdline::default().get_param(search_value) { + None => { log::info!("Failed to get cmdline content, assuming ConditionKernelCommandLine check failed."); return 0; } - Ok(v) => { - if v.is_none() { + Some(v) => { + if v.is_empty() { log::info!( "/proc/cmdline doesn't contain the given item: {}", search_value ); return 0; } - v.unwrap() + v } }; log::debug!("Found kernel command line value: {}", value); @@ -388,7 +386,7 @@ mod test { use super::{Condition, ConditionType}; use crate::{ cmdline, - fs_util::write_string_file, + fs::write_string_file, security::{self}, }; use core::panic; @@ -451,7 +449,7 @@ mod test { ConditionType::Capability, 0, 0, - String::from("CAP_CHOWN"), + String::from("CHOWN"), ); } @@ -816,19 +814,6 @@ mod test { ); } - #[test] - fn test_kernel_command_line() { - run_test( - |c| { - assert!(c.test(), "test kernel_command_line {}", c.params); - }, - ConditionType::KernelCommandLine, - 0, - 0, - String::from("root"), - ); - } - #[test] fn test_path_is_directory() { run_test( @@ -873,13 +858,11 @@ mod test { fn test_condition_first_boot() { run_test( |c| { - if let Ok(ret) = cmdline::proc_cmdline_get_bool("sysmaster.condition-first-boot") { - if ret { - println!( - "this test cannot be tested because we cannot modify the kernel parameters" - ); - return; - } + if cmdline::Cmdline::default().has_param("sysmaster.condition-first-boot") { + println!( + "this test cannot be tested because we cannot modify the kernel parameters" + ); + return; } let existed = Path::new("/run/sysmaster/first-boot").exists(); @@ -899,13 +882,11 @@ mod test { fn test_condition_first_boot_false() { run_test( |c| { - if let Ok(ret) = cmdline::proc_cmdline_get_bool("sysmaster.condition-first-boot") { - if ret { - println!( - "this test cannot be tested because we cannot modify the kernel parameters" - ); - return; - } + if cmdline::Cmdline::default().has_param("sysmaster.condition-first-boot") { + println!( + "this test cannot be tested because we cannot modify the kernel parameters" + ); + return; } let existed = Path::new("/run/sysmaster/first-boot").exists(); diff --git a/libs/basic/src/exec_util.rs b/libs/basic/src/exec.rs similarity index 60% rename from libs/basic/src/exec_util.rs rename to libs/basic/src/exec.rs index e27c4d6201bdb007087b02a90c0069247216d136..c6553f22a44fbc507e422babcd7515f54d495515 100644 --- a/libs/basic/src/exec_util.rs +++ b/libs/basic/src/exec.rs @@ -10,12 +10,22 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -//! +//! exec functions use nix::unistd; use std::{fs, os::unix::prelude::PermissionsExt, path::PathBuf, process::Command}; +/// The function `execute_directories` executes a given list of directories in parallel using fork and +/// waits for all child processes to finish. /// +/// Arguments: +/// +/// * `directories`: The `directories` parameter is a vector of string slices (`&str`) representing the +/// directories that need to be executed. +/// +/// Returns: +/// +/// The function `execute_directories` returns a `std::io::Result<()>`. pub fn execute_directories(directories: Vec<&str>) -> std::io::Result<()> { match unsafe { unistd::fork() } { Ok(unistd::ForkResult::Child) => { @@ -29,7 +39,16 @@ pub fn execute_directories(directories: Vec<&str>) -> std::io::Result<()> { } } +/// The function `do_execute` takes a list of directories, spawns child processes for each directory's +/// generator, and waits for them to finish. +/// +/// Arguments: /// +/// * `directories`: A vector of strings representing directories. +/// +/// Returns: +/// +/// The function `do_execute` returns a `std::io::Result<()>`. fn do_execute(directories: Vec<&str>) -> std::io::Result<()> { let mut child = Vec::new(); for generator in get_generator(directories)? { @@ -56,7 +75,12 @@ fn do_execute(directories: Vec<&str>) -> std::io::Result<()> { Ok(()) } -/// +/// The function `get_generator` takes a vector of directory paths (`directories`) as +/// input. It reads each directory and retrieves a list of file paths that have +/// executable permissions (`permissions().mode() & 0x111 != 0`). These file paths are +/// stored in a vector (`result`) and returned as a `std::io::Result>`. If +/// there is an error while reading a directory, an error message is logged and the +/// directory is skipped. fn get_generator(directories: Vec<&str>) -> std::io::Result> { let mut result: Vec = Vec::new(); @@ -83,3 +107,24 @@ fn get_generator(directories: Vec<&str>) -> std::io::Result> { } Ok(result) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_get_generator() { + let directories = vec!["/usr/bin", "/usr/lib64"]; + let _expected_files = vec![ + PathBuf::from("/usr/bin/ls"), + PathBuf::from("/usr/bin/cat"), + // Add more expected files here + ]; + + let actual_files = get_generator(directories).expect("get_generator() failed"); + + // assert_eq!(actual_files, expected_files); + + println!("get_generator() tests passed.{:?}", actual_files); + } +} diff --git a/libs/basic/src/fd_util.rs b/libs/basic/src/fd.rs similarity index 78% rename from libs/basic/src/fd_util.rs rename to libs/basic/src/fd.rs index 8715891cbb9b64b41ffb57485c3baff992756bc9..254fbf08d5ce0b444b685325de1c9dd97be4f9e7 100644 --- a/libs/basic/src/fd_util.rs +++ b/libs/basic/src/fd.rs @@ -10,7 +10,7 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -//! +//! fd functions use crate::error::*; use libc::off_t; use nix::{ @@ -33,7 +33,19 @@ pub fn stat_is_char(st_mode: u32) -> bool { st_mode & SFlag::S_IFMT.bits() & SFlag::S_IFCHR.bits() > 0 } +/// The function `fd_nonblock` sets the non-blocking flag on a file descriptor in Rust. /// +/// Arguments: +/// +/// * `fd`: The `fd` parameter is of type `RawFd`, which is typically an integer representing a file +/// descriptor. It is used to identify an open file or socket. +/// * `nonblock`: A boolean value indicating whether the file descriptor should be set to non-blocking +/// mode or not. If `nonblock` is `true`, the file descriptor will be set to non-blocking mode. If +/// `nonblock` is `false`, the file descriptor will be set to blocking mode. +/// +/// Returns: +/// +/// a `Result<()>`. pub fn fd_nonblock(fd: RawFd, nonblock: bool) -> Result<()> { assert!(fd >= 0); @@ -54,7 +66,19 @@ pub fn fd_nonblock(fd: RawFd, nonblock: bool) -> Result<()> { Ok(()) } +/// The `fd_cloexec` function sets the `FD_CLOEXEC` flag on a file descriptor in Rust. +/// +/// Arguments: +/// +/// * `fd`: The `fd` parameter is of type `RawFd`, which represents a raw file descriptor. It is an +/// integer value that identifies an open file or socket. +/// * `cloexec`: The `cloexec` parameter is a boolean value that determines whether the file descriptor +/// should be set with the `FD_CLOEXEC` flag or not. If `cloexec` is `true`, the `FD_CLOEXEC` flag will +/// be set on the file descriptor, indicating that it should /// +/// Returns: +/// +/// a `Result<()>`. pub fn fd_cloexec(fd: RawFd, cloexec: bool) -> Result<()> { assert!(fd >= 0); @@ -72,7 +96,17 @@ pub fn fd_cloexec(fd: RawFd, cloexec: bool) -> Result<()> { Ok(()) } +/// The function `fd_is_cloexec` checks if a file descriptor has the `FD_CLOEXEC` flag set. +/// +/// Arguments: +/// +/// * `fd`: The parameter `fd` is of type `RawFd`, which is typically an integer representing a file +/// descriptor. A file descriptor is a unique identifier that is used to access files, sockets, or other +/// I/O resources in an operating system. /// +/// Returns: +/// +/// The function `fd_is_cloexec` returns a boolean value. pub fn fd_is_cloexec(fd: RawFd) -> bool { assert!(fd >= 0); @@ -81,7 +115,12 @@ pub fn fd_is_cloexec(fd: RawFd) -> bool { fd_flag.contains(FdFlag::FD_CLOEXEC) } +/// The function `close` closes a file descriptor and logs a warning if it fails. +/// +/// Arguments: /// +/// * `fd`: The parameter `fd` is of type `RawFd`, which is typically an integer representing a file +/// descriptor. pub fn close(fd: RawFd) { if let Err(e) = nix::unistd::close(fd) { log::warn!("close fd {} failed, errno: {}", fd, e); @@ -113,7 +152,7 @@ pub fn fd_reopen(fd: RawFd, oflags: OFlag) -> Result { return Err(Error::Nix { source: e }); } - if !crate::stat_util::proc_mounted().map_err(|_| Error::Nix { + if !crate::stat::proc_mounted().map_err(|_| Error::Nix { source: Errno::ENOENT, })? { // if /proc/ is not mounted, this function can not work @@ -194,7 +233,7 @@ pub fn dot_or_dot_dot(name: &str) -> bool { } #[cfg(test)] mod tests { - use crate::fd_util::{stat_is_char, stat_is_reg}; + use crate::fd::{stat_is_char, stat_is_reg}; use nix::{ fcntl::{open, OFlag}, sys::stat::{fstat, Mode}, diff --git a/libs/basic/src/fs_util.rs b/libs/basic/src/fs.rs similarity index 100% rename from libs/basic/src/fs_util.rs rename to libs/basic/src/fs.rs diff --git a/libs/basic/src/id128_util.rs b/libs/basic/src/id128.rs similarity index 96% rename from libs/basic/src/id128_util.rs rename to libs/basic/src/id128.rs index 103b013ae434a59dc2b426e64f3a36a7477d6b05..7090e3f23a7e8966876418c11d043701cbd98f0f 100644 --- a/libs/basic/src/id128_util.rs +++ b/libs/basic/src/id128.rs @@ -10,7 +10,7 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -//! +//! id128 functions use bitflags::bitflags; use nix::{errno::Errno, fcntl, fcntl::OFlag, sys::stat::Mode, unistd}; use rand::Rng; @@ -205,7 +205,18 @@ pub fn id128_write(p: &Path, f_sync: &bool, id128: &str, f: Id128FormatFlag) -> Ok(()) } +/// The function generates a random string of hexadecimal characters and converts it to a UUID format if +/// specified. /// +/// Arguments: +/// +/// * `f`: The parameter `f` is of type `Id128FormatFlag`, which is an enum representing the formatting +/// options for the generated ID. It is used to determine whether the generated ID should be in UUID +/// format or not. +/// +/// Returns: +/// +/// a `nix::Result`. pub fn id128_randomize(f: Id128FormatFlag) -> nix::Result { let mut rng = rand::thread_rng(); let mut ret: String = String::new(); diff --git a/libs/basic/src/io_util.rs b/libs/basic/src/io.rs similarity index 99% rename from libs/basic/src/io_util.rs rename to libs/basic/src/io.rs index d443976f4ab375daf69163b3d1c70ff8cb9cf28c..2c7c8529c4b662b0036cf5688c462ce8fd0bd2f9 100644 --- a/libs/basic/src/io_util.rs +++ b/libs/basic/src/io.rs @@ -10,7 +10,7 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -//! +//! io functions use crate::error::*; use nix::{ libc, diff --git a/libs/basic/src/lib.rs b/libs/basic/src/lib.rs index 2b4f3783f01a95dca51f86c0f87af17f04501b67..c7d99d601158eef013df863c96c0a04baa575f3e 100644 --- a/libs/basic/src/lib.rs +++ b/libs/basic/src/lib.rs @@ -12,7 +12,7 @@ //! #[cfg(feature = "argv")] -pub mod argv_util; +pub mod argv; #[cfg(feature = "capability")] pub mod capability; #[cfg(feature = "cargo")] @@ -27,28 +27,28 @@ pub mod config; pub mod cpu; #[cfg(feature = "disk")] pub mod disk; -#[cfg(feature = "exec_util")] -pub mod exec_util; +#[cfg(feature = "exec")] +pub mod exec; #[cfg(feature = "fd")] -pub mod fd_util; +pub mod fd; #[cfg(feature = "fs")] -pub mod fs_util; +pub mod fs; #[cfg(feature = "host")] pub mod host; #[cfg(feature = "id128")] -pub mod id128_util; +pub mod id128; #[cfg(feature = "io")] -pub mod io_util; +pub mod io; #[cfg(feature = "machine")] pub mod machine; #[cfg(feature = "memory")] pub mod memory; #[cfg(feature = "mount")] -pub mod mount_util; +pub mod mount; #[cfg(feature = "murmurhash2")] pub mod murmurhash2; #[cfg(feature = "namespace")] -pub mod namespace_util; +pub mod namespace; #[cfg(feature = "naming_scheme")] pub mod naming_scheme; #[cfg(feature = "network")] @@ -57,12 +57,12 @@ pub mod network; pub mod os_release; #[cfg(feature = "parse")] pub mod parse; -#[cfg(feature = "path_util")] -pub mod path_util; +#[cfg(feature = "path")] +pub mod path; #[cfg(feature = "process")] pub mod process; #[cfg(feature = "random")] -pub mod random_util; +pub mod random; #[cfg(feature = "rlimit")] pub mod rlimit; #[cfg(feature = "security")] @@ -72,19 +72,19 @@ pub mod sensors; #[cfg(feature = "show_table")] pub mod show_table; #[cfg(feature = "signal")] -pub mod signal_util; +pub mod signal; #[cfg(feature = "socket")] -pub mod socket_util; +pub mod socket; #[cfg(feature = "stat")] -pub mod stat_util; +pub mod stat; #[cfg(feature = "strbuf")] pub mod strbuf; #[cfg(feature = "string")] pub mod string; #[cfg(feature = "sysfs")] pub mod sysfs; -#[cfg(feature = "time_util")] -pub mod time_util; +#[cfg(feature = "time")] +pub mod time; #[cfg(feature = "unistd")] pub mod unistd; #[cfg(feature = "unit_name")] diff --git a/libs/basic/src/machine.rs b/libs/basic/src/machine.rs index 990fb8ac6d1fbf97e9e95db69cbe938b8935f27d..c8b5f1ca6fbce8b356488c0f14d7c200e5522077 100644 --- a/libs/basic/src/machine.rs +++ b/libs/basic/src/machine.rs @@ -12,9 +12,8 @@ //! use crate::{ - fs_util, - id128_util::{self, Id128FormatFlag}, - mount_util, namespace_util, + id128::{self, Id128FormatFlag}, + namespace, }; use libc::syncfs; use log; @@ -357,17 +356,17 @@ pub fn machine_id_commit() -> Result<()> { sync(); - if !mount_util::is_mount_point(etc_machine_id) { + if !crate::mount::is_mount_point(etc_machine_id) { log::debug!("{:?} is not a mount point. Nothing to do.", etc_machine_id); return Ok(()); } - if !fs_util::check_filesystem(etc_machine_id, statfs::FsType(libc::TMPFS_MAGIC as FsTypeT)) { + if !crate::fs::check_filesystem(etc_machine_id, statfs::FsType(libc::TMPFS_MAGIC as FsTypeT)) { log::error!("{:?} is not on a temporary file system.", etc_machine_id); return Err(nix::Error::EROFS); } - match id128_util::id128_read_by_path(etc_machine_id, Id128FormatFlag::ID128_FORMAT_PLAIN) { + match id128::id128_read_by_path(etc_machine_id, Id128FormatFlag::ID128_FORMAT_PLAIN) { Ok(id128_string) => id128 = id128_string, Err(e) => { log::error!( @@ -379,23 +378,23 @@ pub fn machine_id_commit() -> Result<()> { } } - mnt_fd = namespace_util::namespace_open(&Pid::from_raw(0), Path::new(&"mnt".to_string()))?; + mnt_fd = namespace::namespace_open(&Pid::from_raw(0), Path::new(&"mnt".to_string()))?; - namespace_util::detach_mount_namespace()?; + namespace::detach_mount_namespace()?; if let Err(e) = mount::umount2(etc_machine_id, mount::MntFlags::from_bits(0).unwrap()) { log::error!("Failed to umount {:?}:{}", etc_machine_id, e); return Err(e); } - id128_util::id128_write( + id128::id128_write( etc_machine_id, &true, &id128, Id128FormatFlag::ID128_FORMAT_PLAIN, )?; - namespace_util::namespace_enter(&mnt_fd, sched::CloneFlags::CLONE_NEWNS)?; + namespace::namespace_enter(&mnt_fd, sched::CloneFlags::CLONE_NEWNS)?; mount::umount2(etc_machine_id, mount::MntFlags::MNT_DETACH) } @@ -404,7 +403,7 @@ fn generate_machine_id() -> Result { let dbus_machine_id = Path::new("/var/lib/dbus/machine-id"); if let Ok(id128) = - id128_util::id128_read_by_path(dbus_machine_id, Id128FormatFlag::ID128_FORMAT_PLAIN) + id128::id128_read_by_path(dbus_machine_id, Id128FormatFlag::ID128_FORMAT_PLAIN) { log::info!("Initializing machine ID from D-Bus machine ID (/var/lib/dbus/machine-id)."); return Ok(id128); @@ -412,7 +411,7 @@ fn generate_machine_id() -> Result { if process::id() == 1 { if let Ok(id128) = env::var("container_uuid") { - if id128_util::id128_is_valid(&id128.clone().into_bytes()) { + if id128::id128_is_valid(&id128.clone().into_bytes()) { log::info!( "Initializing machine ID from container UUID (process 1's container_uuid)." ); @@ -427,17 +426,17 @@ fn generate_machine_id() -> Result { let idplain: String = id128.chars().take(32).collect(); let idrfc: String = id128.chars().take(36).collect(); - if id128_util::id128_is_valid(&idplain.clone().into_bytes()) { + if id128::id128_is_valid(&idplain.clone().into_bytes()) { log::info!("Initializing machine ID from environ's container UUID (/proc/1/environ's container_uuid)."); return Ok(idplain); - } else if id128_util::id128_is_valid(&idrfc.clone().into_bytes()) { + } else if id128::id128_is_valid(&idrfc.clone().into_bytes()) { log::info!("Initializing machine ID from environ's container UUID (/proc/1/environ's container_uuid)."); return Ok(idrfc); } } } - match id128_util::id128_read_by_path( + match id128::id128_read_by_path( Path::new("/sys/class/dmi/id/product_uuid"), Id128FormatFlag::ID128_FORMAT_UUID, ) { @@ -447,7 +446,7 @@ fn generate_machine_id() -> Result { } Err(e) => { if e.kind() == ErrorKind::NotFound { - if let Ok(id128) = id128_util::id128_read_by_path( + if let Ok(id128) = id128::id128_read_by_path( Path::new("/proc/device-tree/vm,uuid"), Id128FormatFlag::ID128_FORMAT_UUID, ) { @@ -459,7 +458,7 @@ fn generate_machine_id() -> Result { } log::info!("Initializing machine ID from random generator."); - id128_util::id128_randomize(Id128FormatFlag::ID128_FORMAT_PLAIN) + id128::id128_randomize(Id128FormatFlag::ID128_FORMAT_PLAIN) } /// @@ -511,7 +510,7 @@ Booting up is supported only when: if machine_id.is_empty() { if let Ok(id128) = - id128_util::id128_read_by_path(etc_machine_id, Id128FormatFlag::ID128_FORMAT_PLAIN) + id128::id128_read_by_path(etc_machine_id, Id128FormatFlag::ID128_FORMAT_PLAIN) { return Ok(id128); } @@ -527,7 +526,7 @@ Booting up is supported only when: return Err(e); } } else { - id128_util::id128_write( + id128::id128_write( etc_machine_id, &true, &ret_id128, @@ -545,7 +544,7 @@ Booting up is supported only when: umask(Mode::from_bits_truncate(0o0022)).bits() | SFlag::S_IFMT.bits(), ); while saved_umask.contains(SFlag::S_IFMT) { - id128_util::id128_write( + id128::id128_write( run_machine_id, &false, &ret_id128, diff --git a/libs/basic/src/mount_util.rs b/libs/basic/src/mount.rs similarity index 99% rename from libs/basic/src/mount_util.rs rename to libs/basic/src/mount.rs index 9666e751a7e534a8a87537f94eec2081572d9dd6..371a07c467779b9ddd6761c523a190f4bc67824d 100644 --- a/libs/basic/src/mount_util.rs +++ b/libs/basic/src/mount.rs @@ -20,7 +20,7 @@ use std::{ use crate::{ error::*, - fs_util::{chase_symlink, is_symlink}, + fs::{chase_symlink, is_symlink}, }; use nix::{ fcntl::AtFlags, diff --git a/libs/basic/src/namespace_util.rs b/libs/basic/src/namespace.rs similarity index 73% rename from libs/basic/src/namespace_util.rs rename to libs/basic/src/namespace.rs index 13ea8b61f160361294359c9b538588faa337d069..2ce8eb2c9bb2b79c33b97d9d5fea1393f673202b 100644 --- a/libs/basic/src/namespace_util.rs +++ b/libs/basic/src/namespace.rs @@ -58,6 +58,13 @@ pub fn detach_mount_namespace() -> Result<()> { ) } +/// The function `reset_uid_gid` resets the user and group IDs to root (0) in Rust. +/// +/// Returns: +/// +/// The function `reset_uid_gid()` returns a `Result` type. If the function executes successfully, it +/// returns `Ok(())`, indicating that there was no error. If there is an error during execution, it +/// returns `Err(Errno::EIO)`, indicating an input/output error. fn reset_uid_gid() -> Result<()> { match fs::read("/proc/self/setgroups") { Ok(s) => { @@ -80,6 +87,19 @@ fn reset_uid_gid() -> Result<()> { } /// +/// The function `namespace_enter` enters a namespace specified by a file descriptor and clone flags, +/// and then resets the user and group IDs. +/// +/// Arguments: +/// +/// * `fd`: A reference to a RawFd, which is a file descriptor. +/// * `f`: The parameter `f` is of type `sched::CloneFlags`. It is used to specify the behavior of the +/// `setns` function. `sched::CloneFlags` is an enum that represents various flags that can be passed to +/// the `setns` function. +/// +/// Returns: +/// +/// a `Result<()>`. pub fn namespace_enter(fd: &RawFd, f: sched::CloneFlags) -> Result<()> { sched::setns(*fd, f)?; reset_uid_gid() diff --git a/libs/basic/src/naming_scheme.rs b/libs/basic/src/naming_scheme.rs index f22bb53412ce578a8537260f7cd0f523a7d9699c..826bf360a9921a78eda3d425aab788db3b674d39 100644 --- a/libs/basic/src/naming_scheme.rs +++ b/libs/basic/src/naming_scheme.rs @@ -116,9 +116,9 @@ impl Display for NamingScheme { /// get the naming scheme according to cmdline and environment variables pub fn naming_scheme() -> NamingScheme { - let cmdline_value = cmdline::cmdline_get_value("net.naming-scheme") - .unwrap_or(None) - .unwrap_or_default(); + let cmdline_value = cmdline::Cmdline::default() + .get_param("net.naming-scheme") + .unwrap_or_else(|| "".to_string()); /* * Environment variable 'NET_NAMING_SCHEME' is prior to cmdline parameter 'net.naming-scheme', @@ -150,7 +150,7 @@ pub fn naming_scheme() -> NamingScheme { /// check whether the naming scheme is enabled pub fn naming_scheme_enabled() -> bool { - if let Ok(Some(v)) = cmdline::cmdline_get_value("net.ifnames") { + if let Some(v) = cmdline::Cmdline::default().get_param("net.ifnames") { if ["0", "false"].contains(&v.as_str()) { return false; } @@ -182,9 +182,8 @@ mod tests { env::set_var("NET_NAMING_SCHEME", "0"); assert_eq!(naming_scheme(), NamingScheme::V000); - let cmdline_value = cmdline::cmdline_get_value("net.naming-scheme") - .unwrap_or(None) - .unwrap_or_default(); + let cmdline = cmdline::Cmdline::default(); + let cmdline_value = cmdline.get_param("net.naming-scheme").unwrap_or_default(); let scheme = cmdline_value .parse::() @@ -202,7 +201,7 @@ mod tests { #[test] fn test_naming_scheme_enabled() { let ret = naming_scheme_enabled(); - if let Ok(Some(v)) = cmdline::cmdline_get_value("net.ifnames") { + if let Some(v) = cmdline::Cmdline::default().get_param("net.ifnames") { if ["0", "false"].contains(&v.as_str()) { assert!(!ret); } else { diff --git a/libs/basic/src/path_util.rs b/libs/basic/src/path.rs similarity index 100% rename from libs/basic/src/path_util.rs rename to libs/basic/src/path.rs diff --git a/libs/basic/src/process.rs b/libs/basic/src/process.rs index 638eafddf0d3a06db3ebfeb1cd64fac2482c4773..bb38269f116325c5e32f4523ca0dcae09254da0d 100644 --- a/libs/basic/src/process.rs +++ b/libs/basic/src/process.rs @@ -10,9 +10,9 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -//! +//! process functions use crate::error::*; -use crate::fs_util; +use crate::fs; use nix::errno::errno; use nix::errno::Errno; use nix::libc::{kill, ESRCH}; @@ -28,7 +28,17 @@ use std::time::{Duration, SystemTime}; const PROCESS_FLAG_POS: usize = 8; const PF_KTHREAD: u64 = 0x00200000; +/// The `process_state` function in Rust reads the state of a process from the `/proc` filesystem and +/// returns the first character of the process state. /// +/// Arguments: +/// +/// * `pid`: The `pid` parameter is of type `Pid`, which represents a process ID. It is used to identify +/// a specific process for which we want to retrieve the process state. +/// +/// Returns: +/// +/// The function `process_state` returns a `Result`. pub fn process_state(pid: Pid) -> Result { if pid == Pid::from_raw(0) || pid == nix::unistd::getpid() { return Ok('R'); @@ -36,7 +46,7 @@ pub fn process_state(pid: Pid) -> Result { let proc_file = format!("/proc/{:?}/stat", pid.as_raw()); let stat_path = Path::new(&proc_file); - let first_line = fs_util::read_first_line(stat_path)?; + let first_line = fs::read_first_line(stat_path)?; let stat: Vec = first_line .split_whitespace() .map(|s| s.to_string()) @@ -58,7 +68,16 @@ pub fn process_state(pid: Pid) -> Result { Ok(p_stat[0]) } +/// The `alive` function in Rust checks if a process with a given PID is alive or not. +/// +/// Arguments: /// +/// * `pid`: The `pid` parameter in the `alive` function is of type `Pid`. It represents the process ID +/// of a process. +/// +/// Returns: +/// +/// a boolean value. pub fn alive(pid: Pid) -> bool { if pid < Pid::from_raw(0) { return false; @@ -83,7 +102,15 @@ pub fn alive(pid: Pid) -> bool { true } +/// The function `valid_pid` checks if a given process ID (`pid`) is valid or not. +/// +/// Arguments: +/// +/// * `pid`: The `pid` parameter is of type `Pid`. /// +/// Returns: +/// +/// a boolean value. pub fn valid_pid(pid: Pid) -> bool { if pid <= Pid::from_raw(0) { return false; @@ -92,7 +119,20 @@ pub fn valid_pid(pid: Pid) -> bool { true } +/// The function `kill_all_pids` in Rust iterates through the `/proc` directory and kills all processes +/// by sending a specified signal, returning a set of the killed process IDs. +/// +/// Arguments: +/// +/// * `signal`: The `signal` parameter is an integer representing the signal that will be sent to each +/// process. Signals are used in Unix-like operating systems to communicate with processes and can be +/// used for various purposes such as terminating a process, interrupting a process, or requesting a +/// process to reload its configuration. +/// +/// Returns: /// +/// The function `kill_all_pids` returns a `HashSet` containing the PIDs (Process IDs) of the processes +/// that were killed. pub fn kill_all_pids(signal: i32) -> HashSet { let mut pids: HashSet = HashSet::new(); let proc_path = Path::new("/proc"); @@ -123,7 +163,18 @@ pub fn kill_all_pids(signal: i32) -> HashSet { pids } +/// The `wait_pids` function waits for a set of process IDs to be killed either by the kernel or by +/// sending a signal, with a specified timeout. +/// +/// Arguments: +/// +/// * `pids`: A HashSet of process IDs (pids) that need to be waited for. +/// * `timeout`: The `timeout` parameter is the maximum amount of time (in microseconds) to wait for the +/// processes to be killed. +/// +/// Returns: /// +/// The function `wait_pids` returns a `HashSet`. pub fn wait_pids(mut pids: HashSet, timeout: u64) -> HashSet { let now = SystemTime::now(); let until = now + Duration::from_micros(timeout); @@ -234,7 +285,7 @@ fn is_kernel_thread(pid: Pid) -> Result { }); } - let first_line = fs_util::read_first_line(Path::new(&format!("/proc/{}/stat", pid.as_raw())))?; + let first_line = fs::read_first_line(Path::new(&format!("/proc/{}/stat", pid.as_raw())))?; let stat: Vec = first_line .split_whitespace() .map(|s| s.to_string()) diff --git a/libs/basic/src/random_util.rs b/libs/basic/src/random.rs similarity index 96% rename from libs/basic/src/random_util.rs rename to libs/basic/src/random.rs index 831bf8ba1f8211e3a2b906980b69e5f692e7e26f..b385a8185b481d60cd100ab27795a54338cf4304 100644 --- a/libs/basic/src/random_util.rs +++ b/libs/basic/src/random.rs @@ -10,7 +10,7 @@ // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. // See the Mulan PSL v2 for more details. -//! +//! Random functions /// Get random data from getrandom() or '/dev/urandom' pub fn random_bytes(data: &mut [u8]) { @@ -64,7 +64,7 @@ pub fn random_bytes(data: &mut [u8]) { log::error!("Failed to open /dev/urandom, err:{}", err); } Ok(mut file) => { - let _ = crate::io_util::loop_read_exact(&mut file, data); + let _ = crate::io::loop_read_exact(&mut file, data); } }; } diff --git a/libs/basic/src/show_table.rs b/libs/basic/src/show_table.rs index 76133f8d801961b23f6a891ad4a43ec01354550a..764ce12a548bc9d02feb3a2fb8f6df84ba452a00 100644 --- a/libs/basic/src/show_table.rs +++ b/libs/basic/src/show_table.rs @@ -256,6 +256,7 @@ impl ShowTable { } self.lines.push(line); } + /// Set all cells's alignment to left pub fn set_all_cell_align_left(&mut self) { for i in 0..self.lines.len() { @@ -264,6 +265,7 @@ impl ShowTable { } } } + /// Set all cell's alignment to right pub fn set_all_cell_align_right(&mut self) { for i in 0..self.lines.len() { @@ -272,6 +274,7 @@ impl ShowTable { } } } + /// Set all cells' alignment to center pub fn set_all_cell_align_center(&mut self) { for i in 0..self.lines.len() { @@ -280,12 +283,14 @@ impl ShowTable { } } } + /// Set a certain row's alignment pub fn set_one_row_align(&mut self, i: usize, align: CellAlign) { for j in 0..self.lines[i].cells.len() { self.lines[i].cells[j].align = align; } } + /// Set current row's alignment /// /// This is useful when one add a new line, and wants to change its format immediately. @@ -299,16 +304,19 @@ impl ShowTable { self.lines[total_line - 1].cells[j].align = align; } } + /// Set a certain column's alignment pub fn set_one_col_align(&mut self, j: usize, align: CellAlign) { for i in 0..self.lines.len() { self.lines[i].cells[j].align = align; } } + /// Set a cell's alignment pub fn set_one_cell_align(&mut self, i: usize, j: usize, align: CellAlign) { self.lines[i].cells[j].align = align; } + /// Set all cells' split space pub fn set_all_cell_space(&mut self, left_space: bool, right_space: bool) { for i in 0..self.lines.len() { @@ -318,6 +326,7 @@ impl ShowTable { } } } + /// Set one row's split space pub fn set_one_row_space(&mut self, i: usize, left_space: bool, right_space: bool) { for j in 0..self.lines[i].cells.len() { @@ -325,6 +334,7 @@ impl ShowTable { self.lines[i].cells[j].right_space = right_space; } } + /// Set one column's split space pub fn set_one_col_space(&mut self, j: usize, left_space: bool, right_space: bool) { for i in 0..self.lines.len() { @@ -332,11 +342,13 @@ impl ShowTable { self.lines[i].cells[j].right_space = right_space; } } + /// Set one cell's split space pub fn set_one_cell_space(&mut self, i: usize, j: usize, left_space: bool, right_space: bool) { self.lines[i].cells[j].left_space = left_space; self.lines[i].cells[j].right_space = right_space; } + /// Set all cells' underline pub fn set_all_cell_underline(&mut self, use_underline: bool) { for i in 0..self.lines.len() { @@ -345,12 +357,14 @@ impl ShowTable { } } } + /// Set one row's underline pub fn set_one_row_underline(&mut self, i: usize, use_underline: bool) { for j in 0..self.lines[i].cells.len() { self.lines[i].cells[j].underline = use_underline; } } + /// Set the current row's underline pub fn set_current_row_underline(&mut self, use_underline: bool) { let total_line = self.lines.len(); @@ -362,16 +376,19 @@ impl ShowTable { self.lines[total_line - 1].cells[j].underline = use_underline; } } + /// Set one column's underline pub fn set_one_col_underline(&mut self, j: usize, use_underline: bool) { for i in 0..self.lines.len() { self.lines[i].cells[j].underline = use_underline; } } + /// Set one cell's underline pub fn set_one_cell_underline(&mut self, i: usize, j: usize, use_underline: bool) { self.lines[i].cells[j].underline = use_underline; } + /// Set all cells' color pub fn set_all_cell_color(&mut self, color: CellColor) { for i in 0..self.lines.len() { @@ -380,12 +397,14 @@ impl ShowTable { } } } + /// Set one row's color pub fn set_one_row_color(&mut self, i: usize, color: CellColor) { for j in 0..self.lines[i].cells.len() { self.lines[i].cells[j].color = color; } } + /// Set current row's color pub fn set_current_row_color(&mut self, color: CellColor) { let total_line = self.lines.len(); @@ -397,12 +416,14 @@ impl ShowTable { self.lines[total_line - 1].cells[j].color = color; } } + /// Set one column's color pub fn set_one_col_color(&mut self, j: usize, color: CellColor) { for i in 0..self.lines.len() { self.lines[i].cells[j].color = color; } } + /// Set one cell's color pub fn set_one_cell_color(&mut self, i: usize, j: usize, color: CellColor) { self.lines[i].cells[j].color = color; diff --git a/libs/basic/src/signal_util.rs b/libs/basic/src/signal.rs similarity index 100% rename from libs/basic/src/signal_util.rs rename to libs/basic/src/signal.rs diff --git a/libs/basic/src/socket_util.rs b/libs/basic/src/socket.rs similarity index 67% rename from libs/basic/src/socket_util.rs rename to libs/basic/src/socket.rs index 6de8e52c53d1dfc651e65c394294485e75d5dd7e..a109d53a33e78d1753de1170dde3c5b727f9c059 100644 --- a/libs/basic/src/socket_util.rs +++ b/libs/basic/src/socket.rs @@ -21,6 +21,12 @@ use nix::{ use std::{os::unix::prelude::RawFd, path::Path}; /// +/// The function checks if IPv6 is supported by checking the existence of the "/proc/net/if_inet6" file. +/// +/// Returns: +/// +/// a boolean value. If the file "/proc/net/if_inet6" exists, it will return true. Otherwise, it will +/// return false. pub fn ipv6_is_supported() -> bool { let inet6 = Path::new("/proc/net/if_inet6"); @@ -32,6 +38,21 @@ pub fn ipv6_is_supported() -> bool { } /// +/// The function `set_pkginfo` sets the packet information option for a given socket file descriptor and +/// address family. +/// +/// Arguments: +/// +/// * `fd`: The `fd` parameter is of type `RawFd`, which represents a raw file descriptor. It is used to +/// identify the socket on which the option is to be set. +/// * `family`: The `family` parameter is of type `AddressFamily` and represents the address family of +/// the socket. It can have one of the following values: +/// * `v`: The parameter `v` is a boolean value that determines whether to enable or disable a specific +/// socket option. +/// +/// Returns: +/// +/// The function `set_pkginfo` returns a `Result` type. pub fn set_pkginfo(fd: RawFd, family: AddressFamily, v: bool) -> Result<()> { match family { socket::AddressFamily::Inet => { @@ -47,11 +68,40 @@ pub fn set_pkginfo(fd: RawFd, family: AddressFamily, v: bool) -> Result<()> { } /// +/// The function `set_pass_cred` sets the `PassCred` socket option for a given file descriptor. +/// +/// Arguments: +/// +/// * `fd`: The `fd` parameter is of type `RawFd`, which represents a raw file descriptor. It is +/// typically used to refer to a socket or file descriptor in Unix-like systems. +/// * `v`: The parameter `v` is a boolean value that determines whether or not to enable the passing of +/// credentials on a socket. If `v` is `true`, it enables the passing of credentials, and if `v` is +/// `false`, it disables the passing of credentials. +/// +/// Returns: +/// +/// The function `set_pass_cred` returns a `Result` type. pub fn set_pass_cred(fd: RawFd, v: bool) -> Result<()> { socket::setsockopt(fd, sockopt::PassCred, &v).context(NixSnafu) } /// +/// The function sets the receive buffer size for a socket and checks if the size was set successfully. +/// +/// Arguments: +/// +/// * `fd`: fd is the file descriptor of the socket. It is used to identify the socket on which the +/// operation will be performed. +/// * `v`: The parameter `v` represents the desired size of the receive buffer. It is of type `usize`, +/// which means it should be a non-negative integer value. The function checks if `v` is greater than +/// the maximum value that can be represented by `isize` (a signed integer type) +/// +/// Returns: +/// +/// The function `set_receive_buffer` returns a `Result` type. If the operation is successful, it +/// returns `Ok(())`, indicating that no error occurred. If there is an error, it returns `Err(Error)`, +/// where `Error` is an enum type that represents different kinds of errors that can occur during the +/// operation. pub fn set_receive_buffer(fd: RawFd, v: usize) -> Result<()> { /* Type of value is usize, so the v should smaller than the half of the value * as the value = 2 * n. @@ -82,6 +132,22 @@ pub fn set_receive_buffer(fd: RawFd, v: usize) -> Result<()> { } /// +/// The function `set_send_buffer` sets the send buffer size for a given file descriptor in Rust, with +/// error handling for exceeding the maximum value. +/// +/// Arguments: +/// +/// * `fd`: The parameter `fd` is of type `RawFd`, which is a platform-specific integer representing a +/// file descriptor. In this case, it is likely referring to a socket file descriptor. +/// * `v`: The parameter `v` represents the desired size of the send buffer. It should be smaller than +/// half of the maximum value of `usize`, which is `(std::isize::MAX) as usize`. +/// +/// Returns: +/// +/// The function `set_send_buffer` returns a `Result` type. If the operation is successful, it returns +/// `Ok(())`, indicating that there was no error. If there is an error, it returns `Err(Error)`, where +/// `Error` is an enum type that represents different kinds of errors that can occur during the +/// operation. pub fn set_send_buffer(fd: RawFd, v: usize) -> Result<()> { /* Type of value is usize, so the v should smaller than the half of the value * as the value = 2 * n. diff --git a/libs/basic/src/stat_util.rs b/libs/basic/src/stat.rs similarity index 100% rename from libs/basic/src/stat_util.rs rename to libs/basic/src/stat.rs diff --git a/libs/basic/src/time_util.rs b/libs/basic/src/time.rs similarity index 100% rename from libs/basic/src/time_util.rs rename to libs/basic/src/time.rs diff --git a/libs/basic/src/uuid.rs b/libs/basic/src/uuid.rs index c1bd8030a4c72f59d396b19f03c8477476f31d3c..45ce8fef41b74bbfb65898bf9fc46d37176be032 100644 --- a/libs/basic/src/uuid.rs +++ b/libs/basic/src/uuid.rs @@ -171,7 +171,7 @@ impl Uuid { pub fn randomize() -> Result { let mut id = Uuid::new(); - crate::random_util::random_bytes(&mut id.0); + crate::random::random_bytes(&mut id.0); /* Turn this into a valid v4 UUID, to be nice. Note that we * only guarantee this for newly generated UUIDs, not for diff --git a/libs/device/src/device.rs b/libs/device/src/device.rs index acff9f394ffbe7283d7ec93695452cb84e0a6ce3..2d8dc1e53b005e5ed44f950e47402dea523c1601 100644 --- a/libs/device/src/device.rs +++ b/libs/device/src/device.rs @@ -14,7 +14,7 @@ //! use crate::utils::readlink_value; use crate::{error::*, DeviceAction}; -use basic::fs_util::{chmod, open_temporary, touch_file}; +use basic::fs::{chmod, open_temporary, touch_file}; use basic::parse::{device_path_parse_devnum, parse_devnum, parse_ifindex}; use basic::string::fnmatch_or_empty; use basic::uuid::{randomize, Uuid}; @@ -1221,7 +1221,7 @@ impl Device { } } - let file2 = basic::fd_util::fd_reopen(file.as_raw_fd(), oflags).context(Basic { + let file2 = basic::fd::fd_reopen(file.as_raw_fd(), oflags).context(Basic { msg: format!("failed to open {}", file.as_raw_fd()), })?; @@ -1229,7 +1229,7 @@ impl Device { return Ok(file2); } - let q = basic::fd_util::fd_get_diskseq(file2.as_raw_fd()).context(Basic { + let q = basic::fd::fd_get_diskseq(file2.as_raw_fd()).context(Basic { msg: format!("failed to get diskseq on fd {}", file2.as_raw_fd()), })?; diff --git a/libs/device/src/device_monitor.rs b/libs/device/src/device_monitor.rs index 713cb9bdf73efef8ec3597bf73f2ac215335b57d..710578e258d0d82172d27477bfa595ba1b1f0e2a 100644 --- a/libs/device/src/device_monitor.rs +++ b/libs/device/src/device_monitor.rs @@ -15,7 +15,7 @@ use crate::{device::Device, error::Error}; use basic::errno_is_transient; use basic::murmurhash2::murmurhash2; -use basic::socket_util::next_datagram_size_fd; +use basic::socket::next_datagram_size_fd; use libc::*; use nix::{ errno::Errno, diff --git a/libs/event/Cargo.toml b/libs/event/Cargo.toml index fb8e343b610d906663e8143e105b6f648f742e3a..8bfdec2c42a8a3812729729d4d9ba78c9609cfad 100644 --- a/libs/event/Cargo.toml +++ b/libs/event/Cargo.toml @@ -6,7 +6,7 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -basic = { path = "../basic", default-features = false, features = ["time_util"]} +basic = { path = "../basic", default-features = false, features = ["time"] } libc = { version = "0.2", default-features = false } nix = { version = "0.24", default-features = false, features = [ diff --git a/libs/event/src/timer.rs b/libs/event/src/timer.rs index bd2e4490e3dfad4320ef8c3d913ee0974a55870c..68133cb2956ac46ec4a50f3d14f92bab65d1be0c 100644 --- a/libs/event/src/timer.rs +++ b/libs/event/src/timer.rs @@ -17,7 +17,7 @@ use std::{ }; use crate::{EventType, Source}; -use basic::time_util::{NSEC_PER_SEC, NSEC_PER_USEC, USEC_INFINITY, USEC_PER_SEC}; +use basic::time::{NSEC_PER_SEC, NSEC_PER_USEC, USEC_INFINITY, USEC_PER_SEC}; #[derive(Debug, Clone, Copy)] pub(crate) struct Timestamp { diff --git a/libs/hwdb/src/sd_hwdb.rs b/libs/hwdb/src/sd_hwdb.rs index 9d4bb5a1fac3fa5acfafd0ab2ec7835432263a22..69c64b41d9687fa038c6e11ebc51423c04d3a0f7 100644 --- a/libs/hwdb/src/sd_hwdb.rs +++ b/libs/hwdb/src/sd_hwdb.rs @@ -1,4 +1,4 @@ -use basic::{fd_util, unistd::timespec_load}; +use basic::{fd, unistd::timespec_load}; use constants::INVALID_FD; use glob::Pattern; use linked_hash_map::LinkedHashMap; @@ -674,7 +674,7 @@ fn hwdb_new(path: &str) -> Result { log::error!("File{:?} is too short", hwdb_path); return Err(Errno::EIO); } - if fd_util::file_offset_beyond_memory_size(hwdb_st.st_size) { + if fd::file_offset_beyond_memory_size(hwdb_st.st_size) { log::error!("File {:?} is too long", hwdb_path); return Err(Errno::EFBIG); } diff --git a/libs/kmod_rs/src/lib.rs b/libs/kmod_rs/src/lib.rs index f95cd32a5fa668e7433000b7ccb6b438423a7884..97c2b0c48e4fb030d009988048c23a7537e92c4d 100644 --- a/libs/kmod_rs/src/lib.rs +++ b/libs/kmod_rs/src/lib.rs @@ -245,8 +245,8 @@ impl LibKmod { Err(e) => { if e == nix::Error::EPERM { if !denylisy_parsed { - cmdline::proc_cmdline_parse( - cmdline::parse_proc_cmdline_item, + cmdline::Cmdline::parse( + cmdline::Cmdline::cmdline_item, &mut denylist, ); denylisy_parsed = true;