mirror of
https://github.com/kvorschk/Magisk.git
synced 2026-12-05 03:20:46 -05:00
Use nix for libc functions
This commit is contained in:
@@ -26,3 +26,4 @@ bytemuck = { workspace = true, features = ["derive"] }
|
||||
thiserror = { workspace = true }
|
||||
bit-set = { workspace = true }
|
||||
argh = { workspace = true }
|
||||
nix = { workspace = true, features = ["fs", "poll", "signal"] }
|
||||
|
||||
@@ -18,11 +18,11 @@ use crate::socket::IpcWrite;
|
||||
use crate::su::SuInfo;
|
||||
use crate::zygisk::ZygiskState;
|
||||
use base::const_format::concatcp;
|
||||
use base::libc::{O_APPEND, O_CLOEXEC, O_RDONLY, O_WRONLY};
|
||||
use base::{
|
||||
AtomicArc, BufReadExt, FsPathBuilder, ReadExt, ResultExt, Utf8CStr, Utf8CStrBuf, WriteExt,
|
||||
cstr, error, info, libc,
|
||||
};
|
||||
use nix::fcntl::OFlag;
|
||||
use std::fmt::Write as FmtWrite;
|
||||
use std::fs::File;
|
||||
use std::io::{BufReader, Write};
|
||||
@@ -304,7 +304,9 @@ pub fn daemon_entry() {
|
||||
unsafe { libc::setsid() };
|
||||
|
||||
// Make sure the current context is magisk
|
||||
if let Ok(mut current) = cstr!("/proc/self/attr/current").open(O_WRONLY | O_CLOEXEC) {
|
||||
if let Ok(mut current) =
|
||||
cstr!("/proc/self/attr/current").open(OFlag::O_WRONLY | OFlag::O_CLOEXEC)
|
||||
{
|
||||
let con = cstr!(MAGISK_PROC_CON);
|
||||
current.write_all(con.as_bytes_with_nul()).log_ok();
|
||||
}
|
||||
@@ -323,7 +325,7 @@ pub fn daemon_entry() {
|
||||
.join_path(magisk_tmp)
|
||||
.join_path(MAIN_CONFIG);
|
||||
let mut is_recovery = false;
|
||||
if let Ok(main_config) = tmp_path.open(O_RDONLY | O_CLOEXEC) {
|
||||
if let Ok(main_config) = tmp_path.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) {
|
||||
BufReader::new(main_config).for_each_prop(|key, val| {
|
||||
if key == "RECOVERYMODE" {
|
||||
is_recovery = val == "true";
|
||||
@@ -335,7 +337,7 @@ pub fn daemon_entry() {
|
||||
tmp_path.truncate(magisk_tmp.len());
|
||||
|
||||
let mut sdk_int = -1;
|
||||
if let Ok(build_prop) = cstr!("/system/build.prop").open(O_RDONLY | O_CLOEXEC) {
|
||||
if let Ok(build_prop) = cstr!("/system/build.prop").open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) {
|
||||
BufReader::new(build_prop).for_each_prop(|key, val| {
|
||||
if key == "ro.build.version.sdk" {
|
||||
sdk_int = val.parse::<i32>().unwrap_or(-1);
|
||||
@@ -370,7 +372,7 @@ pub fn daemon_entry() {
|
||||
|
||||
// Cleanup pre-init mounts
|
||||
tmp_path.append_path(ROOTMNT);
|
||||
if let Ok(mount_list) = tmp_path.open(O_RDONLY | O_CLOEXEC) {
|
||||
if let Ok(mount_list) = tmp_path.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) {
|
||||
BufReader::new(mount_list).for_each_line(|line| {
|
||||
line.truncate(line.trim_end().len());
|
||||
let item = Utf8CStr::from_string(line);
|
||||
@@ -407,7 +409,7 @@ fn switch_cgroup(cgroup: &str, pid: i32) {
|
||||
if !buf.exists() {
|
||||
return;
|
||||
}
|
||||
if let Ok(mut file) = buf.open(O_WRONLY | O_APPEND | O_CLOEXEC) {
|
||||
if let Ok(mut file) = buf.open(OFlag::O_WRONLY | OFlag::O_APPEND | OFlag::O_CLOEXEC) {
|
||||
buf.clear();
|
||||
buf.write_fmt(format_args!("{pid}")).ok();
|
||||
file.write_all(buf.as_bytes()).log_ok();
|
||||
@@ -415,7 +417,7 @@ fn switch_cgroup(cgroup: &str, pid: i32) {
|
||||
}
|
||||
|
||||
fn check_data() -> bool {
|
||||
if let Ok(file) = cstr!("/proc/mounts").open(O_RDONLY | O_CLOEXEC) {
|
||||
if let Ok(file) = cstr!("/proc/mounts").open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) {
|
||||
let mut mnt = false;
|
||||
BufReader::new(file).for_each_line(|line| {
|
||||
if line.contains(" /data ") && !line.contains("tmpfs") {
|
||||
|
||||
+24
-22
@@ -4,13 +4,14 @@ use crate::ffi::{ModuleInfo, exec_module_scripts, exec_script, get_magisk_tmp};
|
||||
use crate::mount::setup_module_mount;
|
||||
use crate::resetprop::load_prop_file;
|
||||
use base::{
|
||||
DirEntry, Directory, FsPathBuilder, LibcReturn, LoggedResult, OsResult, ResultExt,
|
||||
SilentLogExt, Utf8CStr, Utf8CStrBuf, Utf8CString, WalkResult, clone_attr, cstr, debug, error,
|
||||
info, libc, raw_cstr, warn,
|
||||
DirEntry, Directory, FsPathBuilder, LoggedResult, OsResult, ResultExt, SilentLogExt, Utf8CStr,
|
||||
Utf8CStrBuf, Utf8CString, WalkResult, clone_attr, cstr, debug, error, info, libc, raw_cstr,
|
||||
warn,
|
||||
};
|
||||
use libc::{AT_REMOVEDIR, MS_RDONLY, O_CLOEXEC, O_CREAT, O_RDONLY};
|
||||
use libc::MS_RDONLY;
|
||||
use nix::{fcntl::OFlag, unistd::UnlinkatFlags};
|
||||
use std::collections::BTreeMap;
|
||||
use std::os::fd::{AsRawFd, IntoRawFd};
|
||||
use std::os::fd::IntoRawFd;
|
||||
use std::path::{Component, Path};
|
||||
use std::ptr;
|
||||
use std::sync::atomic::Ordering;
|
||||
@@ -51,7 +52,7 @@ fn mount_dummy<'a>(
|
||||
if is_dir {
|
||||
dest.mkdir(0o000)?;
|
||||
} else {
|
||||
dest.create(O_CREAT | O_RDONLY | O_CLOEXEC, 0o000)?;
|
||||
dest.create(OFlag::O_CREAT | OFlag::O_RDONLY | OFlag::O_CLOEXEC, 0o000)?;
|
||||
}
|
||||
bind_mount(reason, src, dest, false);
|
||||
Ok(())
|
||||
@@ -563,7 +564,6 @@ fn inject_zygisk_bins(name: &str, system: &mut FsNode) {
|
||||
|
||||
fn upgrade_modules() -> LoggedResult<()> {
|
||||
let mut upgrade = Directory::open(cstr!(MODULEUPGRADE)).silent()?;
|
||||
let ufd = upgrade.as_raw_fd();
|
||||
let root = Directory::open(cstr!(MODULEROOT))?;
|
||||
while let Some(e) = upgrade.read()? {
|
||||
if !e.is_dir() {
|
||||
@@ -577,23 +577,19 @@ fn upgrade_modules() -> LoggedResult<()> {
|
||||
// If the old module is disabled, we need to also disable the new one
|
||||
disable = module.contains_path(cstr!("disable"));
|
||||
module.remove_all()?;
|
||||
root.unlink_at(module_name, AT_REMOVEDIR)?;
|
||||
root.unlink_at(module_name, UnlinkatFlags::RemoveDir)?;
|
||||
}
|
||||
info!("Upgrade / New module: {module_name}");
|
||||
unsafe {
|
||||
libc::renameat(
|
||||
ufd,
|
||||
module_name.as_ptr(),
|
||||
root.as_raw_fd(),
|
||||
module_name.as_ptr(),
|
||||
)
|
||||
.check_os_err("renameat", Some(module_name), None)?;
|
||||
}
|
||||
e.rename_to(&root, module_name)?;
|
||||
if disable {
|
||||
let path = cstr::buf::default()
|
||||
.join_path(module_name)
|
||||
.join_path("disable");
|
||||
let _ = root.open_as_file_at(&path, O_RDONLY | O_CREAT | O_CLOEXEC, 0)?;
|
||||
let _ = root.open_as_file_at(
|
||||
&path,
|
||||
OFlag::O_RDONLY | OFlag::O_CREAT | OFlag::O_CLOEXEC,
|
||||
0,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
upgrade.remove_all()?;
|
||||
@@ -614,7 +610,11 @@ fn for_each_module(mut func: impl FnMut(&DirEntry) -> LoggedResult<()>) -> Logge
|
||||
pub fn disable_modules() {
|
||||
for_each_module(|e| {
|
||||
let dir = e.open_as_dir()?;
|
||||
dir.open_as_file_at(cstr!("disable"), O_RDONLY | O_CREAT | O_CLOEXEC, 0)?;
|
||||
dir.open_as_file_at(
|
||||
cstr!("disable"),
|
||||
OFlag::O_RDONLY | OFlag::O_CREAT | OFlag::O_CLOEXEC,
|
||||
0,
|
||||
)?;
|
||||
Ok(())
|
||||
})
|
||||
.log_ok();
|
||||
@@ -656,7 +656,8 @@ fn collect_modules(zygisk_enabled: bool, open_zygisk: bool) -> Vec<ModuleInfo> {
|
||||
e.unlink()?;
|
||||
return Ok(());
|
||||
}
|
||||
dir.unlink_at(cstr!("update"), 0).ok();
|
||||
dir.unlink_at(cstr!("update"), UnlinkatFlags::NoRemoveDir)
|
||||
.ok();
|
||||
if dir.contains_path(cstr!("disable")) {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -673,7 +674,7 @@ fn collect_modules(zygisk_enabled: bool, open_zygisk: bool) -> Vec<ModuleInfo> {
|
||||
}
|
||||
|
||||
fn open_fd_safe(dir: &Directory, name: &Utf8CStr) -> i32 {
|
||||
dir.open_as_file_at(name, O_RDONLY | O_CLOEXEC, 0)
|
||||
dir.open_as_file_at(name, OFlag::O_RDONLY | OFlag::O_CLOEXEC, 0)
|
||||
.log()
|
||||
.map(IntoRawFd::into_raw_fd)
|
||||
.unwrap_or(-1)
|
||||
@@ -702,7 +703,8 @@ fn collect_modules(zygisk_enabled: bool, open_zygisk: bool) -> Vec<ModuleInfo> {
|
||||
{
|
||||
z64 = open_fd_safe(&dir, cstr!("zygisk/riscv64.so"));
|
||||
}
|
||||
dir.unlink_at(cstr!("zygisk/unloaded"), 0).ok();
|
||||
dir.unlink_at(cstr!("zygisk/unloaded"), UnlinkatFlags::NoRemoveDir)
|
||||
.ok();
|
||||
}
|
||||
} else {
|
||||
// Ignore zygisk modules when zygisk is not enabled
|
||||
|
||||
@@ -200,9 +200,8 @@ pub fn find_preinit_device() -> String {
|
||||
libc::S_IFBLK | 0o600,
|
||||
info.device as dev_t,
|
||||
)
|
||||
.check_io_err()
|
||||
.log()
|
||||
.ok();
|
||||
.check_os_err("mknod", Some(dev_path), None)
|
||||
.log_ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,12 @@ use crate::consts::{APP_PACKAGE_NAME, MAGISK_VER_CODE};
|
||||
use crate::daemon::{AID_APP_END, AID_APP_START, AID_USER_OFFSET, MagiskD, to_app_id};
|
||||
use crate::ffi::{DbEntryKey, get_magisk_tmp, install_apk, uninstall_pkg};
|
||||
use base::WalkResult::{Abort, Continue, Skip};
|
||||
use base::libc::{O_CLOEXEC, O_CREAT, O_RDONLY, O_TRUNC, O_WRONLY};
|
||||
use base::{
|
||||
BufReadExt, Directory, FsPathBuilder, LoggedResult, ReadExt, ResultExt, Utf8CStrBuf,
|
||||
Utf8CString, cstr, error, fd_get_attr, warn,
|
||||
};
|
||||
use bit_set::BitSet;
|
||||
use nix::fcntl::OFlag;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
@@ -238,7 +238,7 @@ impl ManagerInfo {
|
||||
.join_path("dyn")
|
||||
.join_path("current.apk");
|
||||
let uid: i32;
|
||||
let cert = match apk.open(O_RDONLY | O_CLOEXEC) {
|
||||
let cert = match apk.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) {
|
||||
Ok(mut fd) => {
|
||||
uid = fd_get_attr(fd.as_raw_fd())
|
||||
.map(|attr| attr.st.st_uid as i32)
|
||||
@@ -270,7 +270,7 @@ impl ManagerInfo {
|
||||
return Status::NotInstalled;
|
||||
};
|
||||
|
||||
let cert = match apk.open(O_RDONLY | O_CLOEXEC) {
|
||||
let cert = match apk.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) {
|
||||
Ok(mut fd) => read_certificate(&mut fd, -1),
|
||||
Err(_) => return Status::NotInstalled,
|
||||
};
|
||||
@@ -293,7 +293,7 @@ impl ManagerInfo {
|
||||
return Status::NotInstalled;
|
||||
};
|
||||
|
||||
let cert = match apk.open(O_RDONLY | O_CLOEXEC) {
|
||||
let cert = match apk.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) {
|
||||
Ok(mut fd) => read_certificate(&mut fd, MAGISK_VER_CODE),
|
||||
Err(_) => return Status::NotInstalled,
|
||||
};
|
||||
@@ -317,8 +317,10 @@ impl ManagerInfo {
|
||||
let tmp_apk = cstr!("/data/stub.apk");
|
||||
let result: LoggedResult<()> = try {
|
||||
{
|
||||
let mut tmp_apk_file =
|
||||
tmp_apk.create(O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0o600)?;
|
||||
let mut tmp_apk_file = tmp_apk.create(
|
||||
OFlag::O_WRONLY | OFlag::O_CREAT | OFlag::O_TRUNC | OFlag::O_CLOEXEC,
|
||||
0o600,
|
||||
)?;
|
||||
io::copy(stub_fd, &mut tmp_apk_file)?;
|
||||
}
|
||||
// Seek the fd back to start
|
||||
@@ -445,7 +447,7 @@ impl MagiskD {
|
||||
.join_path(get_magisk_tmp())
|
||||
.join_path("stub.apk");
|
||||
|
||||
if let Ok(mut fd) = apk.open(O_RDONLY | O_CLOEXEC) {
|
||||
if let Ok(mut fd) = apk.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC) {
|
||||
info.trusted_cert = read_certificate(&mut fd, MAGISK_VER_CODE);
|
||||
// Seek the fd back to start
|
||||
fd.seek(SeekFrom::Start(0)).log_ok();
|
||||
|
||||
@@ -6,8 +6,9 @@ use argh::{EarlyExit, FromArgs, MissingRequirements};
|
||||
use base::libc::PROP_VALUE_MAX;
|
||||
use base::{
|
||||
BufReadExt, CmdArgs, EarlyExitExt, LogLevel, LoggedResult, ResultExt, Utf8CStr, Utf8CStrBuf,
|
||||
Utf8CString, cstr, debug, libc, log_err, set_log_level_state,
|
||||
Utf8CString, cstr, debug, log_err, set_log_level_state,
|
||||
};
|
||||
use nix::fcntl::OFlag;
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::c_char;
|
||||
use std::io::BufReader;
|
||||
@@ -211,7 +212,7 @@ impl ResetProp {
|
||||
}
|
||||
|
||||
fn load_file(&self, file: &Utf8CStr) -> LoggedResult<()> {
|
||||
let fd = file.open(libc::O_RDONLY | libc::O_CLOEXEC)?;
|
||||
let fd = file.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC)?;
|
||||
let mut key = cstr::buf::dynamic(128);
|
||||
let mut val = cstr::buf::dynamic(128);
|
||||
BufReader::new(fd).for_each_prop(|k, v| {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use nix::fcntl::OFlag;
|
||||
use quick_protobuf::{BytesReader, MessageRead, MessageWrite, Writer};
|
||||
use std::io::Read;
|
||||
use std::{
|
||||
fs::File,
|
||||
@@ -5,14 +7,11 @@ use std::{
|
||||
os::fd::FromRawFd,
|
||||
};
|
||||
|
||||
use quick_protobuf::{BytesReader, MessageRead, MessageWrite, Writer};
|
||||
|
||||
use crate::resetprop::PropReader;
|
||||
use crate::resetprop::proto::persistent_properties::{
|
||||
PersistentProperties, mod_PersistentProperties::PersistentPropertyRecord,
|
||||
};
|
||||
use base::const_format::concatcp;
|
||||
use base::libc::{O_CLOEXEC, O_RDONLY};
|
||||
use base::{
|
||||
Directory, FsPathBuilder, LibcReturn, LoggedResult, MappedFile, SilentLogExt, Utf8CStr,
|
||||
Utf8CStrBuf, WalkResult, clone_attr, cstr, debug, libc::mkstemp, log_err,
|
||||
@@ -46,7 +45,7 @@ fn file_get_prop(name: &Utf8CStr) -> LoggedResult<String> {
|
||||
let path = cstr::buf::default()
|
||||
.join_path(PERSIST_PROP_DIR)
|
||||
.join_path(name);
|
||||
let mut file = path.open(O_RDONLY | O_CLOEXEC).silent()?;
|
||||
let mut file = path.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC).silent()?;
|
||||
debug!("resetprop: read prop from [{}]", path);
|
||||
let mut s = String::new();
|
||||
file.read_to_string(&mut s)?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::consts::{DATABIN, LOG_PIPE, MAGISK_LOG_CON, MAGISKDB, MODULEROOT, SECURE_DIR};
|
||||
use crate::ffi::get_magisk_tmp;
|
||||
use base::libc::{O_CLOEXEC, O_WRONLY};
|
||||
use base::{Directory, FsPathBuilder, LoggedResult, ResultExt, Utf8CStr, Utf8CStrBuf, cstr, libc};
|
||||
use nix::fcntl::OFlag;
|
||||
use std::io::Write;
|
||||
|
||||
const UNLABEL_CON: &Utf8CStr = cstr!("u:object_r:unlabeled:s0");
|
||||
@@ -53,7 +53,7 @@ fn restore_syscon(path: &mut dyn Utf8CStrBuf) -> LoggedResult<()> {
|
||||
|
||||
pub(crate) fn restorecon() {
|
||||
if let Ok(mut file) = cstr!("/sys/fs/selinux/context")
|
||||
.open(O_WRONLY | O_CLOEXEC)
|
||||
.open(OFlag::O_WRONLY | OFlag::O_CLOEXEC)
|
||||
.log()
|
||||
&& file.write_all(ADB_CON.as_bytes_with_nul()).is_ok()
|
||||
{
|
||||
|
||||
@@ -6,11 +6,16 @@ use crate::ffi::{SuPolicy, SuRequest, get_magisk_tmp};
|
||||
use crate::socket::IpcRead;
|
||||
use ExtraVal::{Bool, Int, IntList, Str};
|
||||
use base::{
|
||||
BytesExt, FileAttr, LibcReturn, LoggedResult, OsError, ResultExt, cstr, fork_dont_care, libc,
|
||||
BytesExt, FileAttr, LibcReturn, LoggedResult, ResultExt, Utf8CStrBuf, cstr, fork_dont_care,
|
||||
libc,
|
||||
};
|
||||
use nix::{
|
||||
fcntl::OFlag,
|
||||
poll::{PollFd, PollFlags, PollTimeout},
|
||||
};
|
||||
use libc::pollfd as PollFd;
|
||||
use num_traits::AsPrimitive;
|
||||
use std::{fmt::Write, fs::File, os::fd::AsRawFd, process::Command, process::exit};
|
||||
use std::os::fd::AsFd;
|
||||
use std::{fmt::Write, fs::File, process::Command, process::exit};
|
||||
|
||||
struct Extra<'a> {
|
||||
key: &'static str,
|
||||
@@ -171,7 +176,7 @@ impl SuAppContext<'_> {
|
||||
attr.st.st_mode = 0o600;
|
||||
attr.st.st_uid = self.info.mgr_uid.as_();
|
||||
attr.st.st_gid = self.info.mgr_uid.as_();
|
||||
attr.con.write_str(MAGISK_FILE_CON).ok();
|
||||
attr.con.push_str(MAGISK_FILE_CON);
|
||||
|
||||
fifo.mkfifo(0o600)?;
|
||||
fifo.set_attr(&attr)?;
|
||||
@@ -193,20 +198,12 @@ impl SuAppContext<'_> {
|
||||
self.exec_cmd("request", &extras, false);
|
||||
|
||||
// Open with O_RDWR to prevent FIFO open block
|
||||
let fd = fifo.open(libc::O_RDWR | libc::O_CLOEXEC)?;
|
||||
let fd = fifo.open(OFlag::O_RDWR | OFlag::O_CLOEXEC)?;
|
||||
let mut pfd = [PollFd::new(fd.as_fd(), PollFlags::POLLIN)];
|
||||
|
||||
// Wait for data input for at most 70 seconds
|
||||
let mut pfd = PollFd {
|
||||
fd: fd.as_raw_fd(),
|
||||
events: libc::POLLIN,
|
||||
revents: 0,
|
||||
};
|
||||
if unsafe { libc::poll(&mut pfd, 1, 70 * 1000).into_os_result("poll", None, None)? }
|
||||
== 0
|
||||
{
|
||||
Err(OsError::new(libc::ETIMEDOUT, "poll", None, None))?;
|
||||
}
|
||||
|
||||
nix::poll::poll(&mut pfd, PollTimeout::try_from(70 * 1000).unwrap())
|
||||
.check_os_err("poll", None, None)?;
|
||||
fd
|
||||
};
|
||||
|
||||
|
||||
+63
-79
@@ -1,21 +1,20 @@
|
||||
use base::libc::ssize_t;
|
||||
use base::{
|
||||
LibcReturn, LoggedResult, OsResult, PipeFd, ReadExt, ResultExt, error, libc, log_err,
|
||||
make_pipe, warn,
|
||||
};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use base::{FileOrStd, LibcReturn, LoggedResult, OsResult, libc, warn};
|
||||
use libc::{
|
||||
O_CLOEXEC, POLLIN, SFD_CLOEXEC, SIG_BLOCK, SIGWINCH, STDIN_FILENO, STDOUT_FILENO, TCSADRAIN,
|
||||
TCSAFLUSH, TIOCGWINSZ, TIOCSWINSZ, cfmakeraw, close, poll, pollfd, raise, sigaddset,
|
||||
sigemptyset, signalfd, signalfd_siginfo, sigprocmask, sigset_t, tcgetattr, tcsetattr, termios,
|
||||
winsize,
|
||||
STDIN_FILENO, STDOUT_FILENO, TCSADRAIN, TCSAFLUSH, TIOCGWINSZ, TIOCSWINSZ, c_int, cfmakeraw,
|
||||
ssize_t, tcgetattr, tcsetattr, termios, winsize,
|
||||
};
|
||||
use nix::{
|
||||
fcntl::OFlag,
|
||||
poll::{PollFd, PollFlags, PollTimeout},
|
||||
sys::signal::{SigSet, Signal},
|
||||
sys::signalfd::{SfdFlags, SignalFd},
|
||||
};
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
use std::mem::{ManuallyDrop, MaybeUninit};
|
||||
use std::os::fd::{AsRawFd, FromRawFd, RawFd};
|
||||
use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd, RawFd};
|
||||
use std::ptr::null_mut;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::{ffi::c_int, ptr::null_mut};
|
||||
|
||||
static mut OLD_STDIN: Option<termios> = None;
|
||||
static SHOULD_USE_SPLICE: AtomicBool = AtomicBool::new(true);
|
||||
@@ -97,13 +96,13 @@ fn pump_via_copy(infd: RawFd, outfd: RawFd) -> LoggedResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pump_via_splice(infd: RawFd, outfd: RawFd, pipe: &PipeFd) -> LoggedResult<()> {
|
||||
fn pump_via_splice(infd: RawFd, outfd: RawFd, pipe: &(OwnedFd, OwnedFd)) -> LoggedResult<()> {
|
||||
if !SHOULD_USE_SPLICE.load(Ordering::Acquire) {
|
||||
return pump_via_copy(infd, outfd);
|
||||
}
|
||||
|
||||
// The pipe capacity is by default 16 pages, let's just use 65536
|
||||
let Ok(len) = splice(infd, pipe.write.as_raw_fd(), 65536_usize, 0) else {
|
||||
let Ok(len) = splice(infd, pipe.1.as_raw_fd(), 65536_usize, 0) else {
|
||||
// If splice failed, stop using splice and fallback to userspace copy
|
||||
SHOULD_USE_SPLICE.store(false, Ordering::Release);
|
||||
return pump_via_copy(infd, outfd);
|
||||
@@ -111,85 +110,70 @@ fn pump_via_splice(infd: RawFd, outfd: RawFd, pipe: &PipeFd) -> LoggedResult<()>
|
||||
if len == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
splice(pipe.read.as_raw_fd(), outfd, len as usize, 0)?;
|
||||
splice(pipe.0.as_raw_fd(), outfd, len as usize, 0)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
#[repr(transparent)]
|
||||
struct SignalFdInfo(signalfd_siginfo);
|
||||
unsafe impl Zeroable for SignalFdInfo {}
|
||||
unsafe impl Pod for SignalFdInfo {}
|
||||
fn pump_tty_impl(infd: OwnedFd, raw_out: RawFd) -> LoggedResult<()> {
|
||||
let mut set = SigSet::empty();
|
||||
set.add(Signal::SIGWINCH);
|
||||
set.thread_block()
|
||||
.check_os_err("pthread_sigmask", None, None)?;
|
||||
let signal_fd =
|
||||
SignalFd::with_flags(&set, SfdFlags::SFD_CLOEXEC).into_os_result("signalfd", None, None)?;
|
||||
|
||||
pub fn pump_tty(infd: i32, outfd: i32) {
|
||||
set_stdin_raw();
|
||||
let raw_in = infd.as_raw_fd();
|
||||
let raw_sig = signal_fd.as_raw_fd();
|
||||
|
||||
let signal_fd = unsafe {
|
||||
let mut mask: sigset_t = std::mem::zeroed();
|
||||
sigemptyset(&mut mask);
|
||||
sigaddset(&mut mask, SIGWINCH);
|
||||
sigprocmask(SIG_BLOCK, &mask, null_mut())
|
||||
.check_os_err("sigprocmask", None, None)
|
||||
.log_ok();
|
||||
signalfd(-1, &mask, SFD_CLOEXEC)
|
||||
};
|
||||
let mut poll_fds = Vec::with_capacity(3);
|
||||
poll_fds.push(PollFd::new(infd.as_fd(), PollFlags::POLLIN));
|
||||
poll_fds.push(PollFd::new(signal_fd.as_fd(), PollFlags::POLLIN));
|
||||
if raw_out >= 0 {
|
||||
poll_fds.push(PollFd::new(
|
||||
FileOrStd::StdIn.as_file().as_fd(),
|
||||
PollFlags::POLLIN,
|
||||
));
|
||||
}
|
||||
|
||||
resize_pty(outfd);
|
||||
// Any flag in this list indicates stop polling
|
||||
let stop_flags = PollFlags::POLLERR | PollFlags::POLLHUP | PollFlags::POLLNVAL;
|
||||
|
||||
let mut pfds = [
|
||||
pollfd {
|
||||
fd: if outfd > 0 { STDIN_FILENO } else { -1 },
|
||||
events: POLLIN,
|
||||
revents: 0,
|
||||
},
|
||||
pollfd {
|
||||
fd: infd,
|
||||
events: POLLIN,
|
||||
revents: 0,
|
||||
},
|
||||
pollfd {
|
||||
fd: signal_fd,
|
||||
events: POLLIN,
|
||||
revents: 0,
|
||||
},
|
||||
];
|
||||
|
||||
let Ok(pipe_fd) = make_pipe(O_CLOEXEC).log() else {
|
||||
return;
|
||||
};
|
||||
// Open a pipe to bypass userspace copy with splice
|
||||
let pipe_fd = nix::unistd::pipe2(OFlag::O_CLOEXEC).into_os_result("pipe2", None, None)?;
|
||||
|
||||
'poll: loop {
|
||||
let ready = unsafe { poll(pfds.as_mut_ptr(), pfds.len() as _, -1) };
|
||||
|
||||
if ready < 0 {
|
||||
error!("poll error");
|
||||
break;
|
||||
}
|
||||
|
||||
for pfd in &pfds {
|
||||
if pfd.revents & POLLIN != 0 {
|
||||
let res = if pfd.fd == STDIN_FILENO {
|
||||
pump_via_splice(STDIN_FILENO, outfd, &pipe_fd)
|
||||
} else if pfd.fd == infd {
|
||||
pump_via_splice(infd, STDOUT_FILENO, &pipe_fd)
|
||||
} else if pfd.fd == signal_fd {
|
||||
resize_pty(outfd);
|
||||
let mut info = SignalFdInfo::zeroed();
|
||||
let mut fd = ManuallyDrop::new(unsafe { File::from_raw_fd(signal_fd) });
|
||||
fd.read_pod(&mut info).log()
|
||||
} else {
|
||||
log_err!()
|
||||
};
|
||||
if res.is_err() {
|
||||
break 'poll;
|
||||
// Wait for event
|
||||
nix::poll::poll(&mut poll_fds, PollTimeout::NONE).check_os_err("poll", None, None)?;
|
||||
for pfd in &poll_fds {
|
||||
if pfd.all().unwrap_or(false) {
|
||||
let raw_fd = pfd.as_fd().as_raw_fd();
|
||||
if raw_fd == STDIN_FILENO {
|
||||
pump_via_splice(STDIN_FILENO, raw_out, &pipe_fd)?;
|
||||
} else if raw_fd == raw_in {
|
||||
pump_via_splice(raw_in, STDOUT_FILENO, &pipe_fd)?;
|
||||
} else if raw_fd == raw_sig {
|
||||
resize_pty(raw_out);
|
||||
signal_fd.read_signal()?;
|
||||
}
|
||||
} else if pfd.revents != 0 && pfd.fd == infd {
|
||||
unsafe { close(pfd.fd) };
|
||||
} else if pfd
|
||||
.revents()
|
||||
.unwrap_or(PollFlags::POLLHUP)
|
||||
.intersects(stop_flags)
|
||||
{
|
||||
// If revents is None or contains any err_flags, stop polling
|
||||
break 'poll;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn pump_tty(infd: i32, outfd: i32) {
|
||||
set_stdin_raw();
|
||||
|
||||
let infd = unsafe { OwnedFd::from_raw_fd(infd) };
|
||||
pump_tty_impl(infd, outfd).ok();
|
||||
|
||||
restore_stdin();
|
||||
unsafe { raise(SIGWINCH) };
|
||||
nix::sys::signal::raise(Signal::SIGWINCH).ok();
|
||||
}
|
||||
|
||||
@@ -3,11 +3,12 @@ use crate::daemon::{MagiskD, to_user_id};
|
||||
use crate::ffi::{ZygiskRequest, ZygiskStateFlags, get_magisk_tmp, update_deny_flags};
|
||||
use crate::resetprop::{get_prop, set_prop};
|
||||
use crate::socket::{IpcRead, UnixSocketExt};
|
||||
use base::libc::{O_CLOEXEC, O_CREAT, O_RDONLY, STDOUT_FILENO};
|
||||
use base::libc::STDOUT_FILENO;
|
||||
use base::{
|
||||
Directory, FsPathBuilder, LoggedResult, ResultExt, Utf8CStr, WriteExt, cstr, fork_dont_care,
|
||||
libc, log_err, raw_cstr, warn,
|
||||
};
|
||||
use nix::fcntl::OFlag;
|
||||
use std::fmt::Write;
|
||||
use std::os::fd::{AsRawFd, OwnedFd, RawFd};
|
||||
use std::os::unix::net::UnixStream;
|
||||
@@ -228,7 +229,7 @@ impl MagiskD {
|
||||
.join_path("zygisk");
|
||||
// Create the unloaded marker file
|
||||
if let Ok(dir) = Directory::open(&path) {
|
||||
dir.open_as_file_at(cstr!("unloaded"), O_CREAT | O_RDONLY, 0o644)
|
||||
dir.open_as_file_at(cstr!("unloaded"), OFlag::O_CREAT | OFlag::O_RDONLY, 0o644)
|
||||
.log()
|
||||
.ok();
|
||||
}
|
||||
@@ -244,7 +245,7 @@ impl MagiskD {
|
||||
let dir = cstr::buf::default()
|
||||
.join_path(MODULEROOT)
|
||||
.join_path(&module.name);
|
||||
let fd = dir.open(O_RDONLY | O_CLOEXEC)?;
|
||||
let fd = dir.open(OFlag::O_RDONLY | OFlag::O_CLOEXEC)?;
|
||||
client.send_fds(&[fd.as_raw_fd()])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user