Compare commits
No commits in common. "master" and "v0.3.7" have entirely different histories.
|
|
@ -388,16 +388,6 @@ version = "1.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "clipboard-win"
|
|
||||||
version = "3.1.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9fdf5e01086b6be750428ba4a40619f847eb2e95756eee84b18e06e5f0b50342"
|
|
||||||
dependencies = [
|
|
||||||
"lazy-bytes-cast",
|
|
||||||
"winapi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "colorchoice"
|
name = "colorchoice"
|
||||||
version = "1.0.5"
|
version = "1.0.5"
|
||||||
|
|
@ -1262,12 +1252,6 @@ version = "0.2.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9dbbfed4e59ba9750e15ba154fdfd9329cee16ff3df539c2666b70f58cc32105"
|
checksum = "9dbbfed4e59ba9750e15ba154fdfd9329cee16ff3df539c2666b70f58cc32105"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "lazy-bytes-cast"
|
|
||||||
version = "5.0.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "10257499f089cd156ad82d0a9cd57d9501fa2c989068992a97eb3c27836f206b"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "lazy_static"
|
name = "lazy_static"
|
||||||
version = "1.5.0"
|
version = "1.5.0"
|
||||||
|
|
@ -1447,18 +1431,16 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp"
|
name = "ostp"
|
||||||
version = "0.3.12"
|
version = "0.3.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64",
|
"base64",
|
||||||
"clap",
|
"clap",
|
||||||
"clipboard-win",
|
|
||||||
"colored",
|
"colored",
|
||||||
"json_comments",
|
"json_comments",
|
||||||
"ostp-client",
|
"ostp-client",
|
||||||
"ostp-core",
|
"ostp-core",
|
||||||
"ostp-server",
|
"ostp-server",
|
||||||
"pico-args",
|
|
||||||
"rand 0.8.5",
|
"rand 0.8.5",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"serde",
|
"serde",
|
||||||
|
|
@ -1471,7 +1453,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-client"
|
name = "ostp-client"
|
||||||
version = "0.3.12"
|
version = "0.3.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64",
|
"base64",
|
||||||
|
|
@ -1506,7 +1488,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-core"
|
name = "ostp-core"
|
||||||
version = "0.3.12"
|
version = "0.3.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"byteorder",
|
"byteorder",
|
||||||
|
|
@ -1515,11 +1497,9 @@ dependencies = [
|
||||||
"hkdf",
|
"hkdf",
|
||||||
"hmac",
|
"hmac",
|
||||||
"rand 0.8.5",
|
"rand 0.8.5",
|
||||||
"serde",
|
|
||||||
"sha2",
|
"sha2",
|
||||||
"snow",
|
"snow",
|
||||||
"thiserror 1.0.69",
|
"thiserror 1.0.69",
|
||||||
"tokio",
|
|
||||||
"tracing",
|
"tracing",
|
||||||
"x25519-dalek",
|
"x25519-dalek",
|
||||||
]
|
]
|
||||||
|
|
@ -1543,7 +1523,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-server"
|
name = "ostp-server"
|
||||||
version = "0.3.12"
|
version = "0.3.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"axum",
|
"axum",
|
||||||
|
|
@ -1576,7 +1556,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-tun"
|
name = "ostp-tun"
|
||||||
version = "0.3.12"
|
version = "0.3.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"libc",
|
"libc",
|
||||||
|
|
@ -1588,7 +1568,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-tun-helper"
|
name = "ostp-tun-helper"
|
||||||
version = "0.3.12"
|
version = "0.3.7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"chrono",
|
"chrono",
|
||||||
|
|
@ -1612,12 +1592,6 @@ version = "2.3.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "pico-args"
|
|
||||||
version = "0.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pin-project-lite"
|
name = "pin-project-lite"
|
||||||
version = "0.2.17"
|
version = "0.2.17"
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ resolver = "2"
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "BSL 1.1"
|
license = "BSL 1.1"
|
||||||
version = "0.3.12"
|
version = "0.3.7"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,36 @@
|
||||||
|
import os
|
||||||
|
|
||||||
|
with open('ostp/src/main.rs', 'r', encoding='utf-8') as f:
|
||||||
|
content = f.read()
|
||||||
|
|
||||||
|
old_block = ''' if let Some(key) = first_key {
|
||||||
|
let host = get_or_ask_public_ip(&args.config);
|
||||||
|
let mut query_params = Vec::<String>::new();
|
||||||
|
query_params.push("type=udp".to_string());
|
||||||
|
|
||||||
|
let mut link = format!("ostp://{}@{}:{}", key, host, port);
|
||||||
|
if !query_params.is_empty() {
|
||||||
|
link.push('?');
|
||||||
|
link.push_str(&query_params.join("&"));
|
||||||
|
}
|
||||||
|
println!(" [1] {}", link);
|
||||||
|
}'''
|
||||||
|
|
||||||
|
new_block = ''' if let Some(key) = first_key {
|
||||||
|
let host = get_or_ask_public_ip(&args.config);
|
||||||
|
let mut query_params = Vec::<String>::new();
|
||||||
|
query_params.push("type=udp".to_string());
|
||||||
|
|
||||||
|
let mut link = format!("ostp://{}@{}:{}", key, host, port);
|
||||||
|
if !query_params.is_empty() {
|
||||||
|
link.push('?');
|
||||||
|
link.push_str(&query_params.join("&"));
|
||||||
|
}
|
||||||
|
println!(" [1] {}", link);
|
||||||
|
}
|
||||||
|
}'''
|
||||||
|
|
||||||
|
content = content.replace(old_block, new_block)
|
||||||
|
|
||||||
|
with open('ostp/src/main.rs', 'w', encoding='utf-8') as f:
|
||||||
|
f.write(content)
|
||||||
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 20 KiB |
|
|
@ -18,7 +18,7 @@ impl Default for BridgeMetrics {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_socket_protector<F>(_f: F)
|
pub fn set_socket_protector<F>(f: F)
|
||||||
where
|
where
|
||||||
F: Fn(i32) -> bool + Send + Sync + 'static,
|
F: Fn(i32) -> bool + Send + Sync + 'static,
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -50,8 +50,6 @@ pub enum InboundConfig {
|
||||||
protocol: String, // "socks" or "http"
|
protocol: String, // "socks" or "http"
|
||||||
listen: String,
|
listen: String,
|
||||||
port: u16,
|
port: u16,
|
||||||
#[serde(default)]
|
|
||||||
set_system_proxy: bool,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -174,42 +172,33 @@ impl ClientConfig {
|
||||||
.with_context(|| format!("failed to parse JSON from {}", path.display()))?;
|
.with_context(|| format!("failed to parse JSON from {}", path.display()))?;
|
||||||
|
|
||||||
let (migrated_json, was_migrated) = Self::migrate_json(raw_json);
|
let (migrated_json, was_migrated) = Self::migrate_json(raw_json);
|
||||||
|
|
||||||
if was_migrated {
|
if was_migrated {
|
||||||
tracing::warn!(
|
tracing::info!("Config was migrated to v0.3.1. Saving to {}", path.display());
|
||||||
"Config at {} is in an outdated format. Run 'ostp --migrate' to upgrade it.",
|
let serialized = serde_json::to_string_pretty(&migrated_json)?;
|
||||||
path.display()
|
let header = "// OSTP Configuration v0.3.1\n// DO NOT EDIT THIS COMMENT - Migrator relies on it\n";
|
||||||
);
|
let final_content = format!("{}{}", header, serialized);
|
||||||
|
std::fs::write(&path, final_content)
|
||||||
|
.with_context(|| format!("failed to save migrated config to {}", path.display()))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let config: ClientConfig = serde_json::from_value(migrated_json)
|
let config: ClientConfig = serde_json::from_value(migrated_json)
|
||||||
.with_context(|| format!("failed to deserialize config from {}", path.display()))?;
|
.with_context(|| format!("failed to deserialize migrated config from {}", path.display()))?;
|
||||||
|
|
||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Migrates old monolithic JSON to the new modular format.
|
/// Migrates old monolithic JSON to the new modular format.
|
||||||
/// Returns the migrated JSON value and a boolean indicating if a migration occurred.
|
/// Returns the migrated JSON value and a boolean indicating if a migration occurred.
|
||||||
pub fn migrate_json(json: serde_json::Value) -> (serde_json::Value, bool) {
|
pub fn migrate_json(mut json: serde_json::Value) -> (serde_json::Value, bool) {
|
||||||
// Consider the config already migrated if:
|
let is_migrated = json.get("version").and_then(|v| v.as_str()) == Some("0.3.1");
|
||||||
// 1. Version matches exactly, OR
|
if is_migrated {
|
||||||
// 2. The JSON already has the new modular format (inbounds + outbounds arrays)
|
|
||||||
let has_version = json.get("version").and_then(|v| v.as_str()) == Some(env!("CARGO_PKG_VERSION"));
|
|
||||||
let has_new_format = json.get("inbounds").and_then(|v| v.as_array()).is_some()
|
|
||||||
&& json.get("outbounds").and_then(|v| v.as_array()).is_some();
|
|
||||||
|
|
||||||
if has_version || has_new_format {
|
|
||||||
// If format is already new but version is old, just bump the version
|
|
||||||
if has_new_format && !has_version {
|
|
||||||
let mut updated = json.clone();
|
|
||||||
updated["version"] = serde_json::json!(env!("CARGO_PKG_VERSION"));
|
|
||||||
return (updated, false);
|
|
||||||
}
|
|
||||||
return (json, false);
|
return (json, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Needs migration
|
// Needs migration
|
||||||
let mut new_json = serde_json::json!({
|
let mut new_json = serde_json::json!({
|
||||||
"version": env!("CARGO_PKG_VERSION"),
|
"version": "0.3.1",
|
||||||
});
|
});
|
||||||
|
|
||||||
// 1. Log level
|
// 1. Log level
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::watch;
|
use tokio::sync::{mpsc, watch};
|
||||||
|
|
||||||
|
use crate::app::{BridgeCommand, ConnectionStatus, UiEvent};
|
||||||
use crate::config::{ClientConfig, InboundConfig};
|
use crate::config::{ClientConfig, InboundConfig};
|
||||||
use crate::tunnel::balancer::Balancer;
|
use crate::tunnel::balancer::Balancer;
|
||||||
use crate::tunnel::outbounds::OutboundManager;
|
use crate::tunnel::outbounds::OutboundManager;
|
||||||
|
|
@ -9,9 +10,9 @@ use crate::tunnel::router::Router;
|
||||||
|
|
||||||
pub async fn run_client_core(
|
pub async fn run_client_core(
|
||||||
config: ClientConfig,
|
config: ClientConfig,
|
||||||
_metrics: Arc<crate::bridge::BridgeMetrics>,
|
metrics: Arc<crate::bridge::BridgeMetrics>,
|
||||||
mut shutdown_rx_ext: watch::Receiver<bool>,
|
mut shutdown_rx_ext: watch::Receiver<bool>,
|
||||||
_config_rx: Option<watch::Receiver<ClientConfig>>,
|
config_rx: Option<watch::Receiver<ClientConfig>>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
println!("[ostp] Starting run_client_core with multi-server architecture");
|
println!("[ostp] Starting run_client_core with multi-server architecture");
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,9 +5,8 @@ use tokio::net::UdpSocket;
|
||||||
use tokio::sync::{mpsc, Mutex};
|
use tokio::sync::{mpsc, Mutex};
|
||||||
use rand::Rng;
|
use rand::Rng;
|
||||||
|
|
||||||
pub use ostp_core::dns::{
|
use ostp_core::dns::{
|
||||||
DnsPacket, DnsRecordType, encode_payload_to_domain,
|
DnsPacket, DnsRecordType, encode_payload_to_domain, decode_domain_to_payload,
|
||||||
decode_domain_to_payload,
|
|
||||||
};
|
};
|
||||||
use crate::transport::Transport;
|
use crate::transport::Transport;
|
||||||
|
|
||||||
|
|
@ -65,7 +64,7 @@ pub async fn start_dns_transport(domain: String, resolver: String, _pubkey: Opti
|
||||||
});
|
});
|
||||||
|
|
||||||
// Receive task (reads from UDP socket, decodes DNS answer, sends to app)
|
// Receive task (reads from UDP socket, decodes DNS answer, sends to app)
|
||||||
let _base_domain_rx = domain.clone();
|
let base_domain_rx = domain.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut buf = vec![0u8; 65535];
|
let mut buf = vec![0u8; 65535];
|
||||||
loop {
|
loop {
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
use crate::config::{ClientConfig, OutboundConfig};
|
use crate::config::{ClientConfig, OutboundConfig};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
pub struct Balancer {
|
pub struct Balancer {
|
||||||
outbounds: HashMap<String, OutboundConfig>,
|
outbounds: HashMap<String, OutboundConfig>,
|
||||||
|
|
@ -59,7 +60,6 @@ impl Balancer {
|
||||||
/// Fetches the config for a concrete outbound
|
/// Fetches the config for a concrete outbound
|
||||||
pub fn get_concrete_outbound(&self, tag: &str) -> Option<&OutboundConfig> {
|
pub fn get_concrete_outbound(&self, tag: &str) -> Option<&OutboundConfig> {
|
||||||
let resolved_tag = self.resolve_outbound(tag);
|
let resolved_tag = self.resolve_outbound(tag);
|
||||||
tracing::debug!("Balancer: tag '{}' resolved to '{}'", tag, resolved_tag);
|
|
||||||
self.outbounds.get(&resolved_tag)
|
self.outbounds.get(&resolved_tag)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,20 +14,13 @@ pub async fn run_socks_inbound(
|
||||||
outbound_manager: Arc<OutboundManager>,
|
outbound_manager: Arc<OutboundManager>,
|
||||||
mut shutdown: watch::Receiver<bool>,
|
mut shutdown: watch::Receiver<bool>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let InboundConfig::LocalProxy { tag, protocol, listen, port, set_system_proxy } = inbound_config else {
|
let InboundConfig::LocalProxy { tag, protocol, listen, port } = inbound_config else {
|
||||||
return Err(anyhow!("Invalid config for LocalProxy inbound"));
|
return Err(anyhow!("Invalid config for LocalProxy inbound"));
|
||||||
};
|
};
|
||||||
|
|
||||||
let bind_addr = format!("{}:{}", listen, port);
|
let bind_addr = format!("{}:{}", listen, port);
|
||||||
tracing::info!("Starting {} proxy inbound on {} (tag: {})", protocol, bind_addr, tag);
|
tracing::info!("Starting {} proxy inbound on {} (tag: {})", protocol, bind_addr, tag);
|
||||||
|
|
||||||
let _proxy_guard = if set_system_proxy {
|
|
||||||
let proxy_host = if listen == "0.0.0.0" { "127.0.0.1" } else { &listen };
|
|
||||||
Some(crate::sysproxy::SystemProxyGuard::enable(&format!("{}:{}", proxy_host, port)))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let listener = TcpListener::bind(&bind_addr).await?;
|
let listener = TcpListener::bind(&bind_addr).await?;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
|
|
@ -92,7 +85,7 @@ async fn handle_socks5_connection(
|
||||||
}
|
}
|
||||||
|
|
||||||
let atyp = buf[3];
|
let atyp = buf[3];
|
||||||
let (target_host, ip_addr) = match atyp {
|
let (target_host, mut ip_addr) = match atyp {
|
||||||
0x01 => { // IPv4
|
0x01 => { // IPv4
|
||||||
stream.read_exact(&mut buf[0..4]).await?;
|
stream.read_exact(&mut buf[0..4]).await?;
|
||||||
let ip = std::net::Ipv4Addr::new(buf[0], buf[1], buf[2], buf[3]);
|
let ip = std::net::Ipv4Addr::new(buf[0], buf[1], buf[2], buf[3]);
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use crate::config::{ClientConfig, InboundConfig};
|
use crate::config::{ClientConfig, InboundConfig};
|
||||||
#[allow(unused_imports)]
|
|
||||||
use crate::tunnel::router::{Router, Session};
|
use crate::tunnel::router::{Router, Session};
|
||||||
use crate::tunnel::outbounds::OutboundManager;
|
use crate::tunnel::outbounds::OutboundManager;
|
||||||
use tokio::sync::watch;
|
use tokio::sync::watch;
|
||||||
|
|
@ -14,7 +13,7 @@ pub async fn run_tun_inbound(
|
||||||
outbound_manager: Arc<OutboundManager>,
|
outbound_manager: Arc<OutboundManager>,
|
||||||
mut shutdown: watch::Receiver<bool>,
|
mut shutdown: watch::Receiver<bool>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
use std::net::ToSocketAddrs;
|
||||||
use netstack_smoltcp::StackBuilder;
|
use netstack_smoltcp::StackBuilder;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
use futures::{StreamExt, SinkExt};
|
use futures::{StreamExt, SinkExt};
|
||||||
|
|
@ -73,7 +72,7 @@ pub async fn run_tun_inbound(
|
||||||
#[allow(unused_variables)]
|
#[allow(unused_variables)]
|
||||||
let mut _route_guard = None;
|
let mut _route_guard = None;
|
||||||
|
|
||||||
let (tun_to_stack, stack_to_tun) = {
|
let (mut tun_to_stack, mut stack_to_tun) = {
|
||||||
#[cfg(target_os = "android")]
|
#[cfg(target_os = "android")]
|
||||||
{
|
{
|
||||||
if let Some(fd) = fd {
|
if let Some(fd) = fd {
|
||||||
|
|
@ -184,7 +183,7 @@ pub async fn run_tun_inbound(
|
||||||
let router_tcp = router.clone();
|
let router_tcp = router.clone();
|
||||||
let tag_tcp = tag.clone();
|
let tag_tcp = tag.clone();
|
||||||
|
|
||||||
let tcp_accept_task = tokio::spawn(async move {
|
let mut tcp_accept_task = tokio::spawn(async move {
|
||||||
let Some(mut listener) = tcp_listener else { return; };
|
let Some(mut listener) = tcp_listener else { return; };
|
||||||
while let Some((mut stream, local, remote)) = listener.next().await {
|
while let Some((mut stream, local, remote)) = listener.next().await {
|
||||||
let om = outbound_manager_tcp.clone();
|
let om = outbound_manager_tcp.clone();
|
||||||
|
|
@ -250,7 +249,7 @@ pub async fn run_tun_inbound(
|
||||||
let router_udp = router.clone();
|
let router_udp = router.clone();
|
||||||
let tag_udp = tag.clone();
|
let tag_udp = tag.clone();
|
||||||
|
|
||||||
let udp_proxy_task = tokio::spawn(async move {
|
let mut udp_proxy_task = tokio::spawn(async move {
|
||||||
if let Some(udp_sock) = udp_socket {
|
if let Some(udp_sock) = udp_socket {
|
||||||
let (mut udp_rx, _udp_tx) = udp_sock.split();
|
let (mut udp_rx, _udp_tx) = udp_sock.split();
|
||||||
while let Some((payload, local, remote)) = udp_rx.next().await {
|
while let Some((payload, local, remote)) = udp_rx.next().await {
|
||||||
|
|
|
||||||
|
|
@ -66,7 +66,7 @@ pub fn bind_socket_to_interface(socket: &tokio::net::TcpSocket, _is_ipv6: bool,
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn dial_tcp(target_host: &str, target_port: u16, _phys_if_idx: Option<u32>) -> Result<TcpStream> {
|
pub async fn dial_tcp(target_host: &str, target_port: u16, phys_if_idx: Option<u32>) -> Result<TcpStream> {
|
||||||
let addrs = tokio::net::lookup_host((target_host, target_port)).await?.collect::<Vec<_>>();
|
let addrs = tokio::net::lookup_host((target_host, target_port)).await?.collect::<Vec<_>>();
|
||||||
if addrs.is_empty() {
|
if addrs.is_empty() {
|
||||||
return Err(anyhow!("Could not resolve target host: {}", target_host));
|
return Err(anyhow!("Could not resolve target host: {}", target_host));
|
||||||
|
|
@ -79,7 +79,7 @@ pub async fn dial_tcp(target_host: &str, target_port: u16, _phys_if_idx: Option<
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
if let Some(idx) = _phys_if_idx {
|
if let Some(idx) = phys_if_idx {
|
||||||
if let Err(e) = bind_socket_to_interface(&socket, target_addr.is_ipv6(), idx) {
|
if let Err(e) = bind_socket_to_interface(&socket, target_addr.is_ipv6(), idx) {
|
||||||
tracing::warn!("DIRECT: Failed to bind to physical interface {}: {}", idx, e);
|
tracing::warn!("DIRECT: Failed to bind to physical interface {}: {}", idx, e);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use tokio::net::TcpStream;
|
||||||
use crate::tunnel::balancer::Balancer;
|
use crate::tunnel::balancer::Balancer;
|
||||||
use crate::config::OutboundConfig;
|
use crate::config::OutboundConfig;
|
||||||
|
|
||||||
|
|
@ -11,7 +12,7 @@ pub mod socks;
|
||||||
pub struct OutboundManager {
|
pub struct OutboundManager {
|
||||||
balancer: Arc<Balancer>,
|
balancer: Arc<Balancer>,
|
||||||
phys_if_index: Option<u32>,
|
phys_if_index: Option<u32>,
|
||||||
_phys_if_name: Option<String>,
|
phys_if_name: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl OutboundManager {
|
impl OutboundManager {
|
||||||
|
|
@ -23,7 +24,7 @@ impl OutboundManager {
|
||||||
Self {
|
Self {
|
||||||
balancer,
|
balancer,
|
||||||
phys_if_index,
|
phys_if_index,
|
||||||
_phys_if_name: phys_if_name,
|
phys_if_name,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -39,7 +40,7 @@ impl OutboundManager {
|
||||||
block::dial_tcp(target_host, target_port).await
|
block::dial_tcp(target_host, target_port).await
|
||||||
}
|
}
|
||||||
OutboundConfig::Ostp { server, port, access_key, transport, multiplex, .. } => {
|
OutboundConfig::Ostp { server, port, access_key, transport, multiplex, .. } => {
|
||||||
ostp::dial_tcp(target_host, target_port, server, *port, access_key, transport, multiplex).await
|
ostp::dial_tcp(server, *port, access_key, transport, multiplex).await
|
||||||
}
|
}
|
||||||
OutboundConfig::Socks { server, port, .. } => {
|
OutboundConfig::Socks { server, port, .. } => {
|
||||||
socks::dial_tcp(target_host, target_port, server, *port).await
|
socks::dial_tcp(target_host, target_port, server, *port).await
|
||||||
|
|
|
||||||
|
|
@ -1,195 +1,76 @@
|
||||||
use anyhow::Result;
|
use anyhow::{anyhow, Result};
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
use crate::config::{TransportConfig, MultiplexConfig};
|
use crate::config::{TransportConfig, MultiplexConfig};
|
||||||
|
|
||||||
use ostp_core::{OstpEvent, ProtocolAction, ProtocolConfig, ProtocolMachine};
|
use ostp_core::{NoiseRole, OstpEvent, ProtocolAction, ProtocolConfig, ProtocolMachine};
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::UdpSocket;
|
||||||
/// Build the handshake payload the server expects:
|
|
||||||
/// [timestamp_u64_be (8 bytes)] [session_id_u32_be (4 bytes)] [access_key bytes]
|
|
||||||
fn build_handshake_payload(session_id: u32, access_key: &str) -> Vec<u8> {
|
|
||||||
let ts = std::time::SystemTime::now()
|
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_secs();
|
|
||||||
let mut payload = Vec::with_capacity(12 + access_key.len());
|
|
||||||
payload.extend_from_slice(&ts.to_be_bytes());
|
|
||||||
payload.extend_from_slice(&session_id.to_be_bytes());
|
|
||||||
payload.extend_from_slice(access_key.as_bytes());
|
|
||||||
payload
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build a correctly configured ProtocolConfig for an outgoing OSTP connection.
|
|
||||||
fn make_initiator_config(
|
|
||||||
session_id: u32,
|
|
||||||
access_key: &str,
|
|
||||||
transport_cfg: &TransportConfig,
|
|
||||||
) -> ProtocolConfig {
|
|
||||||
let secrets = ostp_core::crypto::derive_all_secrets(access_key.as_bytes());
|
|
||||||
let payload = build_handshake_payload(session_id, access_key);
|
|
||||||
|
|
||||||
let mtu = match transport_cfg.r#type.as_str() {
|
|
||||||
"dns" => 1100,
|
|
||||||
_ => 1350,
|
|
||||||
};
|
|
||||||
|
|
||||||
ProtocolConfig {
|
|
||||||
role: ostp_core::NoiseRole::Initiator,
|
|
||||||
psk: secrets.psk,
|
|
||||||
session_id,
|
|
||||||
handshake_payload: payload,
|
|
||||||
max_padding: 256,
|
|
||||||
padding_strategy: ostp_core::framing::PaddingStrategy::Adaptive,
|
|
||||||
obfuscation_key: secrets.obfuscation_key,
|
|
||||||
max_reorder: 16384,
|
|
||||||
max_reorder_buffer: 8192,
|
|
||||||
ack_delay_ms: 5,
|
|
||||||
rto_ms: 100,
|
|
||||||
max_retries: 8,
|
|
||||||
max_sent_history: 32768,
|
|
||||||
handshake_pad_min: secrets.handshake_pad_min,
|
|
||||||
handshake_pad_max: secrets.handshake_pad_max,
|
|
||||||
mtu,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn random_session_id() -> u32 {
|
|
||||||
use std::collections::hash_map::DefaultHasher;
|
|
||||||
use std::hash::{Hash, Hasher};
|
|
||||||
let mut h = DefaultHasher::new();
|
|
||||||
std::time::Instant::now().hash(&mut h);
|
|
||||||
std::thread::current().id().hash(&mut h);
|
|
||||||
h.finish() as u32
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn dial_tcp(
|
pub async fn dial_tcp(
|
||||||
target_host: &str,
|
|
||||||
target_port: u16,
|
|
||||||
server: &str,
|
server: &str,
|
||||||
port: u16,
|
port: u16,
|
||||||
access_key: &str,
|
access_key: &str,
|
||||||
transport_cfg: &TransportConfig,
|
transport_cfg: &TransportConfig,
|
||||||
_multiplex: &MultiplexConfig,
|
_multiplex: &MultiplexConfig,
|
||||||
) -> Result<TcpStream> {
|
) -> Result<TcpStream> {
|
||||||
tracing::info!("Dialing OSTP server {}:{} for target {}:{}", server, port, target_host, target_port);
|
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||||
let local_addr = listener.local_addr()?;
|
let local_addr = listener.local_addr()?;
|
||||||
let client_stream = tokio::net::TcpStream::connect(local_addr).await?;
|
let client_stream = tokio::net::TcpStream::connect(local_addr).await?;
|
||||||
let (mut server_stream, _) = listener.accept().await?;
|
let (mut server_stream, _) = listener.accept().await?;
|
||||||
|
|
||||||
let transport = make_transport(transport_cfg, server, port).await?;
|
let transport = match transport_cfg.r#type.as_str() {
|
||||||
|
"dns" => {
|
||||||
let session_id = random_session_id();
|
let domain = transport_cfg.domain.clone().unwrap_or_else(|| "tunnel.example.com".to_string());
|
||||||
let config = make_initiator_config(session_id, access_key, transport_cfg);
|
let resolver = transport_cfg.resolver.clone().unwrap_or_else(|| "8.8.8.8".to_string());
|
||||||
let mut machine = ProtocolMachine::new(config).unwrap();
|
crate::transport::dns::start_dns_transport(domain, resolver, transport_cfg.pubkey.clone()).await?
|
||||||
|
|
||||||
let target_host_str = target_host.to_string();
|
|
||||||
|
|
||||||
let server_str = server.to_string();
|
|
||||||
|
|
||||||
// Spawn bridge task
|
|
||||||
tokio::spawn(async move {
|
|
||||||
// Send initial handshake
|
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Start) {
|
|
||||||
handle_action(action, &transport, &mut server_stream).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for handshake response (server sends HandshakePayload back)
|
|
||||||
let mut buf = [0u8; 8192];
|
|
||||||
let mut handshake_success = false;
|
|
||||||
match tokio::time::timeout(
|
|
||||||
std::time::Duration::from_millis(15000),
|
|
||||||
transport.recv(&mut buf),
|
|
||||||
).await {
|
|
||||||
Ok(Ok(n)) => {
|
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&buf[..n]))) {
|
|
||||||
handle_action(action, &transport, &mut server_stream).await;
|
|
||||||
handshake_success = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
tracing::warn!("OSTP handshake timeout for {}:{}", server_str, port);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !handshake_success {
|
|
||||||
tracing::warn!("TCP handshake failed or protocol machine error");
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
// Fallback to UDP for now if unknown
|
||||||
// Send connection request
|
_ => {
|
||||||
let connect_msg = ostp_core::relay::RelayMessage::Connect(format!("{}:{}", target_host_str, target_port));
|
let udp = tokio::net::UdpSocket::bind("0.0.0.0:0").await?;
|
||||||
let connect_encoded = connect_msg.encode();
|
udp.connect((server, port)).await?;
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(connect_encoded))) {
|
crate::transport::Transport::Udp(std::sync::Arc::new(udp))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut psk = [0u8; 32];
|
||||||
|
let key_bytes = access_key.as_bytes();
|
||||||
|
let len = key_bytes.len().min(32);
|
||||||
|
psk[..len].copy_from_slice(&key_bytes[..len]);
|
||||||
|
|
||||||
|
let config = ProtocolConfig {
|
||||||
|
role: ostp_core::NoiseRole::Initiator,
|
||||||
|
psk,
|
||||||
|
session_id: 1,
|
||||||
|
handshake_payload: vec![],
|
||||||
|
max_padding: 0,
|
||||||
|
padding_strategy: ostp_core::framing::PaddingStrategy::Fixed(0),
|
||||||
|
obfuscation_key: [0; 8],
|
||||||
|
max_reorder: 16384,
|
||||||
|
max_reorder_buffer: 8192,
|
||||||
|
ack_delay_ms: 10,
|
||||||
|
rto_ms: 100,
|
||||||
|
max_retries: 5,
|
||||||
|
max_sent_history: 32768,
|
||||||
|
handshake_pad_min: 8,
|
||||||
|
handshake_pad_max: 24,
|
||||||
|
mtu: 1400,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut machine = ProtocolMachine::new(config).unwrap();
|
||||||
|
|
||||||
|
// Spawn bridge task
|
||||||
|
tokio::spawn(async move {
|
||||||
|
if let Ok(action) = machine.on_event(OstpEvent::Start) {
|
||||||
handle_action(action, &transport, &mut server_stream).await;
|
handle_action(action, &transport, &mut server_stream).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Wait for ConnectOk before forwarding any data ─────────────────
|
|
||||||
// This is critical: if we enter the data loop immediately, the TLS
|
|
||||||
// ClientHello arrives at the server before it has established the
|
|
||||||
// outbound TCP connection, causing it to drop the packet as
|
|
||||||
// "Relay DATA for unknown stream".
|
|
||||||
// The kernel will buffer incoming data from server_stream while we wait.
|
|
||||||
let mut connect_ok = false;
|
|
||||||
match tokio::time::timeout(
|
|
||||||
std::time::Duration::from_secs(30),
|
|
||||||
async {
|
|
||||||
let mut wait_buf = [0u8; 8192];
|
|
||||||
loop {
|
|
||||||
tokio::select! {
|
|
||||||
Ok(n) = transport.recv(&mut wait_buf) => {
|
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Inbound(
|
|
||||||
bytes::Bytes::copy_from_slice(&wait_buf[..n]),
|
|
||||||
)) {
|
|
||||||
// Check for ConnectOk or Error before dispatching
|
|
||||||
let result = check_connect_result(&action);
|
|
||||||
handle_action(action, &transport, &mut server_stream).await;
|
|
||||||
match result {
|
|
||||||
Some(true) => return true,
|
|
||||||
Some(false) => return false,
|
|
||||||
None => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = tokio::time::sleep(std::time::Duration::from_millis(10)) => {
|
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Tick) {
|
|
||||||
handle_action(action, &transport, &mut server_stream).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(true) => {
|
|
||||||
tracing::debug!("ConnectOk received for {}:{}, starting data forwarding", target_host_str, target_port);
|
|
||||||
connect_ok = true;
|
|
||||||
}
|
|
||||||
Ok(false) => {
|
|
||||||
tracing::warn!("Server refused connection to {}:{}", target_host_str, target_port);
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
tracing::warn!("ConnectOk timeout for {}:{}", target_host_str, target_port);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !connect_ok {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Main bidirectional data forwarding loop ───────────────────────
|
|
||||||
let mut buf = [0u8; 65535];
|
let mut buf = [0u8; 65535];
|
||||||
let mut udp_buf = [0u8; 65535];
|
let mut udp_buf = [0u8; 65535];
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
Ok(n) = server_stream.read(&mut buf) => {
|
Ok(n) = server_stream.read(&mut buf) => {
|
||||||
if n == 0 { break; }
|
if n == 0 { break; }
|
||||||
let data_msg = ostp_core::relay::RelayMessage::Data(buf[..n].to_vec());
|
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::copy_from_slice(&buf[..n]))) {
|
||||||
let encoded = data_msg.encode();
|
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
|
|
||||||
handle_action(action, &transport, &mut server_stream).await;
|
handle_action(action, &transport, &mut server_stream).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -207,7 +88,6 @@ pub async fn dial_tcp(
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
Ok(client_stream)
|
Ok(client_stream)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -221,55 +101,64 @@ pub async fn handle_udp(
|
||||||
transport_cfg: &TransportConfig,
|
transport_cfg: &TransportConfig,
|
||||||
_multiplex: &MultiplexConfig,
|
_multiplex: &MultiplexConfig,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let transport = make_transport(transport_cfg, server, port).await?;
|
let transport = match transport_cfg.r#type.as_str() {
|
||||||
|
"dns" => {
|
||||||
// Derive session_id from client source addr for stable per-flow sessions
|
let domain = transport_cfg.domain.clone().unwrap_or_else(|| "tunnel.example.com".to_string());
|
||||||
let ip_bytes = match client_src.ip() {
|
let resolver = transport_cfg.resolver.clone().unwrap_or_else(|| "8.8.8.8".to_string());
|
||||||
std::net::IpAddr::V4(v4) => {
|
crate::transport::dns::start_dns_transport(domain, resolver, transport_cfg.pubkey.clone()).await?
|
||||||
let o = v4.octets();
|
|
||||||
u32::from_be_bytes(o)
|
|
||||||
}
|
}
|
||||||
std::net::IpAddr::V6(v6) => {
|
_ => {
|
||||||
let o = v6.octets();
|
let udp = tokio::net::UdpSocket::bind("0.0.0.0:0").await?;
|
||||||
u32::from_be_bytes([o[12], o[13], o[14], o[15]])
|
udp.connect((server, port)).await?;
|
||||||
|
crate::transport::Transport::Udp(std::sync::Arc::new(udp))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let session_id = ip_bytes ^ (client_src.port() as u32);
|
|
||||||
|
|
||||||
let config = make_initiator_config(session_id, access_key, transport_cfg);
|
let mut psk = [0u8; 32];
|
||||||
|
let key_bytes = access_key.as_bytes();
|
||||||
|
let len = key_bytes.len().min(32);
|
||||||
|
psk[..len].copy_from_slice(&key_bytes[..len]);
|
||||||
|
|
||||||
|
let config = ProtocolConfig {
|
||||||
|
role: ostp_core::NoiseRole::Initiator,
|
||||||
|
psk,
|
||||||
|
session_id: u32::from_ne_bytes([
|
||||||
|
client_src.ip().to_string().as_bytes().get(0).copied().unwrap_or(0),
|
||||||
|
client_src.ip().to_string().as_bytes().get(1).copied().unwrap_or(0),
|
||||||
|
client_src.ip().to_string().as_bytes().get(2).copied().unwrap_or(0),
|
||||||
|
client_src.ip().to_string().as_bytes().get(3).copied().unwrap_or(0),
|
||||||
|
]),
|
||||||
|
handshake_payload: vec![],
|
||||||
|
max_padding: 0,
|
||||||
|
padding_strategy: ostp_core::framing::PaddingStrategy::Fixed(0),
|
||||||
|
obfuscation_key: [0; 8],
|
||||||
|
max_reorder: 4096,
|
||||||
|
max_reorder_buffer: 2048,
|
||||||
|
ack_delay_ms: 50,
|
||||||
|
rto_ms: 200,
|
||||||
|
max_retries: 3,
|
||||||
|
max_sent_history: 8192,
|
||||||
|
handshake_pad_min: 8,
|
||||||
|
handshake_pad_max: 24,
|
||||||
|
mtu: 1400,
|
||||||
|
};
|
||||||
|
|
||||||
let mut machine = ProtocolMachine::new(config)?;
|
let mut machine = ProtocolMachine::new(config)?;
|
||||||
|
|
||||||
// Send handshake first
|
// Send initial packet with UDP payload
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Start) {
|
if let Ok(action) = machine.on_event(OstpEvent::Start) {
|
||||||
handle_udp_action(action, &transport).await;
|
handle_udp_action(action, &transport).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait for handshake response (server sends HandshakePayload back)
|
// Send the actual UDP payload
|
||||||
let mut buf = [0u8; 8192];
|
let relay_msg = ostp_core::relay::RelayMessage::Connect(format!("{}:{}", target_dst.ip(), target_dst.port()));
|
||||||
match tokio::time::timeout(
|
let encoded = relay_msg.encode();
|
||||||
std::time::Duration::from_millis(15000),
|
|
||||||
transport.recv(&mut buf),
|
|
||||||
).await {
|
|
||||||
Ok(Ok(n)) => {
|
|
||||||
let _ = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&buf[..n])));
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
tracing::warn!("OSTP handshake timeout for {}:{}", server, port);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send relay UdpAssociate + data
|
|
||||||
let assoc_msg = ostp_core::relay::RelayMessage::UdpAssociate;
|
|
||||||
let encoded = assoc_msg.encode();
|
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
|
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
|
||||||
handle_udp_action(action, &transport).await;
|
handle_udp_action(action, &transport).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
let data_msg = ostp_core::relay::RelayMessage::UdpData(
|
// Send data packet
|
||||||
format!("{}:{}", target_dst.ip(), target_dst.port()),
|
let data_msg = ostp_core::relay::RelayMessage::Data(payload.to_vec());
|
||||||
payload.to_vec()
|
|
||||||
);
|
|
||||||
let encoded = data_msg.encode();
|
let encoded = data_msg.encode();
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
|
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
|
||||||
handle_udp_action(action, &transport).await;
|
handle_udp_action(action, &transport).await;
|
||||||
|
|
@ -277,15 +166,13 @@ pub async fn handle_udp(
|
||||||
|
|
||||||
// Keep-alive for a short time to receive response
|
// Keep-alive for a short time to receive response
|
||||||
for _ in 0..5 {
|
for _ in 0..5 {
|
||||||
|
let mut buf = [0u8; 8192];
|
||||||
match tokio::time::timeout(
|
match tokio::time::timeout(
|
||||||
std::time::Duration::from_millis(100),
|
std::time::Duration::from_millis(100),
|
||||||
transport.recv(&mut buf),
|
transport.recv(&mut buf)
|
||||||
).await {
|
).await {
|
||||||
Ok(Ok(n)) => {
|
Ok(Ok(n)) => {
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&buf[..n]))) {
|
let _ = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&buf[..n])));
|
||||||
// Just process incoming UDP response internally
|
|
||||||
let _ = action;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
_ => break,
|
_ => break,
|
||||||
}
|
}
|
||||||
|
|
@ -294,29 +181,6 @@ pub async fn handle_udp(
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn make_transport(
|
|
||||||
transport_cfg: &TransportConfig,
|
|
||||||
server: &str,
|
|
||||||
port: u16,
|
|
||||||
) -> Result<crate::transport::Transport> {
|
|
||||||
match transport_cfg.r#type.as_str() {
|
|
||||||
"dns" => {
|
|
||||||
let domain = transport_cfg.domain.clone()
|
|
||||||
.unwrap_or_else(|| "tunnel.example.com".to_string());
|
|
||||||
let resolver = transport_cfg.resolver.clone()
|
|
||||||
.unwrap_or_else(|| server.to_string());
|
|
||||||
let transport = crate::transport::dns::start_dns_transport(domain, resolver, transport_cfg.pubkey.clone()).await
|
|
||||||
.map_err(|e| anyhow::anyhow!(e))?;
|
|
||||||
Ok(transport)
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
let udp = tokio::net::UdpSocket::bind("0.0.0.0:0").await?;
|
|
||||||
udp.connect((server, port)).await?;
|
|
||||||
Ok(crate::transport::Transport::Udp(std::sync::Arc::new(udp)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_udp_action(action: ProtocolAction, transport: &crate::transport::Transport) {
|
async fn handle_udp_action(action: ProtocolAction, transport: &crate::transport::Transport) {
|
||||||
match action {
|
match action {
|
||||||
ProtocolAction::SendDatagram(data) => {
|
ProtocolAction::SendDatagram(data) => {
|
||||||
|
|
@ -339,53 +203,17 @@ async fn handle_action(action: ProtocolAction, transport: &crate::transport::Tra
|
||||||
let _ = transport.send(&data).await;
|
let _ = transport.send(&data).await;
|
||||||
}
|
}
|
||||||
ProtocolAction::DeliverApp(_stream_id, payload) => {
|
ProtocolAction::DeliverApp(_stream_id, payload) => {
|
||||||
if let Ok(msg) = ostp_core::relay::RelayMessage::decode(&payload) {
|
let _ = server_stream.write_all(&payload).await;
|
||||||
match msg {
|
|
||||||
ostp_core::relay::RelayMessage::Data(data) => {
|
|
||||||
let _ = server_stream.write_all(&data).await;
|
|
||||||
}
|
|
||||||
ostp_core::relay::RelayMessage::ConnectOk => {
|
|
||||||
tracing::debug!("TCP Connection established successfully");
|
|
||||||
}
|
|
||||||
ostp_core::relay::RelayMessage::Error(err) => {
|
|
||||||
tracing::warn!("Server returned TCP connection error: {}", err);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
ProtocolAction::Multiple(actions) => {
|
ProtocolAction::Multiple(actions) => {
|
||||||
for a in actions {
|
for a in actions {
|
||||||
Box::pin(handle_action(a, transport, server_stream)).await;
|
match a {
|
||||||
|
ProtocolAction::SendDatagram(data) => { let _ = transport.send(&data).await; }
|
||||||
|
ProtocolAction::DeliverApp(_stream_id, payload) => { let _ = server_stream.write_all(&payload).await; }
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inspect a ProtocolAction for ConnectOk / Error relay messages.
|
|
||||||
/// Returns Some(true) on ConnectOk, Some(false) on Error, None if neither.
|
|
||||||
/// Works recursively through Multiple actions.
|
|
||||||
fn check_connect_result(action: &ProtocolAction) -> Option<bool> {
|
|
||||||
match action {
|
|
||||||
ProtocolAction::DeliverApp(_stream_id, payload) => {
|
|
||||||
if let Ok(msg) = ostp_core::relay::RelayMessage::decode(payload) {
|
|
||||||
match msg {
|
|
||||||
ostp_core::relay::RelayMessage::ConnectOk => return Some(true),
|
|
||||||
ostp_core::relay::RelayMessage::Error(_) => return Some(false),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
ProtocolAction::Multiple(actions) => {
|
|
||||||
for a in actions {
|
|
||||||
if let Some(result) = check_connect_result(a) {
|
|
||||||
return Some(result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -126,6 +126,7 @@ pub fn get_process_name_from_port(port: u16) -> Option<String> {
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io::{BufRead, BufReader};
|
use std::io::{BufRead, BufReader};
|
||||||
|
|
||||||
|
let mut target_inode = None;
|
||||||
let hex_port = format!("{:04X}", port);
|
let hex_port = format!("{:04X}", port);
|
||||||
|
|
||||||
let check_net_file = |path: &str| -> Option<u64> {
|
let check_net_file = |path: &str| -> Option<u64> {
|
||||||
|
|
@ -145,11 +146,12 @@ pub fn get_process_name_from_port(port: u16) -> Option<String> {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
let target_inode = check_net_file("/proc/net/tcp")
|
target_inode = check_net_file("/proc/net/tcp")
|
||||||
.or_else(|| check_net_file("/proc/net/tcp6"))
|
.or_else(|| check_net_file("/proc/net/tcp6"))
|
||||||
.or_else(|| check_net_file("/proc/net/udp"))
|
.or_else(|| check_net_file("/proc/net/udp"))
|
||||||
.or_else(|| check_net_file("/proc/net/udp6"))?;
|
.or_else(|| check_net_file("/proc/net/udp6"));
|
||||||
|
|
||||||
|
let target_inode = target_inode?;
|
||||||
let socket_str = format!("socket:[{}]", target_inode);
|
let socket_str = format!("socket:[{}]", target_inode);
|
||||||
|
|
||||||
for entry in fs::read_dir("/proc").ok()?.filter_map(Result::ok) {
|
for entry in fs::read_dir("/proc").ok()?.filter_map(Result::ok) {
|
||||||
|
|
|
||||||
|
|
@ -17,5 +17,3 @@ sha2.workspace = true
|
||||||
hmac.workspace = true
|
hmac.workspace = true
|
||||||
x25519-dalek = { version = "2.0.1", features = ["static_secrets"] }
|
x25519-dalek = { version = "2.0.1", features = ["static_secrets"] }
|
||||||
hkdf = "0.12.0"
|
hkdf = "0.12.0"
|
||||||
tokio.workspace = true
|
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
|
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
|
||||||
use std::io::{Cursor, Read};
|
use std::io::{Cursor, Read, Write};
|
||||||
|
|
||||||
const BASE32_ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz234567";
|
const BASE32_ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz234567";
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,94 +0,0 @@
|
||||||
use std::time::Duration;
|
|
||||||
use tokio::time::Instant;
|
|
||||||
use crate::dns::{DnsPacket, DnsRecordType, encode_payload_to_domain};
|
|
||||||
use rand::Rng;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone)]
|
|
||||||
pub struct DnsProbeResult {
|
|
||||||
pub name: String,
|
|
||||||
pub ip: String,
|
|
||||||
pub latency_ms: Option<u64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
const PUBLIC_DNS_SERVERS: &[(&str, &str)] = &[
|
|
||||||
("Cloudflare", "1.1.1.1"),
|
|
||||||
("Cloudflare2", "1.0.0.1"),
|
|
||||||
("Google", "8.8.8.8"),
|
|
||||||
("Google2", "8.8.4.4"),
|
|
||||||
("Quad9", "9.9.9.9"),
|
|
||||||
("AdGuard", "94.140.14.14"),
|
|
||||||
("Yandex", "77.88.8.8"),
|
|
||||||
("Yandex2", "77.88.8.1"),
|
|
||||||
("SkyDNS", "193.58.251.251"),
|
|
||||||
("AliDNS", "223.5.5.5"),
|
|
||||||
("Tencent", "119.29.29.29"),
|
|
||||||
("114DNS", "114.114.114.114"),
|
|
||||||
("Shecan", "178.22.122.100"),
|
|
||||||
("Electro", "78.157.42.100"),
|
|
||||||
("Begzar", "185.55.226.26"),
|
|
||||||
];
|
|
||||||
|
|
||||||
async fn probe_resolver(domain: &str, resolver_ip: &str) -> Option<u64> {
|
|
||||||
let (probe_bytes, id) = {
|
|
||||||
let mut rng = rand::thread_rng();
|
|
||||||
let probe_bytes: [u8; 4] = rng.gen();
|
|
||||||
let id: u16 = rng.gen();
|
|
||||||
(probe_bytes, id)
|
|
||||||
};
|
|
||||||
|
|
||||||
let fqdn = encode_payload_to_domain(&probe_bytes, domain);
|
|
||||||
let qtype = if rand::thread_rng().gen_bool(0.5) { DnsRecordType::TXT } else { DnsRecordType::NULL };
|
|
||||||
let packet = DnsPacket::new_query(id, &fqdn, qtype);
|
|
||||||
let encoded = packet.encode();
|
|
||||||
|
|
||||||
let sock = tokio::net::UdpSocket::bind("0.0.0.0:0").await.ok()?;
|
|
||||||
sock.connect(format!("{}:53", resolver_ip)).await.ok()?;
|
|
||||||
|
|
||||||
let start = Instant::now();
|
|
||||||
sock.send(&encoded).await.ok()?;
|
|
||||||
|
|
||||||
let mut buf = [0u8; 4096];
|
|
||||||
match tokio::time::timeout(Duration::from_secs(2), sock.recv(&mut buf)).await {
|
|
||||||
Ok(Ok(n)) => {
|
|
||||||
if let Some(resp) = DnsPacket::decode(&buf[..n]) {
|
|
||||||
// Check if RCODE == 0 (NOERROR) and it has answers
|
|
||||||
let rcode = resp.flags & 0x000F;
|
|
||||||
if rcode == 0 && !resp.answers.is_empty() {
|
|
||||||
return Some(start.elapsed().as_millis() as u64);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
},
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn run_dns_prober(domain: &str) -> Result<Vec<DnsProbeResult>, String> {
|
|
||||||
if domain.is_empty() {
|
|
||||||
return Err("Please enter the tunnel domain first (e.g. tunnel.myvpn.com)".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
let tasks: Vec<_> = PUBLIC_DNS_SERVERS
|
|
||||||
.iter()
|
|
||||||
.map(|(name, ip)| {
|
|
||||||
let domain = domain.to_string();
|
|
||||||
let name = name.to_string();
|
|
||||||
let ip = ip.to_string();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let latency_ms = probe_resolver(&domain, &ip).await;
|
|
||||||
DnsProbeResult { name, ip, latency_ms }
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let mut results = Vec::with_capacity(tasks.len());
|
|
||||||
for task in tasks {
|
|
||||||
if let Ok(r) = task.await {
|
|
||||||
results.push(r);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
results.sort_by_key(|r| r.latency_ms.unwrap_or(u64::MAX));
|
|
||||||
Ok(results)
|
|
||||||
}
|
|
||||||
|
|
@ -5,7 +5,6 @@ pub mod protocol;
|
||||||
pub mod relay;
|
pub mod relay;
|
||||||
pub mod resumption;
|
pub mod resumption;
|
||||||
pub mod dns;
|
pub mod dns;
|
||||||
pub mod dns_prober;
|
|
||||||
|
|
||||||
pub use crypto::NoiseRole;
|
pub use crypto::NoiseRole;
|
||||||
pub use framing::{TrafficProfile, PaddingStrategy};
|
pub use framing::{TrafficProfile, PaddingStrategy};
|
||||||
|
|
|
||||||
|
|
@ -392,20 +392,12 @@ impl ProtocolMachine {
|
||||||
self.last_recv_advance = Instant::now();
|
self.last_recv_advance = Instant::now();
|
||||||
} else {
|
} else {
|
||||||
// Gap detected
|
// Gap detected
|
||||||
if self.reorder_buffer.len() >= self.max_reorder_buffer {
|
if self.reorder_buffer.len() < self.max_reorder_buffer {
|
||||||
tracing::warn!("Reorder buffer full ({}/{}), dropping new frame nonce={} to wait for recovery of nonce={}",
|
self.reorder_buffer.insert(nonce, action);
|
||||||
self.reorder_buffer.len(), self.max_reorder_buffer, nonce, self.expected_recv_nonce
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if nonce >= self.expected_recv_nonce {
|
|
||||||
if self.reorder_buffer.len() < self.max_reorder_buffer {
|
|
||||||
self.reorder_buffer.insert(nonce, action);
|
|
||||||
} else {
|
|
||||||
tracing::warn!("Reorder buffer still full after gap recovery, dropping frame nonce={}", nonce);
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
tracing::debug!("Frame nonce={} arrived too late after gap recovery, dropping", nonce);
|
tracing::warn!("Reorder buffer full ({}/{}), dropping frame nonce={}",
|
||||||
|
self.reorder_buffer.len(), self.max_reorder_buffer, nonce
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rate-limited NACK: send at most once per 30ms to prevent retransmit storms.
|
// Rate-limited NACK: send at most once per 30ms to prevent retransmit storms.
|
||||||
|
|
@ -519,6 +511,32 @@ impl ProtocolMachine {
|
||||||
fn handle_tick(&mut self) -> Result<ProtocolAction, ProtocolError> {
|
fn handle_tick(&mut self) -> Result<ProtocolAction, ProtocolError> {
|
||||||
let mut actions = Vec::new();
|
let mut actions = Vec::new();
|
||||||
|
|
||||||
|
// ── Gap Recovery ──────────────────────────────────────────────
|
||||||
|
// If expected_recv_nonce hasn't advanced for 500ms+ and there
|
||||||
|
// are buffered frames waiting, the sender likely evicted the lost
|
||||||
|
// frame from sent_history. Skip the gap to restore data flow.
|
||||||
|
// This trades a small amount of data loss for connection liveness.
|
||||||
|
if !self.reorder_buffer.is_empty()
|
||||||
|
&& self.last_recv_advance.elapsed() > Duration::from_millis(500)
|
||||||
|
{
|
||||||
|
if let Some(&first_buffered) = self.reorder_buffer.keys().next() {
|
||||||
|
let skipped = first_buffered.saturating_sub(self.expected_recv_nonce);
|
||||||
|
self.expected_recv_nonce = first_buffered;
|
||||||
|
self.last_recv_advance = Instant::now();
|
||||||
|
|
||||||
|
let mut delivered = 0u64;
|
||||||
|
while let Some(buffered_action) = self.reorder_buffer.remove(&self.expected_recv_nonce) {
|
||||||
|
actions.push(buffered_action);
|
||||||
|
self.expected_recv_nonce = self.expected_recv_nonce.saturating_add(1);
|
||||||
|
delivered += 1;
|
||||||
|
}
|
||||||
|
self.ack_pending = true;
|
||||||
|
tracing::debug!("Gap recovery: skipped {} lost frames, delivered {} buffered frames (reorder_buf={})",
|
||||||
|
skipped, delivered, self.reorder_buffer.len()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ── Pending ACK flush ─────────────────────────────────────────
|
// ── Pending ACK flush ─────────────────────────────────────────
|
||||||
if let Some(ack_frame) = self.build_ack_if_due()? {
|
if let Some(ack_frame) = self.build_ack_if_due()? {
|
||||||
actions.push(ProtocolAction::SendDatagram(ack_frame));
|
actions.push(ProtocolAction::SendDatagram(ack_frame));
|
||||||
|
|
|
||||||
|
|
@ -95,15 +95,6 @@ class MainActivity : FlutterActivity() {
|
||||||
result.error("ERROR", e.message, null)
|
result.error("ERROR", e.message, null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"runDnsProber" -> {
|
|
||||||
try {
|
|
||||||
val domain = call.argument<String>("domain") ?: "example.com"
|
|
||||||
val json = net.ostp.client.OstpClientSdk.nativeRunDnsProber(domain)
|
|
||||||
result.success(json)
|
|
||||||
} catch (e: Throwable) {
|
|
||||||
result.error("ERROR", e.message, null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"getInstalledApps" -> {
|
"getInstalledApps" -> {
|
||||||
try {
|
try {
|
||||||
val pm = packageManager
|
val pm = packageManager
|
||||||
|
|
|
||||||
|
|
@ -50,8 +50,4 @@ object OstpClientSdk {
|
||||||
@Keep
|
@Keep
|
||||||
@JvmStatic
|
@JvmStatic
|
||||||
external fun notifyNetworkChanged()
|
external fun notifyNetworkChanged()
|
||||||
|
|
||||||
@Keep
|
|
||||||
@JvmStatic
|
|
||||||
external fun nativeRunDnsProber(domain: String): String
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
Before Width: | Height: | Size: 22 KiB |
|
|
@ -26,11 +26,11 @@ class OstpApp extends StatelessWidget {
|
||||||
debugShowCheckedModeBanner: false,
|
debugShowCheckedModeBanner: false,
|
||||||
theme: ThemeData(
|
theme: ThemeData(
|
||||||
brightness: Brightness.dark,
|
brightness: Brightness.dark,
|
||||||
scaffoldBackgroundColor: const Color(0xFF030303),
|
scaffoldBackgroundColor: const Color(0xFF08080F),
|
||||||
colorScheme: const ColorScheme.dark(
|
colorScheme: const ColorScheme.dark(
|
||||||
primary: Color(0xFFF9FAFB),
|
primary: Color(0xFF6C72FF),
|
||||||
secondary: Color(0xFF10B981),
|
secondary: Color(0xFF22D3A5),
|
||||||
surface: Color(0xFF09090B),
|
surface: Color(0xFF151522),
|
||||||
),
|
),
|
||||||
fontFamily: 'Inter',
|
fontFamily: 'Inter',
|
||||||
useMaterial3: true,
|
useMaterial3: true,
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@ import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||||
import 'package:flutter_svg/flutter_svg.dart';
|
|
||||||
import '../models/connection_state_enum.dart';
|
import '../models/connection_state_enum.dart';
|
||||||
import 'settings_screen.dart';
|
import 'settings_screen.dart';
|
||||||
import 'logs_screen.dart';
|
import 'logs_screen.dart';
|
||||||
|
|
@ -518,16 +517,31 @@ class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
body: Stack(
|
body: Stack(
|
||||||
children: [
|
children: [
|
||||||
Center(
|
Positioned(
|
||||||
child: Opacity(
|
top: -150, right: -100,
|
||||||
opacity: theme.brightness == Brightness.dark ? 0.05 : 0.06,
|
child: Container(
|
||||||
child: SvgPicture.asset(
|
width: 400, height: 400,
|
||||||
'assets/logo.svg',
|
decoration: BoxDecoration(
|
||||||
width: MediaQuery.of(context).size.width * 0.8,
|
shape: BoxShape.circle,
|
||||||
fit: BoxFit.contain,
|
color: theme.colorScheme.primary.withOpacity(0.15),
|
||||||
colorFilter: theme.brightness == Brightness.light
|
),
|
||||||
? const ColorFilter.mode(Colors.black, BlendMode.srcIn)
|
child: BackdropFilter(
|
||||||
: null,
|
filter: ImageFilter.blur(sigmaX: 100, sigmaY: 100),
|
||||||
|
child: Container(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Positioned(
|
||||||
|
bottom: -100, left: -100,
|
||||||
|
child: Container(
|
||||||
|
width: 350, height: 350,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
color: theme.colorScheme.secondary.withOpacity(0.1),
|
||||||
|
),
|
||||||
|
child: BackdropFilter(
|
||||||
|
filter: ImageFilter.blur(sigmaX: 100, sigmaY: 100),
|
||||||
|
child: Container(),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||||
|
|
||||||
bool _obscureKey = true;
|
bool _obscureKey = true;
|
||||||
bool _debugMode = false;
|
bool _debugMode = false;
|
||||||
late TextEditingController _dnsRegionCtrl;
|
String _dnsRegion = 'Global';
|
||||||
String _transportMode = 'udp'; // 'udp' | 'uot'
|
String _transportMode = 'udp'; // 'udp' | 'uot'
|
||||||
String _tunStack = 'ostp'; // 'system' | 'ostp'
|
String _tunStack = 'ostp'; // 'system' | 'ostp'
|
||||||
bool _muxEnabled = false;
|
bool _muxEnabled = false;
|
||||||
|
|
@ -58,9 +58,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||||
_ipsCtrl = TextEditingController(text: widget.prefs.getString('ex_ips') ?? '');
|
_ipsCtrl = TextEditingController(text: widget.prefs.getString('ex_ips') ?? '');
|
||||||
_processesCtrl = TextEditingController(text: widget.prefs.getString('ex_processes') ?? '');
|
_processesCtrl = TextEditingController(text: widget.prefs.getString('ex_processes') ?? '');
|
||||||
_dnsDomainCtrl = TextEditingController(text: widget.prefs.getString('dns_domain') ?? '');
|
_dnsDomainCtrl = TextEditingController(text: widget.prefs.getString('dns_domain') ?? '');
|
||||||
_dnsRegionCtrl = TextEditingController(text: widget.prefs.getString('dns_region') ?? '1.1.1.1');
|
_pbkCtrl = TextEditingController(text: widget.prefs.getString('pbk') ?? '');
|
||||||
_pbkCtrl = TextEditingController(text: widget.prefs.getString('tun_pbk') ?? '');
|
|
||||||
_sidCtrl = TextEditingController(text: widget.prefs.getString('sid') ?? '');
|
_sidCtrl = TextEditingController(text: widget.prefs.getString('sid') ?? '');
|
||||||
|
_dnsRegion = widget.prefs.getString('dns_region') ?? 'Global';
|
||||||
_transportMode = widget.prefs.getString('transport_mode') ?? 'udp';
|
_transportMode = widget.prefs.getString('transport_mode') ?? 'udp';
|
||||||
_tunStack = widget.prefs.getString('tun_stack') ?? 'ostp';
|
_tunStack = widget.prefs.getString('tun_stack') ?? 'ostp';
|
||||||
_debugMode = widget.prefs.getBool('debug_mode') ?? false;
|
_debugMode = widget.prefs.getBool('debug_mode') ?? false;
|
||||||
|
|
@ -81,7 +81,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||||
_ipsCtrl.dispose();
|
_ipsCtrl.dispose();
|
||||||
_processesCtrl.dispose();
|
_processesCtrl.dispose();
|
||||||
_dnsDomainCtrl.dispose();
|
_dnsDomainCtrl.dispose();
|
||||||
_dnsRegionCtrl.dispose();
|
|
||||||
_pbkCtrl.dispose();
|
_pbkCtrl.dispose();
|
||||||
_sidCtrl.dispose();
|
_sidCtrl.dispose();
|
||||||
_muxSessionsCtrl.dispose();
|
_muxSessionsCtrl.dispose();
|
||||||
|
|
@ -98,11 +97,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||||
widget.prefs.setString('ex_ips', _ipsCtrl.text.trim());
|
widget.prefs.setString('ex_ips', _ipsCtrl.text.trim());
|
||||||
widget.prefs.setString('ex_processes', _processesCtrl.text.trim());
|
widget.prefs.setString('ex_processes', _processesCtrl.text.trim());
|
||||||
widget.prefs.setBool('debug_mode', _debugMode);
|
widget.prefs.setBool('debug_mode', _debugMode);
|
||||||
|
widget.prefs.setString('dns_region', _dnsRegion);
|
||||||
widget.prefs.setString('transport_mode', _transportMode);
|
widget.prefs.setString('transport_mode', _transportMode);
|
||||||
widget.prefs.setString('tun_stack', _tunStack);
|
widget.prefs.setString('tun_stack', _tunStack);
|
||||||
widget.prefs.setString('dns_domain', _dnsDomainCtrl.text.trim());
|
widget.prefs.setString('dns_domain', _dnsDomainCtrl.text.trim());
|
||||||
widget.prefs.setString('dns_region', _dnsRegionCtrl.text.trim());
|
widget.prefs.setString('pbk', _pbkCtrl.text.trim());
|
||||||
widget.prefs.setString('tun_pbk', _pbkCtrl.text.trim());
|
|
||||||
widget.prefs.setString('sid', _sidCtrl.text.trim());
|
widget.prefs.setString('sid', _sidCtrl.text.trim());
|
||||||
widget.prefs.setBool('mux_enabled', _muxEnabled);
|
widget.prefs.setBool('mux_enabled', _muxEnabled);
|
||||||
widget.prefs.setString('mux_sessions', _muxSessionsCtrl.text.trim());
|
widget.prefs.setString('mux_sessions', _muxSessionsCtrl.text.trim());
|
||||||
|
|
@ -238,7 +237,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||||
_serverCtrl.text = host;
|
_serverCtrl.text = host;
|
||||||
_keyCtrl.text = key;
|
_keyCtrl.text = key;
|
||||||
_dnsDomainCtrl.text = uri.queryParameters['domain'] ?? '';
|
_dnsDomainCtrl.text = uri.queryParameters['domain'] ?? '';
|
||||||
_dnsRegionCtrl.text = uri.queryParameters['resolver'] ?? '1.1.1.1';
|
_dnsRegion = uri.queryParameters['region'] ?? 'Global';
|
||||||
|
|
||||||
final type = uri.queryParameters['type'];
|
final type = uri.queryParameters['type'];
|
||||||
_transportMode = type == 'tcp' || type == 'http' ? 'uot' : (type == 'dns' ? 'dns' : 'udp');
|
_transportMode = type == 'tcp' || type == 'http' ? 'uot' : (type == 'dns' ? 'dns' : 'udp');
|
||||||
|
|
@ -350,27 +349,30 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
_buildTextField('Domain (Points to Server)', _dnsDomainCtrl, hint: 'tunnel.myvpn.com'),
|
_buildTextField('Domain (Points to Server)', _dnsDomainCtrl, hint: 'tunnel.myvpn.com'),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Row(
|
DropdownButtonFormField<String>(
|
||||||
children: [
|
value: _dnsRegion,
|
||||||
Expanded(
|
dropdownColor: const Color(0xFF1E1E2C),
|
||||||
child: _buildTextField('DNS Resolver Server', _dnsRegionCtrl, hint: '1.1.1.1'),
|
style: const TextStyle(color: Colors.white, fontSize: 14),
|
||||||
),
|
decoration: InputDecoration(
|
||||||
const SizedBox(width: 8),
|
labelText: 'DNS Resolver Region',
|
||||||
Padding(
|
labelStyle: const TextStyle(color: Colors.white54, fontSize: 13),
|
||||||
padding: const EdgeInsets.only(top: 24.0),
|
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||||
child: ElevatedButton(
|
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||||
onPressed: _showDnsProberDialog,
|
),
|
||||||
style: ElevatedButton.styleFrom(
|
items: ['Global', 'Russia', 'China', 'Iran'].map((String region) {
|
||||||
backgroundColor: Colors.orangeAccent.withOpacity(0.2),
|
return DropdownMenuItem<String>(
|
||||||
foregroundColor: Colors.orangeAccent,
|
value: region,
|
||||||
elevation: 0,
|
child: Text(region),
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
|
);
|
||||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
}).toList(),
|
||||||
),
|
onChanged: (String? newValue) {
|
||||||
child: const Text('PROBER', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 12)),
|
if (newValue != null) {
|
||||||
),
|
setState(() {
|
||||||
)
|
_dnsRegion = newValue;
|
||||||
],
|
_saveSettings();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|
@ -527,9 +529,8 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||||
if (_dnsDomainCtrl.text.trim().isNotEmpty) {
|
if (_dnsDomainCtrl.text.trim().isNotEmpty) {
|
||||||
queryParams.add('domain=${Uri.encodeComponent(_dnsDomainCtrl.text.trim())}');
|
queryParams.add('domain=${Uri.encodeComponent(_dnsDomainCtrl.text.trim())}');
|
||||||
}
|
}
|
||||||
final resolver = _dnsRegionCtrl.text.trim();
|
if (_dnsRegion != 'Global') {
|
||||||
if (resolver.isNotEmpty && resolver != '1.1.1.1') {
|
queryParams.add('region=${Uri.encodeComponent(_dnsRegion)}');
|
||||||
queryParams.add('resolver=${Uri.encodeComponent(resolver)}');
|
|
||||||
}
|
}
|
||||||
if (_pbkCtrl.text.trim().isNotEmpty) {
|
if (_pbkCtrl.text.trim().isNotEmpty) {
|
||||||
queryParams.add('pbk=${Uri.encodeComponent(_pbkCtrl.text.trim())}');
|
queryParams.add('pbk=${Uri.encodeComponent(_pbkCtrl.text.trim())}');
|
||||||
|
|
@ -602,97 +603,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _showDnsProberDialog() async {
|
|
||||||
const channel = MethodChannel('com.ospab.ostp/vpn');
|
|
||||||
showDialog(
|
|
||||||
context: context,
|
|
||||||
barrierDismissible: false,
|
|
||||||
builder: (context) {
|
|
||||||
return StatefulBuilder(
|
|
||||||
builder: (context, setModalState) {
|
|
||||||
return AlertDialog(
|
|
||||||
backgroundColor: Theme.of(context).colorScheme.surface,
|
|
||||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
|
|
||||||
title: const Text('DNS Prober', textAlign: TextAlign.center),
|
|
||||||
content: FutureBuilder<String?>(
|
|
||||||
future: channel.invokeMethod<String>('runDnsProber', {'domain': _dnsDomainCtrl.text.trim()}),
|
|
||||||
builder: (context, snapshot) {
|
|
||||||
if (snapshot.connectionState == ConnectionState.waiting) {
|
|
||||||
return const Column(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
CircularProgressIndicator(),
|
|
||||||
SizedBox(height: 16),
|
|
||||||
Text('Sending real tunnel probes...', style: TextStyle(color: Colors.white54, fontSize: 13), textAlign: TextAlign.center),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (snapshot.hasError || !snapshot.hasData) {
|
|
||||||
return Text('Error: ${snapshot.error}', style: const TextStyle(color: Colors.redAccent));
|
|
||||||
}
|
|
||||||
|
|
||||||
List<dynamic> results = [];
|
|
||||||
try {
|
|
||||||
results = jsonDecode(snapshot.data!);
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
if (results.isEmpty) {
|
|
||||||
return const Text('No results or all timed out.', style: TextStyle(color: Colors.redAccent));
|
|
||||||
}
|
|
||||||
|
|
||||||
return SizedBox(
|
|
||||||
width: double.maxFinite,
|
|
||||||
child: ListView.builder(
|
|
||||||
shrinkWrap: true,
|
|
||||||
itemCount: results.length,
|
|
||||||
itemBuilder: (context, index) {
|
|
||||||
final res = results[index];
|
|
||||||
final name = res['name'] ?? '';
|
|
||||||
final ip = res['ip'] ?? '';
|
|
||||||
final latency = res['latency_ms'];
|
|
||||||
|
|
||||||
final isBest = index == 0 && latency != null;
|
|
||||||
|
|
||||||
return ListTile(
|
|
||||||
onTap: latency != null ? () {
|
|
||||||
setState(() {
|
|
||||||
_dnsRegionCtrl.text = ip;
|
|
||||||
_saveSettings();
|
|
||||||
});
|
|
||||||
Navigator.pop(context);
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('DNS set to $ip')));
|
|
||||||
} : null,
|
|
||||||
title: Text('${isBest ? '⭐ ' : ''}$name', style: const TextStyle(fontSize: 14)),
|
|
||||||
subtitle: Text(ip, style: const TextStyle(fontSize: 12, color: Colors.white54)),
|
|
||||||
trailing: Text(
|
|
||||||
latency != null ? '$latency ms' : 'TIMEOUT',
|
|
||||||
style: TextStyle(
|
|
||||||
color: latency == null ? Colors.redAccent : (latency < 100 ? Colors.greenAccent : Colors.orangeAccent),
|
|
||||||
fontWeight: FontWeight.bold,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
tileColor: isBest ? Colors.blueAccent.withOpacity(0.1) : null,
|
|
||||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
|
||||||
actions: [
|
|
||||||
TextButton(
|
|
||||||
onPressed: () => Navigator.pop(context),
|
|
||||||
child: const Text('Close'),
|
|
||||||
)
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _checkForUpdates() async {
|
Future<void> _checkForUpdates() async {
|
||||||
if (_isCheckingUpdates) return;
|
if (_isCheckingUpdates) return;
|
||||||
setState(() { _isCheckingUpdates = true; });
|
setState(() { _isCheckingUpdates = true; });
|
||||||
|
|
|
||||||
|
|
@ -134,14 +134,6 @@ packages:
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "6.0.0"
|
version: "6.0.0"
|
||||||
flutter_svg:
|
|
||||||
dependency: "direct main"
|
|
||||||
description:
|
|
||||||
name: flutter_svg
|
|
||||||
sha256: "35882981abcbfb8c15b286f0cd690ff25bac12d95eff3e25ee207f37d4c42e7f"
|
|
||||||
url: "https://pub.dev"
|
|
||||||
source: hosted
|
|
||||||
version: "2.3.0"
|
|
||||||
flutter_test:
|
flutter_test:
|
||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description: flutter
|
description: flutter
|
||||||
|
|
@ -280,14 +272,6 @@ packages:
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.9.1"
|
version: "1.9.1"
|
||||||
path_parsing:
|
|
||||||
dependency: transitive
|
|
||||||
description:
|
|
||||||
name: path_parsing
|
|
||||||
sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca"
|
|
||||||
url: "https://pub.dev"
|
|
||||||
source: hosted
|
|
||||||
version: "1.1.0"
|
|
||||||
path_provider_linux:
|
path_provider_linux:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|
@ -597,30 +581,6 @@ packages:
|
||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.1.5"
|
version: "3.1.5"
|
||||||
vector_graphics:
|
|
||||||
dependency: transitive
|
|
||||||
description:
|
|
||||||
name: vector_graphics
|
|
||||||
sha256: "2306c03da2ba81724afeb589c351ebbc0aa7d86005925be8f8735856dbe5e42d"
|
|
||||||
url: "https://pub.dev"
|
|
||||||
source: hosted
|
|
||||||
version: "1.2.2"
|
|
||||||
vector_graphics_codec:
|
|
||||||
dependency: transitive
|
|
||||||
description:
|
|
||||||
name: vector_graphics_codec
|
|
||||||
sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146"
|
|
||||||
url: "https://pub.dev"
|
|
||||||
source: hosted
|
|
||||||
version: "1.1.13"
|
|
||||||
vector_graphics_compiler:
|
|
||||||
dependency: transitive
|
|
||||||
description:
|
|
||||||
name: vector_graphics_compiler
|
|
||||||
sha256: "142a9146f447d15b10bdc00e21d5f4d83e5b32bb5f8f8f5a04c75311344923a3"
|
|
||||||
url: "https://pub.dev"
|
|
||||||
source: hosted
|
|
||||||
version: "1.2.6"
|
|
||||||
vector_math:
|
vector_math:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
# In Windows, build-name is used as the major, minor, and patch parts
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
# of the product and file versions while build-number is used as the build suffix.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 0.3.12+25
|
version: 0.3.6+19
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.11.4
|
sdk: ^3.11.4
|
||||||
|
|
@ -34,7 +34,6 @@ dependencies:
|
||||||
# The following adds the Cupertino Icons font to your application.
|
# The following adds the Cupertino Icons font to your application.
|
||||||
# Use with the CupertinoIcons class for iOS style icons.
|
# Use with the CupertinoIcons class for iOS style icons.
|
||||||
cupertino_icons: ^1.0.8
|
cupertino_icons: ^1.0.8
|
||||||
flutter_svg: ^2.0.10
|
|
||||||
shared_preferences: ^2.5.5
|
shared_preferences: ^2.5.5
|
||||||
mobile_scanner: ^5.0.0
|
mobile_scanner: ^5.0.0
|
||||||
window_manager: ^0.5.1
|
window_manager: ^0.5.1
|
||||||
|
|
@ -73,8 +72,9 @@ flutter:
|
||||||
uses-material-design: true
|
uses-material-design: true
|
||||||
|
|
||||||
# To add assets to your application, add an assets section, like this:
|
# To add assets to your application, add an assets section, like this:
|
||||||
assets:
|
# assets:
|
||||||
- assets/logo.svg
|
# - images/a_dot_burr.jpeg
|
||||||
|
# - images/a_dot_ham.jpeg
|
||||||
|
|
||||||
# An image asset can refer to one or more resolution-specific "variants", see
|
# An image asset can refer to one or more resolution-specific "variants", see
|
||||||
# https://flutter.dev/to/resolution-aware-images
|
# https://flutter.dev/to/resolution-aware-images
|
||||||
|
|
|
||||||
|
|
@ -2665,7 +2665,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-client"
|
name = "ostp-client"
|
||||||
version = "0.3.12"
|
version = "0.2.98"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
|
|
@ -2700,20 +2700,17 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-core"
|
name = "ostp-core"
|
||||||
version = "0.3.12"
|
version = "0.2.98"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"byteorder",
|
|
||||||
"bytes",
|
"bytes",
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
"hkdf",
|
"hkdf",
|
||||||
"hmac",
|
"hmac",
|
||||||
"rand",
|
"rand",
|
||||||
"serde",
|
|
||||||
"sha2",
|
"sha2",
|
||||||
"snow",
|
"snow",
|
||||||
"thiserror 1.0.69",
|
"thiserror 1.0.69",
|
||||||
"tokio",
|
|
||||||
"tracing",
|
"tracing",
|
||||||
"x25519-dalek",
|
"x25519-dalek",
|
||||||
]
|
]
|
||||||
|
|
@ -2723,16 +2720,12 @@ name = "ostp-gui"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"chacha20poly1305",
|
|
||||||
"hex",
|
|
||||||
"json_comments",
|
"json_comments",
|
||||||
"ostp-client",
|
"ostp-client",
|
||||||
"ostp-core",
|
|
||||||
"portable-atomic",
|
"portable-atomic",
|
||||||
"rand",
|
"rand",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-build",
|
"tauri-build",
|
||||||
"tauri-plugin-opener",
|
"tauri-plugin-opener",
|
||||||
|
|
@ -2742,7 +2735,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-tun"
|
name = "ostp-tun"
|
||||||
version = "0.3.12"
|
version = "0.2.98"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"libc",
|
"libc",
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,6 @@ tokio = { version = "1", features = ["full"] }
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
ostp-client = { path = "../../ostp-client" }
|
ostp-client = { path = "../../ostp-client" }
|
||||||
ostp-core = { path = "../../ostp-core" }
|
|
||||||
portable-atomic = "1"
|
portable-atomic = "1"
|
||||||
json_comments = "0.2"
|
json_comments = "0.2"
|
||||||
rand = "0.8"
|
rand = "0.8"
|
||||||
|
|
|
||||||
|
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 4.5 KiB |
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 9.6 KiB |
|
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 4.4 KiB After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 7.7 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 5.1 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 5.4 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 4.8 KiB After Width: | Height: | Size: 2.5 KiB |
|
Before Width: | Height: | Size: 6.3 KiB After Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 6.0 KiB |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 2.5 KiB |
|
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 7.8 KiB After Width: | Height: | Size: 4.0 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 6.5 KiB After Width: | Height: | Size: 5.9 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 8.2 KiB |
|
Before Width: | Height: | Size: 6.2 KiB After Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 9.3 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 8.5 KiB |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 42 KiB After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 955 B After Width: | Height: | Size: 710 B |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 3.9 KiB After Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 3.9 KiB After Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 6.1 KiB After Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 5.6 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 5.6 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 8.7 KiB After Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 55 KiB |
|
Before Width: | Height: | Size: 8.7 KiB After Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 13 KiB After Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 5.3 KiB After Width: | Height: | Size: 2.9 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 6.1 KiB |
|
|
@ -6,15 +6,11 @@ description = "Enables access to core OSTP commands"
|
||||||
allow = [
|
allow = [
|
||||||
"start_tunnel",
|
"start_tunnel",
|
||||||
"stop_tunnel",
|
"stop_tunnel",
|
||||||
"reload_tunnel",
|
|
||||||
"get_tunnel_status",
|
"get_tunnel_status",
|
||||||
"get_metrics",
|
"get_metrics",
|
||||||
"get_config",
|
"get_config",
|
||||||
"save_config",
|
"save_config",
|
||||||
"get_wintun_install_path",
|
"get_wintun_install_path",
|
||||||
"set_autostart",
|
"set_autostart",
|
||||||
"get_autostart",
|
"get_autostart"
|
||||||
"list_running_processes",
|
|
||||||
"kill_auto_search",
|
|
||||||
"run_dns_prober"
|
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
use ostp_core::dns_prober::{run_dns_prober as core_run_dns_prober, DnsProbeResult};
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn run_dns_prober(domain: String) -> Result<Vec<DnsProbeResult>, String> {
|
|
||||||
core_run_dns_prober(&domain).await
|
|
||||||
}
|
|
||||||
|
|
@ -8,7 +8,6 @@ use portable_atomic::Ordering;
|
||||||
use tauri::Emitter;
|
use tauri::Emitter;
|
||||||
|
|
||||||
mod ipc_crypto;
|
mod ipc_crypto;
|
||||||
mod dns_prober;
|
|
||||||
|
|
||||||
// ── Config types ─────────────────────────────────────────────────────────────
|
// ── Config types ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
@ -779,7 +778,7 @@ static SINGLE_INSTANCE_LOCK: std::sync::OnceLock<std::net::TcpListener> = std::s
|
||||||
pub fn run() {
|
pub fn run() {
|
||||||
if let Ok(listener) = std::net::TcpListener::bind("127.0.0.1:49153") {
|
if let Ok(listener) = std::net::TcpListener::bind("127.0.0.1:49153") {
|
||||||
let _ = SINGLE_INSTANCE_LOCK.set(listener);
|
let _ = SINGLE_INSTANCE_LOCK.set(listener);
|
||||||
} else if !cfg!(debug_assertions) {
|
} else {
|
||||||
show_error_dialog("Приложение OSTP GUI уже запущено!");
|
show_error_dialog("Приложение OSTP GUI уже запущено!");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -875,7 +874,7 @@ pub fn run() {
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
})
|
})
|
||||||
.invoke_handler(tauri::generate_handler![start_tunnel, stop_tunnel, reload_tunnel, get_tunnel_status, get_metrics, get_config, save_config, get_wintun_install_path, set_autostart, get_autostart, list_running_processes, dns_prober::run_dns_prober])
|
.invoke_handler(tauri::generate_handler![start_tunnel, stop_tunnel, reload_tunnel, get_tunnel_status, get_metrics, get_config, save_config, get_wintun_install_path, set_autostart, get_autostart, list_running_processes])
|
||||||
.run(tauri::generate_context!())
|
.run(tauri::generate_context!())
|
||||||
.expect("error while running tauri application");
|
.expect("error while running tauri application");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "ostp-gui",
|
"productName": "ostp-gui",
|
||||||
"version": "0.3.12",
|
"version": "0.3.6",
|
||||||
"identifier": "com.ospab.ostp",
|
"identifier": "com.ospab.ostp",
|
||||||
"build": {
|
"build": {
|
||||||
"frontendDist": "../src"
|
"frontendDist": "../src"
|
||||||
|
|
|
||||||
|
Before Width: | Height: | Size: 22 KiB |
|
|
@ -12,9 +12,10 @@
|
||||||
<body>
|
<body>
|
||||||
<div class="app-root">
|
<div class="app-root">
|
||||||
|
|
||||||
<!-- Eagle Watermark -->
|
<!-- Ambient light blobs -->
|
||||||
<div class="watermark" aria-hidden="true">
|
<div class="ambient" aria-hidden="true">
|
||||||
<img src="assets/logo.svg" alt="" />
|
<div class="blob blob-1"></div>
|
||||||
|
<div class="blob blob-2"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ── HOME SCREEN ──────────────────────────────────────────── -->
|
<!-- ── HOME SCREEN ──────────────────────────────────────────── -->
|
||||||
|
|
@ -201,20 +202,24 @@
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="group-dns-proxy" style="display: none; flex-direction: column; gap: 14px;">
|
<div id="group-dns-proxy" style="display: none;">
|
||||||
<div class="field-group">
|
<div class="field-group">
|
||||||
<label class="field-label" for="in-dns-domain" style="color: var(--c-warning);" data-i18n="label_dns_domain">Domain (Points to Server)</label>
|
<label class="field-label" for="in-dns-domain" style="color: var(--c-warning);" data-i18n="label_dns_domain">Domain (Points to Server)</label>
|
||||||
<input id="in-dns-domain" class="field-input" type="text" placeholder="tunnel.myvpn.com" spellcheck="false" />
|
<input id="in-dns-domain" class="field-input" type="text" placeholder="tunnel.myvpn.com" spellcheck="false" />
|
||||||
|
<div style="font-size: 0.8rem; color: var(--c-sub); margin-top: 4px;">
|
||||||
|
<span data-i18n="dns_domain_hint">This is the "last resort" over public DNS servers. You need a domain pointing to your server (NS/A record).</span>
|
||||||
|
<span data-i18n="dns_guide">Detailed setup guide available in</span> <a href="https://github.com/ospab/ostp/wiki/DNS-Transport" target="_blank" style="color: var(--c-accent)" data-i18n="wiki_link">GitHub Wiki</a>.
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="field-group">
|
<div class="field-group">
|
||||||
<label class="field-label" for="in-dns-region" data-i18n="label_dns_region">DNS Resolver Server</label>
|
<label class="field-label" for="in-dns-region" data-i18n="label_dns_region">DNS Resolver Region (Prober)</label>
|
||||||
<div class="input-wrap">
|
<select id="in-dns-region" class="field-input">
|
||||||
<input id="in-dns-region" class="field-input" type="text" placeholder="1.1.1.1" spellcheck="false" />
|
<option value="Global" data-i18n="opt_global">Global (Cloudflare, Google, etc)</option>
|
||||||
<button id="btn-dns-prober" class="peek-btn" tabindex="-1" title="Find fastest DNS server" style="width:auto; padding: 0 8px; font-size: 0.7rem; color: var(--c-accent);">
|
<option value="Russia" data-i18n="opt_russia">Russia (Yandex, VK, etc)</option>
|
||||||
PROBER
|
<option value="China" data-i18n="opt_china">China (AliDNS, DNSPod, etc)</option>
|
||||||
</button>
|
<option value="Iran" data-i18n="opt_iran">Iran (Shatel, Electro, etc)</option>
|
||||||
</div>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
@ -375,23 +380,6 @@
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- DNS Prober Modal -->
|
|
||||||
<div id="dns-prober-modal" class="modal-overlay hidden">
|
|
||||||
<div class="modal-content" style="min-width: 300px; max-width: 420px;">
|
|
||||||
<h3 class="modal-title">DNS Prober</h3>
|
|
||||||
<p class="modal-text" style="font-size: 0.8rem; color: var(--c-txt-2); margin-bottom: 12px;">
|
|
||||||
Sends a real DNS tunnel probe through each resolver and measures the round-trip time to your server. The fastest one is selected automatically.
|
|
||||||
</p>
|
|
||||||
<div id="prober-status" style="font-size: 0.75rem; color: var(--c-accent); margin-bottom: 10px; min-height: 18px;"></div>
|
|
||||||
<div id="prober-list" style="display: flex; flex-direction: column; gap: 5px; max-height: 280px; overflow-y: auto;"></div>
|
|
||||||
<div class="modal-actions" style="margin-top: 16px;">
|
|
||||||
<button id="btn-prober-close" class="btn secondary">Close</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
<script type="module" src="main.js"></script>
|
<script type="module" src="main.js"></script>
|
||||||
|
|
|
||||||
|
|
@ -75,7 +75,7 @@ function bindSettingsInputs() {
|
||||||
if (inTransport) {
|
if (inTransport) {
|
||||||
inTransport.addEventListener('change', () => {
|
inTransport.addEventListener('change', () => {
|
||||||
if (inTransport.value === 'dns') {
|
if (inTransport.value === 'dns') {
|
||||||
groupDnsProxy.style.display = 'flex';
|
groupDnsProxy.style.display = 'block';
|
||||||
} else {
|
} else {
|
||||||
groupDnsProxy.style.display = 'none';
|
groupDnsProxy.style.display = 'none';
|
||||||
}
|
}
|
||||||
|
|
@ -88,86 +88,6 @@ const btnWintunCancel = $('btn-wintun-cancel');
|
||||||
const btnWintunOpen = $('btn-wintun-open');
|
const btnWintunOpen = $('btn-wintun-open');
|
||||||
const wintunInstallPath = $('wintun-install-path');
|
const wintunInstallPath = $('wintun-install-path');
|
||||||
|
|
||||||
const dnsProberModal = $('dns-prober-modal');
|
|
||||||
const proberStatus = $('prober-status');
|
|
||||||
const proberList = $('prober-list');
|
|
||||||
const btnProberClose = $('btn-prober-close');
|
|
||||||
const btnDnsProber = $('btn-dns-prober');
|
|
||||||
|
|
||||||
// ── DNS Prober ───────────────────────────────────────────────────────────────
|
|
||||||
async function openDnsProber() {
|
|
||||||
dnsProberModal.classList.remove('hidden');
|
|
||||||
proberList.innerHTML = '';
|
|
||||||
proberStatus.textContent = 'Running probes...';
|
|
||||||
|
|
||||||
const domain = inDnsDomain?.value?.trim() || 'example.com';
|
|
||||||
|
|
||||||
let results;
|
|
||||||
try {
|
|
||||||
results = await invoke('run_dns_prober', { domain });
|
|
||||||
} catch (err) {
|
|
||||||
proberStatus.textContent = 'Error: ' + err;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
proberList.innerHTML = '';
|
|
||||||
|
|
||||||
if (!results || results.length === 0) {
|
|
||||||
proberStatus.textContent = 'No results.';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let bestIp = null;
|
|
||||||
|
|
||||||
results.forEach((r, i) => {
|
|
||||||
const isBest = i === 0 && r.latency_ms != null;
|
|
||||||
if (isBest && !bestIp) bestIp = r.ip;
|
|
||||||
|
|
||||||
const row = document.createElement('div');
|
|
||||||
row.style.cssText = `
|
|
||||||
display: flex; align-items: center; justify-content: space-between;
|
|
||||||
padding: 6px 10px; border-radius: 6px; cursor: pointer;
|
|
||||||
background: ${isBest ? 'rgba(99,179,237,0.12)' : 'rgba(255,255,255,0.04)'};
|
|
||||||
border: 1px solid ${isBest ? 'rgba(99,179,237,0.35)' : 'transparent'};
|
|
||||||
transition: background 0.15s;
|
|
||||||
`;
|
|
||||||
|
|
||||||
const latText = r.latency_ms != null ? `${r.latency_ms} ms` : 'TIMEOUT';
|
|
||||||
const latColor = r.latency_ms == null ? '#f56565'
|
|
||||||
: r.latency_ms < 50 ? '#68d391'
|
|
||||||
: r.latency_ms < 150 ? '#f6e05e'
|
|
||||||
: '#fc8181';
|
|
||||||
|
|
||||||
row.innerHTML = `
|
|
||||||
<span style="font-size:0.78rem; color: var(--c-txt-1);">${isBest ? '⭐ ' : ''}${r.name}</span>
|
|
||||||
<span style="font-size:0.78rem; color: var(--c-txt-2);">${r.ip}</span>
|
|
||||||
<span style="font-size:0.78rem; font-weight:600; color:${latColor};">${latText}</span>
|
|
||||||
`;
|
|
||||||
|
|
||||||
if (r.latency_ms != null) {
|
|
||||||
row.addEventListener('click', () => {
|
|
||||||
inDnsRegion.value = r.ip;
|
|
||||||
scheduleAutoSave();
|
|
||||||
dnsProberModal.classList.add('hidden');
|
|
||||||
showToast('DNS server set to ' + r.ip, 'ok');
|
|
||||||
});
|
|
||||||
row.addEventListener('mouseenter', () => { row.style.background = 'rgba(99,179,237,0.18)'; });
|
|
||||||
row.addEventListener('mouseleave', () => { row.style.background = isBest ? 'rgba(99,179,237,0.12)' : 'rgba(255,255,255,0.04)'; });
|
|
||||||
}
|
|
||||||
|
|
||||||
proberList.appendChild(row);
|
|
||||||
});
|
|
||||||
|
|
||||||
if (bestIp) {
|
|
||||||
proberStatus.textContent = `✓ Best: ${bestIp} — click any row to select`;
|
|
||||||
// Auto-fill best
|
|
||||||
inDnsRegion.value = bestIp;
|
|
||||||
scheduleAutoSave();
|
|
||||||
} else {
|
|
||||||
proberStatus.textContent = 'All servers timed out.';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Tag-input state ───────────────────────────────────────────────────────────
|
// ── Tag-input state ───────────────────────────────────────────────────────────
|
||||||
// Map of tagId -> Set<string>
|
// Map of tagId -> Set<string>
|
||||||
const tagState = {
|
const tagState = {
|
||||||
|
|
@ -446,7 +366,7 @@ async function loadConfigIntoForm() {
|
||||||
inKey.value = ostpOut.access_key || '';
|
inKey.value = ostpOut.access_key || '';
|
||||||
inTransport.value = ostpOut.transport?.type || 'udp';
|
inTransport.value = ostpOut.transport?.type || 'udp';
|
||||||
if (inTransport.value === 'dns') {
|
if (inTransport.value === 'dns') {
|
||||||
groupDnsProxy.style.display = 'flex';
|
groupDnsProxy.style.display = 'block';
|
||||||
inDnsDomain.value = ostpOut.transport?.domain || '';
|
inDnsDomain.value = ostpOut.transport?.domain || '';
|
||||||
inDnsRegion.value = ostpOut.transport?.resolver || 'Global';
|
inDnsRegion.value = ostpOut.transport?.resolver || 'Global';
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -672,7 +592,6 @@ window.addEventListener('DOMContentLoaded', async () => {
|
||||||
applyTranslations();
|
applyTranslations();
|
||||||
setState('disconnected');
|
setState('disconnected');
|
||||||
updateKillSwitchVisibility();
|
updateKillSwitchVisibility();
|
||||||
bindSettingsInputs();
|
|
||||||
|
|
||||||
// Event wiring
|
// Event wiring
|
||||||
if (window.__TAURI__ && window.__TAURI__.event) {
|
if (window.__TAURI__ && window.__TAURI__.event) {
|
||||||
|
|
@ -818,22 +737,6 @@ window.addEventListener('DOMContentLoaded', async () => {
|
||||||
wintunModal.classList.add('hidden');
|
wintunModal.classList.add('hidden');
|
||||||
});
|
});
|
||||||
|
|
||||||
// DNS Prober modal
|
|
||||||
if (btnDnsProber) {
|
|
||||||
btnDnsProber.addEventListener('click', openDnsProber);
|
|
||||||
}
|
|
||||||
if (btnProberClose) {
|
|
||||||
btnProberClose.addEventListener('click', () => {
|
|
||||||
dnsProberModal.classList.add('hidden');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// Close prober on backdrop click
|
|
||||||
if (dnsProberModal) {
|
|
||||||
dnsProberModal.addEventListener('click', (e) => {
|
|
||||||
if (e.target === dnsProberModal) dnsProberModal.classList.add('hidden');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Open wintun.net link — handled natively by <a target="_blank">, but also wire as fallback
|
// Open wintun.net link — handled natively by <a target="_blank">, but also wire as fallback
|
||||||
if (btnWintunOpen && window.__TAURI__) {
|
if (btnWintunOpen && window.__TAURI__) {
|
||||||
btnWintunOpen.addEventListener('click', (e) => {
|
btnWintunOpen.addEventListener('click', (e) => {
|
||||||
|
|
|
||||||
|
|
@ -5,27 +5,27 @@
|
||||||
|
|
||||||
/* ── Tokens — Dark (default) ─────────────────────────────────────────────── */
|
/* ── Tokens — Dark (default) ─────────────────────────────────────────────── */
|
||||||
:root {
|
:root {
|
||||||
/* Colors - Dark (default) */
|
/* Colors */
|
||||||
--c-bg: #030303;
|
--c-bg: #08080f;
|
||||||
--c-surface: #09090b;
|
--c-surface: #0f0f1a;
|
||||||
--c-card: rgba(255,255,255,0.02);
|
--c-card: rgba(255,255,255,0.04);
|
||||||
--c-card-border: rgba(255,255,255,0.05);
|
--c-card-border: rgba(255,255,255,0.07);
|
||||||
|
|
||||||
--c-accent: #52525b;
|
--c-accent: #6c72ff;
|
||||||
--c-accent-2: #71717a;
|
--c-accent-2: #a78bfa;
|
||||||
--c-accent-glow: rgba(255,255,255,0.05);
|
--c-accent-glow: rgba(108,114,255,0.35);
|
||||||
--c-accent-dim: rgba(255,255,255,0.03);
|
--c-accent-dim: rgba(108,114,255,0.12);
|
||||||
|
|
||||||
--c-green: #10b981;
|
--c-green: #22d3a5;
|
||||||
--c-green-glow: rgba(16,185,129,0.25);
|
--c-green-glow: rgba(34,211,165,0.35);
|
||||||
--c-green-dim: rgba(16,185,129,0.10);
|
--c-green-dim: rgba(34,211,165,0.10);
|
||||||
|
|
||||||
--c-amber: #f59e0b;
|
--c-amber: #f59e0b;
|
||||||
--c-red: #ef4444;
|
--c-red: #f87171;
|
||||||
|
|
||||||
--c-txt-1: #fdfdfd;
|
--c-txt-1: #e2e4f0;
|
||||||
--c-txt-2: #a1a1aa;
|
--c-txt-2: #636882;
|
||||||
--c-txt-3: #52525b;
|
--c-txt-3: #343647;
|
||||||
|
|
||||||
/* Radii */
|
/* Radii */
|
||||||
--r-xs: 6px;
|
--r-xs: 6px;
|
||||||
|
|
@ -46,26 +46,26 @@
|
||||||
|
|
||||||
/* ── Tokens — Light theme override ────────────────────────────────────────── */
|
/* ── Tokens — Light theme override ────────────────────────────────────────── */
|
||||||
[data-theme="light"] {
|
[data-theme="light"] {
|
||||||
--c-bg: #f4f4f5;
|
--c-bg: #f0f2fa;
|
||||||
--c-surface: #ffffff;
|
--c-surface: #ffffff;
|
||||||
--c-card: rgba(0,0,0,0.02);
|
--c-card: rgba(255,255,255,0.75);
|
||||||
--c-card-border: rgba(0,0,0,0.06);
|
--c-card-border: rgba(0,0,0,0.08);
|
||||||
|
|
||||||
--c-accent: #e4e4e7;
|
--c-accent: #5b61f0;
|
||||||
--c-accent-2: #d4d4d8;
|
--c-accent-2: #8b5cf6;
|
||||||
--c-accent-glow: rgba(0,0,0,0.05);
|
--c-accent-glow: rgba(91,97,240,0.25);
|
||||||
--c-accent-dim: rgba(0,0,0,0.03);
|
--c-accent-dim: rgba(91,97,240,0.10);
|
||||||
|
|
||||||
--c-green: #059669;
|
--c-green: #10b981;
|
||||||
--c-green-glow: rgba(5,150,105,0.2);
|
--c-green-glow: rgba(16,185,129,0.25);
|
||||||
--c-green-dim: rgba(5,150,105,0.1);
|
--c-green-dim: rgba(16,185,129,0.10);
|
||||||
|
|
||||||
--c-amber: #d97706;
|
--c-amber: #d97706;
|
||||||
--c-red: #dc2626;
|
--c-red: #ef4444;
|
||||||
|
|
||||||
--c-txt-1: #09090b;
|
--c-txt-1: #0f1020;
|
||||||
--c-txt-2: #52525b;
|
--c-txt-2: #5a5f7a;
|
||||||
--c-txt-3: #a1a1aa;
|
--c-txt-3: #b0b4cc;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Light theme element overrides ───────────────────────────────────────── */
|
/* ── Light theme element overrides ───────────────────────────────────────── */
|
||||||
|
|
@ -74,6 +74,9 @@ html[data-theme="light"] body {
|
||||||
background: var(--c-bg);
|
background: var(--c-bg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
html[data-theme="light"] .blob-1 { opacity: 0.08; }
|
||||||
|
html[data-theme="light"] .blob-2 { opacity: 0.06; }
|
||||||
|
|
||||||
html[data-theme="light"] .power-btn {
|
html[data-theme="light"] .power-btn {
|
||||||
background: var(--c-surface);
|
background: var(--c-surface);
|
||||||
box-shadow:
|
box-shadow:
|
||||||
|
|
@ -195,32 +198,41 @@ input, textarea { font-family: inherit; }
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Watermark ────────────────────────────────────────────────────────────── */
|
/* ── Ambient blobs ────────────────────────────────────────────────────────── */
|
||||||
.watermark {
|
.ambient {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 50%;
|
inset: 0;
|
||||||
left: 50%;
|
|
||||||
transform: translate(-50%, -50%);
|
|
||||||
width: 80%;
|
|
||||||
max-width: 600px;
|
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
z-index: 0;
|
z-index: 0;
|
||||||
opacity: 0.05;
|
overflow: hidden;
|
||||||
user-select: none;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.watermark img {
|
.blob {
|
||||||
width: 100%;
|
position: absolute;
|
||||||
height: auto;
|
border-radius: 50%;
|
||||||
object-fit: contain;
|
filter: blur(100px);
|
||||||
|
will-change: transform;
|
||||||
}
|
}
|
||||||
|
|
||||||
html[data-theme="light"] .watermark {
|
.blob-1 {
|
||||||
opacity: 0.06;
|
width: 400px; height: 400px;
|
||||||
filter: invert(1);
|
background: var(--c-accent);
|
||||||
|
opacity: 0.15;
|
||||||
|
top: -150px; right: -100px;
|
||||||
|
animation: blob-drift 28s infinite alternate ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.blob-2 {
|
||||||
|
width: 350px; height: 350px;
|
||||||
|
background: var(--c-green);
|
||||||
|
opacity: 0.10;
|
||||||
|
bottom: -100px; left: -100px;
|
||||||
|
animation: blob-drift 22s infinite alternate-reverse ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes blob-drift {
|
||||||
|
from { transform: translate(0, 0); }
|
||||||
|
to { transform: translate(30px, 20px); }
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Screen system ────────────────────────────────────────────────────────── */
|
/* ── Screen system ────────────────────────────────────────────────────────── */
|
||||||
|
|
|
||||||
|
|
@ -368,31 +368,3 @@ pub extern "system" fn Java_net_ostp_client_OstpClientSdk_notifyNetworkChanged(
|
||||||
|
|
||||||
// No-op for now; multi-server handles network drops via keep-alives and reconnection
|
// No-op for now; multi-server handles network drops via keep-alives and reconnection
|
||||||
}
|
}
|
||||||
|
|
||||||
#[no_mangle]
|
|
||||||
pub extern "system" fn Java_net_ostp_client_OstpClientSdk_nativeRunDnsProber(
|
|
||||||
mut env: JNIEnv,
|
|
||||||
_class: JClass,
|
|
||||||
domain: JString,
|
|
||||||
) -> jstring {
|
|
||||||
let domain_str: String = match env.get_string(&domain) {
|
|
||||||
Ok(s) => s.into(),
|
|
||||||
Err(_) => return env.new_string("[]").unwrap().into_raw(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let rt = tokio::runtime::Builder::new_current_thread()
|
|
||||||
.enable_all()
|
|
||||||
.build()
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let result = rt.block_on(async {
|
|
||||||
ostp_core::dns_prober::run_dns_prober(&domain_str).await
|
|
||||||
});
|
|
||||||
|
|
||||||
let json = match result {
|
|
||||||
Ok(res) => serde_json::to_string(&res).unwrap_or_else(|_| "[]".to_string()),
|
|
||||||
Err(_) => "[]".to_string(),
|
|
||||||
};
|
|
||||||
|
|
||||||
env.new_string(json).unwrap().into_raw()
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -856,6 +856,7 @@ mod tests {
|
||||||
dns_server: crate::dns::DnsServer::new(Default::default()),
|
dns_server: crate::dns::DnsServer::new(Default::default()),
|
||||||
audit_logs: Arc::new(RwLock::new(Vec::new())),
|
audit_logs: Arc::new(RwLock::new(Vec::new())),
|
||||||
router: Arc::new(crate::router::Router::new(None, crate::dns::DnsServer::new(Default::default()), false)),
|
router: Arc::new(crate::router::Router::new(None, crate::dns::DnsServer::new(Default::default()), false)),
|
||||||
|
is_licensed: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use crate::{fallback::FallbackConfig, dns::DnsConfig};
|
use crate::{api::ApiConfig, fallback::FallbackConfig, outbound::OutboundConfig, dns::DnsConfig};
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
#[serde(tag = "protocol", rename_all = "snake_case")]
|
#[serde(tag = "type", rename_all = "snake_case")]
|
||||||
pub enum ServerInbound {
|
pub enum ServerInbound {
|
||||||
Ostp {
|
Ostp {
|
||||||
tag: String,
|
tag: String,
|
||||||
|
|
@ -27,15 +27,6 @@ pub enum ServerInbound {
|
||||||
username: Option<String>,
|
username: Option<String>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
password_hash: Option<String>,
|
password_hash: Option<String>,
|
||||||
},
|
|
||||||
Dns {
|
|
||||||
tag: String,
|
|
||||||
listen: String,
|
|
||||||
domain: String,
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pubkey: Option<String>,
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
privkey: Option<String>,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -82,9 +73,8 @@ pub struct TransportConfigRaw {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
#[serde(tag = "protocol", rename_all = "snake_case")]
|
#[serde(tag = "type", rename_all = "snake_case")]
|
||||||
pub enum ServerOutbound {
|
pub enum ServerOutbound {
|
||||||
#[serde(rename = "socks5")]
|
|
||||||
Socks {
|
Socks {
|
||||||
tag: String,
|
tag: String,
|
||||||
server: String,
|
server: String,
|
||||||
|
|
@ -131,6 +121,9 @@ pub struct ModularServerConfig {
|
||||||
pub dns: Option<DnsConfig>,
|
pub dns: Option<DnsConfig>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub license_key: Option<String>,
|
pub license_key: Option<String>,
|
||||||
|
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub dns_transport: Option<DnsTransportConfig>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ use portable_atomic::AtomicU64;
|
||||||
// const MAX_SESSIONS removed because dynamic limit is used
|
// const MAX_SESSIONS removed because dynamic limit is used
|
||||||
|
|
||||||
pub enum DispatchOutcome {
|
pub enum DispatchOutcome {
|
||||||
Unauthorized(String),
|
Unauthorized,
|
||||||
Accepted {
|
Accepted {
|
||||||
responses: Vec<Bytes>,
|
responses: Vec<Bytes>,
|
||||||
app_payloads: Vec<(u32, u16, Bytes)>, // session_id, stream_id, payload
|
app_payloads: Vec<(u32, u16, Bytes)>, // session_id, stream_id, payload
|
||||||
|
|
@ -182,7 +182,7 @@ impl Dispatcher {
|
||||||
|
|
||||||
pub fn on_datagram(&mut self, peer: SocketAddr, packet: Bytes) -> Result<DispatchOutcome> {
|
pub fn on_datagram(&mut self, peer: SocketAddr, packet: Bytes) -> Result<DispatchOutcome> {
|
||||||
if packet.len() < 4 {
|
if packet.len() < 4 {
|
||||||
return Ok(DispatchOutcome::Unauthorized("packet too short".to_string()));
|
return Ok(DispatchOutcome::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut session_id_opt = None;
|
let mut session_id_opt = None;
|
||||||
|
|
@ -239,7 +239,7 @@ impl Dispatcher {
|
||||||
tracing::info!("Dropping session {} for key {} (valid={}, over_limit={})",
|
tracing::info!("Dropping session {} for key {} (valid={}, over_limit={})",
|
||||||
session_id, access_key, key_valid, user_stats.is_over_limit());
|
session_id, access_key, key_valid, user_stats.is_over_limit());
|
||||||
self.drop_session(session_id);
|
self.drop_session(session_id);
|
||||||
return Ok(DispatchOutcome::Unauthorized("key invalid or over limit".to_string()));
|
return Ok(DispatchOutcome::Unauthorized);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -260,7 +260,8 @@ impl Dispatcher {
|
||||||
let action = match peer_state.machine.on_event(OstpEvent::Inbound(packet)) {
|
let action = match peer_state.machine.on_event(OstpEvent::Inbound(packet)) {
|
||||||
Ok(a) => a,
|
Ok(a) => a,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return Ok(DispatchOutcome::Unauthorized(format!("protocol error: {}", e)));
|
tracing::warn!("Protocol error for session {}: {}", session_id, e);
|
||||||
|
return Ok(DispatchOutcome::Unauthorized);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -302,17 +303,13 @@ impl Dispatcher {
|
||||||
// Not an existing session — try each registered access key's derived obfuscation key
|
// Not an existing session — try each registered access key's derived obfuscation key
|
||||||
let keys_snapshot: Vec<String> = self.access_keys.read().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect();
|
let keys_snapshot: Vec<String> = self.access_keys.read().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect();
|
||||||
|
|
||||||
let mut failed_trials = Vec::new();
|
|
||||||
for candidate_key in keys_snapshot {
|
for candidate_key in keys_snapshot {
|
||||||
let secrets = ostp_core::crypto::derive_all_secrets(candidate_key.as_bytes());
|
let secrets = ostp_core::crypto::derive_all_secrets(candidate_key.as_bytes());
|
||||||
|
|
||||||
// Decode the session_id using this key's obfuscation
|
// Decode the session_id using this key's obfuscation
|
||||||
// The handshake mask is derived from the Noise payload at bytes [6..],
|
// The handshake mask is derived from the Noise payload at bytes [6..],
|
||||||
// so we must deobfuscate the full packet, not just the header.
|
// so we must deobfuscate the full packet, not just the header.
|
||||||
if packet.len() < 7 {
|
if packet.len() < 7 { continue; }
|
||||||
failed_trials.push(format!("key {}: packet too short", candidate_key));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let mut trial = packet.to_vec();
|
let mut trial = packet.to_vec();
|
||||||
ostp_core::crypto::deobfuscate_packet_inplace(&mut trial, &secrets.obfuscation_key, true);
|
ostp_core::crypto::deobfuscate_packet_inplace(&mut trial, &secrets.obfuscation_key, true);
|
||||||
let candidate_session_id = u32::from_be_bytes([trial[0], trial[1], trial[2], trial[3]]);
|
let candidate_session_id = u32::from_be_bytes([trial[0], trial[1], trial[2], trial[3]]);
|
||||||
|
|
@ -334,10 +331,7 @@ impl Dispatcher {
|
||||||
};
|
};
|
||||||
let action = match machine.on_event(OstpEvent::Inbound(packet.clone())) {
|
let action = match machine.on_event(OstpEvent::Inbound(packet.clone())) {
|
||||||
Ok(a) => a,
|
Ok(a) => a,
|
||||||
Err(e) => {
|
Err(_) => continue,
|
||||||
failed_trials.push(format!("key {}: crypto err: {}", candidate_key, e));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if let ProtocolAction::HandshakePayload(payload, response_opt) = action {
|
if let ProtocolAction::HandshakePayload(payload, response_opt) = action {
|
||||||
|
|
@ -351,7 +345,6 @@ impl Dispatcher {
|
||||||
let sid_from_payload = u32::from_be_bytes(sid_bytes);
|
let sid_from_payload = u32::from_be_bytes(sid_bytes);
|
||||||
|
|
||||||
if sid_from_payload != candidate_session_id {
|
if sid_from_payload != candidate_session_id {
|
||||||
failed_trials.push(format!("key {}: sid mismatch", candidate_key));
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -359,7 +352,6 @@ impl Dispatcher {
|
||||||
if let Ok(key_from_payload) = std::str::from_utf8(key_bytes) {
|
if let Ok(key_from_payload) = std::str::from_utf8(key_bytes) {
|
||||||
// The key embedded in the payload must match the candidate key we decoded with
|
// The key embedded in the payload must match the candidate key we decoded with
|
||||||
if key_from_payload != candidate_key {
|
if key_from_payload != candidate_key {
|
||||||
failed_trials.push(format!("key {}: embedded key mismatch", candidate_key));
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -370,16 +362,14 @@ impl Dispatcher {
|
||||||
|
|
||||||
let drift = (now as i64 - ts as i64).abs();
|
let drift = (now as i64 - ts as i64).abs();
|
||||||
if drift > 300 {
|
if drift > 300 {
|
||||||
let reason = format!("timestamp drift {}s exceeds 300s limit", drift);
|
tracing::warn!("Handshake rejected: timestamp drift {}s exceeds 300s limit (peer={})", drift, peer);
|
||||||
tracing::warn!("Handshake rejected for {}: {}", peer, reason);
|
|
||||||
failed_trials.push(format!("key {}: {}", candidate_key, reason));
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if !self.replay_cache.contains_key(&payload.to_vec()) {
|
if !self.replay_cache.contains_key(&payload.to_vec()) {
|
||||||
if self.replay_cache.len() >= 50_000 {
|
if self.replay_cache.len() >= 50_000 {
|
||||||
tracing::warn!("Replay cache full (100000 entries), rejecting handshake from {}", peer);
|
tracing::warn!("Replay cache full (100000 entries), rejecting handshake from {}", peer);
|
||||||
return Ok(DispatchOutcome::Unauthorized("replay cache full".to_string()));
|
return Ok(DispatchOutcome::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.replay_cache.insert(payload.to_vec(), ts);
|
self.replay_cache.insert(payload.to_vec(), ts);
|
||||||
|
|
@ -393,7 +383,7 @@ impl Dispatcher {
|
||||||
// Check traffic limit before accepting
|
// Check traffic limit before accepting
|
||||||
if user_stats.is_over_limit() {
|
if user_stats.is_over_limit() {
|
||||||
tracing::warn!("User {} exceeded traffic limit, rejecting handshake from {}", candidate_key, peer);
|
tracing::warn!("User {} exceeded traffic limit, rejecting handshake from {}", candidate_key, peer);
|
||||||
return Ok(DispatchOutcome::Unauthorized("user over traffic limit".to_string()));
|
return Ok(DispatchOutcome::Unauthorized);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.peer_machines.insert(candidate_session_id, PeerState {
|
self.peer_machines.insert(candidate_session_id, PeerState {
|
||||||
|
|
@ -420,13 +410,7 @@ impl Dispatcher {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let reason = if failed_trials.is_empty() {
|
Ok(DispatchOutcome::Unauthorized)
|
||||||
"no valid handshake payload found".to_string()
|
|
||||||
} else {
|
|
||||||
format!("all key trials failed: {}", failed_trials.join(", "))
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(DispatchOutcome::Unauthorized(reason))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn outbound_to_session(&mut self, session_id: u32, stream_id: u16, payload: Bytes) -> Result<Option<(Bytes, SocketAddr)>> {
|
pub fn outbound_to_session(&mut self, session_id: u32, stream_id: u16, payload: Bytes) -> Result<Option<(Bytes, SocketAddr)>> {
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,7 @@ pub(crate) enum UiEvent {
|
||||||
PeerSeen { peer: IpAddr },
|
PeerSeen { peer: IpAddr },
|
||||||
#[allow(dead_code)] Rx { peer: IpAddr, bytes: usize },
|
#[allow(dead_code)] Rx { peer: IpAddr, bytes: usize },
|
||||||
#[allow(dead_code)] Tx { peer: IpAddr, bytes: usize },
|
#[allow(dead_code)] Tx { peer: IpAddr, bytes: usize },
|
||||||
UnauthorizedProbe { peer: IpAddr, bytes: usize, reason: String },
|
UnauthorizedProbe { peer: IpAddr, bytes: usize },
|
||||||
KeyCreated { key: String },
|
KeyCreated { key: String },
|
||||||
Log(String),
|
Log(String),
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
|
|
@ -159,12 +159,7 @@ pub async fn run_server(
|
||||||
#[derive(serde::Deserialize)]
|
#[derive(serde::Deserialize)]
|
||||||
#[serde(untagged)]
|
#[serde(untagged)]
|
||||||
enum ReloadUser {
|
enum ReloadUser {
|
||||||
Detailed {
|
Detailed { access_key: String, name: Option<String>, limit_bytes: Option<u64> },
|
||||||
#[serde(rename = "key")]
|
|
||||||
access_key: String,
|
|
||||||
name: Option<String>,
|
|
||||||
limit_bytes: Option<u64>
|
|
||||||
},
|
|
||||||
KeyOnly(String),
|
KeyOnly(String),
|
||||||
}
|
}
|
||||||
#[derive(serde::Deserialize)]
|
#[derive(serde::Deserialize)]
|
||||||
|
|
@ -172,8 +167,6 @@ pub async fn run_server(
|
||||||
mode: String,
|
mode: String,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
access_keys: Vec<ReloadUser>,
|
access_keys: Vec<ReloadUser>,
|
||||||
#[serde(default)]
|
|
||||||
inbounds: Vec<serde_json::Value>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut stripped = json_comments::StripComments::new(content.as_bytes());
|
let mut stripped = json_comments::StripComments::new(content.as_bytes());
|
||||||
|
|
@ -188,23 +181,7 @@ pub async fn run_server(
|
||||||
Ok(cfg) => {
|
Ok(cfg) => {
|
||||||
if cfg.mode == "server" {
|
if cfg.mode == "server" {
|
||||||
let mut new_keys = HashMap::new();
|
let mut new_keys = HashMap::new();
|
||||||
let mut all_users = cfg.access_keys;
|
for uc in cfg.access_keys {
|
||||||
|
|
||||||
for inbound in cfg.inbounds {
|
|
||||||
if let Some(protocol) = inbound.get("protocol").and_then(|p| p.as_str()) {
|
|
||||||
if protocol == "ostp" {
|
|
||||||
if let Some(users) = inbound.get("users").and_then(|u| u.as_array()) {
|
|
||||||
for u in users {
|
|
||||||
if let Ok(ru) = serde_json::from_value::<ReloadUser>(u.clone()) {
|
|
||||||
all_users.push(ru);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for uc in all_users {
|
|
||||||
let (k, m) = match uc {
|
let (k, m) = match uc {
|
||||||
ReloadUser::Detailed { access_key, name, limit_bytes } => (access_key, crate::api::UserMeta { name, limit_bytes }),
|
ReloadUser::Detailed { access_key, name, limit_bytes } => (access_key, crate::api::UserMeta { name, limit_bytes }),
|
||||||
ReloadUser::KeyOnly(k) => (k, crate::api::UserMeta { name: None, limit_bytes: None }),
|
ReloadUser::KeyOnly(k) => (k, crate::api::UserMeta { name: None, limit_bytes: None }),
|
||||||
|
|
@ -328,9 +305,10 @@ pub async fn run_server(
|
||||||
UiEvent::KeyCreated { key } => {
|
UiEvent::KeyCreated { key } => {
|
||||||
tracing::info!("Access key created: {key}");
|
tracing::info!("Access key created: {key}");
|
||||||
}
|
}
|
||||||
UiEvent::UnauthorizedProbe { peer, bytes, reason } => {
|
UiEvent::UnauthorizedProbe { peer, bytes } => {
|
||||||
// Make it a warn so it's always visible outside debug mode!
|
if debug {
|
||||||
tracing::warn!("Unauthorized probe from {peer} ({bytes} bytes): {reason}");
|
tracing::debug!("Unauthorized probe from {peer} ({bytes} bytes)");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
UiEvent::PeerSeen { .. } => {}
|
UiEvent::PeerSeen { .. } => {}
|
||||||
_ => {}
|
_ => {}
|
||||||
|
|
@ -575,8 +553,8 @@ async fn handle_udp_packet(
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let size = packet.len();
|
let size = packet.len();
|
||||||
match dispatcher.on_datagram(peer, packet) {
|
match dispatcher.on_datagram(peer, packet) {
|
||||||
Ok(DispatchOutcome::Unauthorized(reason)) => {
|
Ok(DispatchOutcome::Unauthorized) => {
|
||||||
let _ = ui_event_tx.send(UiEvent::UnauthorizedProbe { peer: peer.ip(), bytes: size, reason });
|
let _ = ui_event_tx.send(UiEvent::UnauthorizedProbe { peer: peer.ip(), bytes: size });
|
||||||
}
|
}
|
||||||
Ok(DispatchOutcome::Accepted { responses, app_payloads, peer_addr }) => {
|
Ok(DispatchOutcome::Accepted { responses, app_payloads, peer_addr }) => {
|
||||||
let peer_ip = peer_addr.ip();
|
let peer_ip = peer_addr.ip();
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ use std::net::SocketAddr;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use tokio::time::Duration;
|
use tokio::time::Duration;
|
||||||
|
|
||||||
use ostp_core::dns::{DnsPacket, DnsRecordType, decode_domain_to_payload};
|
use ostp_core::dns::{DnsPacket, DnsRecordType, decode_domain_to_payload, encode_payload_to_domain};
|
||||||
use crate::config::DnsTransportConfig;
|
use crate::config::DnsTransportConfig;
|
||||||
use crate::UiEvent;
|
use crate::UiEvent;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ pub enum UiEvent {
|
||||||
PeerSeen { peer: IpAddr },
|
PeerSeen { peer: IpAddr },
|
||||||
Rx { peer: IpAddr, bytes: usize },
|
Rx { peer: IpAddr, bytes: usize },
|
||||||
Tx { peer: IpAddr, bytes: usize },
|
Tx { peer: IpAddr, bytes: usize },
|
||||||
UnauthorizedProbe { peer: IpAddr, bytes: usize, reason: String },
|
UnauthorizedProbe { peer: IpAddr, bytes: usize },
|
||||||
KeyCreated { key: String },
|
KeyCreated { key: String },
|
||||||
Log(String),
|
Log(String),
|
||||||
KeyCount(usize),
|
KeyCount(usize),
|
||||||
|
|
|
||||||
|
|
@ -12,8 +12,6 @@ struct LinuxRouteGuard {
|
||||||
|
|
||||||
impl Drop for LinuxRouteGuard {
|
impl Drop for LinuxRouteGuard {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
let _ = Command::new("ip").args(["route", "del", "0.0.0.0/1", "dev", "ostp_tun"]).output();
|
|
||||||
let _ = Command::new("ip").args(["route", "del", "128.0.0.0/1", "dev", "ostp_tun"]).output();
|
|
||||||
let _ = Command::new("ip").args(["route", "del", "default", "dev", "ostp_tun"]).output();
|
let _ = Command::new("ip").args(["route", "del", "default", "dev", "ostp_tun"]).output();
|
||||||
let _ = Command::new("ip").args(["route", "del", &format!("{}/32", self.server_ip)]).output();
|
let _ = Command::new("ip").args(["route", "del", &format!("{}/32", self.server_ip)]).output();
|
||||||
for route in &self.bypass_routes {
|
for route in &self.bypass_routes {
|
||||||
|
|
@ -40,6 +38,10 @@ pub async fn create(opts: OstpTunOptions) -> Result<OstpTunInterface> {
|
||||||
.mtu(opts.mtu)
|
.mtu(opts.mtu)
|
||||||
.up();
|
.up();
|
||||||
|
|
||||||
|
tun_cfg.platform_config(|cfg| {
|
||||||
|
cfg.packet_information(false);
|
||||||
|
});
|
||||||
|
|
||||||
let dev = tun::create(&tun_cfg).map_err(|e| anyhow!("Failed to create TUN device: {}", e))?;
|
let dev = tun::create(&tun_cfg).map_err(|e| anyhow!("Failed to create TUN device: {}", e))?;
|
||||||
let dev = tun::AsyncDevice::new(dev).map_err(|e| anyhow!("TUN device async failed: {}", e))?;
|
let dev = tun::AsyncDevice::new(dev).map_err(|e| anyhow!("TUN device async failed: {}", e))?;
|
||||||
tracing::info!("TUN device 'ostp_tun' created.");
|
tracing::info!("TUN device 'ostp_tun' created.");
|
||||||
|
|
@ -72,9 +74,7 @@ pub async fn create(opts: OstpTunOptions) -> Result<OstpTunInterface> {
|
||||||
bypass_routes.push(route);
|
bypass_routes.push(route);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Override default route gracefully by adding more specific /1 routes
|
let _ = Command::new("ip").args(["route", "add", "default", "dev", "ostp_tun"]).output();
|
||||||
let _ = Command::new("ip").args(["route", "add", "0.0.0.0/1", "dev", "ostp_tun"]).output();
|
|
||||||
let _ = Command::new("ip").args(["route", "add", "128.0.0.0/1", "dev", "ostp_tun"]).output();
|
|
||||||
|
|
||||||
if opts.kill_switch {
|
if opts.kill_switch {
|
||||||
tracing::info!("Kill Switch: deleting original default route to prevent leakage.");
|
tracing::info!("Kill Switch: deleting original default route to prevent leakage.");
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,73 @@
|
||||||
|
# OSTP DNS Transport (Последний Рубеж)
|
||||||
|
|
||||||
|
DNS Transport (DNS Прокси) — это экспериментальный транспорт, который является "последним рубежом" для обхода блокировок. Он используется, когда все остальные протоколы (UDP, UoT/TCP) полностью заблокированы провайдером или DPI.
|
||||||
|
|
||||||
|
Он маскирует весь VPN-трафик под обычные запросы к DNS-серверам (разрешение имен), что делает его блокировку практически невозможной без отключения интернета в целом. OSTP использует запросы типа `TXT` и `NULL` для передачи данных, используя кодировку Base32.
|
||||||
|
|
||||||
|
> **Внимание:** DNS-туннелирование работает значительно медленнее обычных протоколов из-за накладных расходов протокола DNS. Рекомендуется использовать этот режим только когда другие способы не работают.
|
||||||
|
|
||||||
|
## Как это работает?
|
||||||
|
|
||||||
|
Вместо того чтобы отправлять трафик напрямую на ваш сервер, клиент OSTP отправляет стандартный DNS-запрос на **публичные DNS-серверы** (например, 1.1.1.1, 8.8.8.8) или серверы выбранного вами региона (Prober).
|
||||||
|
Публичный сервер-резолвер перенаправляет этот запрос на **ваш сервер** (как на авторитативный DNS-сервер для вашего домена), а ваш сервер отвечает обратно через резолвер.
|
||||||
|
|
||||||
|
Для настройки этого механизма **вам понадобится собственный домен**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Настройка на стороне сервера (Домен)
|
||||||
|
|
||||||
|
Вам необходимо настроить NS-записи вашего домена так, чтобы они указывали на IP-адрес вашего OSTP сервера.
|
||||||
|
|
||||||
|
Например, вы владеете доменом `myvpn.com` и хотите использовать поддомен `t.myvpn.com` для туннеля, а IP вашего сервера — `192.168.1.100`.
|
||||||
|
|
||||||
|
В панели управления вашего DNS-регистратора добавьте следующие записи:
|
||||||
|
|
||||||
|
1. **A-запись:**
|
||||||
|
- Имя (Host): `ns.myvpn.com`
|
||||||
|
- Тип (Type): `A`
|
||||||
|
- Значение (Value): `192.168.1.100` (IP вашего OSTP-сервера)
|
||||||
|
|
||||||
|
2. **NS-запись:**
|
||||||
|
- Имя (Host): `t.myvpn.com`
|
||||||
|
- Тип (Type): `NS`
|
||||||
|
- Значение (Value): `ns.myvpn.com`
|
||||||
|
|
||||||
|
Теперь любой DNS-запрос к поддоменам `t.myvpn.com` будет направляться на ваш сервер (на порт 53).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Настройка сервера OSTP
|
||||||
|
|
||||||
|
В файле конфигурации вашего OSTP сервера (`config.json` или `server.json`) необходимо включить прослушивание порта 53 для DNS транспорта:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mode": "server",
|
||||||
|
"dns_transport": {
|
||||||
|
"enabled": true,
|
||||||
|
"port": 53,
|
||||||
|
"domain": "t.myvpn.com"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Важно:** Для прослушивания порта 53 на Linux обычно требуются root-права. Убедитесь, что сервер запущен с `sudo` или используйте возможности `setcap` для предоставления доступа к порту:
|
||||||
|
> `sudo setcap cap_net_bind_service=+ep /path/to/ostp`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Настройка в приложении (Клиент)
|
||||||
|
|
||||||
|
В клиенте OSTP (Desktop GUI или Mobile):
|
||||||
|
|
||||||
|
1. Перейдите в **Settings (Настройки)**.
|
||||||
|
2. В поле **Transport Protocol** выберите `DNS Proxy (Последний рубеж)`.
|
||||||
|
3. Появится поле **Domain (Points to Server)** — введите сюда настроенный поддомен (например, `t.myvpn.com`).
|
||||||
|
4. Поле **DNS Resolver Region** позволяет выбрать, через серверы какой страны/провайдера будет осуществляться маршрутизация пакетов (например, Global, Russia, China, Iran). Клиент (Prober) автоматически найдет наиболее быстрый публичный резолвер в этом регионе.
|
||||||
|
|
||||||
|
## Ограничения и особенности
|
||||||
|
|
||||||
|
- **Скорость:** Из-за размера DNS-пакетов и задержек публичных серверов, максимальная скорость может составлять 1-5 Мбит/с.
|
||||||
|
- **Polling:** Поскольку DNS работает по принципу "Запрос-Ответ", клиент отправляет пустые поллинговые пакеты каждые 2 секунды, чтобы позволить серверу пересылать входящие данные.
|
||||||
|
- **Поддержка DoH/DoT:** В текущей версии запросы к публичным резолверам отправляются в открытом виде (UDP порт 53). В будущих обновлениях будет добавлена поддержка DNS over HTTPS (DoH) для дополнительного слоя защиты от DPI-фильтров.
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
# OSTP Wiki
|
||||||
|
|
||||||
|
This repository contains the documentation and wiki pages for the Ospab Stealth Transport Protocol (OSTP).
|
||||||
|
|
||||||
|
- [Configuration Guide](configuration_guide.md)
|
||||||
|
- [API Endpoints](api_endpoints.md)
|
||||||
|
- [DNS Transport (Последний Рубеж)](DNS-Transport.md)
|
||||||
|
- [v0.3.1 Configuration Migration Guide](../docs/migration_v0_3_1.md)
|
||||||
|
|
@ -0,0 +1,149 @@
|
||||||
|
# Справочник API управления OSTP
|
||||||
|
|
||||||
|
Сервер OSTP предоставляет REST API для управления пользователями, просмотра статистики трафика и интерактивного редактирования конфигурации.
|
||||||
|
|
||||||
|
По умолчанию API слушает на порту `9090` (хост настраивается в файле конфигурации).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Авторизация
|
||||||
|
|
||||||
|
Все запросы к API (за исключением подписок) должны содержать заголовок `Authorization` с API-токеном (если токен включен в конфигурационном файле):
|
||||||
|
|
||||||
|
```http
|
||||||
|
Authorization: Bearer <ваш_api_токен>
|
||||||
|
```
|
||||||
|
|
||||||
|
Или в упрощенном виде:
|
||||||
|
```http
|
||||||
|
Authorization: <ваш_api_токен>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Формат ответов
|
||||||
|
|
||||||
|
Все ответы API возвращаются в формате JSON следующей структуры:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": true,
|
||||||
|
"data": ...,
|
||||||
|
"error": null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
В случае ошибки:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"ok": false,
|
||||||
|
"data": null,
|
||||||
|
"error": "Описание ошибки"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Список эндпоинтов
|
||||||
|
|
||||||
|
### 1. Статус сервера
|
||||||
|
Возвращает текущую версию, аптайм и количество пользователей.
|
||||||
|
|
||||||
|
* **URL**: `/api/server/status`
|
||||||
|
* **Метод**: `GET`
|
||||||
|
* **Формат `data`**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": "0.2.30",
|
||||||
|
"uptime_seconds": 12053,
|
||||||
|
"active_users": 2,
|
||||||
|
"total_users": 5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Получение текущего конфига
|
||||||
|
Запрашивает полное содержимое файла `config.json` с удалением комментариев для прямой модификации.
|
||||||
|
|
||||||
|
* **URL**: `/api/server/config`
|
||||||
|
* **Метод**: `GET`
|
||||||
|
* **Формат `data`**: Полный JSON-конфиг сервера.
|
||||||
|
|
||||||
|
### 3. Обновление конфига
|
||||||
|
Записывает новый JSON конфигурации сервера в файл `config.json` на диске. Это автоматически вызывает **hot-reload** ядра (применение ключей доступа и лимитов).
|
||||||
|
|
||||||
|
* **URL**: `/api/server/config`
|
||||||
|
* **Метод**: `PUT`
|
||||||
|
* **Тело запроса**: JSON нового конфигурационного файла.
|
||||||
|
* **Формат `data`**: `true` в случае успешного сохранения.
|
||||||
|
|
||||||
|
### 4. Список клиентов и их статистики
|
||||||
|
Возвращает список всех зарегистрированных ключей доступа с их текущей загрузкой, скачиванием, активными сессиями и статусом подключения.
|
||||||
|
|
||||||
|
* **URL**: `/api/users`
|
||||||
|
* **Метод**: `GET`
|
||||||
|
* **Формат `data`**:
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"access_key": "ostp_key_sample1",
|
||||||
|
"bytes_up": 2405020,
|
||||||
|
"bytes_down": 491029402,
|
||||||
|
"connections": 2,
|
||||||
|
"limit_bytes": 10737418240,
|
||||||
|
"online": true,
|
||||||
|
"name": "Ноутбук"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Создание клиента
|
||||||
|
Генерирует новый ключ доступа (или регистрирует пользовательский).
|
||||||
|
|
||||||
|
* **URL**: `/api/users`
|
||||||
|
* **Метод**: `POST`
|
||||||
|
* **Тело запроса**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"access_key": "my_custom_key_optional",
|
||||||
|
"name": "Имя клиента",
|
||||||
|
"limit_bytes": 50000000000
|
||||||
|
}
|
||||||
|
```
|
||||||
|
* **Формат `data`**: Строка созданного ключа доступа.
|
||||||
|
|
||||||
|
### 6. Удаление клиента
|
||||||
|
Отзывает ключ доступа и сбрасывает все связанные активные сессии.
|
||||||
|
|
||||||
|
* **URL**: `/api/users/:key`
|
||||||
|
* **Метод**: `DELETE`
|
||||||
|
* **Формат `data`**: `"User removed"`
|
||||||
|
|
||||||
|
### 7. Обновление клиента
|
||||||
|
Редактирует имя или лимит трафика для клиента.
|
||||||
|
|
||||||
|
* **URL**: `/api/users/:key`
|
||||||
|
* **Метод**: `PUT`
|
||||||
|
* **Тело запроса**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"name": "Новое имя",
|
||||||
|
"limit_bytes": 100000000000
|
||||||
|
}
|
||||||
|
```
|
||||||
|
* **Формат `data`**: `"User updated"`
|
||||||
|
|
||||||
|
### 8. Сброс счетчиков трафика
|
||||||
|
Обнуляет показания загрузки и скачивания для определенного пользователя.
|
||||||
|
|
||||||
|
* **URL**: `/api/users/{key}/reset`
|
||||||
|
* **Метод**: `POST`
|
||||||
|
* **Формат `data`**: `true`
|
||||||
|
|
||||||
|
### 9. Ссылка подписки клиента
|
||||||
|
Возвращает ссылку подписки или конфигурационный файл для клиента. Авторизация по Bearer-токену **не требуется** (ключ авторизуется сам через URL).
|
||||||
|
|
||||||
|
* **URL**: `/api/subscribe/:key`
|
||||||
|
* **Метод**: `GET`
|
||||||
|
* **Заголовки**:
|
||||||
|
- `Accept: text/plain` -> Возвращает текстовую ссылку `ostp://<key>@<host>:<port>?...`
|
||||||
|
- `Accept: application/json` -> Возвращает полный клиентский JSON-конфиг.
|
||||||