implement magic mount
This commit is contained in:
@@ -39,7 +39,6 @@ sha256 = "1"
|
|||||||
sha1 = "0.10"
|
sha1 = "0.10"
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
chrono = "0.4"
|
chrono = "0.4"
|
||||||
hole-punch = { git = "https://github.com/tiann/hole-punch" }
|
|
||||||
regex-lite = "0.1"
|
regex-lite = "0.1"
|
||||||
fs4 = "0.13"
|
fs4 = "0.13"
|
||||||
|
|
||||||
|
|||||||
@@ -161,17 +161,6 @@ enum Debug {
|
|||||||
|
|
||||||
Mount,
|
Mount,
|
||||||
|
|
||||||
/// Copy sparse file
|
|
||||||
Xcp {
|
|
||||||
/// source file
|
|
||||||
src: String,
|
|
||||||
/// destination file
|
|
||||||
dst: String,
|
|
||||||
/// punch hole
|
|
||||||
#[arg(short, long, default_value = "false")]
|
|
||||||
punch_hole: bool,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// For testing
|
/// For testing
|
||||||
Test,
|
Test,
|
||||||
}
|
}
|
||||||
@@ -231,9 +220,6 @@ enum Module {
|
|||||||
|
|
||||||
/// list all modules
|
/// list all modules
|
||||||
List,
|
List,
|
||||||
|
|
||||||
/// Shrink module image size
|
|
||||||
Shrink,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(clap::Subcommand, Debug)]
|
#[derive(clap::Subcommand, Debug)]
|
||||||
@@ -313,7 +299,6 @@ pub fn run() -> Result<()> {
|
|||||||
Module::Disable { id } => module::disable_module(&id),
|
Module::Disable { id } => module::disable_module(&id),
|
||||||
Module::Action { id } => module::run_action(&id),
|
Module::Action { id } => module::run_action(&id),
|
||||||
Module::List => module::list_modules(),
|
Module::List => module::list_modules(),
|
||||||
Module::Shrink => module::shrink_ksu_images(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Commands::Install { magiskboot } => utils::install(magiskboot),
|
Commands::Install { magiskboot } => utils::install(magiskboot),
|
||||||
@@ -347,15 +332,7 @@ pub fn run() -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
Debug::Su { global_mnt } => crate::su::grant_root(global_mnt),
|
Debug::Su { global_mnt } => crate::su::grant_root(global_mnt),
|
||||||
Debug::Mount => init_event::mount_modules_systemlessly(defs::MODULE_DIR),
|
Debug::Mount => init_event::mount_modules_systemlessly(),
|
||||||
Debug::Xcp {
|
|
||||||
src,
|
|
||||||
dst,
|
|
||||||
punch_hole,
|
|
||||||
} => {
|
|
||||||
utils::copy_sparse_file(src, dst, punch_hole)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Debug::Test => assets::ensure_binaries(false),
|
Debug::Test => assets::ensure_binaries(false),
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ pub const PROFILE_SELINUX_DIR: &str = concatcp!(PROFILE_DIR, "selinux/");
|
|||||||
pub const PROFILE_TEMPLATE_DIR: &str = concatcp!(PROFILE_DIR, "templates/");
|
pub const PROFILE_TEMPLATE_DIR: &str = concatcp!(PROFILE_DIR, "templates/");
|
||||||
|
|
||||||
pub const KSURC_PATH: &str = concatcp!(WORKING_DIR, ".ksurc");
|
pub const KSURC_PATH: &str = concatcp!(WORKING_DIR, ".ksurc");
|
||||||
pub const KSU_OVERLAY_SOURCE: &str = "KSU";
|
pub const KSU_MOUNT_SOURCE: &str = "KSU";
|
||||||
pub const DAEMON_PATH: &str = concatcp!(ADB_DIR, "ksud");
|
pub const DAEMON_PATH: &str = concatcp!(ADB_DIR, "ksud");
|
||||||
pub const MAGISKBOOT_PATH: &str = concatcp!(BINARY_DIR, "magiskboot");
|
pub const MAGISKBOOT_PATH: &str = concatcp!(BINARY_DIR, "magiskboot");
|
||||||
|
|
||||||
@@ -18,15 +18,9 @@ pub const MAGISKBOOT_PATH: &str = concatcp!(BINARY_DIR, "magiskboot");
|
|||||||
pub const DAEMON_LINK_PATH: &str = concatcp!(BINARY_DIR, "ksud");
|
pub const DAEMON_LINK_PATH: &str = concatcp!(BINARY_DIR, "ksud");
|
||||||
|
|
||||||
pub const MODULE_DIR: &str = concatcp!(ADB_DIR, "modules/");
|
pub const MODULE_DIR: &str = concatcp!(ADB_DIR, "modules/");
|
||||||
pub const MODULE_IMG: &str = concatcp!(WORKING_DIR, "modules.img");
|
|
||||||
pub const MODULE_UPDATE_IMG: &str = concatcp!(WORKING_DIR, "modules_update.img");
|
|
||||||
|
|
||||||
pub const MODULE_UPDATE_TMP_IMG: &str = concatcp!(WORKING_DIR, "update_tmp.img");
|
|
||||||
|
|
||||||
// warning: this directory should not change, or you need to change the code in module_installer.sh!!!
|
// warning: this directory should not change, or you need to change the code in module_installer.sh!!!
|
||||||
pub const MODULE_UPDATE_TMP_DIR: &str = concatcp!(ADB_DIR, "modules_update/");
|
pub const MODULE_UPDATE_DIR: &str = concatcp!(ADB_DIR, "modules_update/");
|
||||||
|
|
||||||
pub const SYSTEM_RW_DIR: &str = concatcp!(MODULE_DIR, ".rw/");
|
|
||||||
|
|
||||||
pub const TEMP_DIR: &str = "/debug_ramdisk";
|
pub const TEMP_DIR: &str = "/debug_ramdisk";
|
||||||
pub const MODULE_WEB_DIR: &str = "webroot";
|
pub const MODULE_WEB_DIR: &str = "webroot";
|
||||||
|
|||||||
@@ -1,100 +1,11 @@
|
|||||||
use anyhow::{Context, Result, bail};
|
use crate::module::{handle_updated_modules, prune_modules};
|
||||||
use log::{info, warn};
|
|
||||||
use std::{collections::HashMap, path::Path};
|
|
||||||
|
|
||||||
use crate::module::prune_modules;
|
|
||||||
use crate::{
|
use crate::{
|
||||||
assets, defs, ksucalls, mount, restorecon,
|
assets, defs, ksucalls, restorecon,
|
||||||
utils::{self, ensure_clean_dir},
|
utils::self,
|
||||||
};
|
};
|
||||||
|
use anyhow::{Context, Result};
|
||||||
fn mount_partition(partition_name: &str, lowerdir: &Vec<String>) -> Result<()> {
|
use log::{info, warn};
|
||||||
if lowerdir.is_empty() {
|
use std::path::Path;
|
||||||
warn!("partition: {partition_name} lowerdir is empty");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let partition = format!("/{partition_name}");
|
|
||||||
|
|
||||||
// if /partition is a symlink and linked to /system/partition, then we don't need to overlay it separately
|
|
||||||
if Path::new(&partition).read_link().is_ok() {
|
|
||||||
warn!("partition: {partition} is a symlink");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut workdir = None;
|
|
||||||
let mut upperdir = None;
|
|
||||||
let system_rw_dir = Path::new(defs::SYSTEM_RW_DIR);
|
|
||||||
if system_rw_dir.exists() {
|
|
||||||
workdir = Some(system_rw_dir.join(partition_name).join("workdir"));
|
|
||||||
upperdir = Some(system_rw_dir.join(partition_name).join("upperdir"));
|
|
||||||
}
|
|
||||||
|
|
||||||
mount::mount_overlay(&partition, lowerdir, workdir, upperdir)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn mount_modules_systemlessly(module_dir: &str) -> Result<()> {
|
|
||||||
// construct overlay mount params
|
|
||||||
let dir = std::fs::read_dir(module_dir);
|
|
||||||
let Ok(dir) = dir else {
|
|
||||||
bail!("open {} failed", defs::MODULE_DIR);
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut system_lowerdir: Vec<String> = Vec::new();
|
|
||||||
|
|
||||||
let partition = vec!["vendor", "product", "system_ext", "odm", "oem"];
|
|
||||||
let mut partition_lowerdir: HashMap<String, Vec<String>> = HashMap::new();
|
|
||||||
for ele in &partition {
|
|
||||||
partition_lowerdir.insert((*ele).to_string(), Vec::new());
|
|
||||||
}
|
|
||||||
|
|
||||||
for entry in dir.flatten() {
|
|
||||||
let module = entry.path();
|
|
||||||
if !module.is_dir() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let disabled = module.join(defs::DISABLE_FILE_NAME).exists();
|
|
||||||
if disabled {
|
|
||||||
info!("module: {} is disabled, ignore!", module.display());
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let skip_mount = module.join(defs::SKIP_MOUNT_FILE_NAME).exists();
|
|
||||||
if skip_mount {
|
|
||||||
info!("module: {} skip_mount exist, skip!", module.display());
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let module_system = Path::new(&module).join("system");
|
|
||||||
if module_system.is_dir() {
|
|
||||||
system_lowerdir.push(format!("{}", module_system.display()));
|
|
||||||
}
|
|
||||||
|
|
||||||
for part in &partition {
|
|
||||||
// if /partition is a mountpoint, we would move it to $MODPATH/$partition when install
|
|
||||||
// otherwise it must be a symlink and we don't need to overlay!
|
|
||||||
let part_path = Path::new(&module).join(part);
|
|
||||||
if part_path.is_dir() {
|
|
||||||
if let Some(v) = partition_lowerdir.get_mut(*part) {
|
|
||||||
v.push(format!("{}", part_path.display()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// mount /system first
|
|
||||||
if let Err(e) = mount_partition("system", &system_lowerdir) {
|
|
||||||
warn!("mount system failed: {:#}", e);
|
|
||||||
}
|
|
||||||
|
|
||||||
// mount other partitions
|
|
||||||
for (k, v) in partition_lowerdir {
|
|
||||||
if let Err(e) = mount_partition(&k, &v) {
|
|
||||||
warn!("mount {k} failed: {:#}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn on_post_data_fs() -> Result<()> {
|
pub fn on_post_data_fs() -> Result<()> {
|
||||||
ksucalls::report_post_fs_data();
|
ksucalls::report_post_fs_data();
|
||||||
@@ -111,11 +22,9 @@ pub fn on_post_data_fs() -> Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let safe_mode = crate::utils::is_safe_mode();
|
let safe_mode = utils::is_safe_mode();
|
||||||
|
|
||||||
if safe_mode {
|
if safe_mode {
|
||||||
// we should still mount modules.img to `/data/adb/modules` in safe mode
|
|
||||||
// becuase we may need to operate the module dir in safe mode
|
|
||||||
warn!("safe mode, skip common post-fs-data.d scripts");
|
warn!("safe mode, skip common post-fs-data.d scripts");
|
||||||
} else {
|
} else {
|
||||||
// Then exec common post-fs-data scripts
|
// Then exec common post-fs-data scripts
|
||||||
@@ -124,43 +33,8 @@ pub fn on_post_data_fs() -> Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let module_update_img = defs::MODULE_UPDATE_IMG;
|
|
||||||
let module_img = defs::MODULE_IMG;
|
|
||||||
let module_dir = defs::MODULE_DIR;
|
|
||||||
let module_update_flag = Path::new(defs::WORKING_DIR).join(defs::UPDATE_FILE_NAME);
|
|
||||||
|
|
||||||
// modules.img is the default image
|
|
||||||
let mut target_update_img = &module_img;
|
|
||||||
|
|
||||||
// we should clean the module mount point if it exists
|
|
||||||
ensure_clean_dir(module_dir)?;
|
|
||||||
|
|
||||||
assets::ensure_binaries(true).with_context(|| "Failed to extract bin assets")?;
|
assets::ensure_binaries(true).with_context(|| "Failed to extract bin assets")?;
|
||||||
|
|
||||||
if Path::new(module_update_img).exists() {
|
|
||||||
if module_update_flag.exists() {
|
|
||||||
// if modules_update.img exists, and the the flag indicate this is an update
|
|
||||||
// this make sure that if the update failed, we will fallback to the old image
|
|
||||||
// if we boot succeed, we will rename the modules_update.img to modules.img #on_boot_complete
|
|
||||||
target_update_img = &module_update_img;
|
|
||||||
// And we should delete the flag immediately
|
|
||||||
std::fs::remove_file(module_update_flag)?;
|
|
||||||
} else {
|
|
||||||
// if modules_update.img exists, but the flag not exist, we should delete it
|
|
||||||
std::fs::remove_file(module_update_img)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !Path::new(target_update_img).exists() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
// we should always mount the module.img to module dir
|
|
||||||
// becuase we may need to operate the module dir in safe mode
|
|
||||||
info!("mount module image: {target_update_img} to {module_dir}");
|
|
||||||
mount::AutoMountExt4::try_new(target_update_img, module_dir, false)
|
|
||||||
.with_context(|| "mount module image failed".to_string())?;
|
|
||||||
|
|
||||||
// tell kernel that we've mount the module, so that it can do some optimization
|
// tell kernel that we've mount the module, so that it can do some optimization
|
||||||
ksucalls::report_module_mounted();
|
ksucalls::report_module_mounted();
|
||||||
|
|
||||||
@@ -177,6 +51,10 @@ pub fn on_post_data_fs() -> Result<()> {
|
|||||||
warn!("prune modules failed: {}", e);
|
warn!("prune modules failed: {}", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Err(e) = handle_updated_modules() {
|
||||||
|
warn!("handle updated modules failed: {}", e);
|
||||||
|
}
|
||||||
|
|
||||||
if let Err(e) = restorecon::restorecon() {
|
if let Err(e) = restorecon::restorecon() {
|
||||||
warn!("restorecon failed: {}", e);
|
warn!("restorecon failed: {}", e);
|
||||||
}
|
}
|
||||||
@@ -190,11 +68,6 @@ pub fn on_post_data_fs() -> Result<()> {
|
|||||||
warn!("apply root profile sepolicy failed: {}", e);
|
warn!("apply root profile sepolicy failed: {}", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
// mount temp dir
|
|
||||||
if let Err(e) = mount::mount_tmpfs(defs::TEMP_DIR) {
|
|
||||||
warn!("do temp dir mount failed: {}", e);
|
|
||||||
}
|
|
||||||
|
|
||||||
// exec modules post-fs-data scripts
|
// exec modules post-fs-data scripts
|
||||||
// TODO: Add timeout
|
// TODO: Add timeout
|
||||||
if let Err(e) = crate::module::exec_stage_script("post-fs-data", true) {
|
if let Err(e) = crate::module::exec_stage_script("post-fs-data", true) {
|
||||||
@@ -206,15 +79,23 @@ pub fn on_post_data_fs() -> Result<()> {
|
|||||||
warn!("load system.prop failed: {}", e);
|
warn!("load system.prop failed: {}", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
// mount module systemlessly by overlay
|
// mount module systemlessly by magic mount
|
||||||
if let Err(e) = mount_modules_systemlessly(module_dir) {
|
if let Err(e) = mount_modules_systemlessly() {
|
||||||
warn!("do systemless mount failed: {}", e);
|
warn!("do systemless mount failed: {}", e);
|
||||||
}
|
}
|
||||||
|
|
||||||
run_stage("post-mount", true);
|
run_stage("post-mount", true);
|
||||||
|
|
||||||
std::env::set_current_dir("/").with_context(|| "failed to chdir to /")?;
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "android")]
|
||||||
|
pub fn mount_modules_systemlessly() -> Result<()> {
|
||||||
|
crate::magic_mount::magic_mount()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_os = "android"))]
|
||||||
|
pub fn mount_modules_systemlessly() -> Result<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,17 +130,6 @@ pub fn on_services() -> Result<()> {
|
|||||||
pub fn on_boot_completed() -> Result<()> {
|
pub fn on_boot_completed() -> Result<()> {
|
||||||
ksucalls::report_boot_complete();
|
ksucalls::report_boot_complete();
|
||||||
info!("on_boot_completed triggered!");
|
info!("on_boot_completed triggered!");
|
||||||
let module_update_img = Path::new(defs::MODULE_UPDATE_IMG);
|
|
||||||
let module_img = Path::new(defs::MODULE_IMG);
|
|
||||||
if module_update_img.exists() {
|
|
||||||
// this is a update and we successfully booted
|
|
||||||
if std::fs::rename(module_update_img, module_img).is_err() {
|
|
||||||
warn!("Failed to rename images, copy it now.",);
|
|
||||||
utils::copy_sparse_file(module_update_img, module_img, false)
|
|
||||||
.with_context(|| "Failed to copy images")?;
|
|
||||||
std::fs::remove_file(module_update_img).with_context(|| "Failed to remove image!")?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
run_stage("boot-completed", false);
|
run_stage("boot-completed", false);
|
||||||
|
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ setup_flashable() {
|
|||||||
$BOOTMODE && return
|
$BOOTMODE && return
|
||||||
if [ -z $OUTFD ] || readlink /proc/$$/fd/$OUTFD | grep -q /tmp; then
|
if [ -z $OUTFD ] || readlink /proc/$$/fd/$OUTFD | grep -q /tmp; then
|
||||||
# We will have to manually find out OUTFD
|
# We will have to manually find out OUTFD
|
||||||
for FD in `ls /proc/$$/fd`; do
|
for FD in /proc/$$/fd/*; do
|
||||||
if readlink /proc/$$/fd/$FD | grep -q pipe; then
|
if readlink /proc/$$/fd/$FD | grep -q pipe; then
|
||||||
if ps | grep -v grep | grep -qE " 3 $FD |status_fd=$FD"; then
|
if ps | grep -v grep | grep -qE " 3 $FD |status_fd=$FD"; then
|
||||||
OUTFD=$FD
|
OUTFD=$FD
|
||||||
@@ -302,18 +302,15 @@ is_legacy_script() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handle_partition() {
|
handle_partition() {
|
||||||
# if /system/vendor is a symlink, we need to move it out of $MODPATH/system, otherwise it will be overlayed
|
PARTITION="$1"
|
||||||
# if /system/vendor is a normal directory, it is ok to overlay it and we don't need to overlay it separately.
|
if [ ! -e "$MODPATH/system/$PARTITION" ]; then
|
||||||
if [ ! -e $MODPATH/system/$1 ]; then
|
|
||||||
# no partition found
|
# no partition found
|
||||||
return;
|
return;
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ -L "/system/$1" ] && [ "$(readlink -f /system/$1)" = "/$1" ]; then
|
if [ -L "/system/$PARTITION" ] && [ "$(readlink -f "/system/$PARTITION")" = "/$PARTITION" ]; then
|
||||||
ui_print "- Handle partition /$1"
|
ui_print "- Handle partition /$PARTITION"
|
||||||
# we create a symlink if module want to access $MODPATH/system/$1
|
ln -sf "$MODPATH/$PARTITION" "$MODPATH/system/$PARTITION"
|
||||||
# but it doesn't always work(ie. write it in post-fs-data.sh would fail because it is readonly)
|
|
||||||
mv -f $MODPATH/system/$1 $MODPATH/$1 && ln -sf ../$1 $MODPATH/system/$1
|
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
349
userspace/ksud/src/magic_mount.rs
Normal file
349
userspace/ksud/src/magic_mount.rs
Normal file
@@ -0,0 +1,349 @@
|
|||||||
|
use crate::defs::{KSU_MOUNT_SOURCE, MODULE_DIR, SKIP_MOUNT_FILE_NAME, TEMP_DIR};
|
||||||
|
use crate::magic_mount::NodeFileType::{Directory, RegularFile, Symlink};
|
||||||
|
use crate::restorecon::{lgetfilecon, lsetfilecon};
|
||||||
|
use anyhow::{bail, Context, Result};
|
||||||
|
use rustix::fs::{
|
||||||
|
bind_mount, chmod, chown, mount, move_mount, unmount, Gid, MetadataExt, Mode, MountFlags,
|
||||||
|
MountPropagationFlags, Uid, UnmountFlags,
|
||||||
|
};
|
||||||
|
use rustix::mount::mount_change;
|
||||||
|
use rustix::path::Arg;
|
||||||
|
use std::cmp::PartialEq;
|
||||||
|
use std::collections::hash_map::Entry;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fs;
|
||||||
|
use std::fs::{create_dir, create_dir_all, read_dir, DirEntry, FileType};
|
||||||
|
use std::os::unix::fs::symlink;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
|
||||||
|
enum NodeFileType {
|
||||||
|
RegularFile,
|
||||||
|
Directory,
|
||||||
|
Symlink,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NodeFileType {
|
||||||
|
fn from_file_type(file_type: FileType) -> Option<Self> {
|
||||||
|
if file_type.is_file() {
|
||||||
|
Some(RegularFile)
|
||||||
|
} else if file_type.is_dir() {
|
||||||
|
Some(Directory)
|
||||||
|
} else if file_type.is_symlink() {
|
||||||
|
Some(Symlink)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Node {
|
||||||
|
name: String,
|
||||||
|
file_type: NodeFileType,
|
||||||
|
children: HashMap<String, Node>,
|
||||||
|
// the module that owned this node
|
||||||
|
module_path: Option<PathBuf>,
|
||||||
|
replace: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Node {
|
||||||
|
fn collect_module_files<T: AsRef<Path>>(&mut self, module_dir: T) -> Result<bool> {
|
||||||
|
let dir = module_dir.as_ref();
|
||||||
|
let mut has_file = false;
|
||||||
|
for entry in dir.read_dir()?.flatten() {
|
||||||
|
let name = entry.file_name().to_string_lossy().to_string();
|
||||||
|
if name == ".replace" {
|
||||||
|
has_file = true;
|
||||||
|
self.replace = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let file_type = entry.file_type()?;
|
||||||
|
|
||||||
|
let node = match self.children.entry(name.clone()) {
|
||||||
|
Entry::Occupied(o) => Some(o.into_mut()),
|
||||||
|
Entry::Vacant(v) => {
|
||||||
|
Self::new_module(&name, file_type, dir.join(&name)).map(|it| v.insert(it))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(node) = node {
|
||||||
|
has_file |= if let Directory = node.file_type {
|
||||||
|
node.collect_module_files(&dir.join(&node.name))?
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(has_file)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_root<T: ToString>(name: T) -> Self {
|
||||||
|
Node {
|
||||||
|
name: name.to_string(),
|
||||||
|
file_type: Directory,
|
||||||
|
children: Default::default(),
|
||||||
|
module_path: None,
|
||||||
|
replace: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_module<T: ToString, P: AsRef<Path>>(
|
||||||
|
name: T,
|
||||||
|
file_type: FileType,
|
||||||
|
module_path: P,
|
||||||
|
) -> Option<Self> {
|
||||||
|
let file_type = NodeFileType::from_file_type(file_type)?;
|
||||||
|
|
||||||
|
Some(Node {
|
||||||
|
name: name.to_string(),
|
||||||
|
file_type,
|
||||||
|
children: Default::default(),
|
||||||
|
module_path: Some(PathBuf::from(module_path.as_ref())),
|
||||||
|
replace: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_module_files() -> Result<Option<Node>> {
|
||||||
|
let mut root = Node::new_root("");
|
||||||
|
let mut system = Node::new_root("system");
|
||||||
|
let module_root = Path::new(MODULE_DIR);
|
||||||
|
let mut has_file = false;
|
||||||
|
for entry in module_root.read_dir()?.flatten() {
|
||||||
|
if !entry.file_type()?.is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if entry.path().join("disable").exists() || entry.path().join(SKIP_MOUNT_FILE_NAME).exists() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mod_system = entry.path().join("system");
|
||||||
|
if !mod_system.is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
log::debug!("collecting {}", entry.path().display());
|
||||||
|
|
||||||
|
has_file |= system.collect_module_files(&mod_system)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if has_file {
|
||||||
|
for partition in vec!["vendor", "system_ext", "product", "odm"] {
|
||||||
|
let path_of_root = Path::new("/").join(partition);
|
||||||
|
let path_of_system = Path::new("/system").join(partition);
|
||||||
|
if path_of_root.is_dir() && path_of_system.is_symlink() {
|
||||||
|
let name = partition.to_string();
|
||||||
|
if let Some(node) = system.children.remove(&name) {
|
||||||
|
root.children.insert(name, node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
root.children.insert("system".to_string(), system);
|
||||||
|
Ok(Some(root))
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clone_symlink<Src: AsRef<Path>, Dst: AsRef<Path>>(src: Src, dst: Dst) -> Result<()> {
|
||||||
|
symlink(src.as_ref(), dst.as_ref())?;
|
||||||
|
lsetfilecon(dst.as_ref(), lgetfilecon(src.as_ref())?.as_str())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mount_mirror<P: AsRef<Path>, WP: AsRef<Path>>(
|
||||||
|
path: P,
|
||||||
|
work_dir_path: WP,
|
||||||
|
entry: &DirEntry,
|
||||||
|
) -> Result<()> {
|
||||||
|
let path = path.as_ref().join(entry.file_name());
|
||||||
|
let work_dir_path = work_dir_path.as_ref().join(entry.file_name());
|
||||||
|
let file_type = entry.file_type()?;
|
||||||
|
|
||||||
|
if file_type.is_file() {
|
||||||
|
log::debug!(
|
||||||
|
"mount mirror file {} -> {}",
|
||||||
|
path.display(),
|
||||||
|
work_dir_path.display()
|
||||||
|
);
|
||||||
|
fs::File::create(&work_dir_path)?;
|
||||||
|
bind_mount(&path, &work_dir_path)?;
|
||||||
|
} else if file_type.is_dir() {
|
||||||
|
log::debug!(
|
||||||
|
"mount mirror dir {} -> {}",
|
||||||
|
path.display(),
|
||||||
|
work_dir_path.display()
|
||||||
|
);
|
||||||
|
create_dir(&work_dir_path)?;
|
||||||
|
let metadata = entry.metadata()?;
|
||||||
|
chmod(&work_dir_path, Mode::from_raw_mode(metadata.mode()))?;
|
||||||
|
unsafe {
|
||||||
|
chown(
|
||||||
|
&work_dir_path,
|
||||||
|
Some(Uid::from_raw(metadata.uid())),
|
||||||
|
Some(Gid::from_raw(metadata.gid())),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
lsetfilecon(&work_dir_path, lgetfilecon(&path)?.as_str())?;
|
||||||
|
for entry in read_dir(&path)?.flatten() {
|
||||||
|
mount_mirror(&path, &work_dir_path, &entry)?;
|
||||||
|
}
|
||||||
|
} else if file_type.is_symlink() {
|
||||||
|
log::debug!(
|
||||||
|
"create mirror symlink {} -> {}",
|
||||||
|
path.display(),
|
||||||
|
work_dir_path.display()
|
||||||
|
);
|
||||||
|
clone_symlink(&path, &work_dir_path)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn do_magic_mount<P: AsRef<Path>, WP: AsRef<Path>>(
|
||||||
|
path: P,
|
||||||
|
work_dir_path: WP,
|
||||||
|
current: Node,
|
||||||
|
has_tmpfs: bool,
|
||||||
|
) -> Result<()> {
|
||||||
|
let mut current = current;
|
||||||
|
let path = path.as_ref().join(¤t.name);
|
||||||
|
let work_dir_path = work_dir_path.as_ref().join(¤t.name);
|
||||||
|
match current.file_type {
|
||||||
|
RegularFile => {
|
||||||
|
if has_tmpfs {
|
||||||
|
fs::File::create(&work_dir_path)?;
|
||||||
|
}
|
||||||
|
if let Some(module_path) = ¤t.module_path {
|
||||||
|
log::debug!(
|
||||||
|
"mount module file {} -> {}",
|
||||||
|
module_path.display(),
|
||||||
|
work_dir_path.display()
|
||||||
|
);
|
||||||
|
bind_mount(module_path, &work_dir_path)?;
|
||||||
|
} else {
|
||||||
|
bail!("cannot mount root file {}!", path.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Symlink => {
|
||||||
|
if let Some(module_path) = ¤t.module_path {
|
||||||
|
log::debug!(
|
||||||
|
"create module symlink {} -> {}",
|
||||||
|
module_path.display(),
|
||||||
|
work_dir_path.display()
|
||||||
|
);
|
||||||
|
clone_symlink(module_path, &work_dir_path)?;
|
||||||
|
} else {
|
||||||
|
bail!("cannot mount root symlink {}!", path.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Directory => {
|
||||||
|
let mut create_tmpfs = false;
|
||||||
|
if !has_tmpfs {
|
||||||
|
for (name, node) in ¤t.children {
|
||||||
|
let real_path = path.join(name);
|
||||||
|
let need = if node.file_type == Symlink || !real_path.exists() {
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
let file_type = real_path.metadata()?.file_type();
|
||||||
|
let file_type =
|
||||||
|
NodeFileType::from_file_type(file_type).unwrap_or(RegularFile);
|
||||||
|
file_type != node.file_type || file_type == Symlink
|
||||||
|
};
|
||||||
|
if need {
|
||||||
|
create_tmpfs = need;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let has_tmpfs = has_tmpfs || create_tmpfs;
|
||||||
|
|
||||||
|
if has_tmpfs {
|
||||||
|
log::debug!(
|
||||||
|
"creating tmpfs skeleton for {} at {}",
|
||||||
|
path.display(),
|
||||||
|
work_dir_path.display()
|
||||||
|
);
|
||||||
|
create_dir_all(&work_dir_path)?;
|
||||||
|
let (metadata, path) = if path.exists() {
|
||||||
|
(path.metadata()?, &path)
|
||||||
|
} else if let Some(module_path) = ¤t.module_path {
|
||||||
|
(module_path.metadata()?, module_path)
|
||||||
|
} else {
|
||||||
|
bail!("cannot mount root dir {}!", path.display());
|
||||||
|
};
|
||||||
|
chmod(&work_dir_path, Mode::from_raw_mode(metadata.mode()))?;
|
||||||
|
unsafe {
|
||||||
|
chown(
|
||||||
|
&work_dir_path,
|
||||||
|
Some(Uid::from_raw(metadata.uid())),
|
||||||
|
Some(Gid::from_raw(metadata.gid())),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
lsetfilecon(&work_dir_path, lgetfilecon(&path)?.as_str())?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if create_tmpfs {
|
||||||
|
log::debug!(
|
||||||
|
"creating tmpfs for {} at {}",
|
||||||
|
path.display(),
|
||||||
|
work_dir_path.display()
|
||||||
|
);
|
||||||
|
bind_mount(&work_dir_path, &work_dir_path)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if path.exists() && !current.replace {
|
||||||
|
for entry in path.read_dir()?.flatten() {
|
||||||
|
let name = entry.file_name().to_string_lossy().to_string();
|
||||||
|
if let Some(node) = current.children.remove(&name) {
|
||||||
|
do_magic_mount(&path, &work_dir_path, node, has_tmpfs)?;
|
||||||
|
} else if has_tmpfs {
|
||||||
|
mount_mirror(&path, &work_dir_path, &entry)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if current.replace && current.module_path.is_none() {
|
||||||
|
bail!(
|
||||||
|
"dir {} is declared as replaced but it is root!",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
for node in current.children.into_values() {
|
||||||
|
do_magic_mount(&path, &work_dir_path, node, has_tmpfs)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if create_tmpfs {
|
||||||
|
log::debug!(
|
||||||
|
"moving tmpfs {} -> {}",
|
||||||
|
work_dir_path.display(),
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
|
move_mount(&work_dir_path, &path)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn magic_mount() -> Result<()> {
|
||||||
|
if let Some(root) = collect_module_files()? {
|
||||||
|
let tmp_dir = PathBuf::from(TEMP_DIR);
|
||||||
|
mount(KSU_MOUNT_SOURCE, &tmp_dir, "tmpfs", MountFlags::empty(), "").context("mount tmp")?;
|
||||||
|
mount_change(&tmp_dir, MountPropagationFlags::PRIVATE).context("make tmp private")?;
|
||||||
|
let result = do_magic_mount("/", &tmp_dir, root, false);
|
||||||
|
if let Err(e) = unmount(&tmp_dir, UnmountFlags::DETACH) {
|
||||||
|
log::error!("failed to unmount tmp {}", e);
|
||||||
|
}
|
||||||
|
result
|
||||||
|
} else {
|
||||||
|
log::info!("no modules to mount, skipping!");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,8 +6,9 @@ mod debug;
|
|||||||
mod defs;
|
mod defs;
|
||||||
mod init_event;
|
mod init_event;
|
||||||
mod ksucalls;
|
mod ksucalls;
|
||||||
|
#[cfg(target_os = "android")]
|
||||||
|
mod magic_mount;
|
||||||
mod module;
|
mod module;
|
||||||
mod mount;
|
|
||||||
mod profile;
|
mod profile;
|
||||||
mod restorecon;
|
mod restorecon;
|
||||||
mod sepolicy;
|
mod sepolicy;
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
#[allow(clippy::wildcard_imports)]
|
#[allow(clippy::wildcard_imports)]
|
||||||
use crate::utils::*;
|
use crate::utils::*;
|
||||||
use crate::{
|
use crate::{
|
||||||
assets, defs, ksucalls, mount,
|
assets, defs, ksucalls,
|
||||||
restorecon::{restore_syscon, setsyscon},
|
restorecon::{restore_syscon, setsyscon},
|
||||||
sepolicy, utils,
|
sepolicy,
|
||||||
};
|
};
|
||||||
|
|
||||||
use anyhow::{Context, Result, anyhow, bail, ensure};
|
use anyhow::{Context, Result, anyhow, bail, ensure};
|
||||||
@@ -12,20 +12,21 @@ use is_executable::is_executable;
|
|||||||
use java_properties::PropertiesIter;
|
use java_properties::PropertiesIter;
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
|
|
||||||
use std::fs::OpenOptions;
|
use std::fs::{copy, rename};
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
env::var as env_var,
|
env::var as env_var,
|
||||||
fs::{File, Permissions, remove_dir_all, remove_file, set_permissions},
|
fs::{File, Permissions, remove_dir_all, remove_file, set_permissions},
|
||||||
io::Cursor,
|
io::Cursor,
|
||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
process::{Command, Stdio},
|
process::{Command},
|
||||||
str::FromStr,
|
str::FromStr,
|
||||||
};
|
};
|
||||||
use zip_extensions::zip_extract_file_to_memory;
|
use zip_extensions::zip_extract_file_to_memory;
|
||||||
|
|
||||||
|
use crate::defs::{MODULE_DIR, MODULE_UPDATE_DIR, UPDATE_FILE_NAME};
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
use std::os::unix::{fs::MetadataExt, prelude::PermissionsExt, process::CommandExt};
|
use std::os::unix::{prelude::PermissionsExt, process::CommandExt};
|
||||||
|
|
||||||
const INSTALLER_CONTENT: &str = include_str!("./installer.sh");
|
const INSTALLER_CONTENT: &str = include_str!("./installer.sh");
|
||||||
const INSTALL_MODULE_SCRIPT: &str = concatcp!(
|
const INSTALL_MODULE_SCRIPT: &str = concatcp!(
|
||||||
@@ -75,24 +76,34 @@ fn ensure_boot_completed() -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn mark_update() -> Result<()> {
|
fn mark_module_state(module: &str, flag_file: &str, create: bool) -> Result<()> {
|
||||||
ensure_file_exists(concatcp!(defs::WORKING_DIR, defs::UPDATE_FILE_NAME))
|
let module_state_file = Path::new(MODULE_DIR).join(module).join(flag_file);
|
||||||
}
|
if create {
|
||||||
|
|
||||||
fn mark_module_state(module: &str, flag_file: &str, create_or_delete: bool) -> Result<()> {
|
|
||||||
let module_state_file = Path::new(defs::MODULE_DIR).join(module).join(flag_file);
|
|
||||||
if create_or_delete {
|
|
||||||
ensure_file_exists(module_state_file)
|
ensure_file_exists(module_state_file)
|
||||||
} else {
|
} else {
|
||||||
if module_state_file.exists() {
|
if module_state_file.exists() {
|
||||||
std::fs::remove_file(module_state_file)?;
|
remove_file(module_state_file)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn foreach_module(active_only: bool, mut f: impl FnMut(&Path) -> Result<()>) -> Result<()> {
|
#[derive(PartialEq, Eq)]
|
||||||
let modules_dir = Path::new(defs::MODULE_DIR);
|
enum ModuleType {
|
||||||
|
All,
|
||||||
|
Active,
|
||||||
|
Updated,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn foreach_module(module_type: ModuleType, mut f: impl FnMut(&Path) -> Result<()>) -> Result<()> {
|
||||||
|
let modules_dir = Path::new(match module_type {
|
||||||
|
ModuleType::Updated => MODULE_UPDATE_DIR,
|
||||||
|
_ => defs::MODULE_DIR,
|
||||||
|
});
|
||||||
|
if !modules_dir.is_dir() {
|
||||||
|
warn!("{} is not a directory, skip", modules_dir.display());
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
let dir = std::fs::read_dir(modules_dir)?;
|
let dir = std::fs::read_dir(modules_dir)?;
|
||||||
for entry in dir.flatten() {
|
for entry in dir.flatten() {
|
||||||
let path = entry.path();
|
let path = entry.path();
|
||||||
@@ -101,11 +112,11 @@ fn foreach_module(active_only: bool, mut f: impl FnMut(&Path) -> Result<()>) ->
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if active_only && path.join(defs::DISABLE_FILE_NAME).exists() {
|
if module_type == ModuleType::Active && path.join(defs::DISABLE_FILE_NAME).exists() {
|
||||||
info!("{} is disabled, skip", path.display());
|
info!("{} is disabled, skip", path.display());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if active_only && path.join(defs::REMOVE_FILE_NAME).exists() {
|
if module_type == ModuleType::Active && path.join(defs::REMOVE_FILE_NAME).exists() {
|
||||||
warn!("{} is removed, skip", path.display());
|
warn!("{} is removed, skip", path.display());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -117,27 +128,7 @@ fn foreach_module(active_only: bool, mut f: impl FnMut(&Path) -> Result<()>) ->
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn foreach_active_module(f: impl FnMut(&Path) -> Result<()>) -> Result<()> {
|
fn foreach_active_module(f: impl FnMut(&Path) -> Result<()>) -> Result<()> {
|
||||||
foreach_module(true, f)
|
foreach_module(ModuleType::Active, f)
|
||||||
}
|
|
||||||
|
|
||||||
fn check_image(img: &str) -> Result<()> {
|
|
||||||
let result = Command::new("e2fsck")
|
|
||||||
.args(["-yf", img])
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.status()
|
|
||||||
.with_context(|| format!("Failed to exec e2fsck {img}"))?;
|
|
||||||
let code = result.code();
|
|
||||||
// 0 or 1 is ok
|
|
||||||
// 0: no error
|
|
||||||
// 1: file system errors corrected
|
|
||||||
// https://man7.org/linux/man-pages/man8/e2fsck.8.html
|
|
||||||
// ensure!(
|
|
||||||
// code == Some(0) || code == Some(1),
|
|
||||||
// "Failed to check image, e2fsck exit code: {}",
|
|
||||||
// code.unwrap_or(-1)
|
|
||||||
// );
|
|
||||||
info!("e2fsck exit code: {}", code.unwrap_or(-1));
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn load_sepolicy_rule() -> Result<()> {
|
pub fn load_sepolicy_rule() -> Result<()> {
|
||||||
@@ -256,13 +247,8 @@ pub fn load_system_prop() -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn prune_modules() -> Result<()> {
|
pub fn prune_modules() -> Result<()> {
|
||||||
foreach_module(false, |module| {
|
foreach_module(ModuleType::All, |module| {
|
||||||
remove_file(module.join(defs::UPDATE_FILE_NAME)).ok();
|
if module.join(defs::REMOVE_FILE_NAME).exists() {
|
||||||
|
|
||||||
if !module.join(defs::REMOVE_FILE_NAME).exists() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
info!("remove module: {}", module.display());
|
info!("remove module: {}", module.display());
|
||||||
|
|
||||||
let uninstaller = module.join("uninstall.sh");
|
let uninstaller = module.join("uninstall.sh");
|
||||||
@@ -275,48 +261,40 @@ pub fn prune_modules() -> Result<()> {
|
|||||||
if let Err(e) = remove_dir_all(module) {
|
if let Err(e) = remove_dir_all(module) {
|
||||||
warn!("Failed to remove {}: {}", module.display(), e);
|
warn!("Failed to remove {}: {}", module.display(), e);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
remove_file(module.join(defs::UPDATE_FILE_NAME)).ok();
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
// collect remaining modules, if none, remove img
|
Ok(())
|
||||||
let remaining_modules: Vec<_> = std::fs::read_dir(defs::MODULE_DIR)?
|
}
|
||||||
.filter_map(|entry| entry.ok())
|
|
||||||
.filter(|entry| entry.path().join("module.prop").exists())
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
if remaining_modules.is_empty() {
|
pub fn handle_updated_modules() -> Result<()> {
|
||||||
info!("no remaining modules, deleting image files.");
|
let modules_root = Path::new(MODULE_DIR);
|
||||||
std::fs::remove_file(defs::MODULE_IMG).ok();
|
foreach_module(ModuleType::Updated, |module| {
|
||||||
std::fs::remove_file(defs::MODULE_UPDATE_IMG).ok();
|
if !module.is_dir() {
|
||||||
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(name) = module.file_name() {
|
||||||
|
let old_dir = modules_root.join(name);
|
||||||
|
if old_dir.exists() {
|
||||||
|
if let Err(e) = remove_dir_all(&old_dir) {
|
||||||
|
log::error!("Failed to remove old {}: {}", old_dir.display(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Err(e) = rename(&module, &old_dir) {
|
||||||
|
log::error!("Failed to move new module {}: {}", module.display(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_module_image(image: &str, image_size: u64) -> Result<()> {
|
pub fn install_module(zip: &str) -> Result<()> {
|
||||||
File::create(image)
|
fn inner(zip: &str) -> Result<()> {
|
||||||
.context("Failed to create ext4 image file")?
|
|
||||||
.set_len(image_size)
|
|
||||||
.context("Failed to truncate ext4 image")?;
|
|
||||||
|
|
||||||
// format the img to ext4 filesystem
|
|
||||||
let result = Command::new("mkfs.ext4")
|
|
||||||
.arg("-O")
|
|
||||||
.arg("^has_journal")
|
|
||||||
.arg(image)
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.output()?;
|
|
||||||
ensure!(
|
|
||||||
result.status.success(),
|
|
||||||
"Failed to format ext4 image: {}",
|
|
||||||
String::from_utf8(result.stderr).unwrap()
|
|
||||||
);
|
|
||||||
check_image(image)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn _install_module(zip: &str) -> Result<()> {
|
|
||||||
ensure_boot_completed()?;
|
ensure_boot_completed()?;
|
||||||
|
|
||||||
// print banner
|
// print banner
|
||||||
@@ -324,11 +302,11 @@ fn _install_module(zip: &str) -> Result<()> {
|
|||||||
|
|
||||||
assets::ensure_binaries(false).with_context(|| "Failed to extract assets")?;
|
assets::ensure_binaries(false).with_context(|| "Failed to extract assets")?;
|
||||||
|
|
||||||
// first check if workding dir is usable
|
// first check if working dir is usable
|
||||||
ensure_dir_exists(defs::WORKING_DIR).with_context(|| "Failed to create working dir")?;
|
ensure_dir_exists(defs::WORKING_DIR).with_context(|| "Failed to create working dir")?;
|
||||||
ensure_dir_exists(defs::BINARY_DIR).with_context(|| "Failed to create bin dir")?;
|
ensure_dir_exists(defs::BINARY_DIR).with_context(|| "Failed to create bin dir")?;
|
||||||
|
|
||||||
// read the module_id from zip, if faild if will return early.
|
// read the module_id from zip, if failed it will return early.
|
||||||
let mut buffer: Vec<u8> = Vec::new();
|
let mut buffer: Vec<u8> = Vec::new();
|
||||||
let entry_path = PathBuf::from_str("module.prop")?;
|
let entry_path = PathBuf::from_str("module.prop")?;
|
||||||
let zip_path = PathBuf::from_str(zip)?;
|
let zip_path = PathBuf::from_str(zip)?;
|
||||||
@@ -348,20 +326,6 @@ fn _install_module(zip: &str) -> Result<()> {
|
|||||||
};
|
};
|
||||||
let module_id = module_id.trim();
|
let module_id = module_id.trim();
|
||||||
|
|
||||||
let modules_img = Path::new(defs::MODULE_IMG);
|
|
||||||
let modules_update_img = Path::new(defs::MODULE_UPDATE_IMG);
|
|
||||||
let module_update_tmp_dir = defs::MODULE_UPDATE_TMP_DIR;
|
|
||||||
|
|
||||||
let modules_img_exist = modules_img.exists();
|
|
||||||
let modules_update_img_exist = modules_update_img.exists();
|
|
||||||
|
|
||||||
// prepare the tmp module img
|
|
||||||
let tmp_module_img = defs::MODULE_UPDATE_TMP_IMG;
|
|
||||||
let tmp_module_path = Path::new(tmp_module_img);
|
|
||||||
if tmp_module_path.exists() {
|
|
||||||
std::fs::remove_file(tmp_module_path)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let zip_uncompressed_size = get_zip_uncompressed_size(zip)?;
|
let zip_uncompressed_size = get_zip_uncompressed_size(zip)?;
|
||||||
|
|
||||||
info!(
|
info!(
|
||||||
@@ -369,92 +333,28 @@ fn _install_module(zip: &str) -> Result<()> {
|
|||||||
humansize::format_size(zip_uncompressed_size, humansize::DECIMAL)
|
humansize::format_size(zip_uncompressed_size, humansize::DECIMAL)
|
||||||
);
|
);
|
||||||
|
|
||||||
println!("- Preparing image");
|
println!("- Preparing Zip");
|
||||||
println!(
|
println!(
|
||||||
"- Module size: {}",
|
"- Module size: {}",
|
||||||
humansize::format_size(zip_uncompressed_size, humansize::DECIMAL)
|
humansize::format_size(zip_uncompressed_size, humansize::DECIMAL)
|
||||||
);
|
);
|
||||||
|
|
||||||
let data_vfs = fs4::statvfs("/data").with_context(|| "Failed to stat /data".to_string())?;
|
|
||||||
let sparse_image_size = data_vfs.total_space();
|
|
||||||
if !modules_img_exist && !modules_update_img_exist {
|
|
||||||
// if no modules and modules_update, it is brand new installation, we should create a new img
|
|
||||||
// create a tmp module img and mount it to modules_update
|
|
||||||
info!("Creating brand new module image");
|
|
||||||
create_module_image(tmp_module_img, sparse_image_size)?;
|
|
||||||
} else if modules_update_img_exist {
|
|
||||||
// modules_update.img exists, we should use it as tmp img
|
|
||||||
info!("Using existing modules_update.img as tmp image");
|
|
||||||
utils::copy_sparse_file(modules_update_img, tmp_module_img, true).with_context(|| {
|
|
||||||
format!(
|
|
||||||
"Failed to copy {} to {}",
|
|
||||||
modules_update_img.display(),
|
|
||||||
tmp_module_img
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
} else {
|
|
||||||
// modules.img exists, we should use it as tmp img
|
|
||||||
info!("Using existing modules.img as tmp image");
|
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
let blksize = std::fs::metadata(defs::MODULE_DIR)?.blksize();
|
|
||||||
#[cfg(not(unix))]
|
|
||||||
let blksize = 0;
|
|
||||||
// legacy image, it's block size is 1024 with unlimited journal size
|
|
||||||
if blksize == 1024 {
|
|
||||||
println!("- Legacy image, migrating to new format, please be patient...");
|
|
||||||
create_module_image(tmp_module_img, sparse_image_size)?;
|
|
||||||
let _dontdrop =
|
|
||||||
mount::AutoMountExt4::try_new(tmp_module_img, module_update_tmp_dir, true)
|
|
||||||
.with_context(|| format!("Failed to mount {tmp_module_img}"))?;
|
|
||||||
utils::copy_module_files(defs::MODULE_DIR, module_update_tmp_dir)
|
|
||||||
.with_context(|| "Failed to migrate module files".to_string())?;
|
|
||||||
} else {
|
|
||||||
utils::copy_sparse_file(modules_img, tmp_module_img, true)
|
|
||||||
.with_context(|| "Failed to copy module image".to_string())?;
|
|
||||||
|
|
||||||
if std::fs::metadata(tmp_module_img)?.len() < sparse_image_size {
|
|
||||||
// truncate the file to new size
|
|
||||||
OpenOptions::new()
|
|
||||||
.write(true)
|
|
||||||
.open(tmp_module_img)
|
|
||||||
.context("Failed to open ext4 image")?
|
|
||||||
.set_len(sparse_image_size)
|
|
||||||
.context("Failed to truncate ext4 image")?;
|
|
||||||
|
|
||||||
// resize the image to new size
|
|
||||||
check_image(tmp_module_img)?;
|
|
||||||
Command::new("resize2fs")
|
|
||||||
.arg(tmp_module_img)
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.status()?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ensure modules_update exists
|
// ensure modules_update exists
|
||||||
ensure_dir_exists(module_update_tmp_dir)?;
|
ensure_dir_exists(MODULE_UPDATE_DIR)?;
|
||||||
|
setsyscon(MODULE_UPDATE_DIR)?;
|
||||||
|
|
||||||
// mount the modules_update.img to mountpoint
|
let update_module_dir = Path::new(MODULE_UPDATE_DIR).join(module_id);
|
||||||
println!("- Mounting image");
|
ensure_clean_dir(&update_module_dir)?;
|
||||||
|
info!("module dir: {}", update_module_dir.display());
|
||||||
let _dontdrop = mount::AutoMountExt4::try_new(tmp_module_img, module_update_tmp_dir, true)?;
|
|
||||||
|
|
||||||
info!("mounted {} to {}", tmp_module_img, module_update_tmp_dir);
|
|
||||||
|
|
||||||
setsyscon(module_update_tmp_dir)?;
|
|
||||||
|
|
||||||
let module_dir = format!("{module_update_tmp_dir}/{module_id}");
|
|
||||||
ensure_clean_dir(&module_dir)?;
|
|
||||||
info!("module dir: {}", module_dir);
|
|
||||||
|
|
||||||
|
let do_install = || -> Result<()> {
|
||||||
// unzip the image and move it to modules_update/<id> dir
|
// unzip the image and move it to modules_update/<id> dir
|
||||||
let file = File::open(zip)?;
|
let file = File::open(zip)?;
|
||||||
let mut archive = zip::ZipArchive::new(file)?;
|
let mut archive = zip::ZipArchive::new(file)?;
|
||||||
archive.extract(&module_dir)?;
|
archive.extract(&update_module_dir)?;
|
||||||
|
|
||||||
// set permission and selinux context for $MOD/system
|
// set permission and selinux context for $MOD/system
|
||||||
let module_system_dir = PathBuf::from(module_dir).join("system");
|
let module_system_dir = update_module_dir.join("system");
|
||||||
if module_system_dir.exists() {
|
if module_system_dir.exists() {
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
set_permissions(&module_system_dir, Permissions::from_mode(0o755))?;
|
set_permissions(&module_system_dir, Permissions::from_mode(0o755))?;
|
||||||
@@ -463,124 +363,33 @@ fn _install_module(zip: &str) -> Result<()> {
|
|||||||
|
|
||||||
exec_install_script(zip)?;
|
exec_install_script(zip)?;
|
||||||
|
|
||||||
info!("rename {tmp_module_img} to {}", defs::MODULE_UPDATE_IMG);
|
let module_dir = Path::new(MODULE_DIR).join(module_id);
|
||||||
// all done, rename the tmp image to modules_update.img
|
ensure_dir_exists(&module_dir)?;
|
||||||
if std::fs::rename(tmp_module_img, defs::MODULE_UPDATE_IMG).is_err() {
|
copy(
|
||||||
warn!("Rename image failed, try copy it.");
|
update_module_dir.join("module.prop"),
|
||||||
utils::copy_sparse_file(tmp_module_img, defs::MODULE_UPDATE_IMG, true)
|
module_dir.join("module.prop"),
|
||||||
.with_context(|| "Failed to copy image.".to_string())?;
|
)?;
|
||||||
let _ = std::fs::remove_file(tmp_module_img);
|
ensure_file_exists(module_dir.join(UPDATE_FILE_NAME))?;
|
||||||
}
|
|
||||||
|
|
||||||
mark_update()?;
|
|
||||||
|
|
||||||
info!("Module install successfully!");
|
info!("Module install successfully!");
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
};
|
||||||
|
let result = do_install();
|
||||||
pub fn install_module(zip: &str) -> Result<()> {
|
if result.is_err() {
|
||||||
let result = _install_module(zip);
|
remove_dir_all(&update_module_dir).ok();
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
let result = inner(zip);
|
||||||
if let Err(ref e) = result {
|
if let Err(ref e) = result {
|
||||||
// error happened, do some cleanup!
|
|
||||||
let _ = std::fs::remove_file(defs::MODULE_UPDATE_TMP_IMG);
|
|
||||||
let _ = mount::umount_dir(defs::MODULE_UPDATE_TMP_DIR);
|
|
||||||
println!("- Error: {e}");
|
println!("- Error: {e}");
|
||||||
}
|
}
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_module<F>(update_dir: &str, id: &str, func: F) -> Result<()>
|
|
||||||
where
|
|
||||||
F: Fn(&str, &str) -> Result<()>,
|
|
||||||
{
|
|
||||||
ensure_boot_completed()?;
|
|
||||||
|
|
||||||
let modules_img = Path::new(defs::MODULE_IMG);
|
|
||||||
let modules_update_img = Path::new(defs::MODULE_UPDATE_IMG);
|
|
||||||
let modules_update_tmp_img = Path::new(defs::MODULE_UPDATE_TMP_IMG);
|
|
||||||
if !modules_update_img.exists() && !modules_img.exists() {
|
|
||||||
bail!("Please install module first!");
|
|
||||||
} else if modules_update_img.exists() {
|
|
||||||
info!(
|
|
||||||
"copy {} to {}",
|
|
||||||
modules_update_img.display(),
|
|
||||||
modules_update_tmp_img.display()
|
|
||||||
);
|
|
||||||
utils::copy_sparse_file(modules_update_img, modules_update_tmp_img, true)?;
|
|
||||||
} else {
|
|
||||||
info!(
|
|
||||||
"copy {} to {}",
|
|
||||||
modules_img.display(),
|
|
||||||
modules_update_tmp_img.display()
|
|
||||||
);
|
|
||||||
utils::copy_sparse_file(modules_img, modules_update_tmp_img, true)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ensure modules_update dir exist
|
|
||||||
ensure_clean_dir(update_dir)?;
|
|
||||||
|
|
||||||
// mount the modules_update img
|
|
||||||
let _dontdrop = mount::AutoMountExt4::try_new(defs::MODULE_UPDATE_TMP_IMG, update_dir, true)?;
|
|
||||||
|
|
||||||
// call the operation func
|
|
||||||
let result = func(id, update_dir);
|
|
||||||
|
|
||||||
if let Err(e) = std::fs::rename(modules_update_tmp_img, defs::MODULE_UPDATE_IMG) {
|
|
||||||
warn!("Rename image failed: {e}, try copy it.");
|
|
||||||
utils::copy_sparse_file(modules_update_tmp_img, defs::MODULE_UPDATE_IMG, true)
|
|
||||||
.with_context(|| "Failed to copy image.".to_string())?;
|
|
||||||
let _ = std::fs::remove_file(modules_update_tmp_img);
|
|
||||||
}
|
|
||||||
|
|
||||||
mark_update()?;
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn uninstall_module(id: &str) -> Result<()> {
|
pub fn uninstall_module(id: &str) -> Result<()> {
|
||||||
update_module(defs::MODULE_UPDATE_TMP_DIR, id, |mid, update_dir| {
|
mark_module_state(id, defs::REMOVE_FILE_NAME, true)
|
||||||
let dir = Path::new(update_dir);
|
|
||||||
ensure!(dir.exists(), "No module installed");
|
|
||||||
|
|
||||||
// iterate the modules_update dir, find the module to be removed
|
|
||||||
let dir = std::fs::read_dir(dir)?;
|
|
||||||
for entry in dir.flatten() {
|
|
||||||
let path = entry.path();
|
|
||||||
let module_prop = path.join("module.prop");
|
|
||||||
if !module_prop.exists() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let content = std::fs::read(module_prop)?;
|
|
||||||
let mut module_id: String = String::new();
|
|
||||||
PropertiesIter::new_with_encoding(Cursor::new(content), encoding_rs::UTF_8).read_into(
|
|
||||||
|k, v| {
|
|
||||||
if k.eq("id") {
|
|
||||||
module_id = v;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)?;
|
|
||||||
if module_id.eq(mid) {
|
|
||||||
let remove_file = path.join(defs::REMOVE_FILE_NAME);
|
|
||||||
File::create(remove_file).with_context(|| "Failed to create remove file.")?;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// santity check
|
|
||||||
let target_module_path = format!("{update_dir}/{mid}");
|
|
||||||
let target_module = Path::new(&target_module_path);
|
|
||||||
if target_module.exists() {
|
|
||||||
let remove_file = target_module.join(defs::REMOVE_FILE_NAME);
|
|
||||||
if !remove_file.exists() {
|
|
||||||
File::create(remove_file).with_context(|| "Failed to create remove file.")?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = mark_module_state(id, defs::REMOVE_FILE_NAME, true);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run_action(id: &str) -> Result<()> {
|
pub fn run_action(id: &str) -> Result<()> {
|
||||||
@@ -588,37 +397,12 @@ pub fn run_action(id: &str) -> Result<()> {
|
|||||||
exec_script(&action_script_path, true)
|
exec_script(&action_script_path, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn _enable_module(module_dir: &str, mid: &str, enable: bool) -> Result<()> {
|
|
||||||
let src_module_path = format!("{module_dir}/{mid}");
|
|
||||||
let src_module = Path::new(&src_module_path);
|
|
||||||
ensure!(src_module.exists(), "module: {} not found!", mid);
|
|
||||||
|
|
||||||
let disable_path = src_module.join(defs::DISABLE_FILE_NAME);
|
|
||||||
if enable {
|
|
||||||
if disable_path.exists() {
|
|
||||||
std::fs::remove_file(&disable_path).with_context(|| {
|
|
||||||
format!("Failed to remove disable file: {}", &disable_path.display())
|
|
||||||
})?;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ensure_file_exists(disable_path)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = mark_module_state(mid, defs::DISABLE_FILE_NAME, !enable);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn enable_module(id: &str) -> Result<()> {
|
pub fn enable_module(id: &str) -> Result<()> {
|
||||||
update_module(defs::MODULE_UPDATE_TMP_DIR, id, |mid, update_dir| {
|
mark_module_state(id, defs::DISABLE_FILE_NAME, true)
|
||||||
_enable_module(update_dir, mid, true)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn disable_module(id: &str) -> Result<()> {
|
pub fn disable_module(id: &str) -> Result<()> {
|
||||||
update_module(defs::MODULE_UPDATE_TMP_DIR, id, |mid, update_dir| {
|
mark_module_state(id, defs::DISABLE_FILE_NAME, false)
|
||||||
_enable_module(update_dir, mid, false)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn disable_all_modules() -> Result<()> {
|
pub fn disable_all_modules() -> Result<()> {
|
||||||
@@ -630,8 +414,7 @@ pub fn uninstall_all_modules() -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn mark_all_modules(flag_file: &str) -> Result<()> {
|
fn mark_all_modules(flag_file: &str) -> Result<()> {
|
||||||
// we assume the module dir is already mounted
|
let dir = std::fs::read_dir(MODULE_DIR)?;
|
||||||
let dir = std::fs::read_dir(defs::MODULE_DIR)?;
|
|
||||||
for entry in dir.flatten() {
|
for entry in dir.flatten() {
|
||||||
let path = entry.path();
|
let path = entry.path();
|
||||||
let flag = path.join(flag_file);
|
let flag = path.join(flag_file);
|
||||||
@@ -712,21 +495,3 @@ pub fn list_modules() -> Result<()> {
|
|||||||
println!("{}", serde_json::to_string_pretty(&modules)?);
|
println!("{}", serde_json::to_string_pretty(&modules)?);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn shrink_image(img: &str) -> Result<()> {
|
|
||||||
check_image(img)?;
|
|
||||||
Command::new("resize2fs")
|
|
||||||
.arg("-M")
|
|
||||||
.arg(img)
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.status()?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn shrink_ksu_images() -> Result<()> {
|
|
||||||
shrink_image(defs::MODULE_IMG)?;
|
|
||||||
if Path::new(defs::MODULE_UPDATE_IMG).exists() {
|
|
||||||
shrink_image(defs::MODULE_UPDATE_IMG)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,306 +0,0 @@
|
|||||||
use anyhow::{Ok, Result, anyhow, bail};
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
use anyhow::Context;
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
use rustix::{fd::AsFd, fs::CWD, mount::*};
|
|
||||||
|
|
||||||
use crate::defs::KSU_OVERLAY_SOURCE;
|
|
||||||
use log::{info, warn};
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
use procfs::process::Process;
|
|
||||||
use std::path::Path;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
pub struct AutoMountExt4 {
|
|
||||||
target: String,
|
|
||||||
auto_umount: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AutoMountExt4 {
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
pub fn try_new(source: &str, target: &str, auto_umount: bool) -> Result<Self> {
|
|
||||||
mount_ext4(source, target)?;
|
|
||||||
Ok(Self {
|
|
||||||
target: target.to_string(),
|
|
||||||
auto_umount,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "android")))]
|
|
||||||
pub fn try_new(_src: &str, _mnt: &str, _auto_umount: bool) -> Result<Self> {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
pub fn umount(&self) -> Result<()> {
|
|
||||||
unmount(self.target.as_str(), UnmountFlags::DETACH)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
impl Drop for AutoMountExt4 {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
log::info!(
|
|
||||||
"AutoMountExt4 drop: {}, auto_umount: {}",
|
|
||||||
self.target,
|
|
||||||
self.auto_umount
|
|
||||||
);
|
|
||||||
if self.auto_umount {
|
|
||||||
let _ = self.umount();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
pub fn mount_ext4(source: impl AsRef<Path>, target: impl AsRef<Path>) -> Result<()> {
|
|
||||||
let new_loopback = loopdev::LoopControl::open()?
|
|
||||||
.next_free()
|
|
||||||
.with_context(|| "Failed to alloc loop")?;
|
|
||||||
new_loopback
|
|
||||||
.with()
|
|
||||||
.attach(source)
|
|
||||||
.with_context(|| "Failed to attach loop")?;
|
|
||||||
let lo = new_loopback.path().ok_or(anyhow!("no loop"))?;
|
|
||||||
let fs = fsopen("ext4", FsOpenFlags::FSOPEN_CLOEXEC)?;
|
|
||||||
let fs = fs.as_fd();
|
|
||||||
fsconfig_set_string(fs, "source", lo)?;
|
|
||||||
fsconfig_create(fs)?;
|
|
||||||
let mount = fsmount(fs, FsMountFlags::FSMOUNT_CLOEXEC, MountAttrFlags::empty())?;
|
|
||||||
move_mount(
|
|
||||||
mount.as_fd(),
|
|
||||||
"",
|
|
||||||
CWD,
|
|
||||||
target.as_ref(),
|
|
||||||
MoveMountFlags::MOVE_MOUNT_F_EMPTY_PATH,
|
|
||||||
)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
pub fn umount_dir(src: impl AsRef<Path>) -> Result<()> {
|
|
||||||
unmount(src.as_ref(), UnmountFlags::empty())
|
|
||||||
.with_context(|| format!("Failed to umount {}", src.as_ref().display()))?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
pub fn mount_overlayfs(
|
|
||||||
lower_dirs: &[String],
|
|
||||||
lowest: &str,
|
|
||||||
upperdir: Option<PathBuf>,
|
|
||||||
workdir: Option<PathBuf>,
|
|
||||||
dest: impl AsRef<Path>,
|
|
||||||
) -> Result<()> {
|
|
||||||
let lowerdir_config = lower_dirs
|
|
||||||
.iter()
|
|
||||||
.map(|s| s.as_ref())
|
|
||||||
.chain(std::iter::once(lowest))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(":");
|
|
||||||
info!(
|
|
||||||
"mount overlayfs on {:?}, lowerdir={}, upperdir={:?}, workdir={:?}",
|
|
||||||
dest.as_ref(),
|
|
||||||
lowerdir_config,
|
|
||||||
upperdir,
|
|
||||||
workdir
|
|
||||||
);
|
|
||||||
|
|
||||||
let upperdir = upperdir
|
|
||||||
.filter(|up| up.exists())
|
|
||||||
.map(|e| e.display().to_string());
|
|
||||||
let workdir = workdir
|
|
||||||
.filter(|wd| wd.exists())
|
|
||||||
.map(|e| e.display().to_string());
|
|
||||||
|
|
||||||
let result = (|| {
|
|
||||||
let fs = fsopen("overlay", FsOpenFlags::FSOPEN_CLOEXEC)?;
|
|
||||||
let fs = fs.as_fd();
|
|
||||||
fsconfig_set_string(fs, "lowerdir", &lowerdir_config)?;
|
|
||||||
if let (Some(upperdir), Some(workdir)) = (&upperdir, &workdir) {
|
|
||||||
fsconfig_set_string(fs, "upperdir", upperdir)?;
|
|
||||||
fsconfig_set_string(fs, "workdir", workdir)?;
|
|
||||||
}
|
|
||||||
fsconfig_set_string(fs, "source", KSU_OVERLAY_SOURCE)?;
|
|
||||||
fsconfig_create(fs)?;
|
|
||||||
let mount = fsmount(fs, FsMountFlags::FSMOUNT_CLOEXEC, MountAttrFlags::empty())?;
|
|
||||||
move_mount(
|
|
||||||
mount.as_fd(),
|
|
||||||
"",
|
|
||||||
CWD,
|
|
||||||
dest.as_ref(),
|
|
||||||
MoveMountFlags::MOVE_MOUNT_F_EMPTY_PATH,
|
|
||||||
)
|
|
||||||
})();
|
|
||||||
|
|
||||||
if let Err(e) = result {
|
|
||||||
warn!("fsopen mount failed: {:#}, fallback to mount", e);
|
|
||||||
let mut data = format!("lowerdir={lowerdir_config}");
|
|
||||||
if let (Some(upperdir), Some(workdir)) = (upperdir, workdir) {
|
|
||||||
data = format!("{data},upperdir={upperdir},workdir={workdir}");
|
|
||||||
}
|
|
||||||
mount(
|
|
||||||
KSU_OVERLAY_SOURCE,
|
|
||||||
dest.as_ref(),
|
|
||||||
"overlay",
|
|
||||||
MountFlags::empty(),
|
|
||||||
data,
|
|
||||||
)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
pub fn mount_tmpfs(dest: impl AsRef<Path>) -> Result<()> {
|
|
||||||
info!("mount tmpfs on {}", dest.as_ref().display());
|
|
||||||
let fs = fsopen("tmpfs", FsOpenFlags::FSOPEN_CLOEXEC)?;
|
|
||||||
let fs = fs.as_fd();
|
|
||||||
fsconfig_set_string(fs, "source", KSU_OVERLAY_SOURCE)?;
|
|
||||||
fsconfig_create(fs)?;
|
|
||||||
let mount = fsmount(fs, FsMountFlags::FSMOUNT_CLOEXEC, MountAttrFlags::empty())?;
|
|
||||||
move_mount(
|
|
||||||
mount.as_fd(),
|
|
||||||
"",
|
|
||||||
CWD,
|
|
||||||
dest.as_ref(),
|
|
||||||
MoveMountFlags::MOVE_MOUNT_F_EMPTY_PATH,
|
|
||||||
)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
pub fn bind_mount(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<()> {
|
|
||||||
info!(
|
|
||||||
"bind mount {} -> {}",
|
|
||||||
from.as_ref().display(),
|
|
||||||
to.as_ref().display()
|
|
||||||
);
|
|
||||||
let tree = open_tree(
|
|
||||||
CWD,
|
|
||||||
from.as_ref(),
|
|
||||||
OpenTreeFlags::OPEN_TREE_CLOEXEC
|
|
||||||
| OpenTreeFlags::OPEN_TREE_CLONE
|
|
||||||
| OpenTreeFlags::AT_RECURSIVE,
|
|
||||||
)?;
|
|
||||||
move_mount(
|
|
||||||
tree.as_fd(),
|
|
||||||
"",
|
|
||||||
CWD,
|
|
||||||
to.as_ref(),
|
|
||||||
MoveMountFlags::MOVE_MOUNT_F_EMPTY_PATH,
|
|
||||||
)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
fn mount_overlay_child(
|
|
||||||
mount_point: &str,
|
|
||||||
relative: &String,
|
|
||||||
module_roots: &Vec<String>,
|
|
||||||
stock_root: &String,
|
|
||||||
) -> Result<()> {
|
|
||||||
if !module_roots
|
|
||||||
.iter()
|
|
||||||
.any(|lower| Path::new(&format!("{lower}{relative}")).exists())
|
|
||||||
{
|
|
||||||
return bind_mount(stock_root, mount_point);
|
|
||||||
}
|
|
||||||
if !Path::new(&stock_root).is_dir() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let mut lower_dirs: Vec<String> = vec![];
|
|
||||||
for lower in module_roots {
|
|
||||||
let lower_dir = format!("{lower}{relative}");
|
|
||||||
let path = Path::new(&lower_dir);
|
|
||||||
if path.is_dir() {
|
|
||||||
lower_dirs.push(lower_dir);
|
|
||||||
} else if path.exists() {
|
|
||||||
// stock root has been blocked by this file
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if lower_dirs.is_empty() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
// merge modules and stock
|
|
||||||
if let Err(e) = mount_overlayfs(&lower_dirs, stock_root, None, None, mount_point) {
|
|
||||||
warn!("failed: {:#}, fallback to bind mount", e);
|
|
||||||
bind_mount(stock_root, mount_point)?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
pub fn mount_overlay(
|
|
||||||
root: &String,
|
|
||||||
module_roots: &Vec<String>,
|
|
||||||
workdir: Option<PathBuf>,
|
|
||||||
upperdir: Option<PathBuf>,
|
|
||||||
) -> Result<()> {
|
|
||||||
info!("mount overlay for {}", root);
|
|
||||||
std::env::set_current_dir(root).with_context(|| format!("failed to chdir to {root}"))?;
|
|
||||||
let stock_root = ".";
|
|
||||||
|
|
||||||
// collect child mounts before mounting the root
|
|
||||||
let mounts = Process::myself()?
|
|
||||||
.mountinfo()
|
|
||||||
.with_context(|| "get mountinfo")?;
|
|
||||||
let mut mount_seq = mounts
|
|
||||||
.0
|
|
||||||
.iter()
|
|
||||||
.filter(|m| {
|
|
||||||
m.mount_point.starts_with(root) && !Path::new(&root).starts_with(&m.mount_point)
|
|
||||||
})
|
|
||||||
.map(|m| m.mount_point.to_str())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
mount_seq.sort();
|
|
||||||
mount_seq.dedup();
|
|
||||||
|
|
||||||
mount_overlayfs(module_roots, root, upperdir, workdir, root)
|
|
||||||
.with_context(|| "mount overlayfs for root failed")?;
|
|
||||||
for mount_point in mount_seq.iter() {
|
|
||||||
let Some(mount_point) = mount_point else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let relative = mount_point.replacen(root, "", 1);
|
|
||||||
let stock_root: String = format!("{stock_root}{relative}");
|
|
||||||
if !Path::new(&stock_root).exists() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if let Err(e) = mount_overlay_child(mount_point, &relative, module_roots, &stock_root) {
|
|
||||||
warn!(
|
|
||||||
"failed to mount overlay for child {}: {:#}, revert",
|
|
||||||
mount_point, e
|
|
||||||
);
|
|
||||||
umount_dir(root).with_context(|| format!("failed to revert {root}"))?;
|
|
||||||
bail!(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "android")))]
|
|
||||||
pub fn mount_ext4(_src: &str, _target: &str, _autodrop: bool) -> Result<()> {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "android")))]
|
|
||||||
pub fn umount_dir(_src: &str) -> Result<()> {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "android")))]
|
|
||||||
pub fn mount_overlay(
|
|
||||||
_root: &String,
|
|
||||||
_module_roots: &Vec<String>,
|
|
||||||
_workdir: Option<PathBuf>,
|
|
||||||
_upperdir: Option<PathBuf>,
|
|
||||||
) -> Result<()> {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "android")))]
|
|
||||||
pub fn mount_tmpfs(_dest: impl AsRef<Path>) -> Result<()> {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
@@ -15,10 +15,6 @@ use std::fs::{Permissions, set_permissions};
|
|||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
use std::os::unix::prelude::PermissionsExt;
|
use std::os::unix::prelude::PermissionsExt;
|
||||||
|
|
||||||
use hole_punch::*;
|
|
||||||
use std::io::{Read, Seek, SeekFrom};
|
|
||||||
|
|
||||||
use jwalk::WalkDir;
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||||
@@ -39,7 +35,7 @@ pub fn ensure_clean_dir(dir: impl AsRef<Path>) -> Result<()> {
|
|||||||
|
|
||||||
pub fn ensure_file_exists<T: AsRef<Path>>(file: T) -> Result<()> {
|
pub fn ensure_file_exists<T: AsRef<Path>>(file: T) -> Result<()> {
|
||||||
match File::options().write(true).create_new(true).open(&file) {
|
match File::options().write(true).create_new(true).open(&file) {
|
||||||
std::result::Result::Ok(_) => Ok(()),
|
Result::Ok(_) => Ok(()),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if err.kind() == AlreadyExists && file.as_ref().is_file() {
|
if err.kind() == AlreadyExists && file.as_ref().is_file() {
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -218,9 +214,7 @@ pub fn uninstall(magiskboot_path: Option<PathBuf>) -> Result<()> {
|
|||||||
println!("- Removing directories..");
|
println!("- Removing directories..");
|
||||||
std::fs::remove_dir_all(defs::WORKING_DIR).ok();
|
std::fs::remove_dir_all(defs::WORKING_DIR).ok();
|
||||||
std::fs::remove_file(defs::DAEMON_PATH).ok();
|
std::fs::remove_file(defs::DAEMON_PATH).ok();
|
||||||
crate::mount::umount_dir(defs::MODULE_DIR).ok();
|
|
||||||
std::fs::remove_dir_all(defs::MODULE_DIR).ok();
|
std::fs::remove_dir_all(defs::MODULE_DIR).ok();
|
||||||
std::fs::remove_dir_all(defs::MODULE_UPDATE_TMP_DIR).ok();
|
|
||||||
println!("- Restore boot image..");
|
println!("- Restore boot image..");
|
||||||
boot_patch::restore(None, magiskboot_path, true)?;
|
boot_patch::restore(None, magiskboot_path, true)?;
|
||||||
println!("- Uninstall KernelSU manager..");
|
println!("- Uninstall KernelSU manager..");
|
||||||
@@ -232,153 +226,3 @@ pub fn uninstall(magiskboot_path: Option<PathBuf>) -> Result<()> {
|
|||||||
Command::new("reboot").spawn()?;
|
Command::new("reboot").spawn()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: use libxcp to improve the speed if cross's MSRV is 1.70
|
|
||||||
pub fn copy_sparse_file<P: AsRef<Path>, Q: AsRef<Path>>(
|
|
||||||
src: P,
|
|
||||||
dst: Q,
|
|
||||||
punch_hole: bool,
|
|
||||||
) -> Result<()> {
|
|
||||||
let mut src_file = File::open(src.as_ref())?;
|
|
||||||
let mut dst_file = OpenOptions::new()
|
|
||||||
.write(true)
|
|
||||||
.create(true)
|
|
||||||
.truncate(true)
|
|
||||||
.open(dst.as_ref())?;
|
|
||||||
|
|
||||||
dst_file.set_len(src_file.metadata()?.len())?;
|
|
||||||
|
|
||||||
let segments = src_file.scan_chunks()?;
|
|
||||||
for segment in segments {
|
|
||||||
if let SegmentType::Data = segment.segment_type {
|
|
||||||
let start = segment.start;
|
|
||||||
let end = segment.end + 1;
|
|
||||||
|
|
||||||
src_file.seek(SeekFrom::Start(start))?;
|
|
||||||
dst_file.seek(SeekFrom::Start(start))?;
|
|
||||||
|
|
||||||
let mut buffer = [0; 4096];
|
|
||||||
let mut total_bytes_copied = 0;
|
|
||||||
|
|
||||||
while total_bytes_copied < end - start {
|
|
||||||
let bytes_to_read =
|
|
||||||
std::cmp::min(buffer.len() as u64, end - start - total_bytes_copied);
|
|
||||||
let bytes_read = src_file.read(&mut buffer[..bytes_to_read as usize])?;
|
|
||||||
|
|
||||||
if bytes_read == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if punch_hole && buffer[..bytes_read].iter().all(|&x| x == 0) {
|
|
||||||
// all zero, don't copy it at all!
|
|
||||||
dst_file.seek(SeekFrom::Current(bytes_read as i64))?;
|
|
||||||
total_bytes_copied += bytes_read as u64;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
dst_file.write_all(&buffer[..bytes_read])?;
|
|
||||||
total_bytes_copied += bytes_read as u64;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
fn copy_xattrs(src_path: impl AsRef<Path>, dest_path: impl AsRef<Path>) -> Result<()> {
|
|
||||||
use rustix::path::Arg;
|
|
||||||
let std::result::Result::Ok(xattrs) = extattr::llistxattr(src_path.as_ref()) else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
for xattr in xattrs {
|
|
||||||
let std::result::Result::Ok(value) = extattr::lgetxattr(src_path.as_ref(), &xattr) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
log::info!(
|
|
||||||
"Set {:?} xattr {} = {}",
|
|
||||||
dest_path.as_ref(),
|
|
||||||
xattr.to_string_lossy(),
|
|
||||||
value.to_string_lossy(),
|
|
||||||
);
|
|
||||||
if let Err(e) =
|
|
||||||
extattr::lsetxattr(dest_path.as_ref(), &xattr, &value, extattr::Flags::empty())
|
|
||||||
{
|
|
||||||
log::warn!("Failed to set xattr: {}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
|
||||||
pub fn copy_module_files(source: impl AsRef<Path>, destination: impl AsRef<Path>) -> Result<()> {
|
|
||||||
use rustix::fs::FileTypeExt;
|
|
||||||
use rustix::fs::MetadataExt;
|
|
||||||
|
|
||||||
for entry in WalkDir::new(source.as_ref()).into_iter() {
|
|
||||||
let entry = entry.context("Failed to access entry")?;
|
|
||||||
let source_path = entry.path();
|
|
||||||
let relative_path = source_path
|
|
||||||
.strip_prefix(source.as_ref())
|
|
||||||
.context("Failed to generate relative path")?;
|
|
||||||
let dest_path = destination.as_ref().join(relative_path);
|
|
||||||
|
|
||||||
if let Some(parent) = dest_path.parent() {
|
|
||||||
std::fs::create_dir_all(parent).context("Failed to create directory")?;
|
|
||||||
}
|
|
||||||
|
|
||||||
if entry.file_type().is_file() {
|
|
||||||
std::fs::copy(&source_path, &dest_path).with_context(|| {
|
|
||||||
format!("Failed to copy file from {source_path:?} to {dest_path:?}",)
|
|
||||||
})?;
|
|
||||||
copy_xattrs(&source_path, &dest_path)?;
|
|
||||||
} else if entry.file_type().is_symlink() {
|
|
||||||
if dest_path.exists() {
|
|
||||||
std::fs::remove_file(&dest_path).context("Failed to remove file")?;
|
|
||||||
}
|
|
||||||
let target = std::fs::read_link(entry.path()).context("Failed to read symlink")?;
|
|
||||||
log::info!("Symlink: {:?} -> {:?}", dest_path, target);
|
|
||||||
std::os::unix::fs::symlink(target, &dest_path).context("Failed to create symlink")?;
|
|
||||||
copy_xattrs(&source_path, &dest_path)?;
|
|
||||||
} else if entry.file_type().is_dir() {
|
|
||||||
create_dir_all(&dest_path)?;
|
|
||||||
let metadata = std::fs::metadata(&source_path).context("Failed to read metadata")?;
|
|
||||||
std::fs::set_permissions(&dest_path, metadata.permissions())
|
|
||||||
.with_context(|| format!("Failed to set permissions for {dest_path:?}"))?;
|
|
||||||
copy_xattrs(&source_path, &dest_path)?;
|
|
||||||
} else if entry.file_type().is_char_device() {
|
|
||||||
if dest_path.exists() {
|
|
||||||
std::fs::remove_file(&dest_path).context("Failed to remove file")?;
|
|
||||||
}
|
|
||||||
let metadata = std::fs::metadata(&source_path).context("Failed to read metadata")?;
|
|
||||||
let mode = metadata.permissions().mode();
|
|
||||||
let dev = metadata.rdev();
|
|
||||||
if dev == 0 {
|
|
||||||
log::info!(
|
|
||||||
"Found a char device with major 0: {}",
|
|
||||||
entry.path().display()
|
|
||||||
);
|
|
||||||
rustix::fs::mknodat(
|
|
||||||
rustix::fs::CWD,
|
|
||||||
&dest_path,
|
|
||||||
rustix::fs::FileType::CharacterDevice,
|
|
||||||
mode.into(),
|
|
||||||
dev,
|
|
||||||
)
|
|
||||||
.with_context(|| format!("Failed to create device file at {dest_path:?}"))?;
|
|
||||||
copy_xattrs(&source_path, &dest_path)?;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log::info!(
|
|
||||||
"Unknown file type: {:?}, {:?},",
|
|
||||||
entry.file_type(),
|
|
||||||
entry.path(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "android")))]
|
|
||||||
pub fn copy_module_files(_source: impl AsRef<Path>, _destination: impl AsRef<Path>) -> Result<()> {
|
|
||||||
unimplemented!()
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user