Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions userspace/ksud/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,14 @@ loopdev = { git = "https://github.com/Kernel-SU/loopdev" }
[target.'cfg(target_os = "android")'.dependencies]
android_logger = { version = "0.15", default-features = false }

[profile.release]
[profile.dev]
overflow-checks = false
opt-level = 3
strip = true
opt-level = "z"
lto = true

[profile.release]
overflow-checks = false
codegen-units = 1
lto = "fat"
opt-level = 3
strip = true
3 changes: 2 additions & 1 deletion userspace/ksud/src/apk_sign.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use anyhow::{Result, ensure};
use std::io::{Read, Seek, SeekFrom};

use anyhow::{Result, ensure};

pub fn get_apk_signature(apk: &str) -> Result<(u32, String)> {
let mut buffer = [0u8; 0x10];
let mut size4 = [0u8; 4];
Expand Down
3 changes: 2 additions & 1 deletion userspace/ksud/src/assets.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::path::Path;

use anyhow::Result;
use const_format::concatcp;
use rust_embed::RustEmbed;
use std::path::Path;

use crate::{defs::BINARY_DIR, utils};

Expand Down
43 changes: 19 additions & 24 deletions userspace/ksud/src/boot_patch.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,19 @@
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::process::Stdio;

use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use anyhow::ensure;
use std::{
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
process::{Command, Stdio},
};

use anyhow::{Context, Result, anyhow, bail, ensure};
use regex_lite::Regex;
use which::which;

use crate::defs;
use crate::defs::BACKUP_FILENAME;
use crate::defs::{KSU_BACKUP_DIR, KSU_BACKUP_FILE_PREFIX};
use crate::{assets, utils};
use crate::{
assets,
defs::{self, BACKUP_FILENAME, KSU_BACKUP_DIR, KSU_BACKUP_FILE_PREFIX},
utils,
};

#[cfg(target_os = "android")]
fn ensure_gki_kernel() -> Result<()> {
Expand Down Expand Up @@ -118,11 +115,11 @@ fn parse_kmi_from_kernel(kernel: &PathBuf, workdir: &Path) -> Result<String> {
let re =
Regex::new(r"(?:.* )?(\d+\.\d+)(?:\S+)?(android\d+)").context("Failed to compile regex")?;
for s in printable_strings {
if let Some(caps) = re.captures(s) {
if let (Some(kernel_version), Some(android_version)) = (caps.get(1), caps.get(2)) {
let kmi = format!("{}-{}", android_version.as_str(), kernel_version.as_str());
return Ok(kmi);
}
if let Some(caps) = re.captures(s)
&& let (Some(kernel_version), Some(android_version)) = (caps.get(1), caps.get(2))
{
let kmi = format!("{}-{}", android_version.as_str(), kernel_version.as_str());
return Ok(kmi);
}
}
println!("- Failed to get KMI version");
Expand Down Expand Up @@ -502,10 +499,8 @@ fn do_patch(
)?;

#[cfg(target_os = "android")]
if need_backup {
if let Err(e) = do_backup(&magiskboot, workdir, ramdisk, bootimage) {
println!("- Backup stock image failed: {e}");
}
if need_backup && let Err(e) = do_backup(&magiskboot, workdir, ramdisk, bootimage) {
println!("- Backup stock image failed: {e}");
}

println!("- Repacking boot image");
Expand Down
4 changes: 2 additions & 2 deletions userspace/ksud/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use anyhow::{Ok, Result};
use clap::Parser;
use std::path::PathBuf;

#[cfg(target_os = "android")]
use android_logger::Config;
use anyhow::{Ok, Result};
use clap::Parser;
#[cfg(target_os = "android")]
use log::LevelFilter;

Expand Down
3 changes: 2 additions & 1 deletion userspace/ksud/src/debug.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use anyhow::{Context, Ok, Result, ensure};
use std::{
path::{Path, PathBuf},
process::Command,
};

use anyhow::{Context, Ok, Result, ensure};

const KERNEL_PARAM_PATH: &str = "/sys/module/kernelsu";

fn read_u32(path: &PathBuf) -> Result<u32> {
Expand Down
16 changes: 9 additions & 7 deletions userspace/ksud/src/init_event.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use std::{collections::HashMap, path::Path};

use anyhow::{Context, Result, bail};
use log::{info, warn};
use std::{collections::HashMap, path::Path};

use crate::module::prune_modules;
use crate::{
assets, defs, ksucalls, mount, restorecon,
assets, defs, ksucalls,
module::prune_modules,
mount, restorecon,
utils::{self, ensure_clean_dir},
};

Expand Down Expand Up @@ -73,10 +75,10 @@ pub fn mount_modules_systemlessly(module_dir: &str) -> Result<()> {
// 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()));
}
if part_path.is_dir()
&& let Some(v) = partition_lowerdir.get_mut(*part)
{
v.push(format!("{}", part_path.display()));
}
}
}
Expand Down
8 changes: 4 additions & 4 deletions userspace/ksud/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,10 +266,10 @@ pub fn prune_modules() -> Result<()> {
info!("remove module: {}", module.display());

let uninstaller = module.join("uninstall.sh");
if uninstaller.exists() {
if let Err(e) = exec_script(uninstaller, true) {
warn!("Failed to exec uninstaller: {e}");
}
if uninstaller.exists()
&& let Err(e) = exec_script(uninstaller, true)
{
warn!("Failed to exec uninstaller: {e}");
}

if let Err(e) = remove_dir_all(module) {
Expand Down
11 changes: 5 additions & 6 deletions userspace/ksud/src/mount.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
use anyhow::{Ok, Result, anyhow, bail};
use std::path::{Path, PathBuf};

#[cfg(any(target_os = "linux", target_os = "android"))]
use anyhow::Context;
use anyhow::{Ok, Result, anyhow, bail};
use log::{info, warn};
#[cfg(any(target_os = "linux", target_os = "android"))]
use procfs::process::Process;
#[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,
Expand Down
18 changes: 9 additions & 9 deletions userspace/ksud/src/restorecon.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use crate::defs;
use anyhow::Result;
use jwalk::{Parallelism::Serial, WalkDir};
use std::path::Path;

use anyhow::Result;
#[cfg(any(target_os = "linux", target_os = "android"))]
use anyhow::{Context, Ok};
#[cfg(any(target_os = "linux", target_os = "android"))]
use extattr::{Flags as XattrFlags, lsetxattr};
use jwalk::{Parallelism::Serial, WalkDir};

use crate::defs;

pub const SYSTEM_CON: &str = "u:object_r:system_file:s0";
pub const ADB_CON: &str = "u:object_r:adb_data_file:s0";
Expand Down Expand Up @@ -63,12 +64,11 @@ pub fn restore_syscon<P: AsRef<Path>>(dir: P) -> Result<()> {

fn restore_syscon_if_unlabeled<P: AsRef<Path>>(dir: P) -> Result<()> {
for dir_entry in WalkDir::new(dir).parallelism(Serial) {
if let Some(path) = dir_entry.ok().map(|dir_entry| dir_entry.path()) {
if let anyhow::Result::Ok(con) = lgetfilecon(&path) {
if con == UNLABEL_CON || con.is_empty() {
lsetfilecon(&path, SYSTEM_CON)?;
}
}
if let Some(path) = dir_entry.ok().map(|dir_entry| dir_entry.path())
&& let anyhow::Result::Ok(con) = lgetfilecon(&path)
&& (con == UNLABEL_CON || con.is_empty())
{
lsetfilecon(&path, SYSTEM_CON)?;
}
}
Ok(())
Expand Down
13 changes: 7 additions & 6 deletions userspace/ksud/src/sepolicy.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::{ffi, path::Path, vec};

use anyhow::{Result, bail};
use derive_new::new;
use nom::{
Expand All @@ -7,7 +9,6 @@ use nom::{
character::complete::{space0, space1},
combinator::map,
};
use std::{ffi, path::Path, vec};

type SeObject<'a> = Vec<&'a str>;

Expand All @@ -19,7 +20,7 @@ fn parse_single_word(input: &str) -> IResult<&str, &str> {
take_while1(is_sepolicy_char).parse(input)
}

fn parse_bracket_objs(input: &str) -> IResult<&str, SeObject> {
fn parse_bracket_objs(input: &str) -> IResult<&str, SeObject<'_>> {
let (input, (_, words, _)) = (
tag("{"),
take_while_m_n(1, 100, |c: char| is_sepolicy_char(c) || c.is_whitespace()),
Expand All @@ -29,25 +30,25 @@ fn parse_bracket_objs(input: &str) -> IResult<&str, SeObject> {
Ok((input, words.split_whitespace().collect()))
}

fn parse_single_obj(input: &str) -> IResult<&str, SeObject> {
fn parse_single_obj(input: &str) -> IResult<&str, SeObject<'_>> {
let (input, word) = take_while1(is_sepolicy_char).parse(input)?;
Ok((input, vec![word]))
}

fn parse_star(input: &str) -> IResult<&str, SeObject> {
fn parse_star(input: &str) -> IResult<&str, SeObject<'_>> {
let (input, _) = tag("*").parse(input)?;
Ok((input, vec!["*"]))
}

// 1. a single sepolicy word
// 2. { obj1 obj2 obj3 ...}
// 3. *
fn parse_seobj(input: &str) -> IResult<&str, SeObject> {
fn parse_seobj(input: &str) -> IResult<&str, SeObject<'_>> {
let (input, strs) = alt((parse_single_obj, parse_bracket_objs, parse_star)).parse(input)?;
Ok((input, strs))
}

fn parse_seobj_no_star(input: &str) -> IResult<&str, SeObject> {
fn parse_seobj_no_star(input: &str) -> IResult<&str, SeObject<'_>> {
let (input, strs) = alt((parse_single_obj, parse_bracket_objs)).parse(input)?;
Ok((input, strs))
}
Expand Down
18 changes: 8 additions & 10 deletions userspace/ksud/src/su.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
use anyhow::{Ok, Result};
use getopts::Options;
use std::env;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::{ffi::CStr, process::Command};

use crate::{
defs,
utils::{self, umask},
};
use std::{env, ffi::CStr, path::PathBuf, process::Command};

use anyhow::{Ok, Result};
use getopts::Options;
#[cfg(any(target_os = "linux", target_os = "android"))]
use rustix::{
process::getuid,
thread::{Gid, Uid, set_thread_res_gid, set_thread_res_uid},
};

use crate::{
defs,
utils::{self, umask},
};

#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn grant_root(global_mnt: bool) -> Result<()> {
rustix::process::ksu_grant_root()?;
Expand Down
28 changes: 11 additions & 17 deletions userspace/ksud/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,20 @@
use anyhow::{Context, Error, Ok, Result, bail};
use std::{
fs::{File, OpenOptions, create_dir_all, remove_file, write},
fs::{File, OpenOptions, Permissions, create_dir_all, remove_file, set_permissions, write},
io::{
ErrorKind::{AlreadyExists, NotFound},
Write,
Read, Seek, SeekFrom, Write,
},
path::Path,
path::{Path, PathBuf},
process::Command,
};

use crate::{assets, boot_patch, defs, ksucalls, module, restorecon};
#[allow(unused_imports)]
use std::fs::{Permissions, set_permissions};
#[cfg(unix)]
use std::os::unix::prelude::PermissionsExt;

use hole_punch::*;
use std::io::{Read, Seek, SeekFrom};
use crate::{assets, boot_patch, defs, ksucalls, module, restorecon};

use anyhow::{Context, Error, Ok, Result, bail};
use hole_punch::*;
use jwalk::WalkDir;
use std::path::PathBuf;

#[cfg(any(target_os = "linux", target_os = "android"))]
use rustix::{
process,
Expand Down Expand Up @@ -78,11 +72,11 @@ pub fn ensure_binary<T: AsRef<Path>>(
)
})?)?;

if let Err(e) = remove_file(path.as_ref()) {
if e.kind() != NotFound {
return Err(Error::from(e))
.with_context(|| format!("failed to unlink {}", path.as_ref().display()));
}
if let Err(e) = remove_file(path.as_ref())
&& e.kind() != NotFound
{
return Err(Error::from(e))
.with_context(|| format!("failed to unlink {}", path.as_ref().display()));
}

write(&path, contents)?;
Expand Down
Loading