2780 lines
91 KiB
Rust
2780 lines
91 KiB
Rust
//! LD FDPI — Tauri v2 backend.
|
||
//!
|
||
//! "Set & forget" design:
|
||
//! * `%LOCALAPPDATA%\LD-FDPI\config.json` is read before the webview loads.
|
||
//! * With `auto_connect` on, the engine + system proxy start during `setup`,
|
||
//! without waiting for React.
|
||
//! * A 15-second supervisor restarts the engine silently after a crash or wake.
|
||
//! * Autostart is a Task Scheduler entry with `RunLevel = HighestAvailable`, so the
|
||
//! elevated executable starts at logon without a UAC prompt.
|
||
|
||
pub mod auto_bypass;
|
||
pub mod autostart;
|
||
pub mod captive;
|
||
pub mod config;
|
||
pub mod eduroam;
|
||
pub mod engine;
|
||
pub mod identity;
|
||
pub mod pac_server;
|
||
pub mod proxy_sentinel;
|
||
pub mod supervisor;
|
||
pub mod vpn;
|
||
pub mod updater;
|
||
#[cfg(target_os = "windows")]
|
||
pub mod wfp_killswitch;
|
||
pub mod winhttp;
|
||
|
||
use config::AppConfig;
|
||
use engine::{EngineConfig, ProbeSummary};
|
||
use pac_server::PacHandle;
|
||
use proxy_sentinel::{RestoreReport, SystemProxyState};
|
||
use serde::Serialize;
|
||
use std::io::Write;
|
||
use std::path::PathBuf;
|
||
use std::process::Child;
|
||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||
use std::sync::{Arc, Mutex, MutexGuard};
|
||
use std::time::{Duration, Instant};
|
||
use sysinfo::{Pid, System};
|
||
use tauri::{
|
||
menu::{Menu, MenuItem},
|
||
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
|
||
AppHandle, Manager, RunEvent, State, WindowEvent,
|
||
};
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Crash-safe state
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/// PID of the currently running sidecar. The panic hook kills it without taking
|
||
/// any mutex (a panicking thread may still hold the state lock).
|
||
static CHILD_PID: AtomicU32 = AtomicU32::new(0);
|
||
|
||
/// Global transition lock: serializes start/stop/restart so rapid UI clicks can
|
||
/// never spawn overlapping sidecars or race on the same port.
|
||
static TRANSITION: Mutex<()> = Mutex::new(());
|
||
|
||
fn transition_guard() -> MutexGuard<'static, ()> {
|
||
lock(&TRANSITION)
|
||
}
|
||
|
||
/// Test-only CLI hooks are inert unless this environment variable is present.
|
||
/// Normal shortcuts must not trigger disk I/O or startup races.
|
||
fn test_cli_enabled() -> bool {
|
||
std::env::var_os("LD_FDPI_TEST_CLI").is_some()
|
||
}
|
||
|
||
/// Recovers a poisoned mutex instead of panicking (`unwrap` is forbidden here).
|
||
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||
mutex
|
||
.lock()
|
||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||
}
|
||
|
||
fn terminate_child(child: Child) {
|
||
CHILD_PID.store(0, Ordering::SeqCst);
|
||
engine::terminate_child(child);
|
||
}
|
||
|
||
/// Last-resort fail-safe: runs before the process dies from a panic.
|
||
///
|
||
/// 1. kills the elevated sidecar by PID (Win32, no locks),
|
||
/// 2. restores the original proxy / WinHTTP configuration,
|
||
/// 3. writes a panic log and exits with a non-zero status.
|
||
fn panic_cleanup(info: &std::panic::PanicHookInfo<'_>) {
|
||
let location = info
|
||
.location()
|
||
.map(|loc| format!("{}:{}", loc.file(), loc.line()))
|
||
.unwrap_or_else(|| "unknown".to_string());
|
||
let message = if let Some(text) = info.payload().downcast_ref::<&str>() {
|
||
(*text).to_string()
|
||
} else if let Some(text) = info.payload().downcast_ref::<String>() {
|
||
text.clone()
|
||
} else {
|
||
"unknown panic payload".to_string()
|
||
};
|
||
|
||
let line = format!("PANIC {location} :: {message}\n");
|
||
let log_path = engine::app_data_dir().join("panic.log");
|
||
if let Ok(mut file) = std::fs::OpenOptions::new()
|
||
.create(true)
|
||
.append(true)
|
||
.open(log_path)
|
||
{
|
||
let _ = file.write_all(line.as_bytes());
|
||
}
|
||
eprintln!("[LD FDPI][PANIC] {line}");
|
||
|
||
let pid = CHILD_PID.swap(0, Ordering::SeqCst);
|
||
#[cfg(target_os = "windows")]
|
||
if pid != 0 {
|
||
use windows_sys::Win32::System::Threading::{
|
||
OpenProcess, TerminateProcess, PROCESS_TERMINATE,
|
||
};
|
||
unsafe {
|
||
let handle = OpenProcess(PROCESS_TERMINATE, 0, pid);
|
||
if !handle.is_null() {
|
||
let _ = TerminateProcess(handle, 1);
|
||
let _ = windows_sys::Win32::Foundation::CloseHandle(handle);
|
||
}
|
||
}
|
||
}
|
||
#[cfg(not(target_os = "windows"))]
|
||
let _ = pid;
|
||
|
||
// Restores WinINet, WinHTTP (if we changed it) and clears the dirty sentinel.
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
#[cfg(target_os = "windows")]
|
||
let _ = wfp_killswitch::disable_fdpi_quic_block();
|
||
// Restore an MTU left behind by a crash/panic.
|
||
let _ = eduroam::restore_from_backup();
|
||
|
||
// Do not continue running an elevated process in an unknown state.
|
||
std::process::exit(1);
|
||
}
|
||
|
||
fn install_panic_hook() {
|
||
std::panic::set_hook(Box::new(|info| panic_cleanup(info)));
|
||
}
|
||
|
||
/// Installs the fail-safe hook as early as possible (also for CLI modes).
|
||
pub fn install_panic_hook_public() {
|
||
install_panic_hook();
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// State
|
||
// ---------------------------------------------------------------------------
|
||
|
||
pub struct Runtime {
|
||
pub connected: bool,
|
||
pub desired_connected: bool,
|
||
pub connecting: bool,
|
||
pub child: Option<Child>,
|
||
pub config: EngineConfig,
|
||
pub generation: u64,
|
||
pub sidecar_path: Option<PathBuf>,
|
||
pub last_probe: Option<ProbeSummary>,
|
||
pub last_error: Option<String>,
|
||
pub winhttp_applied: bool,
|
||
pub recovered_once: bool,
|
||
pub eduroam_interface: Option<String>,
|
||
pub eduroam_original_mtu: Option<u16>,
|
||
}
|
||
|
||
pub struct AppState {
|
||
pub inner: Arc<Mutex<Runtime>>,
|
||
pub app_config: Arc<Mutex<AppConfig>>,
|
||
pub pac: Mutex<Option<PacHandle>>,
|
||
pub pac_running: Arc<AtomicBool>,
|
||
pub lan_lock: tokio::sync::Mutex<()>,
|
||
pub sentinel_clean_boot: bool,
|
||
pub sentinel_recovered: bool,
|
||
pub autostart_effective: AtomicBool,
|
||
pub autostart_error: Mutex<Option<String>>,
|
||
}
|
||
|
||
impl AppState {
|
||
fn new(
|
||
clean_boot: bool,
|
||
recovered: bool,
|
||
cfg: AppConfig,
|
||
autostart_effective: bool,
|
||
autostart_error: Option<String>,
|
||
) -> Self {
|
||
Self {
|
||
inner: Arc::new(Mutex::new(Runtime {
|
||
connected: false,
|
||
desired_connected: cfg.auto_connect,
|
||
connecting: false,
|
||
child: None,
|
||
config: cfg.engine_config(),
|
||
generation: 0,
|
||
sidecar_path: None,
|
||
last_probe: None,
|
||
last_error: None,
|
||
winhttp_applied: false,
|
||
recovered_once: false,
|
||
eduroam_interface: None,
|
||
eduroam_original_mtu: None,
|
||
})),
|
||
app_config: Arc::new(Mutex::new(cfg)),
|
||
pac: Mutex::new(None),
|
||
pac_running: Arc::new(AtomicBool::new(false)),
|
||
lan_lock: tokio::sync::Mutex::new(()),
|
||
sentinel_clean_boot: clean_boot,
|
||
sentinel_recovered: recovered,
|
||
autostart_effective: AtomicBool::new(autostart_effective),
|
||
autostart_error: Mutex::new(autostart_error),
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Wire types
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[derive(Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct InitialStateResponse {
|
||
pub is_connected: bool,
|
||
pub desired_connected: bool,
|
||
pub connecting: bool,
|
||
pub engine_found: bool,
|
||
pub engine_path: String,
|
||
pub engine_version: String,
|
||
pub local_ip: String,
|
||
pub pac_running: bool,
|
||
pub config: AppConfig,
|
||
pub autostart_effective: bool,
|
||
pub autostart_error: Option<String>,
|
||
pub is_admin: bool,
|
||
pub system_proxy: SystemProxyState,
|
||
pub winhttp_status: String,
|
||
pub memory_mb: f64,
|
||
pub app_version: String,
|
||
pub sentinel_clean_last_boot: bool,
|
||
pub sentinel_recovered: bool,
|
||
pub last_error: Option<String>,
|
||
}
|
||
|
||
#[derive(Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct StatusResponse {
|
||
pub is_connected: bool,
|
||
pub desired_connected: bool,
|
||
pub connecting: bool,
|
||
pub engine_alive: bool,
|
||
pub proxy_routed: bool,
|
||
pub pac_running: bool,
|
||
pub window_visible: bool,
|
||
pub discord_verified: bool,
|
||
pub web_verified: bool,
|
||
pub latency_ms: u64,
|
||
pub last_error: Option<String>,
|
||
}
|
||
|
||
#[derive(Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct ConnectResponse {
|
||
pub connected: bool,
|
||
pub proxy_ok: bool,
|
||
pub discord_verified: bool,
|
||
pub web_verified: bool,
|
||
pub latency_ms: u64,
|
||
pub proxy_backup_saved: bool,
|
||
pub sentinel_armed: bool,
|
||
pub winhttp_applied: bool,
|
||
pub cli_args: Vec<String>,
|
||
pub engine_path: String,
|
||
pub engine_version: String,
|
||
pub doh_provider: String,
|
||
pub doh_latency_ms: u64,
|
||
pub message: String,
|
||
pub warning: Option<String>,
|
||
}
|
||
|
||
#[derive(Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct DisconnectResponse {
|
||
pub connected: bool,
|
||
pub restored_original_proxy: bool,
|
||
pub external_proxy_detected: bool,
|
||
pub sentinel_disarmed: bool,
|
||
pub status: String,
|
||
pub message: String,
|
||
}
|
||
|
||
#[derive(Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct SoftRestartResponse {
|
||
pub restarted: bool,
|
||
pub latency_ms: u64,
|
||
pub cli_args: Vec<String>,
|
||
pub doh_provider: String,
|
||
pub doh_latency_ms: u64,
|
||
pub message: String,
|
||
}
|
||
|
||
#[derive(Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct VerifyResponse {
|
||
pub proxy_ok: bool,
|
||
pub discord_ok: bool,
|
||
pub web_ok: bool,
|
||
pub latency_ms: u64,
|
||
pub resolver: String,
|
||
pub engine_alive: bool,
|
||
pub detail: String,
|
||
}
|
||
|
||
#[derive(Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct LanToggleResponse {
|
||
pub enabled: bool,
|
||
pub pac_url: String,
|
||
pub manual_proxy: String,
|
||
pub max_connections: usize,
|
||
pub firewall_rule_updated: bool,
|
||
pub message: String,
|
||
}
|
||
|
||
#[derive(Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct SentinelRestoreResponse {
|
||
pub restored: bool,
|
||
pub status: String,
|
||
pub message: String,
|
||
}
|
||
|
||
#[derive(Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct SaveConfigResponse {
|
||
pub config: AppConfig,
|
||
pub autostart_effective: bool,
|
||
pub warning: Option<String>,
|
||
}
|
||
|
||
#[derive(Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct DiagnosticItem {
|
||
pub id: String,
|
||
pub name: String,
|
||
pub passed: bool,
|
||
pub detail: String,
|
||
}
|
||
|
||
fn diag(id: &str, name: &str, passed: bool, detail: impl Into<String>) -> DiagnosticItem {
|
||
DiagnosticItem {
|
||
id: id.to_string(),
|
||
name: name.to_string(),
|
||
passed,
|
||
detail: detail.into(),
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Helpers
|
||
// ---------------------------------------------------------------------------
|
||
|
||
fn validate_config(cfg: &EngineConfig) -> Result<(), String> {
|
||
if cfg.proxy_port < 1024 {
|
||
return Err(format!(
|
||
"Proxy portu 1024 veya üzeri olmalı (verilen: {}).",
|
||
cfg.proxy_port
|
||
));
|
||
}
|
||
if cfg.pac_port < 1024 {
|
||
return Err(format!(
|
||
"PAC portu 1024 veya üzeri olmalı (verilen: {}).",
|
||
cfg.pac_port
|
||
));
|
||
}
|
||
if cfg.proxy_port == cfg.pac_port {
|
||
return Err("Proxy portu ile PAC portu aynı olamaz.".to_string());
|
||
}
|
||
if !matches!(cfg.bypass_mode, 0..=2) {
|
||
return Err("Geçersiz bypass modu (0, 1 veya 2 olmalı).".to_string());
|
||
}
|
||
if !matches!(cfg.chunk_size, 4 | 8 | 16) {
|
||
return Err("Geçersiz chunk boyutu (yalnızca 4, 8 veya 16).".to_string());
|
||
}
|
||
if !matches!(cfg.connection_mode.as_str(), "normal" | "game" | "eduroam") {
|
||
return Err("Geçersiz çalışma modu.".to_string());
|
||
}
|
||
if !matches!(
|
||
cfg.doh_provider.as_str(),
|
||
"auto" | "cloudflare" | "google" | "adguard"
|
||
) {
|
||
return Err("Geçersiz DoH sağlayıcısı.".to_string());
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
fn engine_alive(inner: &Arc<Mutex<Runtime>>) -> bool {
|
||
let mut rt = match inner.lock() {
|
||
Ok(g) => g,
|
||
Err(_) => return false,
|
||
};
|
||
match rt.child.as_mut() {
|
||
Some(child) => matches!(child.try_wait(), Ok(None)),
|
||
None => false,
|
||
}
|
||
}
|
||
|
||
fn proxy_routed(port: u16) -> bool {
|
||
proxy_sentinel::system_proxy_state()
|
||
.map(|s| s.proxy_enable == 1 && s.points_to_ld_fdpi_port == Some(port))
|
||
.unwrap_or(false)
|
||
}
|
||
|
||
#[cfg(target_os = "windows")]
|
||
fn is_admin() -> bool {
|
||
unsafe { windows_sys::Win32::UI::Shell::IsUserAnAdmin() != 0 }
|
||
}
|
||
|
||
#[cfg(not(target_os = "windows"))]
|
||
fn is_admin() -> bool {
|
||
false
|
||
}
|
||
|
||
fn memory_mb() -> f64 {
|
||
let mut sys = System::new_all();
|
||
sys.refresh_all();
|
||
let mb = sys
|
||
.process(Pid::from_u32(std::process::id()))
|
||
.map(|p| (p.memory() as f64) / (1024.0 * 1024.0))
|
||
.unwrap_or(0.0);
|
||
(mb * 10.0).round() / 10.0
|
||
}
|
||
|
||
fn persist_engine_choice(app_config: &Arc<Mutex<AppConfig>>, cfg: &EngineConfig) {
|
||
if let Ok(mut saved) = app_config.lock() {
|
||
saved.update_from_engine(cfg);
|
||
let _ = saved.save();
|
||
}
|
||
}
|
||
|
||
/// Resolves `doh_provider = "auto"` with the parallel Smart-DoH probe.
|
||
/// Returns the concrete engine config plus the selection (for UI/logging).
|
||
fn resolve_engine_doh(mut cfg: EngineConfig) -> (EngineConfig, Option<engine::DohSelection>) {
|
||
if cfg.doh_provider != "auto" {
|
||
return (cfg, None);
|
||
}
|
||
match engine::select_fastest_doh() {
|
||
Some(selection) => {
|
||
cfg.doh_provider = selection.id.clone();
|
||
(cfg, Some(selection))
|
||
}
|
||
None => {
|
||
cfg.doh_provider = "cloudflare".to_string();
|
||
(cfg, None)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Applies the saved autostart intent and updates the effective flag.
|
||
fn sync_autostart(state: &AppState) -> (bool, Option<String>) {
|
||
let enabled = state
|
||
.app_config
|
||
.lock()
|
||
.map(|c| c.auto_start)
|
||
.unwrap_or(false);
|
||
|
||
match autostart::apply(enabled) {
|
||
Ok(effective) => {
|
||
state.autostart_effective.store(effective, Ordering::SeqCst);
|
||
if let Ok(mut err) = state.autostart_error.lock() {
|
||
*err = if effective == enabled {
|
||
None
|
||
} else {
|
||
Some("Görev Zamanlayıcı görevi oluşturulamadı.".to_string())
|
||
};
|
||
}
|
||
(effective, None)
|
||
}
|
||
Err(e) => {
|
||
let effective = autostart::is_enabled();
|
||
state.autostart_effective.store(effective, Ordering::SeqCst);
|
||
if let Ok(mut err) = state.autostart_error.lock() {
|
||
*err = Some(e.clone());
|
||
}
|
||
(effective, Some(e))
|
||
}
|
||
}
|
||
}
|
||
|
||
fn shutdown_all(app: &AppHandle) {
|
||
supervisor::force_disconnected();
|
||
if let Some(state) = app.try_state::<AppState>() {
|
||
// Publish the intent first, then wait for any in-flight start to finish
|
||
// so it cannot apply the proxy after we exit.
|
||
{
|
||
let mut rt = lock(&state.inner);
|
||
rt.desired_connected = false;
|
||
}
|
||
let _transition = transition_guard();
|
||
|
||
if let Ok(mut pac) = state.pac.lock() {
|
||
if let Some(handle) = pac.take() {
|
||
handle.stop();
|
||
}
|
||
}
|
||
state.pac_running.store(false, Ordering::SeqCst);
|
||
|
||
let child = {
|
||
let mut rt = lock(&state.inner);
|
||
rt.generation = rt.generation.wrapping_add(1);
|
||
rt.connected = false;
|
||
rt.desired_connected = false;
|
||
rt.child.take()
|
||
};
|
||
if let Some(child) = child {
|
||
terminate_child(child);
|
||
}
|
||
// Restore a crash-safe MTU backup even if this instance did not apply it.
|
||
let _ = eduroam::restore_from_backup();
|
||
let _ = proxy_sentinel::restore_system_proxy(false);
|
||
#[cfg(target_os = "windows")]
|
||
let _ = wfp_killswitch::disable_fdpi_quic_block();
|
||
vpn::shutdown();
|
||
}
|
||
}
|
||
|
||
/// Keeps the tunnel alive without user interaction.
|
||
fn start_supervisor(
|
||
inner: Arc<Mutex<Runtime>>,
|
||
app_config: Arc<Mutex<AppConfig>>,
|
||
pac_running: Arc<AtomicBool>,
|
||
) {
|
||
std::thread::spawn(move || {
|
||
let mut last_tick = Instant::now();
|
||
let mut last_failure: Option<Instant> = None;
|
||
|
||
loop {
|
||
std::thread::sleep(Duration::from_secs(15));
|
||
let now = Instant::now();
|
||
let slept = now.duration_since(last_tick);
|
||
last_tick = now;
|
||
let woke = slept > Duration::from_secs(45);
|
||
|
||
let (desired, connecting, connected, port, cfg) = {
|
||
let rt = lock(&inner);
|
||
(
|
||
rt.desired_connected,
|
||
rt.connecting,
|
||
rt.connected,
|
||
rt.config.proxy_port,
|
||
rt.config.clone(),
|
||
)
|
||
};
|
||
|
||
if !desired || connecting {
|
||
continue;
|
||
}
|
||
if matches!(
|
||
supervisor::current(),
|
||
supervisor::NetMode::VpnActive | supervisor::NetMode::Transitioning
|
||
) {
|
||
continue;
|
||
}
|
||
|
||
// Simple backoff so a broken network does not spawn an engine every 15s.
|
||
if let Some(failed_at) = last_failure {
|
||
if failed_at.elapsed() < Duration::from_secs(30) {
|
||
continue;
|
||
}
|
||
}
|
||
|
||
let lan_allowed = pac_running.load(Ordering::SeqCst);
|
||
let alive = engine_alive(&inner);
|
||
let routed = proxy_routed(port);
|
||
// A PID can exist while the listener is dead (sleep/wake, Wi-Fi flap).
|
||
let socket_ok = engine::probe_local_port(port);
|
||
|
||
// WinHTTP is best-effort (an existing corporate proxy is preserved);
|
||
// do not restart forever just because it was not applied.
|
||
if alive && routed && socket_ok && !woke {
|
||
continue;
|
||
}
|
||
|
||
// Another tool (Clash/v2rayN) took over the system proxy: do not fight it.
|
||
if !routed && !woke {
|
||
let external = proxy_sentinel::system_proxy_state()
|
||
.ok()
|
||
.and_then(|s| s.proxy_server)
|
||
.map(|s| !s.starts_with("127.0.0.1:") && s != format!("127.0.0.1:{port}"))
|
||
.unwrap_or(false);
|
||
if external {
|
||
continue;
|
||
}
|
||
}
|
||
|
||
let result = if alive && connected {
|
||
do_restart(inner.clone(), app_config.clone(), cfg, lan_allowed).map(|_| ())
|
||
} else {
|
||
do_start(inner.clone(), app_config.clone(), cfg, lan_allowed).map(|_| ())
|
||
};
|
||
|
||
if let Err(e) = result {
|
||
let mut rt = lock(&inner);
|
||
rt.last_error = Some(e);
|
||
rt.connected = false;
|
||
last_failure = Some(Instant::now());
|
||
} else {
|
||
last_failure = None;
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Core operations (blocking, executed on a worker thread)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
fn do_start(
|
||
inner: Arc<Mutex<Runtime>>,
|
||
app_config: Arc<Mutex<AppConfig>>,
|
||
cfg: EngineConfig,
|
||
lan_allowed: bool,
|
||
) -> Result<ConnectResponse, String> {
|
||
// A single writer owns the network mode. Supervisor/tray/UI cannot overlap.
|
||
let mode_guard = supervisor::begin(supervisor::NetMode::DpiActive, true)?;
|
||
// Serialize all transitions: rapid UI clicks can never overlap sidecars.
|
||
let _transition = transition_guard();
|
||
|
||
let requested_provider = cfg.doh_provider.clone();
|
||
let (mut cfg, auto_selection) = resolve_engine_doh(cfg);
|
||
|
||
// Follow a loopback proxy that the OS/Sandbox already enforces (for
|
||
// example 18080 from a previous LD-FDPI build). The engine must listen on
|
||
// the same port Windows is actually using, not the configured default.
|
||
if let Ok(state) = proxy_sentinel::system_proxy_state() {
|
||
if state.proxy_enable == 1 {
|
||
if let Some(port) = state.points_to_ld_fdpi_port {
|
||
if port != cfg.proxy_port && engine::port_is_free(port, false) {
|
||
cfg.proxy_port = port;
|
||
if cfg.pac_port == port {
|
||
cfg.pac_port = port.saturating_add(1);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// Never fight a foreign listener (Sandbox host-proxy forwarder, old
|
||
// SpoofDPI, Clash, ...). Pick the next free port and make the engine own it.
|
||
let preferred = cfg.proxy_port;
|
||
for _ in 0..40 {
|
||
if engine::port_is_free(cfg.proxy_port, false) {
|
||
break;
|
||
}
|
||
cfg.proxy_port = cfg.proxy_port.saturating_add(1);
|
||
if cfg.proxy_port >= 65535 {
|
||
cfg.proxy_port = preferred;
|
||
break;
|
||
}
|
||
}
|
||
if cfg.pac_port == cfg.proxy_port {
|
||
cfg.pac_port = cfg.proxy_port.saturating_add(1);
|
||
}
|
||
|
||
// 0.0.0.0 is only possible while the LAN PAC/firewall layer is active.
|
||
if !lan_allowed {
|
||
cfg.lan_sharing = false;
|
||
}
|
||
validate_config(&cfg)?;
|
||
|
||
{
|
||
let mut rt = lock(&inner);
|
||
if rt.connecting {
|
||
return Err("Bağlantı zaten kuruluyor.".to_string());
|
||
}
|
||
if rt.connected {
|
||
return Err("Zaten bağlısınız. Önce bağlantıyı kesin.".to_string());
|
||
}
|
||
rt.connecting = true;
|
||
rt.desired_connected = true;
|
||
rt.last_error = None;
|
||
}
|
||
|
||
let mut result = Err("Hiçbir FDPI profili denenemedi.".to_string());
|
||
let mut chosen_profile = None;
|
||
let last_profile = lock(&app_config).last_dpi_profile.min(2);
|
||
for profile in [
|
||
last_profile,
|
||
(last_profile + 1) % 3,
|
||
(last_profile + 2) % 3,
|
||
] {
|
||
let profile_cfg = strategy_cfg(&cfg, profile);
|
||
match do_start_inner(&inner, &profile_cfg, true) {
|
||
Ok(response) => {
|
||
result = Ok(response);
|
||
chosen_profile = Some(profile);
|
||
break;
|
||
}
|
||
Err(error) => {
|
||
result = Err(error);
|
||
let _ = wait_for_port_release(profile_cfg.proxy_port, profile_cfg.lan_sharing, Duration::from_secs(3));
|
||
}
|
||
}
|
||
}
|
||
let mut result = result;
|
||
if chosen_profile.is_none() {
|
||
let _ = wait_for_port_release(cfg.proxy_port, cfg.lan_sharing, Duration::from_secs(3));
|
||
// Never leave the user without a working local proxy. The last resort
|
||
// starts the base profile even if Discord TLS verification failed; the
|
||
// UI receives an explicit warning and the engine stays available.
|
||
match do_start_inner(&inner, &cfg, false) {
|
||
Ok(mut response) => {
|
||
let note = "Discord TLS doğrulanamadı; temel profil açık bırakıldı. Gerekirse Bypass modunu değiştirin.";
|
||
response.warning = Some(match response.warning {
|
||
Some(existing) => format!("{existing} {note}"),
|
||
None => note.to_string(),
|
||
});
|
||
result = Ok(response);
|
||
chosen_profile = Some(0);
|
||
}
|
||
Err(error) => {
|
||
result = Err(format!(
|
||
"Tüm FDPI profilleri başarısız oldu ve temel profil de açılamadı: {error}"
|
||
));
|
||
}
|
||
}
|
||
}
|
||
if let Ok(ref mut response) = result {
|
||
if let Some(selection) = &auto_selection {
|
||
response.doh_provider = selection.id.clone();
|
||
response.doh_latency_ms = selection.median_ms;
|
||
}
|
||
}
|
||
if let Some(profile) = chosen_profile {
|
||
let mut persisted = lock(&app_config);
|
||
persisted.last_dpi_profile = profile;
|
||
let _ = persisted.save();
|
||
}
|
||
{
|
||
let mut rt = lock(&inner);
|
||
rt.connecting = false;
|
||
if let Err(ref e) = result {
|
||
rt.last_error = Some(e.clone());
|
||
}
|
||
}
|
||
|
||
if result.is_ok() {
|
||
// Preserve the user's "auto" preference while persisting the rest.
|
||
let mut persist = cfg.clone();
|
||
persist.doh_provider = requested_provider;
|
||
persist_engine_choice(&app_config, &persist);
|
||
mode_guard.commit();
|
||
} else {
|
||
// Belt-and-braces: no failed start may leave a dead local proxy behind.
|
||
let _ = proxy_sentinel::force_disable_loopback(cfg.proxy_port);
|
||
}
|
||
result
|
||
}
|
||
|
||
struct LoopbackProxyGuard {
|
||
port: u16,
|
||
armed: bool,
|
||
}
|
||
|
||
impl Drop for LoopbackProxyGuard {
|
||
fn drop(&mut self) {
|
||
if self.armed {
|
||
let _ = proxy_sentinel::clear_loopback(self.port);
|
||
}
|
||
}
|
||
}
|
||
|
||
fn strategy_cfg(base: &EngineConfig, profile: u8) -> EngineConfig {
|
||
let mut cfg = base.clone();
|
||
match profile {
|
||
1 => {
|
||
cfg.bypass_mode = 1;
|
||
cfg.chunk_size = 2;
|
||
cfg.doh_provider = "google".to_string();
|
||
}
|
||
2 => {
|
||
cfg.bypass_mode = 0;
|
||
cfg.chunk_size = 1;
|
||
cfg.doh_provider = "adguard".to_string();
|
||
}
|
||
_ => {}
|
||
}
|
||
cfg
|
||
}
|
||
|
||
fn wait_for_port_release(port: u16, lan: bool, timeout: Duration) -> bool {
|
||
let deadline = Instant::now() + timeout;
|
||
let mut ticks = 0u32;
|
||
while Instant::now() < deadline {
|
||
if engine::port_is_free(port, lan) {
|
||
return true;
|
||
}
|
||
if ticks == 0 || ticks % 4 == 0 {
|
||
engine::hunt_zombie_processes();
|
||
}
|
||
ticks += 1;
|
||
std::thread::sleep(Duration::from_millis(150));
|
||
}
|
||
engine::port_is_free(port, lan)
|
||
}
|
||
|
||
fn do_start_inner(
|
||
inner: &Arc<Mutex<Runtime>>,
|
||
cfg: &EngineConfig,
|
||
require_discord: bool,
|
||
) -> Result<ConnectResponse, String> {
|
||
// Any early return after this point must leave Windows without a dead
|
||
// 127.0.0.1 proxy. On success the guard is disarmed below.
|
||
let mut proxy_guard = LoopbackProxyGuard {
|
||
port: cfg.proxy_port,
|
||
armed: true,
|
||
};
|
||
// Remove a dead proxy left by a cancelled/raced previous start.
|
||
let _ = proxy_sentinel::clear_dead_loopback(cfg.proxy_port);
|
||
// Remove orphaned engines first so their listener does not look like a conflict.
|
||
engine::hunt_zombie_processes();
|
||
|
||
if !engine::port_is_free(cfg.proxy_port, cfg.lan_sharing) {
|
||
return Err(format!(
|
||
"{} portu zaten kullanımda. Clash/v2rayN gibi bir proxy veya eski bir SpoofDPI \
|
||
süreci bu portu tutuyor olabilir. Ayarlardan farklı bir port seçin.",
|
||
cfg.proxy_port
|
||
));
|
||
}
|
||
|
||
let (mut child, path, args) = engine::spawn_sidecar(cfg)?;
|
||
CHILD_PID.store(child.id(), Ordering::SeqCst);
|
||
|
||
if let Err(e) = engine::wait_until_listening(cfg.proxy_port, Duration::from_secs(8), &mut child)
|
||
{
|
||
terminate_child(child);
|
||
return Err(e);
|
||
}
|
||
|
||
let probe = engine::probe_connectivity(cfg.proxy_port);
|
||
// The local proxy must accept connections. A site-specific 502 (Discord,
|
||
// Cloudflare, Sandbox NAT) is a warning, not a reason to kill the engine.
|
||
if !probe.proxy_ok && !engine::probe_local_port(cfg.proxy_port) {
|
||
terminate_child(child);
|
||
return Err(format!(
|
||
"SpoofDPI dinlemeye başladı ancak yerel proxy bağlantısı kurulamadı.\n{}\n\
|
||
Öneri: Bypass modunu değiştirin (Güçlü / 4 bayt) ve tekrar deneyin.",
|
||
probe.detail
|
||
));
|
||
}
|
||
if require_discord && !probe.discord_ok {
|
||
terminate_child(child);
|
||
return Err(format!(
|
||
"Bu FDPI profili Discord TLS el sıkışmasını geçemedi.\n{}",
|
||
probe.detail
|
||
));
|
||
}
|
||
|
||
// The user may have quit/disconnected while we were waiting for the engine;
|
||
// never apply a system proxy after shutdown was requested.
|
||
if !lock(inner).desired_connected {
|
||
terminate_child(child);
|
||
let _ = proxy_sentinel::clear_dead_loopback(cfg.proxy_port);
|
||
return Err("Başlatma iptal edildi.".to_string());
|
||
}
|
||
|
||
// Eduroam profile: clamp MTU before redirecting traffic. A failure is a
|
||
// warning, never a reason to leave the user offline.
|
||
let mut eduroam_warning: Option<String> = None;
|
||
let mut eduroam_interface: Option<String> = None;
|
||
let mut eduroam_original_mtu: Option<u16> = None;
|
||
if cfg.is_eduroam() {
|
||
let wifi = eduroam::wifi_status();
|
||
if wifi.is_eduroam && !wifi.interface.is_empty() {
|
||
match eduroam::apply_mtu(&wifi.interface) {
|
||
Ok(applied_mtu) => {
|
||
if applied_mtu.changed {
|
||
eduroam_interface = Some(applied_mtu.interface.clone());
|
||
eduroam_original_mtu = Some(applied_mtu.original_mtu);
|
||
}
|
||
}
|
||
Err(error) => {
|
||
eduroam_warning = Some(format!(
|
||
"Eduroam MTU 1400 uygulanamadı (yönetici izni gerekli olabilir): {error}"
|
||
));
|
||
}
|
||
}
|
||
} else {
|
||
eduroam_warning = Some(
|
||
"eduroam Wi-Fi algılanmadı. Mod yine de uygulandı; MTU ayarı atlandı.".to_string(),
|
||
);
|
||
}
|
||
}
|
||
|
||
// Engine is proven healthy: now (and only now) redirect Windows traffic.
|
||
let applied = match proxy_sentinel::apply_system_proxy(cfg.proxy_port, cfg.is_system_wide()) {
|
||
Ok(a) => a,
|
||
Err(e) => {
|
||
if let (Some(interface), Some(original)) =
|
||
(eduroam_interface.as_deref(), eduroam_original_mtu)
|
||
{
|
||
let _ = eduroam::restore_mtu(interface, original);
|
||
}
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
terminate_child(child);
|
||
return Err(e);
|
||
}
|
||
};
|
||
|
||
let mut quic_warning = None;
|
||
if cfg.quic_block {
|
||
match wfp_killswitch::enable_fdpi_quic_block() {
|
||
Ok(0) => {
|
||
quic_warning = Some(
|
||
"QUIC uyumluluk modu açık ancak bilinen tarayıcı/Discord yolu bulunamadı."
|
||
.to_string(),
|
||
);
|
||
}
|
||
Ok(count) => {
|
||
eprintln!("[LD-FDPI][WFP] FDPI QUIC block active for {count} app path(s)");
|
||
}
|
||
Err(error) => {
|
||
quic_warning = Some(format!("QUIC uyumluluk filtresi uygulanamadı: {error}"));
|
||
}
|
||
}
|
||
}
|
||
|
||
let generation = {
|
||
let mut rt = lock(inner);
|
||
rt.generation = rt.generation.wrapping_add(1);
|
||
rt.connected = true;
|
||
rt.desired_connected = true;
|
||
rt.child = Some(child);
|
||
rt.config = cfg.clone();
|
||
rt.sidecar_path = Some(path.clone());
|
||
rt.last_probe = Some(probe.clone());
|
||
rt.winhttp_applied = applied.winhttp_applied;
|
||
rt.last_error = None;
|
||
rt.eduroam_interface = eduroam_interface;
|
||
rt.eduroam_original_mtu = eduroam_original_mtu;
|
||
rt.generation
|
||
};
|
||
arm_watchdog(inner.clone(), generation);
|
||
|
||
let mut warning = applied.warning.clone();
|
||
if let Some(quic) = quic_warning {
|
||
warning = Some(match warning {
|
||
Some(existing) => format!("{existing} {quic}"),
|
||
None => quic,
|
||
});
|
||
}
|
||
let mut message = if probe.discord_ok {
|
||
format!(
|
||
"SpoofDPI {} başlatıldı; discord.com TLS el sıkışması proxy üzerinden doğrulandı. \
|
||
Sistem proxy'si 127.0.0.1:{} adresine yönlendirildi.",
|
||
engine::ENGINE_VERSION,
|
||
cfg.proxy_port
|
||
)
|
||
} else {
|
||
warning = Some(match warning {
|
||
Some(w) => format!("discord.com TLS doğrulanamadı. {w}"),
|
||
None => "discord.com için TLS yanıtı alınamadı; kontrol sitesi çalışıyor. \
|
||
Güçlü modu (4 bayt) deneyin."
|
||
.to_string(),
|
||
});
|
||
format!(
|
||
"SpoofDPI {} başlatıldı; genel internet erişimi doğrulandı ancak discord.com \
|
||
doğrulanamadı.",
|
||
engine::ENGINE_VERSION
|
||
)
|
||
};
|
||
|
||
if cfg.is_system_wide() {
|
||
message = if applied.winhttp_applied {
|
||
format!(
|
||
"{message} {}: WinHTTP + WinINet etkin.",
|
||
if cfg.is_eduroam() {
|
||
"Eduroam Modu"
|
||
} else {
|
||
"Oyun Modu"
|
||
}
|
||
)
|
||
} else {
|
||
format!(
|
||
"{message} {} seçildi ancak WinHTTP uygulanamadı; WinINet aktif.",
|
||
if cfg.is_eduroam() {
|
||
"Eduroam Modu"
|
||
} else {
|
||
"Oyun Modu"
|
||
}
|
||
)
|
||
};
|
||
}
|
||
|
||
if let Some(note) = eduroam_warning {
|
||
warning = Some(match warning {
|
||
Some(existing) => format!("{existing} {note}"),
|
||
None => note,
|
||
});
|
||
}
|
||
|
||
proxy_guard.armed = false;
|
||
Ok(ConnectResponse {
|
||
connected: true,
|
||
proxy_ok: probe.proxy_ok,
|
||
discord_verified: probe.discord_ok,
|
||
web_verified: probe.web_ok,
|
||
latency_ms: probe.connect_ms,
|
||
proxy_backup_saved: applied.backup_saved,
|
||
sentinel_armed: true,
|
||
winhttp_applied: applied.winhttp_applied,
|
||
cli_args: args,
|
||
engine_path: path.display().to_string(),
|
||
engine_version: engine::engine_version_string(),
|
||
doh_provider: cfg.doh_provider.clone(),
|
||
doh_latency_ms: 0,
|
||
message,
|
||
warning,
|
||
})
|
||
}
|
||
|
||
fn do_stop(inner: Arc<Mutex<Runtime>>) -> Result<DisconnectResponse, String> {
|
||
if supervisor::current() == supervisor::NetMode::VpnActive {
|
||
return Err("VPN açıkken DPI bağlantısı kesilemez; önce VPN'i durdurun.".to_string());
|
||
}
|
||
let mode_guard = supervisor::begin(supervisor::NetMode::Disconnected, true)?;
|
||
let _transition = transition_guard();
|
||
|
||
let (child, was_connected, eduroam_interface, eduroam_original_mtu, stopped_port) = {
|
||
let mut rt = lock(&inner);
|
||
let was = rt.connected;
|
||
rt.generation = rt.generation.wrapping_add(1);
|
||
rt.connected = false;
|
||
rt.desired_connected = false;
|
||
rt.winhttp_applied = false;
|
||
(
|
||
rt.child.take(),
|
||
was,
|
||
rt.eduroam_interface.take(),
|
||
rt.eduroam_original_mtu.take(),
|
||
rt.config.proxy_port,
|
||
)
|
||
};
|
||
|
||
if let Some(child) = child {
|
||
terminate_child(child);
|
||
}
|
||
#[cfg(target_os = "windows")]
|
||
let _ = wfp_killswitch::disable_fdpi_quic_block();
|
||
|
||
if let (Some(interface), Some(original)) = (eduroam_interface.as_deref(), eduroam_original_mtu)
|
||
{
|
||
let _ = eduroam::restore_mtu(interface, original);
|
||
}
|
||
|
||
let report: RestoreReport = proxy_sentinel::restore_system_proxy(false)?;
|
||
// Some Sandbox/host-policy environments re-assert the old loopback proxy
|
||
// after restore. Engine is gone; never leave that dead port enabled.
|
||
let dead_proxy_cleared = proxy_sentinel::force_disable_loopback(stopped_port);
|
||
let restored = report.restored() || dead_proxy_cleared;
|
||
let external = report.status == "externalChangeKept" && !dead_proxy_cleared;
|
||
|
||
let message = if dead_proxy_cleared {
|
||
"Bağlantı kesildi. Ölü loopback proxy temizlendi (ProxyEnable=0).".to_string()
|
||
} else if restored {
|
||
format!(
|
||
"Bağlantı kesildi. Orijinal proxy ayarları geri yüklendi (ProxyEnable={}).",
|
||
report.proxy_enable
|
||
)
|
||
} else if external {
|
||
report.message.clone()
|
||
} else if report.status == "noBackup" {
|
||
"Bağlantı kesildi, ancak kayıtlı bir proxy yedeği bulunmadığı için sistem ayarlarına dokunulmadı."
|
||
.to_string()
|
||
} else if was_connected {
|
||
"Bağlantı kesildi. Sentinel zaten temiz durumdaydı.".to_string()
|
||
} else {
|
||
"Bağlantı zaten kapalıydı.".to_string()
|
||
};
|
||
|
||
mode_guard.commit();
|
||
Ok(DisconnectResponse {
|
||
connected: false,
|
||
restored_original_proxy: restored,
|
||
external_proxy_detected: external,
|
||
sentinel_disarmed: restored || external || report.status == "noBackup",
|
||
status: report.status,
|
||
message,
|
||
})
|
||
}
|
||
|
||
fn do_restart(
|
||
inner: Arc<Mutex<Runtime>>,
|
||
app_config: Arc<Mutex<AppConfig>>,
|
||
cfg: EngineConfig,
|
||
lan_allowed: bool,
|
||
) -> Result<SoftRestartResponse, String> {
|
||
let mode_guard = supervisor::begin(supervisor::NetMode::DpiActive, true)?;
|
||
let _transition = transition_guard();
|
||
|
||
let requested_provider = cfg.doh_provider.clone();
|
||
let (mut cfg, auto_selection) = resolve_engine_doh(cfg);
|
||
|
||
if !lan_allowed {
|
||
cfg.lan_sharing = false;
|
||
}
|
||
validate_config(&cfg)?;
|
||
|
||
{
|
||
let mut rt = lock(&inner);
|
||
if rt.connecting {
|
||
return Err("Bağlantı zaten kuruluyor.".to_string());
|
||
}
|
||
rt.connecting = true;
|
||
}
|
||
|
||
let mut result = do_restart_inner(&inner, &cfg);
|
||
if let Ok(ref mut response) = result {
|
||
if let Some(selection) = &auto_selection {
|
||
response.doh_provider = selection.id.clone();
|
||
response.doh_latency_ms = selection.median_ms;
|
||
}
|
||
}
|
||
{
|
||
let mut rt = lock(&inner);
|
||
rt.connecting = false;
|
||
if let Err(ref e) = result {
|
||
rt.last_error = Some(e.clone());
|
||
}
|
||
}
|
||
if result.is_ok() {
|
||
let mut persist = cfg.clone();
|
||
persist.doh_provider = requested_provider;
|
||
persist_engine_choice(&app_config, &persist);
|
||
mode_guard.commit();
|
||
} else {
|
||
drop(mode_guard);
|
||
supervisor::force_disconnected();
|
||
}
|
||
result
|
||
}
|
||
|
||
fn do_restart_inner(
|
||
inner: &Arc<Mutex<Runtime>>,
|
||
cfg: &EngineConfig,
|
||
) -> Result<SoftRestartResponse, String> {
|
||
let (old_child, old_port, old_eduroam_interface, old_eduroam_mtu) = {
|
||
let mut rt = lock(inner);
|
||
if !rt.connected {
|
||
return Err("Canlı yenileme için önce bağlanın.".to_string());
|
||
}
|
||
let old_port = rt.config.proxy_port;
|
||
rt.generation = rt.generation.wrapping_add(1);
|
||
rt.connected = false;
|
||
rt.desired_connected = true;
|
||
rt.winhttp_applied = false;
|
||
(
|
||
rt.child.take(),
|
||
old_port,
|
||
rt.eduroam_interface.take(),
|
||
rt.eduroam_original_mtu.take(),
|
||
)
|
||
};
|
||
|
||
if let Some(child) = old_child {
|
||
terminate_child(child);
|
||
}
|
||
#[cfg(target_os = "windows")]
|
||
let _ = wfp_killswitch::disable_fdpi_quic_block();
|
||
|
||
if old_port != cfg.proxy_port {
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
}
|
||
|
||
let wait_until = Instant::now() + Duration::from_secs(3);
|
||
while !engine::port_is_free(cfg.proxy_port, cfg.lan_sharing) && Instant::now() < wait_until {
|
||
std::thread::sleep(Duration::from_millis(100));
|
||
}
|
||
if !engine::port_is_free(cfg.proxy_port, cfg.lan_sharing) {
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
return Err(format!(
|
||
"{} portu yeniden başlatma sırasında boşaltılamadı.",
|
||
cfg.proxy_port
|
||
));
|
||
}
|
||
|
||
let (mut child, _path, args) = match engine::spawn_sidecar(cfg) {
|
||
Ok(v) => v,
|
||
Err(e) => {
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
return Err(e);
|
||
}
|
||
};
|
||
CHILD_PID.store(child.id(), Ordering::SeqCst);
|
||
|
||
if let Err(e) = engine::wait_until_listening(cfg.proxy_port, Duration::from_secs(8), &mut child)
|
||
{
|
||
terminate_child(child);
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
return Err(e);
|
||
}
|
||
|
||
let probe = engine::probe_connectivity(cfg.proxy_port);
|
||
if !probe.proxy_ok || (!probe.discord_ok && !probe.web_ok) {
|
||
terminate_child(child);
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
return Err(format!(
|
||
"Yeni motor ayarları doğrulanamadı, sistem proxy'si geri alındı.\n{}",
|
||
probe.detail
|
||
));
|
||
}
|
||
|
||
let mut eduroam_interface = old_eduroam_interface.clone();
|
||
let mut eduroam_original_mtu = old_eduroam_mtu;
|
||
let mut eduroam_note: Option<String> = None;
|
||
|
||
if cfg.is_eduroam() {
|
||
if eduroam_interface.is_none() {
|
||
let wifi = eduroam::wifi_status();
|
||
if wifi.is_eduroam && !wifi.interface.is_empty() {
|
||
match eduroam::apply_mtu(&wifi.interface) {
|
||
Ok(applied_mtu) => {
|
||
if applied_mtu.changed {
|
||
eduroam_interface = Some(applied_mtu.interface.clone());
|
||
eduroam_original_mtu = Some(applied_mtu.original_mtu);
|
||
}
|
||
}
|
||
Err(error) => {
|
||
eduroam_note = Some(format!("Eduroam MTU uygulanamadı: {error}"));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} else if let (Some(interface), Some(original)) =
|
||
(eduroam_interface.take(), eduroam_original_mtu.take())
|
||
{
|
||
let _ = eduroam::restore_mtu(&interface, original);
|
||
}
|
||
|
||
let applied = match proxy_sentinel::apply_system_proxy(cfg.proxy_port, cfg.is_system_wide()) {
|
||
Ok(a) => a,
|
||
Err(e) => {
|
||
if let (Some(interface), Some(original)) =
|
||
(eduroam_interface.as_deref(), eduroam_original_mtu)
|
||
{
|
||
let _ = eduroam::restore_mtu(interface, original);
|
||
}
|
||
terminate_child(child);
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
return Err(e);
|
||
}
|
||
};
|
||
|
||
let mut quic_note = None;
|
||
if cfg.quic_block {
|
||
match wfp_killswitch::enable_fdpi_quic_block() {
|
||
Ok(0) => quic_note = Some("QUIC modu: bilinen uygulama yolu bulunamadı.".to_string()),
|
||
Ok(_) => {}
|
||
Err(error) => quic_note = Some(format!("QUIC modu uygulanamadı: {error}")),
|
||
}
|
||
}
|
||
|
||
let generation = {
|
||
let mut rt = lock(inner);
|
||
rt.connected = true;
|
||
rt.desired_connected = true;
|
||
rt.child = Some(child);
|
||
rt.config = cfg.clone();
|
||
rt.last_probe = Some(probe.clone());
|
||
rt.winhttp_applied = applied.winhttp_applied;
|
||
rt.last_error = None;
|
||
rt.eduroam_interface = eduroam_interface;
|
||
rt.eduroam_original_mtu = eduroam_original_mtu;
|
||
rt.generation
|
||
};
|
||
arm_watchdog(inner.clone(), generation);
|
||
|
||
let mut message = format!(
|
||
"Motor canlı olarak yenilendi (Mod {} | Chunk {} B | DoH {}).",
|
||
cfg.connection_mode, cfg.chunk_size, cfg.doh_provider
|
||
);
|
||
if let Some(note) = eduroam_note {
|
||
message = format!("{message} {note}");
|
||
}
|
||
if let Some(note) = quic_note {
|
||
message = format!("{message} {note}");
|
||
}
|
||
|
||
Ok(SoftRestartResponse {
|
||
restarted: true,
|
||
latency_ms: probe.connect_ms,
|
||
cli_args: args,
|
||
doh_provider: cfg.doh_provider.clone(),
|
||
doh_latency_ms: 0,
|
||
message,
|
||
})
|
||
}
|
||
|
||
/// Watches the sidecar. If it dies, the system proxy is restored immediately
|
||
/// instead of leaving the machine without internet.
|
||
fn arm_watchdog(inner: Arc<Mutex<Runtime>>, generation: u64) {
|
||
std::thread::spawn(move || loop {
|
||
std::thread::sleep(Duration::from_millis(2000));
|
||
|
||
let mut guard = lock(&inner);
|
||
if guard.generation != generation || !guard.connected {
|
||
break;
|
||
}
|
||
|
||
let died = match guard.child.as_mut() {
|
||
Some(child) => matches!(child.try_wait(), Ok(Some(_)) | Err(_)),
|
||
None => true,
|
||
};
|
||
|
||
if died {
|
||
guard.child = None;
|
||
guard.connected = false;
|
||
guard.last_error = Some("SpoofDPI süreci beklenmedik şekilde kapandı.".to_string());
|
||
let interface = guard.eduroam_interface.take();
|
||
let original_mtu = guard.eduroam_original_mtu.take();
|
||
drop(guard);
|
||
CHILD_PID.store(0, Ordering::SeqCst);
|
||
if let (Some(interface), Some(original)) = (interface.as_deref(), original_mtu) {
|
||
let _ = eduroam::restore_mtu(interface, original);
|
||
}
|
||
let _ = proxy_sentinel::restore_system_proxy(false);
|
||
break;
|
||
}
|
||
});
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Commands
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[tauri::command(async)]
|
||
fn get_initial_state(state: State<'_, AppState>) -> InitialStateResponse {
|
||
let (connected, desired, connecting, path, last_error) = {
|
||
let rt = lock(&state.inner);
|
||
(
|
||
rt.connected,
|
||
rt.desired_connected,
|
||
rt.connecting,
|
||
rt.sidecar_path.clone(),
|
||
rt.last_error.clone(),
|
||
)
|
||
};
|
||
let app_cfg = lock(&state.app_config).clone();
|
||
let resolved = engine::resolve_sidecar();
|
||
let engine_path = path
|
||
.clone()
|
||
.or_else(|| resolved.as_ref().ok().cloned())
|
||
.map(|p| p.display().to_string())
|
||
.unwrap_or_default();
|
||
|
||
InitialStateResponse {
|
||
is_connected: connected,
|
||
desired_connected: desired,
|
||
connecting,
|
||
engine_found: resolved.is_ok(),
|
||
engine_path,
|
||
engine_version: engine::engine_version_string(),
|
||
local_ip: engine::detect_lan_ip(),
|
||
pac_running: state.pac_running.load(Ordering::SeqCst),
|
||
config: app_cfg,
|
||
autostart_effective: state.autostart_effective.load(Ordering::SeqCst),
|
||
autostart_error: lock(&state.autostart_error).clone(),
|
||
is_admin: is_admin(),
|
||
system_proxy: proxy_sentinel::system_proxy_state().unwrap_or(SystemProxyState {
|
||
proxy_enable: 0,
|
||
proxy_server: None,
|
||
proxy_override: None,
|
||
auto_config_url: None,
|
||
auto_detect: None,
|
||
points_to_ld_fdpi_port: None,
|
||
}),
|
||
winhttp_status: winhttp::describe(),
|
||
memory_mb: memory_mb(),
|
||
app_version: env!("CARGO_PKG_VERSION").to_string(),
|
||
sentinel_clean_last_boot: state.sentinel_clean_boot,
|
||
sentinel_recovered: state.sentinel_recovered,
|
||
last_error,
|
||
}
|
||
}
|
||
|
||
#[tauri::command]
|
||
fn get_status(app: AppHandle, state: State<'_, AppState>) -> StatusResponse {
|
||
let (connected, desired, connecting, port, probe, last_error) = {
|
||
let rt = lock(&state.inner);
|
||
(
|
||
rt.connected,
|
||
rt.desired_connected,
|
||
rt.connecting,
|
||
rt.config.proxy_port,
|
||
rt.last_probe.clone(),
|
||
rt.last_error.clone(),
|
||
)
|
||
};
|
||
let alive = engine_alive(&state.inner);
|
||
let window_visible = app
|
||
.get_webview_window("main")
|
||
.and_then(|w| w.is_visible().ok())
|
||
.unwrap_or(false);
|
||
|
||
StatusResponse {
|
||
is_connected: connected,
|
||
desired_connected: desired,
|
||
connecting,
|
||
engine_alive: alive,
|
||
proxy_routed: proxy_routed(port),
|
||
pac_running: state.pac_running.load(Ordering::SeqCst),
|
||
window_visible,
|
||
discord_verified: probe.as_ref().map(|p| p.discord_ok).unwrap_or(false),
|
||
web_verified: probe.as_ref().map(|p| p.web_ok).unwrap_or(false),
|
||
latency_ms: probe.as_ref().map(|p| p.connect_ms).unwrap_or(0),
|
||
last_error,
|
||
}
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn get_eduroam_status() -> Result<eduroam::EduroamStatus, String> {
|
||
tauri::async_runtime::spawn_blocking(eduroam::status)
|
||
.await
|
||
.map_err(|e| format!("Eduroam durum görevi çöktü: {e}"))
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn connect_eduroam_wifi() -> Result<String, String> {
|
||
tauri::async_runtime::spawn_blocking(eduroam::connect_wifi)
|
||
.await
|
||
.map_err(|e| format!("Eduroam bağlantı görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
fn open_wifi_settings() -> Result<(), String> {
|
||
eduroam::open_wifi_settings()
|
||
}
|
||
|
||
|
||
#[tauri::command]
|
||
fn open_download_page() -> Result<(), String> {
|
||
updater::open_download_page()
|
||
}
|
||
|
||
#[tauri::command]
|
||
fn open_data_folder() -> Result<(), String> {
|
||
let path = engine::app_data_dir();
|
||
#[cfg(target_os = "windows")]
|
||
{
|
||
use std::os::windows::process::CommandExt;
|
||
let mut command = std::process::Command::new("explorer.exe");
|
||
command.arg(path).stdin(std::process::Stdio::null());
|
||
command.creation_flags(0x0800_0000);
|
||
command
|
||
.spawn()
|
||
.map_err(|e| format!("Ayar klasörü açılamadı: {e}"))?;
|
||
Ok(())
|
||
}
|
||
#[cfg(not(target_os = "windows"))]
|
||
{
|
||
let _ = path;
|
||
Err("Bu platformda desteklenmiyor.".to_string())
|
||
}
|
||
}
|
||
|
||
#[tauri::command]
|
||
fn prepare_for_update(state: State<'_, AppState>) -> Result<(), String> {
|
||
// The updater installer replaces files under Program Files. Stop the
|
||
// sidecar first and remove any loopback proxy so Windows never reports a
|
||
// locked file or leaves the machine pointed at a dead port.
|
||
let _ = vpn::shutdown();
|
||
let _ = do_stop(state.inner.clone());
|
||
#[cfg(target_os = "windows")]
|
||
let _ = wfp_killswitch::disable_fdpi_quic_block();
|
||
let port = lock(&state.inner).config.proxy_port;
|
||
let _ = proxy_sentinel::force_disable_loopback(port);
|
||
engine::hunt_zombie_processes();
|
||
Ok(())
|
||
}
|
||
|
||
#[tauri::command]
|
||
fn restart_app(app: tauri::AppHandle) {
|
||
app.restart();
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn connect_without_login() -> Result<captive::CaptiveResult, String> {
|
||
tauri::async_runtime::spawn_blocking(captive::connect_without_login)
|
||
.await
|
||
.map_err(|e| format!("Captive portal görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn auto_select_bypass() -> Result<auto_bypass::AutoBypassResult, String> {
|
||
tauri::async_runtime::spawn_blocking(auto_bypass::select)
|
||
.await
|
||
.map_err(|e| format!("Otomatik bypass görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn get_vpn_status() -> Result<vpn::VpnStatus, String> {
|
||
tauri::async_runtime::spawn_blocking(vpn::status)
|
||
.await
|
||
.map_err(|e| format!("VPN durum görevi çöktü: {e}"))
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn install_vpn_client(app: AppHandle) -> Result<vpn::VpnStatus, String> {
|
||
tauri::async_runtime::spawn_blocking(move || vpn::install_client(&app))
|
||
.await
|
||
.map_err(|e| format!("VPN kurulum görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn connect_vpn(
|
||
state: State<'_, AppState>,
|
||
app: tauri::AppHandle,
|
||
) -> Result<vpn::VpnStatus, String> {
|
||
let dpi_connected = {
|
||
let runtime = lock(&state.inner);
|
||
runtime.connected
|
||
};
|
||
if dpi_connected {
|
||
return Err(
|
||
"DPI bağlantısı açıkken VPN başlatılamaz. Önce DPI bağlantısını kesin.".to_string(),
|
||
);
|
||
}
|
||
let allow_lan = {
|
||
let cfg = lock(&state.app_config);
|
||
cfg.lan_sharing
|
||
};
|
||
tauri::async_runtime::spawn_blocking(move || {
|
||
let mode_guard = supervisor::begin(supervisor::NetMode::VpnActive, false)?;
|
||
let status = vpn::connect(&app, allow_lan)?;
|
||
mode_guard.commit();
|
||
Ok(status)
|
||
})
|
||
.await
|
||
.map_err(|e| format!("VPN bağlantı görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn enroll_vpn(token: String) -> Result<vpn::VpnStatus, String> {
|
||
tauri::async_runtime::spawn_blocking(move || {
|
||
let identity = identity::get_or_create_identity()?;
|
||
let response = identity::enroll("ttmadethat.shop", "/api/v1/enroll", &token)?;
|
||
let config = identity::render_config(&identity, &response);
|
||
identity::save_enrollment_token(&token)?;
|
||
vpn::save_config(config)
|
||
})
|
||
.await
|
||
.map_err(|e| format!("Enrollment görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn run_dns_check() -> Result<vpn::DnsCheck, String> {
|
||
tauri::async_runtime::spawn_blocking(vpn::dns_check)
|
||
.await
|
||
.map_err(|e| format!("DNS kontrol görevi çöktü: {e}"))
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn disconnect_vpn() -> Result<vpn::VpnStatus, String> {
|
||
tauri::async_runtime::spawn_blocking(move || {
|
||
// A VPN disconnect must never overwrite the DPI mode.
|
||
if supervisor::current() == supervisor::NetMode::DpiActive {
|
||
return Ok(vpn::status());
|
||
}
|
||
let mode_guard = supervisor::begin(supervisor::NetMode::Disconnected, true)?;
|
||
let status = vpn::disconnect()?;
|
||
mode_guard.commit();
|
||
Ok(status)
|
||
})
|
||
.await
|
||
.map_err(|e| format!("VPN kesme görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn save_vpn_config(config: String) -> Result<vpn::VpnStatus, String> {
|
||
tauri::async_runtime::spawn_blocking(move || vpn::save_config(config))
|
||
.await
|
||
.map_err(|e| format!("VPN yapılandırma görevi çöktü: {e}"))?
|
||
}
|
||
|
||
fn eduroam_diagnostics_blocking() -> Vec<DiagnosticItem> {
|
||
let wifi = eduroam::wifi_status();
|
||
let mut items = Vec::new();
|
||
|
||
items.push(diag(
|
||
"eduroam_wifi",
|
||
"Wi-Fi / SSID",
|
||
wifi.connected,
|
||
if wifi.connected {
|
||
format!(
|
||
"{} · {} · {}",
|
||
wifi.ssid, wifi.interface, wifi.authentication
|
||
)
|
||
} else {
|
||
"Kablosuz bağlantı yok".to_string()
|
||
},
|
||
));
|
||
items.push(diag(
|
||
"eduroam_ssid",
|
||
"eduroam algılama",
|
||
wifi.is_eduroam,
|
||
if wifi.is_eduroam {
|
||
"eduroam ağındasınız".to_string()
|
||
} else {
|
||
format!(
|
||
"SSID: {}",
|
||
if wifi.ssid.is_empty() {
|
||
"—"
|
||
} else {
|
||
&wifi.ssid
|
||
}
|
||
)
|
||
},
|
||
));
|
||
|
||
let enterprise = wifi.authentication.to_lowercase().contains("enterprise")
|
||
|| wifi.authentication.to_lowercase().contains("kurumsal")
|
||
|| wifi.authentication.to_lowercase().contains("802.1x");
|
||
items.push(diag(
|
||
"eduroam_8021x",
|
||
"802.1X / kurumsal kimlik",
|
||
enterprise,
|
||
if enterprise {
|
||
wifi.authentication.clone()
|
||
} else {
|
||
"Kurumsal kimlik doğrulama algılanmadı".to_string()
|
||
},
|
||
));
|
||
|
||
let mtu = if wifi.interface.is_empty() {
|
||
None
|
||
} else {
|
||
eduroam::current_mtu(&wifi.interface)
|
||
};
|
||
items.push(diag(
|
||
"eduroam_mtu",
|
||
"Wi-Fi MTU",
|
||
mtu.map(|value| value <= 1420).unwrap_or(false),
|
||
mtu.map(|value| {
|
||
format!(
|
||
"{value} B{}",
|
||
if value > 1420 {
|
||
" — Eduroam modu 1400'e indirir"
|
||
} else {
|
||
""
|
||
}
|
||
)
|
||
})
|
||
.unwrap_or_else(|| "Okunamadı".to_string()),
|
||
));
|
||
|
||
let targets = [
|
||
("eduroam_discord_tcp", "Discord TCP 443", "discord.com", 443),
|
||
(
|
||
"eduroam_media_tcp",
|
||
"Discord Media TCP 443",
|
||
"discord.media",
|
||
443,
|
||
),
|
||
(
|
||
"eduroam_voice_tcp",
|
||
"Discord ses TCP 2087",
|
||
"discord.media",
|
||
2087,
|
||
),
|
||
];
|
||
let mut handles = Vec::new();
|
||
for (id, name, host, port) in targets {
|
||
handles.push(std::thread::spawn(move || {
|
||
let latency = eduroam::tcp_probe(host, port, Duration::from_millis(2500));
|
||
(id, name, host, port, latency)
|
||
}));
|
||
}
|
||
for handle in handles {
|
||
if let Ok((id, name, host, port, latency)) = handle.join() {
|
||
items.push(diag(
|
||
id,
|
||
name,
|
||
latency.is_some(),
|
||
match latency {
|
||
Some(ms) => format!("{host}:{port} · {ms} ms"),
|
||
None => format!("{host}:{port} · bağlantı kurulamadı"),
|
||
},
|
||
));
|
||
}
|
||
}
|
||
|
||
let udp_ok = eduroam::udp_stun_probe("stun.l.google.com", 19302, Duration::from_millis(1800));
|
||
items.push(diag(
|
||
"eduroam_voice_udp",
|
||
"UDP / STUN (ses ön koşulu)",
|
||
udp_ok,
|
||
if udp_ok {
|
||
"UDP çıkışı çalışıyor. Discord sesi ayrıca UDP 19294-19344 ve 50000-50100 kullanır; \
|
||
kurum bu aralıkları engelliyorsa HTTP proxy sesi taşıyamaz."
|
||
.to_string()
|
||
} else {
|
||
"UDP çıkışı engelli görünüyor. Discord metin/uygulama çalışabilir; ses çalışmaz."
|
||
.to_string()
|
||
},
|
||
));
|
||
|
||
items
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn run_eduroam_diagnostics() -> Result<Vec<DiagnosticItem>, String> {
|
||
tauri::async_runtime::spawn_blocking(eduroam_diagnostics_blocking)
|
||
.await
|
||
.map_err(|e| format!("Eduroam tanılama görevi çöktü: {e}"))
|
||
}
|
||
|
||
#[tauri::command(async)]
|
||
fn save_config(
|
||
state: State<'_, AppState>,
|
||
config: AppConfig,
|
||
) -> Result<SaveConfigResponse, String> {
|
||
let mut cfg = config;
|
||
// LAN listening is only valid while the PAC/firewall layer is actually running.
|
||
cfg.lan_sharing = state.pac_running.load(Ordering::SeqCst);
|
||
cfg.normalize();
|
||
cfg.save()?;
|
||
|
||
let previous_auto = lock(&state.app_config).auto_start;
|
||
let effective_before = state.autostart_effective.load(Ordering::SeqCst);
|
||
let error_before = lock(&state.autostart_error).clone();
|
||
|
||
{
|
||
let mut stored = lock(&state.app_config);
|
||
*stored = cfg.clone();
|
||
}
|
||
|
||
let (effective, warning) = if previous_auto != cfg.auto_start {
|
||
sync_autostart(&state)
|
||
} else {
|
||
(effective_before, error_before)
|
||
};
|
||
|
||
{
|
||
let mut rt = lock(&state.inner);
|
||
let lan = state.pac_running.load(Ordering::SeqCst);
|
||
rt.config = cfg.engine_config();
|
||
rt.config.lan_sharing = lan;
|
||
if !cfg.auto_connect && !rt.connected {
|
||
rt.desired_connected = false;
|
||
}
|
||
}
|
||
|
||
Ok(SaveConfigResponse {
|
||
config: cfg,
|
||
autostart_effective: effective,
|
||
warning,
|
||
})
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn start_connection(
|
||
state: State<'_, AppState>,
|
||
config: EngineConfig,
|
||
) -> Result<ConnectResponse, String> {
|
||
if vpn::status().connected {
|
||
return Err(
|
||
"VPN açıkken DPI bağlantısı başlatılamaz. Önce VPN bağlantısını kesin.".to_string(),
|
||
);
|
||
}
|
||
let inner = state.inner.clone();
|
||
let app_config = state.app_config.clone();
|
||
let lan_allowed = state.pac_running.load(Ordering::SeqCst);
|
||
let result = tauri::async_runtime::spawn_blocking(move || {
|
||
do_start(inner.clone(), app_config, config, lan_allowed)
|
||
})
|
||
.await
|
||
.map_err(|e| format!("Bağlantı görevi çöktü: {e}"))?;
|
||
|
||
if result.is_err() {
|
||
let mut rt = lock(&state.inner);
|
||
rt.desired_connected = false;
|
||
}
|
||
result
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn stop_connection(state: State<'_, AppState>) -> Result<DisconnectResponse, String> {
|
||
let inner = state.inner.clone();
|
||
tauri::async_runtime::spawn_blocking(move || do_stop(inner))
|
||
.await
|
||
.map_err(|e| format!("Bağlantı kesme görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn soft_restart_engine(
|
||
state: State<'_, AppState>,
|
||
config: EngineConfig,
|
||
) -> Result<SoftRestartResponse, String> {
|
||
let inner = state.inner.clone();
|
||
let app_config = state.app_config.clone();
|
||
let lan_allowed = state.pac_running.load(Ordering::SeqCst);
|
||
tauri::async_runtime::spawn_blocking(move || do_restart(inner, app_config, config, lan_allowed))
|
||
.await
|
||
.map_err(|e| format!("Yenileme görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn verify_connectivity(
|
||
state: State<'_, AppState>,
|
||
doh_provider: Option<String>,
|
||
proxy_port: Option<u16>,
|
||
) -> Result<VerifyResponse, String> {
|
||
let inner = state.inner.clone();
|
||
tauri::async_runtime::spawn_blocking(move || {
|
||
let (connected, cfg) = {
|
||
let rt = lock(&inner);
|
||
(rt.connected, rt.config.clone())
|
||
};
|
||
let port = proxy_port.unwrap_or(cfg.proxy_port);
|
||
let alive = engine_alive(&inner);
|
||
|
||
let probe = engine::probe_connectivity(port);
|
||
let engine_alive = alive && probe.proxy_ok;
|
||
|
||
Ok(VerifyResponse {
|
||
proxy_ok: probe.proxy_ok,
|
||
discord_ok: probe.discord_ok,
|
||
web_ok: probe.web_ok,
|
||
latency_ms: probe.connect_ms,
|
||
resolver: doh_provider.unwrap_or(cfg.doh_provider),
|
||
engine_alive,
|
||
detail: format!(
|
||
"{}{}",
|
||
if connected {
|
||
""
|
||
} else {
|
||
"Uygulama bağlı değil. "
|
||
},
|
||
probe.detail
|
||
),
|
||
})
|
||
})
|
||
.await
|
||
.map_err(|e| format!("Doğrulama görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn benchmark_doh_resolvers() -> Result<Vec<engine::ResolverBenchmark>, String> {
|
||
tauri::async_runtime::spawn_blocking(engine::benchmark_all_doh_resolvers)
|
||
.await
|
||
.map_err(|e| format!("DoH testi çöktü: {e}"))
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn toggle_lan_sharing(
|
||
state: State<'_, AppState>,
|
||
enabled: bool,
|
||
proxy_port: u16,
|
||
pac_port: u16,
|
||
) -> Result<LanToggleResponse, String> {
|
||
// Serialize rapid LAN toggles; PAC start/stop and engine restart must not overlap.
|
||
let _lan = state.lan_lock.lock().await;
|
||
|
||
if proxy_port == pac_port {
|
||
return Err("Proxy portu ile PAC portu aynı olamaz.".to_string());
|
||
}
|
||
if proxy_port < 1024 || pac_port < 1024 {
|
||
return Err("LAN portları 1024 veya üzeri olmalı.".to_string());
|
||
}
|
||
|
||
let local_ip = engine::detect_lan_ip();
|
||
|
||
if let Ok(mut pac) = state.pac.lock() {
|
||
if let Some(handle) = pac.take() {
|
||
handle.stop();
|
||
}
|
||
}
|
||
state.pac_running.store(false, Ordering::SeqCst);
|
||
|
||
let firewall_ok = tauri::async_runtime::spawn_blocking(move || {
|
||
engine::configure_lan_firewall_rule(enabled, proxy_port, pac_port)
|
||
})
|
||
.await
|
||
.unwrap_or(false);
|
||
|
||
let was_connected = {
|
||
let mut rt = lock(&state.inner);
|
||
rt.config.lan_sharing = enabled;
|
||
rt.config.proxy_port = proxy_port;
|
||
rt.config.pac_port = pac_port;
|
||
rt.connected
|
||
};
|
||
|
||
if let Ok(mut saved) = state.app_config.lock() {
|
||
saved.lan_sharing = enabled;
|
||
saved.proxy_port = proxy_port;
|
||
saved.pac_port = pac_port;
|
||
let _ = saved.save();
|
||
}
|
||
|
||
let pac_url = format!("http://{local_ip}:{pac_port}/proxy.pac");
|
||
let manual_proxy = format!("{local_ip}:{proxy_port}");
|
||
|
||
if enabled {
|
||
let handle = pac_server::start(local_ip.clone(), proxy_port, pac_port, enabled).await?;
|
||
if let Ok(mut pac) = state.pac.lock() {
|
||
*pac = Some(handle);
|
||
}
|
||
state.pac_running.store(true, Ordering::SeqCst);
|
||
}
|
||
|
||
if was_connected {
|
||
let inner = state.inner.clone();
|
||
let app_config = state.app_config.clone();
|
||
let cfg_for_restart = {
|
||
let rt = lock(&state.inner);
|
||
rt.config.clone()
|
||
};
|
||
let result = tauri::async_runtime::spawn_blocking(move || {
|
||
do_restart(inner, app_config, cfg_for_restart, enabled)
|
||
})
|
||
.await
|
||
.map_err(|e| format!("LAN yeniden başlatma görevi çöktü: {e}"))?;
|
||
|
||
if let Err(e) = result {
|
||
if enabled {
|
||
if let Ok(mut pac) = state.pac.lock() {
|
||
if let Some(handle) = pac.take() {
|
||
handle.stop();
|
||
}
|
||
}
|
||
state.pac_running.store(false, Ordering::SeqCst);
|
||
}
|
||
return Err(e);
|
||
}
|
||
}
|
||
|
||
let mut notes = Vec::new();
|
||
if enabled && !firewall_ok {
|
||
notes.push(
|
||
"Güvenlik duvarı kuralı eklenemedi (yönetici yetkisi gerekli). Diğer cihazlar için \
|
||
Windows Güvenlik Duvarı'nda TCP portlarına izin verin."
|
||
.to_string(),
|
||
);
|
||
}
|
||
|
||
let message = if enabled {
|
||
format!(
|
||
"LAN paylaşımı açıldı. PAC: {}{}",
|
||
pac_url,
|
||
if notes.is_empty() {
|
||
String::new()
|
||
} else {
|
||
format!(" — {}", notes.join(" "))
|
||
}
|
||
)
|
||
} else {
|
||
"LAN paylaşımı kapatıldı; proxy yeniden yalnızca 127.0.0.1 üzerinde dinliyor.".to_string()
|
||
};
|
||
|
||
Ok(LanToggleResponse {
|
||
enabled,
|
||
pac_url,
|
||
manual_proxy,
|
||
max_connections: pac_server::MAX_CONCURRENT,
|
||
firewall_rule_updated: firewall_ok,
|
||
message,
|
||
})
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn emergency_sentinel_restore(
|
||
state: State<'_, AppState>,
|
||
) -> Result<SentinelRestoreResponse, String> {
|
||
let inner = state.inner.clone();
|
||
tauri::async_runtime::spawn_blocking(move || {
|
||
let child = {
|
||
let mut rt = lock(&inner);
|
||
rt.generation = rt.generation.wrapping_add(1);
|
||
rt.connected = false;
|
||
rt.desired_connected = false;
|
||
rt.child.take()
|
||
};
|
||
if let Some(child) = child {
|
||
terminate_child(child);
|
||
}
|
||
let killed = engine::hunt_zombie_processes();
|
||
let report = proxy_sentinel::restore_system_proxy(true)?;
|
||
|
||
Ok(SentinelRestoreResponse {
|
||
restored: report.restored(),
|
||
status: report.status.clone(),
|
||
message: format!(
|
||
"{}\n{} zombi SpoofDPI süreci temizlendi.",
|
||
report.message, killed
|
||
),
|
||
})
|
||
})
|
||
.await
|
||
.map_err(|e| format!("Sentinel onarım görevi çöktü: {e}"))?
|
||
}
|
||
|
||
#[tauri::command]
|
||
async fn run_diagnostics(state: State<'_, AppState>) -> Result<Vec<DiagnosticItem>, String> {
|
||
let inner = state.inner.clone();
|
||
let pac_running = state.pac_running.load(Ordering::SeqCst);
|
||
let app_cfg = lock(&state.app_config).clone();
|
||
let autostart_effective = state.autostart_effective.load(Ordering::SeqCst);
|
||
let autostart_error = lock(&state.autostart_error).clone();
|
||
|
||
tauri::async_runtime::spawn_blocking(move || {
|
||
let mut items = Vec::new();
|
||
|
||
items.push(diag(
|
||
"ipc",
|
||
"Tauri v2 IPC köprüsü",
|
||
true,
|
||
"Rust komutları yanıt veriyor.",
|
||
));
|
||
|
||
let sidecar = engine::resolve_sidecar();
|
||
match &sidecar {
|
||
Ok(path) => {
|
||
let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
|
||
items.push(diag(
|
||
"sidecar",
|
||
"SpoofDPI ikilisi",
|
||
true,
|
||
format!("{} — {:.1} MB", path.display(), size as f64 / 1_048_576.0),
|
||
));
|
||
}
|
||
Err(e) => items.push(diag("sidecar", "SpoofDPI ikilisi", false, e.clone())),
|
||
}
|
||
|
||
let version = engine::engine_version_string();
|
||
items.push(diag(
|
||
"engine_version",
|
||
"Motor sürümü",
|
||
version.contains(engine::ENGINE_VERSION),
|
||
version,
|
||
));
|
||
|
||
let cfg_path = AppConfig::path();
|
||
items.push(diag(
|
||
"config",
|
||
"Ayar dosyası",
|
||
cfg_path.exists(),
|
||
cfg_path.display().to_string(),
|
||
));
|
||
|
||
items.push(diag(
|
||
"autostart",
|
||
"Yönetici otomatik başlatma (Görev Zamanlayıcı)",
|
||
autostart_effective,
|
||
match autostart_error {
|
||
Some(ref e) => format!("Görev aktif değil: {e}"),
|
||
None => autostart::printable_command(autostart_effective),
|
||
},
|
||
));
|
||
|
||
items.push(diag(
|
||
"admin",
|
||
"Yönetici (UAC) yetkisi",
|
||
is_admin(),
|
||
if is_admin() {
|
||
"Uygulama yönetici olarak çalışıyor.".to_string()
|
||
} else {
|
||
"Yönetici değil; WinHTTP/WinDivert ve görev oluşturma kısıtlı.".to_string()
|
||
},
|
||
));
|
||
|
||
let (connected, cfg) = {
|
||
let rt = lock(&inner);
|
||
(rt.connected, rt.config.clone())
|
||
};
|
||
|
||
match proxy_sentinel::system_proxy_state() {
|
||
Ok(state) => {
|
||
let points = state.points_to_ld_fdpi_port == Some(cfg.proxy_port);
|
||
let passed = if connected {
|
||
state.proxy_enable == 1 && points
|
||
} else {
|
||
state.points_to_ld_fdpi_port != Some(cfg.proxy_port) || state.proxy_enable == 0
|
||
};
|
||
items.push(diag(
|
||
"system_proxy",
|
||
"Windows sistem proxy (HKCU)",
|
||
passed,
|
||
format!(
|
||
"ProxyEnable={} ProxyServer={:?} PAC={}",
|
||
state.proxy_enable,
|
||
state.proxy_server,
|
||
if points { "bizde" } else { "değil" }
|
||
),
|
||
));
|
||
}
|
||
Err(e) => items.push(diag("system_proxy", "Windows sistem proxy", false, e)),
|
||
}
|
||
|
||
items.push(diag(
|
||
"winhttp",
|
||
"WinHTTP (Oyun Modu)",
|
||
if app_cfg.connection_mode == "game" {
|
||
winhttp::is_direct() == Some(false)
|
||
} else {
|
||
true
|
||
},
|
||
winhttp::describe(),
|
||
));
|
||
|
||
let backup_exists = proxy_sentinel::sentinel_file_path().exists();
|
||
items.push(diag(
|
||
"sentinel",
|
||
"Çökme kurtarma yedeği",
|
||
backup_exists,
|
||
proxy_sentinel::sentinel_file_path().display().to_string(),
|
||
));
|
||
|
||
if connected {
|
||
let probe = engine::probe_connectivity(cfg.proxy_port);
|
||
items.push(diag(
|
||
"proxy_tls",
|
||
"Proxy üzerinden TLS",
|
||
probe.proxy_ok && probe.discord_ok,
|
||
probe.detail,
|
||
));
|
||
} else {
|
||
items.push(diag(
|
||
"proxy_tls",
|
||
"Proxy üzerinden TLS",
|
||
false,
|
||
"Bağlı değil.",
|
||
));
|
||
}
|
||
|
||
if pac_running {
|
||
match pac_server::fetch_pac_blocking(cfg.pac_port) {
|
||
Ok(body) => items.push(diag(
|
||
"pac",
|
||
"LAN PAC sunucusu",
|
||
body.contains("FindProxyForURL"),
|
||
format!("http://0.0.0.0:{}/proxy.pac", cfg.pac_port),
|
||
)),
|
||
Err(e) => items.push(diag("pac", "LAN PAC sunucusu", false, e)),
|
||
}
|
||
} else {
|
||
items.push(diag("pac", "LAN PAC sunucusu", false, "Kapalı."));
|
||
}
|
||
|
||
let bench = engine::benchmark_all_doh_resolvers();
|
||
let best = bench.iter().find(|b| b.reachable);
|
||
items.push(diag(
|
||
"doh",
|
||
"DoH çözücüler",
|
||
best.is_some(),
|
||
best.map(|b| format!("En hızlı: {} — {} ms", b.name, b.latency_ms))
|
||
.unwrap_or_else(|| "Hiçbir DoH uç noktasına ulaşılamadı.".to_string()),
|
||
));
|
||
|
||
items
|
||
})
|
||
.await
|
||
.map_err(|e| format!("Tanılama görevi çöktü: {e}"))
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// App entry
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[cfg(target_os = "windows")]
|
||
fn init_app_user_model_id() {
|
||
use std::os::windows::ffi::OsStrExt;
|
||
let wide: Vec<u16> = std::ffi::OsStr::new("com.ldfdpi.desktop")
|
||
.encode_wide()
|
||
.chain(std::iter::once(0))
|
||
.collect();
|
||
unsafe {
|
||
windows_sys::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID(wide.as_ptr());
|
||
}
|
||
}
|
||
|
||
fn ensure_window_visible(app: &AppHandle) {
|
||
if let Some(w) = app.get_webview_window("main") {
|
||
if let Some(icon) = app.default_window_icon() {
|
||
let _ = w.set_icon((*icon).clone());
|
||
}
|
||
let _ = w.show();
|
||
let _ = w.unminimize();
|
||
let _ = w.set_focus();
|
||
}
|
||
}
|
||
|
||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||
pub fn run() {
|
||
#[cfg(target_os = "windows")]
|
||
init_app_user_model_id();
|
||
#[cfg(target_os = "windows")]
|
||
let _ = wfp_killswitch::disable_fdpi_quic_block();
|
||
engine::rotate_logs();
|
||
|
||
let (clean_boot, recovered) = proxy_sentinel::run_startup_sentinel_check();
|
||
// Kill orphaned sidecars before deciding whether a loopback proxy is dead.
|
||
engine::hunt_zombie_processes();
|
||
let _ = proxy_sentinel::clear_dead_loopback(18080);
|
||
// A crash may have left the Wi-Fi MTU clamped.
|
||
let _ = eduroam::restore_from_backup();
|
||
|
||
let vpn_connected_at_boot = vpn::status().connected;
|
||
// A previous GUI crash can leave persistent kill-switch filters behind.
|
||
// Keep them while the tunnel is up; clear them only when it is down.
|
||
#[cfg(target_os = "windows")]
|
||
if !vpn_connected_at_boot {
|
||
let _ = wfp_killswitch::disable_killswitch();
|
||
}
|
||
supervisor::init(if vpn_connected_at_boot {
|
||
supervisor::NetMode::VpnActive
|
||
} else {
|
||
supervisor::NetMode::Disconnected
|
||
});
|
||
|
||
let mut app_config = AppConfig::load();
|
||
app_config.normalize();
|
||
// Clean a loopback proxy left by a crash/forced kill, including a custom
|
||
// port from config. The engine is not running yet at this point.
|
||
let _ = proxy_sentinel::clear_dead_loopback(app_config.proxy_port);
|
||
let _ = proxy_sentinel::clear_dead_loopback(18080);
|
||
// SECURITY: never restore a LAN (0.0.0.0) listener at boot. LAN sharing must be
|
||
// explicitly enabled for this session via the PAC/firewall toggle.
|
||
app_config.lan_sharing = false;
|
||
let _ = app_config.save();
|
||
|
||
install_panic_hook();
|
||
let _ = engine::resolve_sidecar();
|
||
|
||
let (autostart_effective, autostart_error) = match autostart::apply(app_config.auto_start) {
|
||
Ok(effective) => (effective, None),
|
||
Err(e) => (autostart::is_enabled(), Some(e)),
|
||
};
|
||
|
||
let cfg_for_setup = app_config.clone();
|
||
let state = AppState::new(
|
||
clean_boot,
|
||
recovered,
|
||
app_config,
|
||
autostart_effective,
|
||
autostart_error,
|
||
);
|
||
|
||
let supervisor_inner = state.inner.clone();
|
||
let supervisor_config = state.app_config.clone();
|
||
let supervisor_pac = state.pac_running.clone();
|
||
|
||
let built = tauri::Builder::default()
|
||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||
.plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
|
||
ensure_window_visible(app);
|
||
}))
|
||
.manage(state)
|
||
.on_window_event(|window, event| {
|
||
if let WindowEvent::CloseRequested { api, .. } = event {
|
||
let minimize = window
|
||
.app_handle()
|
||
.try_state::<AppState>()
|
||
.and_then(|s| s.app_config.lock().ok().map(|c| c.minimize_to_tray))
|
||
.unwrap_or(true);
|
||
|
||
if minimize {
|
||
let _ = window.hide();
|
||
api.prevent_close();
|
||
} else {
|
||
let app = window.app_handle().clone();
|
||
shutdown_all(&app);
|
||
app.exit(0);
|
||
}
|
||
}
|
||
})
|
||
.setup(move |app| {
|
||
let show_i =
|
||
MenuItem::with_id(app, "show", "LD FDPI Arayüzünü Aç", true, None::<&str>)?;
|
||
let connect_i = MenuItem::with_id(app, "connect", "Bağlan", true, None::<&str>)?;
|
||
let disconnect_i =
|
||
MenuItem::with_id(app, "disconnect", "Bağlantıyı Kes", true, None::<&str>)?;
|
||
let restore_i = MenuItem::with_id(
|
||
app,
|
||
"restore",
|
||
"Acil Proxy Onarımı (Sentinel)",
|
||
true,
|
||
None::<&str>,
|
||
)?;
|
||
let quit_i = MenuItem::with_id(
|
||
app,
|
||
"quit",
|
||
"Güvenli Çıkış (Proxy Geri Yükle)",
|
||
true,
|
||
None::<&str>,
|
||
)?;
|
||
let menu = Menu::with_items(
|
||
app,
|
||
&[&show_i, &connect_i, &disconnect_i, &restore_i, &quit_i],
|
||
)?;
|
||
|
||
let mut tray = TrayIconBuilder::new()
|
||
.menu(&menu)
|
||
.tooltip("LD FDPI — Yerel Proxy & DPI Bypass")
|
||
.on_menu_event(|app, event| match event.id.as_ref() {
|
||
"show" => {
|
||
ensure_window_visible(app);
|
||
}
|
||
"connect" => {
|
||
if let Some(state) = app.try_state::<AppState>() {
|
||
let inner = state.inner.clone();
|
||
let app_config = state.app_config.clone();
|
||
let lan_allowed = state.pac_running.load(Ordering::SeqCst);
|
||
let cfg = lock(&state.app_config).engine_config();
|
||
std::thread::spawn(move || {
|
||
let mut rt = lock(&inner);
|
||
rt.desired_connected = true;
|
||
drop(rt);
|
||
let _ = do_start(inner, app_config, cfg, lan_allowed);
|
||
});
|
||
}
|
||
}
|
||
"disconnect" => {
|
||
if let Some(state) = app.try_state::<AppState>() {
|
||
let inner = state.inner.clone();
|
||
std::thread::spawn(move || {
|
||
let _ = do_stop(inner);
|
||
});
|
||
}
|
||
}
|
||
"restore" => {
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
let _ = engine::hunt_zombie_processes();
|
||
}
|
||
"quit" => {
|
||
shutdown_all(app);
|
||
app.exit(0);
|
||
}
|
||
_ => {}
|
||
})
|
||
.on_tray_icon_event(|tray, event| {
|
||
if let TrayIconEvent::Click {
|
||
button: MouseButton::Left,
|
||
button_state: MouseButtonState::Up,
|
||
..
|
||
} = event
|
||
{
|
||
ensure_window_visible(tray.app_handle());
|
||
}
|
||
});
|
||
|
||
if let Some(icon) = app.default_window_icon() {
|
||
tray = tray.icon((*icon).clone());
|
||
}
|
||
tray.build(app)?;
|
||
|
||
if let Some(w) = app.get_webview_window("main") {
|
||
if let Some(icon) = app.default_window_icon() {
|
||
let _ = w.set_icon((*icon).clone());
|
||
}
|
||
}
|
||
|
||
let silent = std::env::args().any(|a| a == "--minimized" || a == "--autostart");
|
||
if !silent {
|
||
ensure_window_visible(app.handle());
|
||
}
|
||
|
||
if test_cli_enabled() && std::env::args().any(|a| a == "--auto-connect-vpn") {
|
||
let handle = app.handle().clone();
|
||
std::thread::spawn(move || {
|
||
let result = vpn::connect(&handle, false);
|
||
let text = match &result {
|
||
Ok(status) => format!(
|
||
"OK\nconnected={}\naddress={}\nendpoint={}\ndetail={}\n",
|
||
status.connected,
|
||
status.address.as_deref().unwrap_or(""),
|
||
status.endpoint.as_deref().unwrap_or(""),
|
||
status.detail
|
||
),
|
||
Err(error) => format!("ERR\n{error}\n"),
|
||
};
|
||
let dir = engine::app_data_dir();
|
||
let _ = std::fs::create_dir_all(&dir);
|
||
let _ = std::fs::write(dir.join("auto-connect-result.txt"), text);
|
||
});
|
||
}
|
||
|
||
if test_cli_enabled() && std::env::args().any(|a| a == "--auto-dpi-cycle") {
|
||
if let Some(state) = app.try_state::<AppState>() {
|
||
let inner = state.inner.clone();
|
||
let app_config = state.app_config.clone();
|
||
std::thread::spawn(move || {
|
||
std::thread::sleep(Duration::from_secs(5));
|
||
let mut rt = lock(&inner);
|
||
rt.desired_connected = true;
|
||
drop(rt);
|
||
let cfg = lock(&app_config).engine_config();
|
||
let started = do_start(inner.clone(), app_config, cfg, false);
|
||
std::thread::sleep(Duration::from_secs(6));
|
||
let stopped = do_stop(inner);
|
||
let text = format!(
|
||
"START={}\nSTOP={}\n",
|
||
match started {
|
||
Ok(response) => format!("OK {}", response.message),
|
||
Err(error) => format!("ERR {error}"),
|
||
},
|
||
match stopped {
|
||
Ok(response) => format!("OK {}", response.message),
|
||
Err(error) => format!("ERR {error}"),
|
||
}
|
||
);
|
||
let dir = engine::app_data_dir();
|
||
let _ = std::fs::create_dir_all(&dir);
|
||
let _ = std::fs::write(dir.join("auto-dpi-cycle-result.txt"), text);
|
||
});
|
||
}
|
||
}
|
||
|
||
if test_cli_enabled() && std::env::args().any(|a| a == "--auto-start-dpi") {
|
||
if let Some(state) = app.try_state::<AppState>() {
|
||
let inner = state.inner.clone();
|
||
let app_config = state.app_config.clone();
|
||
std::thread::spawn(move || {
|
||
// Let the webview finish its initial state sync first.
|
||
std::thread::sleep(Duration::from_secs(5));
|
||
let mut rt = lock(&inner);
|
||
rt.desired_connected = true;
|
||
drop(rt);
|
||
let cfg = lock(&app_config).engine_config();
|
||
let result = do_start(inner, app_config, cfg, false);
|
||
let text = match &result {
|
||
Ok(response) => format!("OK\n{}\n", response.message),
|
||
Err(error) => format!("ERR\n{error}\n"),
|
||
};
|
||
let dir = engine::app_data_dir();
|
||
let _ = std::fs::create_dir_all(&dir);
|
||
let _ = std::fs::write(dir.join("auto-dpi-result.txt"), text);
|
||
});
|
||
}
|
||
}
|
||
|
||
// Auto-connect starts before React loads, as requested.
|
||
if cfg_for_setup.auto_connect && !vpn_connected_at_boot {
|
||
let inner = supervisor_inner.clone();
|
||
let app_config = supervisor_config.clone();
|
||
let cfg = cfg_for_setup.engine_config();
|
||
std::thread::spawn(move || {
|
||
let mut rt = lock(&inner);
|
||
rt.desired_connected = true;
|
||
drop(rt);
|
||
// LAN is deliberately off at boot; loopback only.
|
||
let _ = do_start(inner, app_config, cfg, false);
|
||
});
|
||
}
|
||
|
||
start_supervisor(supervisor_inner, supervisor_config, supervisor_pac);
|
||
|
||
Ok(())
|
||
})
|
||
.invoke_handler(tauri::generate_handler![
|
||
get_initial_state,
|
||
get_status,
|
||
save_config,
|
||
start_connection,
|
||
stop_connection,
|
||
soft_restart_engine,
|
||
verify_connectivity,
|
||
benchmark_doh_resolvers,
|
||
toggle_lan_sharing,
|
||
emergency_sentinel_restore,
|
||
run_diagnostics,
|
||
get_eduroam_status,
|
||
connect_eduroam_wifi,
|
||
open_wifi_settings,
|
||
open_download_page,
|
||
open_data_folder,
|
||
prepare_for_update,
|
||
restart_app,
|
||
connect_without_login,
|
||
auto_select_bypass,
|
||
get_vpn_status,
|
||
install_vpn_client,
|
||
connect_vpn,
|
||
enroll_vpn,
|
||
disconnect_vpn,
|
||
save_vpn_config,
|
||
run_dns_check,
|
||
run_eduroam_diagnostics
|
||
])
|
||
.build(tauri::generate_context!());
|
||
|
||
let app = match built {
|
||
Ok(app) => app,
|
||
Err(error) => {
|
||
eprintln!("[LD FDPI] Uygulama başlatılamadı: {error}");
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
return;
|
||
}
|
||
};
|
||
|
||
app.run(|app_handle, event| {
|
||
if let RunEvent::Exit = event {
|
||
shutdown_all(app_handle);
|
||
}
|
||
});
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// CLI modes (no GUI)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/// Isolated acceptance-test entry point: brings the tunnel up and installs the
|
||
/// persistent WFP filters, then exits without tearing anything down.
|
||
pub fn wfp_enable() -> i32 {
|
||
match vpn::connect_for_test(false) {
|
||
Ok(status) => {
|
||
println!(
|
||
"WFP_ENABLE_OK connected={} address={:?}",
|
||
status.connected, status.address
|
||
);
|
||
0
|
||
}
|
||
Err(error) => {
|
||
eprintln!("WFP_ENABLE_ERROR {error}");
|
||
1
|
||
}
|
||
}
|
||
}
|
||
|
||
/// `ld-fdpi.exe --restore-only`: restore the WinINet/WinHTTP proxy and kill the
|
||
/// engine, then exit. Used by the NSIS uninstaller and by crash-recovery tests.
|
||
/// (The autostart task is removed separately by the uninstaller.)
|
||
pub fn restore_only() -> i32 {
|
||
#[cfg(target_os = "windows")]
|
||
let _ = wfp_killswitch::disable_killswitch();
|
||
#[cfg(target_os = "windows")]
|
||
let _ = wfp_killswitch::disable_fdpi_quic_block();
|
||
vpn::shutdown();
|
||
let killed = engine::hunt_zombie_processes();
|
||
let _ = eduroam::restore_from_backup();
|
||
match proxy_sentinel::restore_system_proxy(true) {
|
||
Ok(report) => {
|
||
println!("{killed} zombi süreç temizlendi.");
|
||
println!("{}", report.message);
|
||
0
|
||
}
|
||
Err(e) => {
|
||
eprintln!("Proxy geri yüklenemedi: {e}");
|
||
1
|
||
}
|
||
}
|
||
}
|
||
|
||
/// `ld-fdpi.exe --print-autostart`: shows the exact Task Scheduler command and
|
||
/// attempts to apply it (used to validate quoting without admin rights).
|
||
pub fn print_autostart() -> i32 {
|
||
println!("task={}", autostart::TASK_NAME);
|
||
println!("command={}", autostart::printable_command(true));
|
||
println!("enabled_before={}", autostart::is_enabled());
|
||
match autostart::enable() {
|
||
Ok(()) => println!("enable=OK"),
|
||
Err(e) => println!("enable=ERR {e}"),
|
||
}
|
||
println!("enabled_after={}", autostart::is_enabled());
|
||
0
|
||
}
|
||
|
||
struct SelfTestGuard {
|
||
child: Option<Child>,
|
||
proxy_applied: bool,
|
||
}
|
||
|
||
impl Drop for SelfTestGuard {
|
||
fn drop(&mut self) {
|
||
if let Some(child) = self.child.take() {
|
||
terminate_child(child);
|
||
}
|
||
if self.proxy_applied {
|
||
let _ = proxy_sentinel::restore_system_proxy(true);
|
||
}
|
||
}
|
||
}
|
||
|
||
fn report(name: &str, ok: bool, detail: String, failures: &mut usize, total: &mut usize) {
|
||
*total += 1;
|
||
println!("[{}] {name}: {detail}", if ok { "PASS" } else { "FAIL" });
|
||
if !ok {
|
||
*failures += 1;
|
||
}
|
||
}
|
||
|
||
/// `ld-fdpi.exe --self-test`: real engine + proxy + registry + config pipeline.
|
||
pub fn self_test() -> i32 {
|
||
let mut failures = 0usize;
|
||
let mut total = 0usize;
|
||
|
||
let cfg_path = AppConfig::path();
|
||
let mut cfg = AppConfig::load();
|
||
cfg.normalize();
|
||
let saved = cfg.save().is_ok() && cfg_path.exists();
|
||
let reloaded = AppConfig::load();
|
||
report(
|
||
"config_roundtrip",
|
||
saved && reloaded.auto_connect == cfg.auto_connect,
|
||
cfg_path.display().to_string(),
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
|
||
let original = proxy_sentinel::system_proxy_state().ok();
|
||
println!(
|
||
"Mevcut sistem proxy: ProxyEnable={:?} ProxyServer={:?}",
|
||
original.as_ref().map(|s| s.proxy_enable),
|
||
original.as_ref().and_then(|s| s.proxy_server.clone())
|
||
);
|
||
|
||
let sidecar = engine::resolve_sidecar();
|
||
report(
|
||
"sidecar",
|
||
sidecar.is_ok(),
|
||
match &sidecar {
|
||
Ok(p) => p.display().to_string(),
|
||
Err(e) => e.clone(),
|
||
},
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
let Ok(_sidecar_path) = sidecar else {
|
||
println!("\nSidecar bulunamadı; kalan testler atlandı.");
|
||
return 1;
|
||
};
|
||
|
||
let version = engine::engine_version_string();
|
||
report(
|
||
"engine_version",
|
||
version.contains(engine::ENGINE_VERSION),
|
||
version,
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
|
||
let mut port = 18080u16;
|
||
while !engine::port_is_free(port, false) && port < 18120 {
|
||
port += 1;
|
||
}
|
||
report(
|
||
"free_port",
|
||
engine::port_is_free(port, false),
|
||
format!("port {port}"),
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
|
||
let cfg_engine = EngineConfig {
|
||
proxy_port: port,
|
||
pac_port: port + 1,
|
||
..EngineConfig::default()
|
||
};
|
||
|
||
let (mut child, path, args) = match engine::spawn_sidecar(&cfg_engine) {
|
||
Ok(v) => v,
|
||
Err(e) => {
|
||
report("spawn", false, e, &mut failures, &mut total);
|
||
return 1;
|
||
}
|
||
};
|
||
CHILD_PID.store(child.id(), Ordering::SeqCst);
|
||
println!("Motor: {} | Argümanlar: {}", path.display(), args.join(" "));
|
||
|
||
let mut guard = SelfTestGuard {
|
||
child: None,
|
||
proxy_applied: false,
|
||
};
|
||
|
||
match engine::wait_until_listening(port, Duration::from_secs(8), &mut child) {
|
||
Ok(ms) => report(
|
||
"listen",
|
||
true,
|
||
format!("{ms} ms içinde {port} portunda"),
|
||
&mut failures,
|
||
&mut total,
|
||
),
|
||
Err(e) => {
|
||
report("listen", false, e, &mut failures, &mut total);
|
||
engine::terminate_child(child);
|
||
return 1;
|
||
}
|
||
}
|
||
|
||
let probe = engine::probe_connectivity(port);
|
||
report(
|
||
"proxy_connect",
|
||
probe.proxy_ok,
|
||
probe.detail.clone(),
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
report(
|
||
"discord_tls",
|
||
probe.discord_ok,
|
||
format!("CONNECT {} ms", probe.connect_ms),
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
report(
|
||
"web_tls",
|
||
probe.web_ok,
|
||
"www.cloudflare.com üzerinden TLS".to_string(),
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
|
||
match proxy_sentinel::apply_system_proxy(port, false) {
|
||
Ok(applied) => {
|
||
guard.proxy_applied = true;
|
||
let current = proxy_sentinel::system_proxy_state().ok();
|
||
let ok = current
|
||
.as_ref()
|
||
.map(|s| {
|
||
s.proxy_enable == 1
|
||
&& s.proxy_server.as_deref() == Some(applied.applied_server.as_str())
|
||
})
|
||
.unwrap_or(false);
|
||
report(
|
||
"registry_write",
|
||
ok,
|
||
format!(
|
||
"ProxyEnable={:?} ProxyServer={:?}",
|
||
current.as_ref().map(|s| s.proxy_enable),
|
||
current.as_ref().and_then(|s| s.proxy_server.clone())
|
||
),
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
report(
|
||
"backup_written",
|
||
proxy_sentinel::sentinel_file_path().exists(),
|
||
proxy_sentinel::sentinel_file_path().display().to_string(),
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
}
|
||
Err(e) => report("registry_write", false, e, &mut failures, &mut total),
|
||
}
|
||
|
||
match proxy_sentinel::restore_system_proxy(true) {
|
||
Ok(restored) => {
|
||
guard.proxy_applied = false;
|
||
let restored_enable = original.as_ref().map(|s| s.proxy_enable).unwrap_or(0);
|
||
let restored_server = original.as_ref().and_then(|s| s.proxy_server.clone());
|
||
report(
|
||
"registry_restore",
|
||
restored.proxy_enable == restored_enable
|
||
&& restored.proxy_server == restored_server,
|
||
format!(
|
||
"ProxyEnable={} ProxyServer={:?}",
|
||
restored.proxy_enable, restored.proxy_server
|
||
),
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
}
|
||
Err(e) => report("registry_restore", false, e, &mut failures, &mut total),
|
||
}
|
||
|
||
guard.child = Some(child);
|
||
drop(guard);
|
||
|
||
report(
|
||
"cleanup",
|
||
engine::port_is_free(port, false),
|
||
format!("{port} portu serbest bırakıldı"),
|
||
&mut failures,
|
||
&mut total,
|
||
);
|
||
|
||
println!("\nSONUÇ: {total} test, {failures} başarısız");
|
||
if failures == 0 {
|
||
0
|
||
} else {
|
||
1
|
||
}
|
||
}
|