No hardcode temp dir

This commit is contained in:
Nullptr
2024-01-04 03:44:57 +08:00
parent 32931cf3a8
commit 043cfd93d6
11 changed files with 56 additions and 50 deletions

View File

@@ -1,6 +1,6 @@
[versions]
agp = "8.1.2"
kotlin = "1.9.10"
agp = "8.2.0"
kotlin = "1.9.22"
[plugins]
agp-lib = { id = "com.android.library", version.ref = "agp" }

View File

@@ -7,19 +7,13 @@
#include "socket_utils.h"
namespace zygiskd {
static std::string zygisk_path;
void Init(const char *path) {
LOGI("zygisk path set to %s", path);
zygisk_path = path;
}
int Connect(uint8_t retry) {
int fd = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
struct sockaddr_un addr{
.sun_family = AF_UNIX,
.sun_path={0},
};
auto socket_path = zygisk_path + kCPSocketName;
auto socket_path = std::string(TMP_PATH) + kCPSocketName;
strcpy(addr.sun_path, socket_path.c_str());
socklen_t socklen = sizeof(addr);

View File

@@ -12,7 +12,7 @@
#endif
constexpr auto kCPSocketName = "/" LP_SELECT("cp32", "cp64") ".sock";
#define TMP_PATH "/debug_ramdisk/zygisksu"
inline static const char* TMP_PATH = getenv("TMP_PATH");
class UniqueFd {
using Fd = int;
@@ -63,8 +63,6 @@ namespace zygiskd {
SystemServerStarted,
};
void Init(const char *path = TMP_PATH);
bool PingHeartbeat();
int RequestLogcatFd();

View File

@@ -12,7 +12,6 @@ void entry(void* handle) {
LOGI("Zygisk library injected, version %s", ZKSU_VERSION);
self_handle = handle;
zygiskd::Init();
if (!zygiskd::PingHeartbeat()) {
LOGE("Zygisk daemon is not running");
return;

View File

@@ -19,7 +19,6 @@ int main(int argc, char **argv) {
return 0;
} else if (argc >= 3 && argv[1] == "trace"sv) {
if (argc >= 4 && argv[3] == "--restart"sv) {
zygiskd::Init();
zygiskd::ZygoteRestart();
}
auto pid = strtol(argv[2], 0, 0);

View File

@@ -37,7 +37,7 @@ enum TracingState {
std::string monitor_stop_reason;
constexpr char SOCKET_NAME[] = TMP_PATH "/init_monitor";
constexpr char SOCKET_NAME[] = "init_monitor";
struct EventLoop;
@@ -136,7 +136,7 @@ struct SocketHandler : public EventHandler {
.sun_family = AF_UNIX,
.sun_path={0},
};
strcpy(addr.sun_path, SOCKET_NAME);
sprintf(addr.sun_path, "%s/%s", TMP_PATH, SOCKET_NAME);
socklen_t socklen = sizeof(sa_family_t) + strlen(addr.sun_path);
if (bind(sock_fd_, (struct sockaddr *) &addr, socklen) == -1) {
PLOGE("bind socket");
@@ -544,7 +544,7 @@ static void updateStatus() {
}
static bool prepare_environment() {
prop_path = TMP_PATH "/module.prop";
prop_path = std::string(TMP_PATH) + "/module.prop";
close(open(prop_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644));
auto orig_prop = xopen_file("./module.prop", "r");
if (orig_prop == nullptr) {
@@ -595,7 +595,7 @@ void send_control_command(Command cmd) {
.sun_family = AF_UNIX,
.sun_path={0},
};
strcpy(addr.sun_path, SOCKET_NAME);
sprintf(addr.sun_path, "%s/%s", TMP_PATH, SOCKET_NAME);
socklen_t socklen = sizeof(sa_family_t) + strlen(addr.sun_path);
auto nsend = sendto(sockfd, (void *) &cmd, sizeof(cmd), 0, (sockaddr *) &addr, socklen);
if (nsend == -1) {

View File

@@ -26,7 +26,11 @@ create_sys_perm() {
chcon u:object_r:system_file:s0 $1
}
TMP_PATH="/debug_ramdisk/zygisksu"
if [ "$(which magisk)" ]; then
export TMP_PATH="$(magisk --path)/zygisksu"
else
export TMP_PATH="/debug_ramdisk/zygisksu"
fi
create_sys_perm $TMP_PATH

View File

@@ -1,2 +1,9 @@
MODDIR=${0%/*}/..
if [ "$(which magisk)" ]; then
export TMP_PATH="$(magisk --path)/zygisksu"
else
export TMP_PATH="/debug_ramdisk/zygisksu"
fi
exec $MODDIR/bin/zygisk-ptrace64 ctl $*

View File

@@ -24,9 +24,6 @@ pub const ZYGOTE_INJECTED: i32 = lp_select!(5, 4);
pub const DAEMON_SET_INFO: i32 = lp_select!(7, 6);
pub const DAEMON_SET_ERROR_INFO: i32 = lp_select!(9, 8);
pub const SYSTEM_SERVER_STARTED: i32 = 10;
pub const TMP_DIR: &str = "/debug_ramdisk/zygisksu";
pub const CONTROLLER_SOCKET: &str = concatcp!(TMP_DIR, "/init_monitor");
pub const PATH_CP_NAME: &str = concatcp!(TMP_DIR, lp_select!("/cp32.sock", "/cp64.sock"));
pub const MAX_RESTART_COUNT: i32 = 5;

View File

@@ -1,24 +1,24 @@
use crate::constants::{DaemonSocketAction, ProcessFlags};
use crate::utils::{check_unix_socket, UnixStreamExt};
use crate::{constants, dl, lp_select, root_impl, utils};
use crate::utils::{check_unix_socket, LateInit, UnixStreamExt};
use crate::{constants, lp_select, root_impl, utils};
use anyhow::{bail, Result};
use passfd::FdPassingExt;
use std::sync::{Arc, Mutex};
use std::thread;
use std::fs;
use std::io::Error;
use std::os::fd::{OwnedFd, RawFd};
use std::ops::Deref;
use std::os::fd::{AsFd, OwnedFd, RawFd};
use std::os::unix::{
net::{UnixListener, UnixStream},
prelude::AsRawFd,
};
use std::path::PathBuf;
use std::process::{Command, exit};
use log::info;
use log::{debug, error, info, trace, warn};
use std::os::unix::process::CommandExt;
use bitflags::Flags;
type ZygiskCompanionEntryFn = unsafe extern "C" fn(i32);
use rustix::fs::{fcntl_setfd, FdFlags};
struct Module {
name: String,
@@ -30,11 +30,19 @@ struct Context {
modules: Vec<Module>,
}
static TMP_PATH: LateInit<String> = LateInit::new();
static CONTROLLER_SOCKET: LateInit<String> = LateInit::new();
static PATH_CP_NAME: LateInit<String> = LateInit::new();
pub fn main() -> Result<()> {
log::info!("Welcome to Zygisk Next ({}) !", constants::ZKSU_VERSION);
info!("Welcome to Zygisk Next ({}) !", constants::ZKSU_VERSION);
TMP_PATH.init(std::env::var("TMP_PATH")?);
CONTROLLER_SOCKET.init(format!("{}/init_monitor", TMP_PATH.deref()));
PATH_CP_NAME.init(format!("{}/{}", TMP_PATH.deref(), lp_select!("/cp32.sock", "/cp64.sock")));
let arch = get_arch()?;
log::debug!("Daemon architecture: {arch}");
debug!("Daemon architecture: {arch}");
let modules = load_modules(arch)?;
{
@@ -54,7 +62,7 @@ pub fn main() -> Result<()> {
msg.extend_from_slice(&(info.len() as u32 + 1).to_le_bytes());
msg.extend_from_slice(info.as_bytes());
msg.extend_from_slice(&[0u8]);
utils::unix_datagram_sendto(constants::CONTROLLER_SOCKET, msg.as_slice()).expect("failed to send info");
utils::unix_datagram_sendto(&CONTROLLER_SOCKET, msg.as_slice()).expect("failed to send info");
}
let context = Context {
@@ -67,11 +75,11 @@ pub fn main() -> Result<()> {
let context = Arc::clone(&context);
let action = stream.read_u8()?;
let action = DaemonSocketAction::try_from(action)?;
log::trace!("New daemon action {:?}", action);
trace!("New daemon action {:?}", action);
match action {
DaemonSocketAction::PingHeartbeat => {
let value = constants::ZYGOTE_INJECTED;
utils::unix_datagram_sendto(constants::CONTROLLER_SOCKET, &value.to_le_bytes())?;
utils::unix_datagram_sendto(&CONTROLLER_SOCKET, &value.to_le_bytes())?;
}
DaemonSocketAction::ZygoteRestart => {
info!("Zygote restarted, clean up companions");
@@ -82,12 +90,12 @@ pub fn main() -> Result<()> {
}
DaemonSocketAction::SystemServerStarted => {
let value = constants::SYSTEM_SERVER_STARTED;
utils::unix_datagram_sendto(constants::CONTROLLER_SOCKET, &value.to_le_bytes())?;
utils::unix_datagram_sendto(&CONTROLLER_SOCKET, &value.to_le_bytes())?;
}
_ => {
thread::spawn(move || {
if let Err(e) = handle_daemon_action(action, stream, &context) {
log::warn!("Error handling daemon action: {}\n{}", e, e.backtrace());
warn!("Error handling daemon action: {}\n{}", e, e.backtrace());
}
});
}
@@ -113,7 +121,7 @@ fn load_modules(arch: &str) -> Result<Vec<Module>> {
let dir = match fs::read_dir(constants::PATH_MODULES_DIR) {
Ok(dir) => dir,
Err(e) => {
log::warn!("Failed reading modules directory: {}", e);
warn!("Failed reading modules directory: {}", e);
return Ok(modules);
}
};
@@ -125,11 +133,11 @@ fn load_modules(arch: &str) -> Result<Vec<Module>> {
if !so_path.exists() || disabled.exists() {
continue;
}
log::info!(" Loading module `{name}`...");
info!(" Loading module `{name}`...");
let lib_fd = match create_library_fd(&so_path) {
Ok(fd) => fd,
Err(e) => {
log::warn!(" Failed to create memfd for `{name}`: {e}");
warn!(" Failed to create memfd for `{name}`: {e}");
continue;
}
};
@@ -161,7 +169,7 @@ fn create_library_fd(so_path: &PathBuf) -> Result<OwnedFd> {
fn create_daemon_socket() -> Result<UnixListener> {
utils::set_socket_create_context("u:r:zygote:s0")?;
let listener = utils::unix_listener_from_path(constants::PATH_CP_NAME)?;
let listener = utils::unix_listener_from_path(&PATH_CP_NAME)?;
Ok(listener)
}
@@ -187,13 +195,13 @@ fn spawn_companion(name: &str, lib_fd: RawFd) -> Result<Option<UnixStream>> {
0 => Ok(None),
1 => Ok(Some(daemon)),
_ => bail!("Invalid companion response"),
}
};
} else {
bail!("exited with status {}", status);
}
} else {
// Remove FD_CLOEXEC flag
unsafe { libc::fcntl(companion.as_raw_fd() as libc::c_int, libc::F_SETFD, 0i32); };
fcntl_setfd(companion.as_fd(), FdFlags::empty())?;
}
}
@@ -236,8 +244,8 @@ fn handle_daemon_action(action: DaemonSocketAction, mut stream: UnixStream, cont
root_impl::RootImpl::Magisk => flags |= ProcessFlags::PROCESS_ROOT_IS_MAGISK,
_ => panic!("wrong root impl: {:?}", root_impl::get_impl()),
}
log::trace!("Uid {} granted root: {}", uid, flags.contains(ProcessFlags::PROCESS_GRANTED_ROOT));
log::trace!("Uid {} on denylist: {}", uid, flags.contains(ProcessFlags::PROCESS_ON_DENYLIST));
trace!("Uid {} granted root: {}", uid, flags.contains(ProcessFlags::PROCESS_GRANTED_ROOT));
trace!("Uid {} on denylist: {}", uid, flags.contains(ProcessFlags::PROCESS_ON_DENYLIST));
stream.write_u32(flags.bits())?;
}
DaemonSocketAction::ReadModules => {
@@ -253,7 +261,7 @@ fn handle_daemon_action(action: DaemonSocketAction, mut stream: UnixStream, cont
let mut companion = module.companion.lock().unwrap();
if let Some(Some(sock)) = companion.as_ref() {
if !check_unix_socket(sock, false) {
log::error!("Poll companion for module `{}` crashed", module.name);
error!("Poll companion for module `{}` crashed", module.name);
companion.take();
}
}
@@ -261,21 +269,21 @@ fn handle_daemon_action(action: DaemonSocketAction, mut stream: UnixStream, cont
match spawn_companion(&module.name, module.lib_fd.as_raw_fd()) {
Ok(c) => {
if c.is_some() {
log::trace!(" Spawned companion for `{}`", module.name);
trace!(" Spawned companion for `{}`", module.name);
} else {
log::trace!(" No companion spawned for `{}` because it has not entry", module.name);
trace!(" No companion spawned for `{}` because it has not entry", module.name);
}
*companion = Some(c);
},
}
Err(e) => {
log::warn!(" Failed to spawn companion for `{}`: {}", module.name, e);
warn!(" Failed to spawn companion for `{}`: {}", module.name, e);
}
};
}
match companion.as_ref() {
Some(Some(sock)) => {
if let Err(e) = sock.send_fd(stream.as_raw_fd()) {
log::error!("Failed to send companion fd socket of module `{}`: {}", module.name, e);
error!("Failed to send companion fd socket of module `{}`: {}", module.name, e);
stream.write_u8(0)?;
}
// Ok: Send by companion