Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exposed unsafe API scheme, replace libc crate with Nix #62

Merged
merged 2 commits into from
May 31, 2023
Merged
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
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ env_logger = "0.10.0"
chrono = "0.4.25"
anyhow = "1.0.71"
rust-embed = "6.6.0"
libc = "0.2.144"
nix = "0.26.2"
nix = { version = "0.26.2", features = ["mount", "signal", "user"]}
rand = "0.8.5"
ureq = "2.6.2"
sha3 = "0.10.8"
Expand Down
104 changes: 49 additions & 55 deletions src/daemon.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
extern crate libc;

use std::ops::Not;
use std::path::Path;
use std::path::PathBuf;
Expand Down Expand Up @@ -31,16 +29,14 @@ pub struct XunleiInstall {

impl From<(bool, Config)> for XunleiInstall {
fn from(value: (bool, Config)) -> Self {
let uid = unsafe { libc::getuid() };
let gid = unsafe { libc::getgid() };
Self {
description: "Thunder remote download service",
host: value.1.host,
port: value.1.port,
download_path: value.1.download_path,
config_path: value.1.config_path,
uid,
gid,
uid: nix::unistd::getuid().into(),
gid: nix::unistd::getgid().into(),
auth_user: value.1.auth_user,
auth_password: value.1.auth_password,
debug: value.0,
Expand Down Expand Up @@ -78,7 +74,8 @@ impl XunleiInstall {

fn install(&self) -> anyhow::Result<std::path::PathBuf> {
log::info!("[XunleiInstall] Installing in progress");

// /var/packages/pan-xunlei-com
let base_dir = Path::new(env::SYNOPKG_PKGBASE);
// /var/packages/pan-xunlei-com/target
let target_dir = PathBuf::from(env::SYNOPKG_PKGDEST);
// /var/packages/pan-xunlei-com/target/host
Expand All @@ -95,29 +92,26 @@ impl XunleiInstall {
log::info!("[XunleiInstall] Install to: {}", target_filepath.display());
}

util::set_permissions(env::SYNOPKG_PKGBASE, self.uid, self.gid).context(format!(
util::set_permissions(&base_dir, self.uid, self.gid).context(format!(
"Failed to set permission: {}, PUID:{}, GUID:{}",
env::SYNOPKG_PKGBASE,
base_dir.display(),
self.uid,
self.gid
))?;

util::set_permissions(target_dir.to_str().unwrap(), self.uid, self.gid).context(
format!(
"Failed to set permission: {}, PUID:{}, GUID:{}",
target_dir.display(),
self.uid,
self.gid
),
)?;
util::set_permissions(&target_dir, self.uid, self.gid).context(format!(
"Failed to set permission: {}, PUID:{}, GUID:{}",
target_dir.display(),
self.uid,
self.gid
))?;

// path: /var/packages/pan-xunlei-com/target/host/etc/synoinfo.conf
let syno_info_path =
PathBuf::from(format!("{}{}", host_dir.display(), env::SYNO_INFO_PATH));
let synoinfo_path = PathBuf::from(format!("{}{}", host_dir.display(), env::SYNO_INFO_PATH));
util::create_dir_all(
syno_info_path.parent().context(format!(
synoinfo_path.parent().context(format!(
"the path: {} parent not exists",
syno_info_path.display()
synoinfo_path.display()
))?,
0o755,
)?;
Expand All @@ -131,7 +125,7 @@ impl XunleiInstall {
.take(7)
.collect::<String>();
util::write_file(
&syno_info_path,
&synoinfo_path,
std::borrow::Cow::Borrowed(
format!("unique=\"synology_{}_720+\"", hex_string).as_bytes(),
),
Expand All @@ -157,38 +151,25 @@ impl XunleiInstall {
0o755,
)?;

// symlink
unsafe {
if Path::new(env::SYNO_INFO_PATH).exists().not() {
let source_sys_info_path =
std::ffi::CString::new(syno_info_path.display().to_string())?;
let target_sys_info_path = std::ffi::CString::new(env::SYNO_INFO_PATH)?;
if libc::symlink(source_sys_info_path.as_ptr(), target_sys_info_path.as_ptr()) != 0
{
anyhow::bail!(std::io::Error::last_os_error());
}
}
let target_synoinfo_path = Path::new(env::SYNO_INFO_PATH);
nix::unistd::symlinkat(&synoinfo_path, None, target_synoinfo_path).context(format!(
"falied symlink {} to {}",
synoinfo_path.display(),
target_synoinfo_path.display()
))?;

let link_syno_authenticate_path = Path::new(env::SYNO_AUTHENTICATE_PATH);
if link_syno_authenticate_path.exists().not() {
let source_syno_authenticate_path =
std::ffi::CString::new(syno_authenticate_path.display().to_string())?;
let target_syno_authenticate_path =
std::ffi::CString::new(env::SYNO_AUTHENTICATE_PATH)?;
let patent_ = link_syno_authenticate_path.parent().context(format!(
"directory path: {} not exists",
link_syno_authenticate_path.display()
))?;
util::create_dir_all(patent_, 0o755)?;
if libc::symlink(
source_syno_authenticate_path.as_ptr(),
target_syno_authenticate_path.as_ptr(),
) != 0
{
anyhow::bail!(std::io::Error::last_os_error());
}
}
}
let target_syno_authenticate_path = Path::new(env::SYNO_AUTHENTICATE_PATH);
let patent_ = target_syno_authenticate_path.parent().context(format!(
"directory path: {} not exists",
target_syno_authenticate_path.display()
))?;
util::create_dir_all(patent_, 0o755)?;
nix::unistd::symlinkat(&syno_authenticate_path, None, target_syno_authenticate_path)
.context(format!(
"falied symlink {} to {}",
syno_authenticate_path.display(),
target_syno_authenticate_path.display()
))?;

log::info!("[XunleiInstall] Installation completed");
Ok(std::env::current_exe()?)
Expand Down Expand Up @@ -222,8 +203,8 @@ impl XunleiInstall {
[Service]
Type=simple
ExecStart={} launcher -H {} -P {} --download-path {} --config-path {} {} {}
LimitNOFILE=1024
LimitNPROC=512
LimitNOFILE=2048
LimitNPROC=1024
User={}

[Install]
Expand Down Expand Up @@ -278,6 +259,19 @@ impl XunleiUninstall {
log::info!("[XunleiUninstall] Uninstall xunlei package");
}

fn remove_if_symlink(path: &Path) -> Result<(), std::io::Error> {
if let Ok(metadata) = std::fs::symlink_metadata(path) {
if metadata.file_type().is_symlink() {
std::fs::remove_file(path)?;
log::info!("[XunleiUninstall] Uninstall xunlei {}", path.display());
}
}
Ok(())
}

remove_if_symlink(Path::new(env::SYNO_INFO_PATH))?;
remove_if_symlink(Path::new(env::SYNO_AUTHENTICATE_PATH))?;

// Clear xunlei default config directory
if self.clear {
let path = Path::new(env::DEFAULT_CONFIG_PATH);
Expand Down
119 changes: 52 additions & 67 deletions src/launcher.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use nix::mount::MsFlags;
use nix::unistd::Pid;
use rouille::router;
use rouille::Request;
use rouille::Response;
Expand Down Expand Up @@ -164,48 +166,13 @@ impl Running for XunleiLauncher {
}
}

use libc::{mount, umount2, MNT_DETACH, MS_BIND};
use std::ffi::CString;
use std::os::raw::c_int;
use std::ptr;

struct XunleiBackendServer {
download_path: PathBuf,
mount_bind_download_path: PathBuf,
envs: HashMap<String, String>,
debug: bool,
}

impl XunleiBackendServer {
fn bind_mount(source: &Path, target: &Path) -> c_int {
if Self::umount(target) == 0 {
log::info!(
"[XunleiBackendServer] Unmount {} succeeded.",
target.display()
)
}
let source_cstr =
CString::new(format!("{}", source.display())).expect("source CString new error");
let target_cstr =
CString::new(format!("{}", target.display())).expect("target CString new error");
unsafe {
mount(
source_cstr.as_ptr(),
target_cstr.as_ptr(),
ptr::null(),
MS_BIND,
ptr::null(),
)
}
}

fn umount(target: &Path) -> c_int {
let target_cstr =
CString::new(format!("{}", target.display())).expect("target CString new error");
unsafe { umount2(target_cstr.as_ptr(), MNT_DETACH) }
}
}

impl Running for XunleiBackendServer {
fn run(self) -> anyhow::Result<()> {
let var_path = Path::new(env::SYNOPKG_VAR);
Expand All @@ -223,18 +190,28 @@ impl Running for XunleiBackendServer {
util::create_dir_all(&self.download_path, 0o755)?;
}

match Self::bind_mount(&self.download_path, &self.mount_bind_download_path) {
0 => log::info!(
"[XunleiBackendServer] Mount {} to {} succeeded",
self.download_path.display(),
self.mount_bind_download_path.display()
),
_ => anyhow::bail!(
"[XunleiBackendServer] Mount {} to {} failed",
self.download_path.display(),
self.mount_bind_download_path.display()
),
}
match nix::mount::mount(
Some(&self.download_path),
&self.mount_bind_download_path,
<Option<&'static [u8]>>::None,
MsFlags::MS_BIND,
<Option<&'static [u8]>>::None,
) {
Ok(_) => {
log::info!(
"[XunleiBackendServer] Mount {} to {} succeeded",
self.download_path.display(),
self.mount_bind_download_path.display()
)
}
Err(_) => {
anyhow::bail!(
"[XunleiBackendServer] Mount {} to {} failed",
self.download_path.display(),
self.mount_bind_download_path.display()
)
}
};

log::info!("[XunleiBackendServer] Start Xunlei Backend Server");
let mut cmd = std::process::Command::new(env::LAUNCHER_EXE);
Expand All @@ -251,7 +228,7 @@ impl Running for XunleiBackendServer {
.stdout(Stdio::null());
}
let backend_process = cmd.spawn()?;
let backend_pid = backend_process.id() as libc::pid_t;
let backend_pid = backend_process.id() as i32;
log::info!(
"[XunleiBackendServer] Xunlei Backend Server PID: {}",
backend_pid
Expand All @@ -268,17 +245,21 @@ impl Running for XunleiBackendServer {
signal_hook::consts::SIGINT
| signal_hook::consts::SIGHUP
| signal_hook::consts::SIGTERM => {
let state = unsafe { libc::kill(backend_pid, libc::SIGINT) };
if state < 0 {
log::warn!(
"[XunleiBackendServer] The backend kill error: {}, An attempt was made to send SIGTERM to continue terminating",
std::io::Error::last_os_error()
);
unsafe {
libc::kill(backend_pid, libc::SIGTERM);
match nix::sys::signal::kill(
Pid::from_raw(backend_pid),
nix::sys::signal::SIGINT,
) {
Ok(_) => {
log::info!(
"[XunleiBackendServer] The backend service has been terminated"
)
}
Err(_) => {
nix::sys::signal::kill(Pid::from_raw(backend_pid),
nix::sys::signal::SIGTERM).expect(&format!("[XunleiBackendServer] The backend kill error: {}, An attempt was made to send SIGTERM to continue terminating",
std::io::Error::last_os_error()));
}
}
log::info!("[XunleiBackendServer] The backend service has been terminated");
break;
}
_ => {
Expand All @@ -288,16 +269,20 @@ impl Running for XunleiBackendServer {
}

// umount bind directory
match Self::umount(&self.mount_bind_download_path) {
0 => log::info!(
"[XunleiBackendServer] Unmount {} succeeded",
self.mount_bind_download_path.display()
),
_ => log::error!(
"[XunleiBackendServer] Unmount {} failed",
self.mount_bind_download_path.display()
),
}
match nix::mount::umount(&self.mount_bind_download_path) {
Ok(_) => {
log::info!(
"[XunleiBackendServer] Unmount {} succeeded",
self.mount_bind_download_path.display()
)
}
Err(_) => {
log::error!(
"[XunleiBackendServer] Unmount {} failed",
self.mount_bind_download_path.display()
)
}
};

Ok(())
}
Expand Down
9 changes: 2 additions & 7 deletions src/libc_asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,8 @@ pub(crate) fn ld_env(envs: &mut std::collections::HashMap<String, String>) -> an
return Ok(());
}
let syno_ld_path = Path::new(env::SYNOPKG_LIB).join(LD);
unsafe {
let source_path = CString::new(syno_ld_path.display().to_string())?;
let target_path = CString::new(sys_ld_path.display().to_string())?;
if libc::symlink(source_path.as_ptr(), target_path.as_ptr()) != 0 {
anyhow::bail!(std::io::Error::last_os_error());
}
}
nix::unistd::symlinkat(syno_ld_path, None, &sys_ld_path)?;

envs.insert(
String::from("LD_LIBRARY_PATH"),
env::SYNOPKG_LIB.to_string(),
Expand Down
Loading