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

feat: Support background daemon process #4

Merged
merged 3 commits into from
Dec 28, 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
14 changes: 12 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ repository = "https://github.com/gngpp/vproxy"

[dependencies]
cidr = "0.2.2"
getopts = "0.2.21"
hyper = { version = "1.1.0", features = ["http1", "server"] }
hyper-util = { version = "0.1.2", features = ["full"] }
http-body-util = "0.1"
Expand All @@ -21,20 +20,31 @@ rand = "0.8.5"
bytes = "1.5.0"
pin-project-lite = "0.2.13"
http = "1.0.0"
clap = { version = "4.4.3", features = ["derive", "env"] }
tracing = "0.1.40"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

# allocator
tcmalloc = { version = "0.3.0", optional = true }
snmalloc-rs = { version = "0.3.4", optional = true }
rpmalloc = { version = "0.2.2", optional = true }
jemallocator = { package = "tikv-jemallocator", version = "0.5.4", optional = true }
mimalloc = { version = "0.1.39", default-features = false, optional = true }
thiserror = "1.0.52"

[target.'cfg(target_os = "linux")'.dependencies]
sysctl = "0.5.5"
nix = { version = "0.27.1", features = ["user"] }

[target.'cfg(target_family = "unix")'.dependencies]
daemonize = "0.5.0"
nix = { version = "0.27.1", features = ["user", "signal"]}

[features]
default = []
http = []
https = []
socks5 = []
# Enable jemalloc for binaries
jemalloc = ["jemallocator"]
# Enable bundled tcmalloc
Expand All @@ -51,4 +61,4 @@ lto = true
opt-level = 'z'
codegen-units = 1
strip = true
panic = "abort"
panic = "abort"
153 changes: 153 additions & 0 deletions src/daemon.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
use std::{
fs::{File, Permissions},
os::unix::fs::PermissionsExt,
path::Path,
};

use daemonize::Daemonize;

use crate::{proxy, BootArgs};

#[cfg(target_family = "unix")]
pub(crate) const PID_PATH: &str = "/var/run/vproxy.pid";
#[cfg(target_family = "unix")]
pub(crate) const DEFAULT_STDOUT_PATH: &str = "/var/run/vproxy.out";
#[cfg(target_family = "unix")]
pub(crate) const DEFAULT_STDERR_PATH: &str = "/var/run/vproxy.err";

/// Get the pid of the daemon
#[cfg(target_family = "unix")]
pub(crate) fn get_pid() -> Option<String> {
if let Ok(data) = std::fs::read(PID_PATH) {
let binding = String::from_utf8(data).expect("pid file is not utf8");
return Some(binding.trim().to_string());
}
None
}

/// Check if the current user is root
#[cfg(target_family = "unix")]
pub fn check_root() {
if !nix::unistd::Uid::effective().is_root() {
println!("You must run this executable with root permissions");
std::process::exit(-1)
}
}

/// Start the daemon
#[cfg(target_family = "unix")]
pub fn start(args: BootArgs) -> crate::Result<()> {
if let Some(pid) = get_pid() {
println!("vproxy is already running with pid: {}", pid);
return Ok(());
}

check_root();

let pid_file = File::create(PID_PATH)?;
pid_file.set_permissions(Permissions::from_mode(0o755))?;

let stdout = File::create(DEFAULT_STDOUT_PATH)?;
stdout.set_permissions(Permissions::from_mode(0o755))?;

let stderr = File::create(DEFAULT_STDERR_PATH)?;
stdout.set_permissions(Permissions::from_mode(0o755))?;

let mut daemonize = Daemonize::new()
.pid_file(PID_PATH) // Every method except `new` and `start`
.chown_pid_file(true) // is optional, see `Daemonize` documentation
.umask(0o777) // Set umask, `0o027` by default.
.stdout(stdout) // Redirect stdout to `/tmp/daemon.out`.
.stderr(stderr) // Redirect stderr to `/tmp/daemon.err`.
.privileged_action(|| "Executed before drop privileges");

if let Ok(user) = std::env::var("SUDO_USER") {
if let Ok(Some(real_user)) = nix::unistd::User::from_name(&user) {
daemonize = daemonize
.user(real_user.name.as_str())
.group(real_user.gid.as_raw());
}
}

if let Some(err) = daemonize.start().err() {
eprintln!("Error: {err}");
std::process::exit(-1)
}

proxy::run(args)
}

/// Stop the daemon
#[cfg(target_family = "unix")]
pub fn stop() -> crate::Result<()> {
use nix::sys::signal;
use nix::unistd::Pid;

check_root();

if let Some(pid) = get_pid() {
let pid = pid.parse::<i32>()?;
for _ in 0..360 {
if signal::kill(Pid::from_raw(pid), signal::SIGINT).is_err() {
break;
}
std::thread::sleep(std::time::Duration::from_secs(1))
}
let _ = std::fs::remove_file(PID_PATH);
}

Ok(())
}

/// Show the status of the daemon
#[cfg(target_family = "unix")]
pub fn status() {
match get_pid() {
Some(pid) => println!("vproxy is running with pid: {}", pid),
None => println!("vproxy is not running"),
}
}

/// Show the log of the daemon
#[cfg(target_family = "unix")]
pub fn log() -> crate::Result<()> {
fn read_and_print_file(file_path: &Path, placeholder: &str) -> crate::Result<()> {
if !file_path.exists() {
return Ok(());
}

// Check if the file is empty before opening it
let metadata = std::fs::metadata(file_path)?;
if metadata.len() == 0 {
return Ok(());
}

let file = File::open(file_path)?;
let reader = std::io::BufReader::new(file);
let mut start = true;

use std::io::BufRead;

for line in reader.lines() {
if let Ok(content) = line {
if start {
start = false;
println!("{placeholder}");
}
println!("{}", content);
} else if let Err(err) = line {
eprintln!("Error reading line: {}", err);
}
}

Ok(())
}

let stdout_path = Path::new(DEFAULT_STDOUT_PATH);
read_and_print_file(stdout_path, "STDOUT>")?;

let stderr_path = Path::new(DEFAULT_STDERR_PATH);
read_and_print_file(stderr_path, "STDERR>")?;

Ok(())
}
13 changes: 13 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use thiserror::Error;

#[derive(Error, Debug)]
pub enum Error {
#[error("IO error")]
IOError(#[from] std::io::Error),
#[error("Parse int error")]
ParseIntError(#[from] std::num::ParseIntError),
#[error("Network parse error")]
NetworkParseError(#[from] cidr::errors::NetworkParseError),
#[error("Address parse error")]
AddressParseError(#[from] std::net::AddrParseError),
}
Loading