summaryrefslogtreecommitdiffhomepage
path: root/src/platform
diff options
context:
space:
mode:
Diffstat (limited to 'src/platform')
-rw-r--r--src/platform/linux.rs36
-rw-r--r--src/platform/windows.rs46
2 files changed, 81 insertions, 1 deletions
diff --git a/src/platform/linux.rs b/src/platform/linux.rs
index 32fd819..e6cf577 100644
--- a/src/platform/linux.rs
+++ b/src/platform/linux.rs
@@ -220,3 +220,39 @@ pub fn run() -> Result<()> {
Ok(())
}
+
+const PKG_NAME: &str = env!("CARGO_PKG_NAME");
+const DAEMON_PREFIX: &str = "/tmp";
+
+fn daemonize() -> Result<()> {
+ use std::fs;
+ use daemonize::Daemonize;
+
+ let log_file = fs::File::create(format!("{DAEMON_PREFIX}/{PKG_NAME}.log"))?;
+ let pid_file = format!("{DAEMON_PREFIX}/{PKG_NAME}.pid");
+
+ let daemonize = Daemonize::new()
+ .pid_file(&pid_file)
+ .chown_pid_file(true)
+ .working_directory(DAEMON_PREFIX)
+ .stdout(log_file);
+
+ daemonize.start()?;
+
+ // TODO: detach damonize and opt.rs and use log_println here
+ println!("start as daemon: pid {}", std::process::id());
+
+ Ok(())
+}
+
+pub fn daemonize_1() {
+ const EXIT_DAEMON_FAIL: i32 = 2;
+
+ match daemonize() {
+ Ok(_) => {},
+ Err(e) => {
+ println!("{PKG_NAME}: fail to start as daemon: {e}");
+ std::process::exit(EXIT_DAEMON_FAIL);
+ }
+ }
+}
diff --git a/src/platform/windows.rs b/src/platform/windows.rs
index 37a6654..9ad2474 100644
--- a/src/platform/windows.rs
+++ b/src/platform/windows.rs
@@ -22,6 +22,7 @@ use windivert::{
};
use std::sync::{atomic::Ordering, LazyLock, Mutex, MutexGuard};
use crate::{log::LogLevel, log_println, splash};
+use crate::opt;
fn windivert_filter() -> String {
let base = "(outbound and tcp and tcp.DstPort == 443 \
@@ -93,8 +94,10 @@ pub fn send_to_raw(pkt: &[u8]) -> Result<()> {
Ok(())
}
+use crate::RUNNING;
+
pub fn run() -> Result<()> {
- use crate::{handle_packet, RUNNING, MESSAGE_AT_RUN};
+ use crate::{handle_packet, MESSAGE_AT_RUN};
use super::PACKET_SIZE_CAP;
let mut windivert_buf = vec![0u8; 65536];
@@ -115,3 +118,44 @@ pub fn run() -> Result<()> {
Ok(())
}
+
+fn service_main() -> Result<()> {
+ let opt = opt::Opt::from_args()?;
+ opt.set_opt()?;
+ bootstrap()?;
+ run()?;
+ cleanup()?;
+
+ Ok(())
+}
+
+fn service_main_1() {
+ if service_main().is_err() {
+ std::process::exit(1);
+ }
+ std::process::exit(0);
+}
+
+pub fn daemonize_1() {
+ use windows_services::Command;
+
+ match windows_services::Service::new()
+ .can_stop()
+ .run(|_, command| {
+ match command {
+ Command::Start => {
+ std::thread::spawn(|| service_main_1());
+ }
+ Command::Stop => {
+ RUNNING.store(false, Ordering::SeqCst);
+ }
+ _ => {}
+ }
+ }) {
+ Ok(_) => {}
+ Err(e) => {
+ println!("{e}");
+ std::process::exit(1);
+ }
+ };
+}