LD-FDPI/linuxFDPI/src-tauri/src/proxy.rs
2026-11-23 03:45:09 +03:00

387 lines
11 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::process::Command;
const MATE_PROXY: &str = "org.mate.system.proxy";
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Backup {
pub backend: String,
pub schema: String,
pub mode: String,
pub http_host: String,
pub http_port: String,
pub https_host: String,
pub https_port: String,
pub kde_file: String,
pub kde_existed: bool,
pub env_existed: bool,
pub env_text: String,
}
impl Default for Backup {
fn default() -> Self {
Self {
backend: String::new(),
schema: String::new(),
mode: String::new(),
http_host: String::new(),
http_port: String::new(),
https_host: String::new(),
https_port: String::new(),
kde_file: String::new(),
kde_existed: false,
env_existed: false,
env_text: String::new(),
}
}
}
fn desktop() -> String {
std::env::var("XDG_CURRENT_DESKTOP")
.or_else(|_| std::env::var("DESKTOP_SESSION"))
.unwrap_or_default()
.to_lowercase()
}
fn has_cmd(name: &str) -> bool {
Command::new("sh")
.args(["-c", &format!("command -v {}", name)])
.output()
.map(|out| out.status.success())
.unwrap_or(false)
}
fn gsettings_schema(name: &str) -> bool {
if !has_cmd("gsettings") {
return false;
}
Command::new("gsettings")
.args(["list-schemas"])
.output()
.map(|out| {
String::from_utf8_lossy(&out.stdout)
.lines()
.any(|line| line.trim() == name)
})
.unwrap_or(false)
}
fn is_kde_desktop() -> bool {
let d = desktop();
d.contains("kde") || d.contains("plasma")
|| std::env::var("KDE_FULL_SESSION").is_ok()
|| std::env::var("KDE_SESSION_VERSION").is_ok()
}
fn is_mate_desktop() -> bool {
desktop().contains("mate")
}
fn is_gnome_family() -> bool {
let d = desktop();
d.contains("gnome")
|| d.contains("unity")
|| d.contains("cinnamon")
|| d.contains("budgie")
|| d.contains("pantheon")
|| d.contains("zorin")
}
fn kde_tool() -> Option<&'static str> {
if has_cmd("kwriteconfig6") {
Some("kwriteconfig6")
} else if has_cmd("kwriteconfig5") {
Some("kwriteconfig5")
} else {
None
}
}
fn kde_reload() {
for (tool, service) in [
("qdbus6", "org.kde.kded6"),
("qdbus", "org.kde.kded5"),
] {
if !has_cmd(tool) {
continue;
}
let _ = Command::new("timeout")
.args([
"3",
tool,
service,
"/modules/proxy",
&format!("{service}.proxy.reparseConfiguration"),
])
.output();
}
}
fn kde_file() -> PathBuf {
dirs::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("kioslaverc")
}
fn env_file() -> PathBuf {
dirs::config_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join("environment.d")
.join("90-ld-fdpi.conf")
}
pub fn backup_path() -> PathBuf {
super::config::data_dir().join("proxy-backup.json")
}
fn get(schema: &str, key: &str) -> Result<String, String> {
let out = Command::new("gsettings")
.args(["get", schema, key])
.output()
.map_err(|e| format!("gsettings çalıştırılamadı: {e}"))?;
if !out.status.success() {
return Err(String::from_utf8_lossy(&out.stderr).trim().to_string());
}
Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}
fn set(schema: &str, key: &str, value: &str) -> Result<(), String> {
let status = Command::new("gsettings")
.args(["set", schema, key, value])
.status()
.map_err(|e| format!("gsettings çalıştırılamadı: {e}"))?;
if status.success() {
Ok(())
} else {
Err(format!("gsettings {schema} {key} ayarlanamadı"))
}
}
fn unquote(value: &str) -> String {
value.trim().trim_matches('\'').trim_matches('"').to_string()
}
fn write_backup(backup: &Backup) -> Result<(), String> {
let path = backup_path();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
fs::write(
&path,
serde_json::to_string_pretty(backup).map_err(|e| e.to_string())?,
)
.map_err(|e| format!("Proxy yedeği yazılamadı: {e}"))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
}
Ok(())
}
fn apply_gsettings(schema: &str, port: u16, backend: &str) -> Result<Backup, String> {
let backup = Backup {
backend: backend.to_string(),
schema: schema.to_string(),
mode: unquote(&get(&format!("{schema}"), "mode")?),
http_host: unquote(&get(&format!("{schema}.http"), "host")?),
http_port: get(&format!("{schema}.http"), "port")?,
https_host: unquote(&get(&format!("{schema}.https"), "host")?),
https_port: get(&format!("{schema}.https"), "port")?,
..Backup::default()
};
write_backup(&backup)?;
let result = (|| -> Result<(), String> {
set(schema, "mode", "manual")?;
set(&format!("{schema}.http"), "host", "127.0.0.1")?;
set(&format!("{schema}.http"), "port", &port.to_string())?;
set(&format!("{schema}.https"), "host", "127.0.0.1")?;
set(&format!("{schema}.https"), "port", &port.to_string())?;
Ok(())
})();
if let Err(error) = result {
let _ = restore_gsettings(&backup);
return Err(error);
}
Ok(backup)
}
fn restore_gsettings(backup: &Backup) -> Result<(), String> {
let schema = if backup.schema.is_empty() {
if backup.backend == "mate" {
MATE_PROXY
} else {
"org.gnome.system.proxy"
}
} else {
backup.schema.as_str()
};
set(schema, "mode", &format!("'{}'", backup.mode))?;
set(&format!("{schema}.http"), "host", &format!("'{}'", backup.http_host))?;
set(&format!("{schema}.http"), "port", &backup.http_port)?;
set(
&format!("{schema}.https"),
"host",
&format!("'{}'", backup.https_host),
)?;
set(&format!("{schema}.https"), "port", &backup.https_port)?;
Ok(())
}
fn apply_kde(port: u16) -> Result<Backup, String> {
let tool = kde_tool().ok_or("KDE proxy aracı bulunamadı (kwriteconfig5/6).")?;
let path = kde_file();
let raw = fs::read_to_string(&path).ok();
let mut backup = Backup {
backend: "kde".to_string(),
kde_file: path.to_string_lossy().to_string(),
kde_existed: raw.is_some(),
..Backup::default()
};
if let Some(text) = raw {
backup.env_text = text;
}
write_backup(&backup)?;
let proxy = format!("http://127.0.0.1:{port}");
let set_key = |key: &str, value: &str| -> Result<(), String> {
let out = Command::new("timeout")
.args([
"5",
tool,
"--file",
"kioslaverc",
"--group",
"Proxy Settings",
"--key",
key,
value,
])
.output()
.map_err(|e| format!("{tool} çalıştırılamadı: {e}"))?;
if out.status.success() {
Ok(())
} else {
Err(format!(
"KDE proxy ayarı yazılamadı: {}",
String::from_utf8_lossy(&out.stderr).trim()
))
}
};
set_key("ProxyType", "1")?;
set_key("httpProxy", &proxy)?;
set_key("httpsProxy", &proxy)?;
set_key("ftpProxy", &proxy)?;
set_key("NoProxyFor", "localhost,127.0.0.1,::1")?;
kde_reload();
Ok(backup)
}
fn restore_kde(backup: &Backup) -> Result<(), String> {
let path = if backup.kde_file.is_empty() {
kde_file()
} else {
PathBuf::from(&backup.kde_file)
};
if backup.kde_existed {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
fs::write(&path, &backup.env_text).map_err(|e| e.to_string())?;
} else {
let _ = fs::remove_file(&path);
}
kde_reload();
Ok(())
}
fn apply_env(port: u16) -> Result<Backup, String> {
let path = env_file();
let raw = fs::read_to_string(&path).ok();
let backup = Backup {
backend: "environment".to_string(),
env_existed: raw.is_some(),
env_text: raw.unwrap_or_default(),
..Backup::default()
};
write_backup(&backup)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let proxy = format!("http://127.0.0.1:{port}");
let body = format!(
"http_proxy={proxy}\nhttps_proxy={proxy}\nHTTP_PROXY={proxy}\nHTTPS_PROXY={proxy}\nno_proxy=localhost,127.0.0.1,::1\nNO_PROXY=localhost,127.0.0.1,::1\n"
);
fs::write(&path, body).map_err(|e| format!("Proxy ortam dosyası yazılamadı: {e}"))?;
if has_cmd("systemctl") {
let _ = Command::new("systemctl")
.args(["--user", "set-environment", "http_proxy", &proxy])
.output();
}
Ok(backup)
}
fn restore_env(backup: &Backup) -> Result<(), String> {
let path = env_file();
if backup.env_existed {
fs::write(&path, &backup.env_text).map_err(|e| e.to_string())?;
} else {
let _ = fs::remove_file(&path);
}
Ok(())
}
pub fn apply(port: u16) -> Result<Backup, String> {
if is_kde_desktop() && kde_tool().is_some() {
return apply_kde(port);
}
if is_gnome_family() && gsettings_schema("org.gnome.system.proxy") {
return apply_gsettings("org.gnome.system.proxy", port, "gnome");
}
if is_mate_desktop() && gsettings_schema(MATE_PROXY) {
return apply_gsettings(MATE_PROXY, port, "mate");
}
apply_env(port)
}
pub fn restore() -> Result<(), String> {
let path = backup_path();
let raw = match fs::read_to_string(&path) {
Ok(raw) => raw,
Err(_) => return Ok(()),
};
let backup: Backup =
serde_json::from_str(&raw).map_err(|e| format!("Proxy yedeği geçersiz: {e}"))?;
match backup.backend.as_str() {
"kde" => restore_kde(&backup)?,
"environment" => restore_env(&backup)?,
_ => restore_gsettings(&backup)?,
}
let _ = fs::remove_file(path);
Ok(())
}
pub fn has_backup() -> bool {
backup_path().exists()
}
pub fn desktop_label() -> String {
if is_kde_desktop() && kde_tool().is_some() {
return "kde".to_string();
}
if is_gnome_family() && gsettings_schema("org.gnome.system.proxy") {
return "gnome".to_string();
}
if is_mate_desktop() && gsettings_schema(MATE_PROXY) {
return "mate".to_string();
}
let raw = desktop();
if raw.is_empty() {
"environment".to_string()
} else {
format!("{raw} (env)")
}
}