mirror of https://github.com/ospab/ostp.git
Compare commits
No commits in common. "master" and "v0.3.12" 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"
|
||||||
|
|
@ -1452,13 +1436,11 @@ 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",
|
||||||
|
|
@ -1612,12 +1594,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"
|
||||||
|
|
|
||||||
|
|
@ -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,15 +172,18 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
@ -190,20 +191,8 @@ impl ClientConfig {
|
||||||
/// 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(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(env!("CARGO_PKG_VERSION"));
|
||||||
// 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,43 +1,19 @@
|
||||||
/// DNS tunnel transport — dnstt-style implementation.
|
|
||||||
///
|
|
||||||
/// Protocol (client → server, embedded in DNS query domain name):
|
|
||||||
/// Base32([client_id: 8][msg_id: 2 BE][total_frags: 1][frag_idx: 1][payload: ≤MAX_CHUNK])
|
|
||||||
/// Split into DNS labels of max 63 chars, suffixed with base_domain.
|
|
||||||
///
|
|
||||||
/// Poll query: payload is empty (total_frags=1, frag_idx=0, len=0).
|
|
||||||
///
|
|
||||||
/// Protocol (server → client, in TXT rdata):
|
|
||||||
/// Concatenated length-prefixed OSTP packets: [len: 2 BE][data ...]...
|
|
||||||
///
|
|
||||||
/// Polling: adaptive 500ms → 10s, like dnstt. Resets to 500ms on real data.
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use rand::Rng;
|
|
||||||
use tokio::net::UdpSocket;
|
use tokio::net::UdpSocket;
|
||||||
use tokio::sync::{mpsc, Mutex};
|
use tokio::sync::{mpsc, Mutex};
|
||||||
|
use rand::Rng;
|
||||||
|
|
||||||
|
pub use ostp_core::dns::{
|
||||||
|
DnsPacket, DnsRecordType, encode_payload_to_domain,
|
||||||
|
decode_domain_to_payload,
|
||||||
|
};
|
||||||
use crate::transport::Transport;
|
use crate::transport::Transport;
|
||||||
use rand::RngCore;
|
|
||||||
use ostp_core::dns::{base32_encode, DnsPacket, DnsRecordType};
|
|
||||||
|
|
||||||
/// Max raw payload bytes we put into one DNS query.
|
pub async fn start_dns_transport(domain: String, resolver: String, _pubkey: Option<String>) -> std::io::Result<Transport> {
|
||||||
/// Calculation: FQDN ≤ 253 chars. Domain suffix ~30 chars max.
|
let (app_tx, transport_rx) = mpsc::channel::<Bytes>(100);
|
||||||
/// Remaining: ~220 chars for base32 labels. 220/8*5 = 137 bytes raw.
|
let (transport_tx, app_rx) = mpsc::channel::<Bytes>(100);
|
||||||
/// Header = 12 bytes → payload ≤ 120 bytes (conservative, works for any domain ≤ 40 chars).
|
|
||||||
const MAX_CHUNK_PAYLOAD: usize = 120;
|
|
||||||
const CLIENT_ID_LEN: usize = 8;
|
|
||||||
const INIT_POLL_DELAY: Duration = Duration::from_millis(500);
|
|
||||||
const MAX_POLL_DELAY: Duration = Duration::from_secs(10);
|
|
||||||
const POLL_DELAY_MULTIPLIER: f64 = 2.0;
|
|
||||||
|
|
||||||
pub async fn start_dns_transport(
|
|
||||||
domain: String,
|
|
||||||
resolver: String,
|
|
||||||
_pubkey: Option<String>,
|
|
||||||
) -> std::io::Result<Transport> {
|
|
||||||
let (app_tx, transport_rx) = mpsc::channel::<Bytes>(256);
|
|
||||||
let (transport_tx, app_rx) = mpsc::channel::<Bytes>(256);
|
|
||||||
|
|
||||||
let resolver_addr = if resolver.contains(':') {
|
let resolver_addr = if resolver.contains(':') {
|
||||||
resolver.clone()
|
resolver.clone()
|
||||||
|
|
@ -49,124 +25,69 @@ pub async fn start_dns_transport(
|
||||||
socket.connect(&resolver_addr).await?;
|
socket.connect(&resolver_addr).await?;
|
||||||
let socket = Arc::new(socket);
|
let socket = Arc::new(socket);
|
||||||
|
|
||||||
// Generate random ClientID for this tunnel session
|
let sock_rx = socket.clone();
|
||||||
let mut client_id = [0u8; CLIENT_ID_LEN];
|
let sock_tx = socket;
|
||||||
rand::thread_rng().fill_bytes(&mut client_id);
|
let base_domain = domain.clone();
|
||||||
let client_id = Arc::new(client_id);
|
|
||||||
|
|
||||||
tracing::info!("DNS transport: domain={} resolver={} client_id={}",
|
// Send task (reads from app, encodes into DNS TXT, sends to UDP socket)
|
||||||
domain, resolver_addr,
|
|
||||||
hex::encode(client_id.as_slice()));
|
|
||||||
|
|
||||||
// ── Send task ─────────────────────────────────────────────────────────────
|
|
||||||
let sock_send = socket.clone();
|
|
||||||
let cid_send = client_id.clone();
|
|
||||||
let domain_send = domain.clone();
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut rx = transport_rx;
|
let mut rx = transport_rx;
|
||||||
let mut msg_id: u16 = 0;
|
|
||||||
let mut poll_delay = INIT_POLL_DELAY;
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let data: Option<Bytes> = tokio::select! {
|
let data_opt = tokio::select! {
|
||||||
data = rx.recv() => data,
|
res = rx.recv() => res,
|
||||||
_ = tokio::time::sleep(poll_delay) => {
|
_ = tokio::time::sleep(Duration::from_secs(2)) => Some(Bytes::new()),
|
||||||
poll_delay = Duration::from_secs_f64(
|
|
||||||
(poll_delay.as_secs_f64() * POLL_DELAY_MULTIPLIER)
|
|
||||||
.min(MAX_POLL_DELAY.as_secs_f64())
|
|
||||||
);
|
|
||||||
// Send poll (empty payload)
|
|
||||||
Some(Bytes::new())
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let data = match data {
|
let data = match data_opt {
|
||||||
Some(d) => d,
|
Some(d) => d,
|
||||||
None => {
|
None => break, // App closed
|
||||||
tracing::debug!("DNS send task: channel closed, exiting");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if data.is_empty() {
|
// Encode data to base32 domain
|
||||||
// Poll query — one empty chunk
|
let fqdn = encode_payload_to_domain(&data, &base_domain);
|
||||||
if let Err(e) = send_chunk(&sock_send, &cid_send, msg_id, 1, 0, &[], &domain_send).await {
|
let id: u16 = rand::thread_rng().gen();
|
||||||
tracing::warn!("DNS poll send error: {}", e);
|
|
||||||
}
|
// Randomly choose TXT or NULL for diversity (as requested)
|
||||||
|
let qtype = if rand::thread_rng().gen_bool(0.5) {
|
||||||
|
DnsRecordType::TXT
|
||||||
} else {
|
} else {
|
||||||
// Real OSTP packet — fragment into chunks
|
DnsRecordType::NULL
|
||||||
poll_delay = INIT_POLL_DELAY; // reset on real data
|
};
|
||||||
|
|
||||||
let data_slice = data.as_ref();
|
let packet = DnsPacket::new_query(id, &fqdn, qtype);
|
||||||
let total_chunks = data_slice.chunks(MAX_CHUNK_PAYLOAD).count();
|
let encoded = packet.encode();
|
||||||
let total_u8 = total_chunks.min(255) as u8;
|
|
||||||
|
|
||||||
for (idx, chunk) in data_slice.chunks(MAX_CHUNK_PAYLOAD).enumerate() {
|
if let Err(e) = sock_tx.send(&encoded).await {
|
||||||
if let Err(e) = send_chunk(
|
tracing::warn!("DNS transport send error: {}", e);
|
||||||
&sock_send, &cid_send,
|
|
||||||
msg_id, total_u8, idx as u8,
|
|
||||||
chunk, &domain_send,
|
|
||||||
).await {
|
|
||||||
tracing::warn!("DNS chunk send error (idx={}): {}", idx, e);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
// Brief inter-fragment delay to avoid flooding the resolver
|
|
||||||
if total_chunks > 1 {
|
|
||||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
msg_id = msg_id.wrapping_add(1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Receive task ──────────────────────────────────────────────────────────
|
// Receive task (reads from UDP socket, decodes DNS answer, sends to app)
|
||||||
let sock_recv = socket.clone();
|
let _base_domain_rx = domain.clone();
|
||||||
let tx_recv = transport_tx.clone();
|
|
||||||
let domain_recv = domain.clone();
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut buf = vec![0u8; 65535];
|
let mut buf = vec![0u8; 65535];
|
||||||
// Reassembly buffers: msg_id → (total, Vec<Option<chunk>>)
|
|
||||||
let reassembly: HashMap<u16, (u8, Vec<Option<Vec<u8>>>)> = HashMap::new();
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match sock_recv.recv(&mut buf).await {
|
match sock_rx.recv(&mut buf).await {
|
||||||
Ok(n) => {
|
Ok(n) => {
|
||||||
let Some(pkt) = DnsPacket::decode(&buf[..n]) else { continue };
|
if let Some(packet) = DnsPacket::decode(&buf[..n]) {
|
||||||
|
for answer in packet.answers {
|
||||||
|
if answer.rtype == DnsRecordType::TXT || answer.rtype == DnsRecordType::NULL {
|
||||||
|
// If it's a TXT record, the response might be base32 encoded payload?
|
||||||
|
// Actually, dnstt puts the payload in the TXT/NULL record data.
|
||||||
|
// We'll just assume the rdata is the raw payload, or base32 encoded if it was sent as such.
|
||||||
|
// Let's just pass the raw data (TXT strings are decoded in DnsPacket::decode)
|
||||||
|
|
||||||
// Only process DNS responses
|
// Wait, dnstt server responds with raw bytes in NULL, and base32/chunked strings in TXT.
|
||||||
if pkt.flags & 0x8000 == 0 { continue; }
|
// Our `DnsPacket::decode` already handles extracting TXT string bytes or NULL raw bytes into `rdata`.
|
||||||
|
// Let's just send `rdata` to the app.
|
||||||
for answer in pkt.answers {
|
if transport_tx.send(Bytes::from(answer.rdata)).await.is_err() {
|
||||||
if answer.rtype != DnsRecordType::TXT && answer.rtype != DnsRecordType::NULL {
|
return; // App closed
|
||||||
continue;
|
}
|
||||||
}
|
|
||||||
let rdata = answer.rdata;
|
|
||||||
// Parse length-prefixed OSTP packets packed in rdata:
|
|
||||||
// [len_hi: 1][len_lo: 1][data: len]...
|
|
||||||
let mut pos = 0;
|
|
||||||
while pos + 2 <= rdata.len() {
|
|
||||||
let pkt_len = u16::from_be_bytes([rdata[pos], rdata[pos + 1]]) as usize;
|
|
||||||
pos += 2;
|
|
||||||
if pkt_len == 0 { continue; }
|
|
||||||
if pos + pkt_len > rdata.len() {
|
|
||||||
tracing::debug!("DNS recv: truncated packet in rdata");
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
let payload = Bytes::copy_from_slice(&rdata[pos..pos + pkt_len]);
|
|
||||||
pos += pkt_len;
|
|
||||||
|
|
||||||
if tx_recv.send(payload).await.is_err() {
|
|
||||||
return; // app closed
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Also check for responses packed in the server's extra DNS answer rdata
|
|
||||||
// that use our fragmentation scheme (server→client fragments)
|
|
||||||
// This is handled above via the length-prefix protocol.
|
|
||||||
let _ = &reassembly; // Keep for future upstream fragmentation support
|
|
||||||
let _ = &domain_recv;
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
tracing::warn!("DNS transport recv error: {}", e);
|
tracing::warn!("DNS transport recv error: {}", e);
|
||||||
|
|
@ -181,50 +102,3 @@ pub async fn start_dns_transport(
|
||||||
rx: Arc::new(Mutex::new(app_rx)),
|
rx: Arc::new(Mutex::new(app_rx)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build and send one DNS TXT query with a framed chunk.
|
|
||||||
///
|
|
||||||
/// Frame format (before base32 encoding):
|
|
||||||
/// [client_id: 8][msg_id: 2 BE][total_frags: 1][frag_idx: 1][payload: 0–120]
|
|
||||||
async fn send_chunk(
|
|
||||||
socket: &UdpSocket,
|
|
||||||
client_id: &[u8; CLIENT_ID_LEN],
|
|
||||||
msg_id: u16,
|
|
||||||
total_frags: u8,
|
|
||||||
frag_idx: u8,
|
|
||||||
payload: &[u8],
|
|
||||||
base_domain: &str,
|
|
||||||
) -> std::io::Result<()> {
|
|
||||||
// Build frame
|
|
||||||
let mut frame = Vec::with_capacity(CLIENT_ID_LEN + 4 + payload.len());
|
|
||||||
frame.extend_from_slice(client_id);
|
|
||||||
frame.extend_from_slice(&msg_id.to_be_bytes());
|
|
||||||
frame.push(total_frags);
|
|
||||||
frame.push(frag_idx);
|
|
||||||
frame.extend_from_slice(payload);
|
|
||||||
|
|
||||||
// Base32-encode
|
|
||||||
let encoded = base32_encode(&frame);
|
|
||||||
|
|
||||||
// Split into 63-char labels and append domain
|
|
||||||
let mut fqdn = String::with_capacity(encoded.len() + base_domain.len() + 10);
|
|
||||||
let mut start = 0;
|
|
||||||
while start < encoded.len() {
|
|
||||||
let end = (start + 63).min(encoded.len());
|
|
||||||
fqdn.push_str(&encoded[start..end]);
|
|
||||||
fqdn.push('.');
|
|
||||||
start = end;
|
|
||||||
}
|
|
||||||
fqdn.push_str(base_domain);
|
|
||||||
|
|
||||||
// Build DNS TXT query with random ID
|
|
||||||
let id: u16 = rand::thread_rng().gen();
|
|
||||||
let pkt = DnsPacket::new_query(id, &fqdn, DnsRecordType::TXT);
|
|
||||||
let wire = pkt.encode();
|
|
||||||
|
|
||||||
tracing::trace!("DNS send chunk: msg_id={} frag={}/{} payload={}B fqdn_len={}",
|
|
||||||
msg_id, frag_idx + 1, total_frags, payload.len(), fqdn.len());
|
|
||||||
|
|
||||||
socket.send(&wire).await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -59,7 +59,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 {
|
||||||
|
|
|
||||||
|
|
@ -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;
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,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
|
||||||
|
|
|
||||||
|
|
@ -63,15 +63,12 @@ fn random_session_id() -> 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?;
|
||||||
|
|
@ -83,103 +80,12 @@ pub async fn dial_tcp(
|
||||||
let config = make_initiator_config(session_id, access_key, transport_cfg);
|
let config = make_initiator_config(session_id, access_key, transport_cfg);
|
||||||
let mut machine = ProtocolMachine::new(config).unwrap();
|
let mut machine = ProtocolMachine::new(config).unwrap();
|
||||||
|
|
||||||
let target_host_str = target_host.to_string();
|
|
||||||
|
|
||||||
let server_str = server.to_string();
|
|
||||||
|
|
||||||
// Spawn bridge task
|
// Spawn bridge task
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
// Send initial handshake
|
// Send initial handshake
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Start) {
|
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 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send connection request
|
|
||||||
let connect_msg = ostp_core::relay::RelayMessage::Connect(format!("{}:{}", target_host_str, target_port));
|
|
||||||
let connect_encoded = connect_msg.encode();
|
|
||||||
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(connect_encoded))) {
|
|
||||||
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];
|
||||||
|
|
||||||
|
|
@ -187,9 +93,7 @@ pub async fn dial_tcp(
|
||||||
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 +111,6 @@ pub async fn dial_tcp(
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
Ok(client_stream)
|
Ok(client_stream)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -247,29 +150,28 @@ pub async fn handle_udp(
|
||||||
// Wait for handshake response (server sends HandshakePayload back)
|
// Wait for handshake response (server sends HandshakePayload back)
|
||||||
let mut buf = [0u8; 8192];
|
let mut buf = [0u8; 8192];
|
||||||
match tokio::time::timeout(
|
match tokio::time::timeout(
|
||||||
std::time::Duration::from_millis(15000),
|
std::time::Duration::from_millis(2000),
|
||||||
transport.recv(&mut buf),
|
transport.recv(&mut buf),
|
||||||
).await {
|
).await {
|
||||||
Ok(Ok(n)) => {
|
Ok(Ok(n)) => {
|
||||||
let _ = 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])));
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
tracing::warn!("OSTP handshake timeout for {}:{}", server, port);
|
tracing::warn!("UDP handshake timeout for {}:{}", server, port);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send relay UdpAssociate + data
|
// Send relay connect + data
|
||||||
let assoc_msg = ostp_core::relay::RelayMessage::UdpAssociate;
|
let relay_msg = ostp_core::relay::RelayMessage::Connect(
|
||||||
let encoded = assoc_msg.encode();
|
format!("{}:{}", target_dst.ip(), target_dst.port())
|
||||||
|
);
|
||||||
|
let encoded = relay_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(
|
let data_msg = ostp_core::relay::RelayMessage::Data(payload.to_vec());
|
||||||
format!("{}:{}", target_dst.ip(), target_dst.port()),
|
|
||||||
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;
|
||||||
|
|
@ -282,10 +184,7 @@ pub async fn handle_udp(
|
||||||
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,
|
||||||
}
|
}
|
||||||
|
|
@ -304,7 +203,7 @@ async fn make_transport(
|
||||||
let domain = transport_cfg.domain.clone()
|
let domain = transport_cfg.domain.clone()
|
||||||
.unwrap_or_else(|| "tunnel.example.com".to_string());
|
.unwrap_or_else(|| "tunnel.example.com".to_string());
|
||||||
let resolver = transport_cfg.resolver.clone()
|
let resolver = transport_cfg.resolver.clone()
|
||||||
.unwrap_or_else(|| server.to_string());
|
.unwrap_or_else(|| "8.8.8.8".to_string());
|
||||||
let transport = crate::transport::dns::start_dns_transport(domain, resolver, transport_cfg.pubkey.clone()).await
|
let transport = crate::transport::dns::start_dns_transport(domain, resolver, transport_cfg.pubkey.clone()).await
|
||||||
.map_err(|e| anyhow::anyhow!(e))?;
|
.map_err(|e| anyhow::anyhow!(e))?;
|
||||||
Ok(transport)
|
Ok(transport)
|
||||||
|
|
@ -339,53 +238,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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -136,17 +136,13 @@ impl DnsPacket {
|
||||||
qtype: rtype.clone(),
|
qtype: rtype.clone(),
|
||||||
qclass: 1, // IN
|
qclass: 1, // IN
|
||||||
}],
|
}],
|
||||||
answers: if rdata.is_empty() {
|
answers: vec![DnsAnswer {
|
||||||
vec![]
|
|
||||||
} else {
|
|
||||||
vec![DnsAnswer {
|
|
||||||
name: name.to_string(),
|
name: name.to_string(),
|
||||||
rtype,
|
rtype,
|
||||||
rclass: 1,
|
rclass: 1,
|
||||||
ttl: 0, // No caching
|
ttl: 0, // No caching
|
||||||
rdata,
|
rdata,
|
||||||
}]
|
}],
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -393,9 +393,23 @@ impl ProtocolMachine {
|
||||||
} 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={}",
|
tracing::warn!("Reorder buffer full ({}/{}), forcing gap recovery to prevent packet drops",
|
||||||
self.reorder_buffer.len(), self.max_reorder_buffer, nonce, self.expected_recv_nonce
|
self.reorder_buffer.len(), self.max_reorder_buffer
|
||||||
);
|
);
|
||||||
|
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) {
|
||||||
|
app_actions.push(buffered_action);
|
||||||
|
self.expected_recv_nonce = self.expected_recv_nonce.saturating_add(1);
|
||||||
|
delivered += 1;
|
||||||
|
}
|
||||||
|
self.ack_pending = true;
|
||||||
|
tracing::debug!("Forced Gap recovery: skipped {} lost frames, delivered {} buffered frames", skipped, delivered);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if nonce >= self.expected_recv_nonce {
|
if nonce >= self.expected_recv_nonce {
|
||||||
|
|
@ -519,6 +533,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));
|
||||||
|
|
|
||||||
|
|
@ -527,9 +527,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())}');
|
||||||
|
|
|
||||||
|
|
@ -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.11+24
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.11.4
|
sdk: ^3.11.4
|
||||||
|
|
|
||||||
|
|
@ -2665,7 +2665,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-client"
|
name = "ostp-client"
|
||||||
version = "0.3.12"
|
version = "0.3.10"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
|
|
@ -2700,7 +2700,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-core"
|
name = "ostp-core"
|
||||||
version = "0.3.12"
|
version = "0.3.10"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"byteorder",
|
"byteorder",
|
||||||
|
|
@ -2742,7 +2742,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ostp-tun"
|
name = "ostp-tun"
|
||||||
version = "0.3.12"
|
version = "0.3.10"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"libc",
|
"libc",
|
||||||
|
|
|
||||||
|
|
@ -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.11",
|
||||||
"identifier": "com.ospab.ostp",
|
"identifier": "com.ospab.ostp",
|
||||||
"build": {
|
"build": {
|
||||||
"frontendDist": "../src"
|
"frontendDist": "../src"
|
||||||
|
|
|
||||||
|
|
@ -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)]
|
||||||
|
|
@ -328,9 +328,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 +576,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();
|
||||||
|
|
|
||||||
|
|
@ -1,83 +1,15 @@
|
||||||
/// DNS tunnel transport — dnstt-style server implementation.
|
|
||||||
///
|
|
||||||
/// Each DNS TXT query from client contains a framed chunk:
|
|
||||||
/// Base32([client_id: 8][msg_id: 2 BE][total_frags: 1][frag_idx: 1][payload: ≤120])
|
|
||||||
///
|
|
||||||
/// Server:
|
|
||||||
/// 1. Decodes ClientID + fragment from query name
|
|
||||||
/// 2. Reassembles fragments per (client_id, msg_id)
|
|
||||||
/// 3. Forwards complete OSTP packet to dispatcher (udp_tx)
|
|
||||||
/// 4. Waits up to MAX_RESPONSE_DELAY for responses
|
|
||||||
/// 5. Bundles responses as length-prefixed packets in DNS TXT answer
|
|
||||||
///
|
|
||||||
/// Server → client data in TXT rdata: [len_hi][len_lo][data...]...
|
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::net::SocketAddr;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use bytes::Bytes;
|
|
||||||
use tokio::net::UdpSocket;
|
use tokio::net::UdpSocket;
|
||||||
use tokio::sync::{mpsc, RwLock};
|
use tokio::sync::{mpsc, RwLock};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use bytes::Bytes;
|
||||||
use tokio::time::Duration;
|
use tokio::time::Duration;
|
||||||
|
|
||||||
use ostp_core::dns::{base32_decode, DnsPacket, DnsRecordType};
|
use ostp_core::dns::{DnsPacket, DnsRecordType, decode_domain_to_payload};
|
||||||
use crate::config::DnsTransportConfig;
|
use crate::config::DnsTransportConfig;
|
||||||
use crate::UiEvent;
|
use crate::UiEvent;
|
||||||
|
|
||||||
const CLIENT_ID_LEN: usize = 8;
|
|
||||||
const HEADER_LEN: usize = CLIENT_ID_LEN + 4; // client_id + msg_id(2) + total(1) + idx(1)
|
|
||||||
/// How long to wait for downstream OSTP data before sending an empty response.
|
|
||||||
const MAX_RESPONSE_DELAY: Duration = Duration::from_millis(800);
|
|
||||||
/// Maximum number of response packets to bundle into one DNS answer.
|
|
||||||
const MAX_RESPONSE_PACKETS: usize = 8;
|
|
||||||
/// How long to keep per-client reassembly state without activity.
|
|
||||||
const CLIENT_EXPIRY: Duration = Duration::from_secs(30);
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
|
||||||
struct ClientId([u8; CLIENT_ID_LEN]);
|
|
||||||
|
|
||||||
struct ReassemblyState {
|
|
||||||
total: u8,
|
|
||||||
frags: Vec<Option<Vec<u8>>>,
|
|
||||||
received: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ReassemblyState {
|
|
||||||
fn new(total: u8) -> Self {
|
|
||||||
Self {
|
|
||||||
total,
|
|
||||||
frags: vec![None; total as usize],
|
|
||||||
received: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn insert(&mut self, idx: u8, payload: Vec<u8>) -> bool {
|
|
||||||
let idx = idx as usize;
|
|
||||||
if idx >= self.frags.len() { return false; }
|
|
||||||
if self.frags[idx].is_none() {
|
|
||||||
self.frags[idx] = Some(payload);
|
|
||||||
self.received += 1;
|
|
||||||
}
|
|
||||||
self.received >= self.total
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assemble(self) -> Option<Vec<u8>> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
for frag in self.frags {
|
|
||||||
out.extend_from_slice(&frag?);
|
|
||||||
}
|
|
||||||
Some(out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct ClientState {
|
|
||||||
/// msg_id → reassembly buffer
|
|
||||||
reassembly: HashMap<u16, ReassemblyState>,
|
|
||||||
/// Channel to push pending responses into; DNS handler polls this per-query
|
|
||||||
#[allow(dead_code)]
|
|
||||||
resp_tx: mpsc::Sender<Bytes>,
|
|
||||||
last_seen: std::time::Instant,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn start_dns_transport_server(
|
pub(crate) async fn start_dns_transport_server(
|
||||||
config: DnsTransportConfig,
|
config: DnsTransportConfig,
|
||||||
udp_tx: mpsc::Sender<(Bytes, SocketAddr)>,
|
udp_tx: mpsc::Sender<(Bytes, SocketAddr)>,
|
||||||
|
|
@ -102,245 +34,80 @@ pub(crate) async fn start_dns_transport_server(
|
||||||
tracing::info!("DNS Transport listening on {}", listen_addr);
|
tracing::info!("DNS Transport listening on {}", listen_addr);
|
||||||
let _ = ui_event_tx.send(UiEvent::Log(format!("DNS Transport listening on {}", listen_addr)));
|
let _ = ui_event_tx.send(UiEvent::Log(format!("DNS Transport listening on {}", listen_addr)));
|
||||||
|
|
||||||
// Per-client state: ClientId → ClientState
|
|
||||||
// Access is serialised by a single Mutex so fragments from the same client
|
|
||||||
// are always reassembled atomically.
|
|
||||||
let clients: Arc<tokio::sync::Mutex<HashMap<ClientId, ClientState>>> =
|
|
||||||
Arc::new(tokio::sync::Mutex::new(HashMap::new()));
|
|
||||||
|
|
||||||
// Cleanup task: evict stale client state
|
|
||||||
{
|
|
||||||
let clients_gc = clients.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
loop {
|
|
||||||
tokio::time::sleep(Duration::from_secs(15)).await;
|
|
||||||
let mut map = clients_gc.lock().await;
|
|
||||||
map.retain(|_, v| v.last_seen.elapsed() < CLIENT_EXPIRY);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let base_domain = config.domain.clone();
|
|
||||||
let mut buf = vec![0u8; 65535];
|
let mut buf = vec![0u8; 65535];
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let (size, peer) = match socket.recv_from(&mut buf).await {
|
match socket.recv_from(&mut buf).await {
|
||||||
Ok(v) => v,
|
Ok((size, peer)) => {
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!("DNS Transport recv error: {}", e);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let packet_bytes = buf[..size].to_vec();
|
let packet_bytes = buf[..size].to_vec();
|
||||||
let udp_tx = udp_tx.clone();
|
let udp_tx = udp_tx.clone();
|
||||||
let tcp_map = tcp_map.clone();
|
let tcp_map = tcp_map.clone();
|
||||||
let socket = socket.clone();
|
let socket = socket.clone();
|
||||||
let clients = clients.clone();
|
let base_domain = config.domain.clone();
|
||||||
let base_domain = base_domain.clone();
|
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
handle_dns_query(
|
if let Some(dns_req) = DnsPacket::decode(&packet_bytes) {
|
||||||
packet_bytes, peer,
|
|
||||||
udp_tx, tcp_map, socket, clients, base_domain,
|
|
||||||
).await;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_dns_query(
|
|
||||||
packet_bytes: Vec<u8>,
|
|
||||||
peer: SocketAddr,
|
|
||||||
udp_tx: mpsc::Sender<(Bytes, SocketAddr)>,
|
|
||||||
tcp_map: Arc<RwLock<HashMap<SocketAddr, mpsc::Sender<Bytes>>>>,
|
|
||||||
socket: Arc<UdpSocket>,
|
|
||||||
clients: Arc<tokio::sync::Mutex<HashMap<ClientId, ClientState>>>,
|
|
||||||
base_domain: String,
|
|
||||||
) {
|
|
||||||
let dns_req = match DnsPacket::decode(&packet_bytes) {
|
|
||||||
Some(p) => p,
|
|
||||||
None => {
|
|
||||||
tracing::debug!("DNS: failed to decode packet from {}", peer);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if dns_req.questions.is_empty() { return; }
|
if dns_req.questions.is_empty() { return; }
|
||||||
let query = &dns_req.questions[0];
|
let query = &dns_req.questions[0];
|
||||||
|
|
||||||
if query.qtype != DnsRecordType::TXT && query.qtype != DnsRecordType::NULL {
|
// Check if it's our target domain and it's a TXT or NULL query
|
||||||
let resp = build_dns_response(&dns_req, &query.name, query.qtype.clone(), vec![]);
|
if (query.qtype == DnsRecordType::TXT || query.qtype == DnsRecordType::NULL) && query.name.ends_with(&base_domain) {
|
||||||
let _ = socket.send_to(&resp, peer).await;
|
// Decode base32 payload
|
||||||
return;
|
if let Some(payload) = decode_domain_to_payload(&query.name, &base_domain) {
|
||||||
}
|
|
||||||
if !query.name.ends_with(&base_domain) {
|
let (resp_tx, mut resp_rx) = mpsc::channel::<Bytes>(10);
|
||||||
let mut resp = DnsPacket::new_response(dns_req.id, &query.name, query.qtype.clone(), vec![]);
|
|
||||||
resp.flags = 0x8183; // NXDOMAIN
|
// Insert into tcp_map so Dispatcher routes responses to us
|
||||||
let _ = socket.send_to(&resp.encode(), peer).await;
|
tcp_map.write().await.insert(peer, resp_tx);
|
||||||
return;
|
|
||||||
|
// Send payload to dispatcher
|
||||||
|
if udp_tx.send((Bytes::from(payload), peer)).await.is_ok() {
|
||||||
|
// Wait up to 50ms for any responses
|
||||||
|
let mut responses = Vec::new();
|
||||||
|
|
||||||
|
while let Ok(Some(resp)) = tokio::time::timeout(Duration::from_millis(50), resp_rx.recv()).await {
|
||||||
|
responses.push(resp);
|
||||||
|
if responses.len() >= 3 { break; }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Strip base domain and labels separator to get base32 subdomain
|
// Remove from tcp_map
|
||||||
let subdomain = {
|
tcp_map.write().await.remove(&peer);
|
||||||
let name_lower = query.name.to_lowercase();
|
|
||||||
let suffix = format!(".{}", base_domain.to_lowercase());
|
// Build DNS Answer
|
||||||
let suffix_bare = base_domain.to_lowercase();
|
let mut dns_resp = DnsPacket::new_response(dns_req.id, &query.name, query.qtype.clone(), vec![]);
|
||||||
let stripped = if name_lower.ends_with(&suffix) {
|
dns_resp.answers.clear(); // We'll add our own
|
||||||
&query.name[..name_lower.len() - suffix.len()]
|
|
||||||
} else if name_lower == suffix_bare {
|
if !responses.is_empty() {
|
||||||
""
|
for r in responses {
|
||||||
|
dns_resp.answers.push(ostp_core::dns::DnsAnswer {
|
||||||
|
name: query.name.clone(),
|
||||||
|
rtype: query.qtype.clone(),
|
||||||
|
rclass: 1,
|
||||||
|
ttl: 0,
|
||||||
|
rdata: r.to_vec(),
|
||||||
|
});
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
return;
|
// Empty response
|
||||||
};
|
dns_resp.answers.push(ostp_core::dns::DnsAnswer {
|
||||||
// Remove dots (label separators) to get contiguous base32
|
name: query.name.clone(),
|
||||||
stripped.replace('.', "")
|
rtype: query.qtype.clone(),
|
||||||
};
|
rclass: 1,
|
||||||
|
ttl: 0,
|
||||||
if subdomain.is_empty() {
|
rdata: vec![],
|
||||||
// Pure poll — no payload
|
});
|
||||||
let resp = build_dns_response(&dns_req, &query.name, query.qtype.clone(), vec![]);
|
|
||||||
let _ = socket.send_to(&resp, peer).await;
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Base32-decode
|
let resp_encoded = dns_resp.encode();
|
||||||
let raw = match base32_decode(&subdomain) {
|
let _ = socket.send_to(&resp_encoded, peer).await;
|
||||||
Some(b) => b,
|
}
|
||||||
None => {
|
|
||||||
tracing::debug!("DNS: base32 decode failed from {}", peer);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
if raw.len() < HEADER_LEN {
|
|
||||||
tracing::debug!("DNS: frame too short ({} bytes) from {}", raw.len(), peer);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse header
|
|
||||||
let client_id = ClientId(raw[..CLIENT_ID_LEN].try_into().unwrap());
|
|
||||||
let msg_id = u16::from_be_bytes([raw[8], raw[9]]);
|
|
||||||
let total_frags = raw[10];
|
|
||||||
let frag_idx = raw[11];
|
|
||||||
let payload = raw[HEADER_LEN..].to_vec();
|
|
||||||
|
|
||||||
let fake_peer = client_id_to_fake_addr(&client_id);
|
|
||||||
|
|
||||||
tracing::trace!("DNS: client={} msg={} frag={}/{} payload={}B",
|
|
||||||
hex::encode(&client_id.0), msg_id, frag_idx + 1, total_frags, payload.len());
|
|
||||||
|
|
||||||
// ── Reassembly ────────────────────────────────────────────────────────────
|
|
||||||
let complete_packet: Option<Vec<u8>> = {
|
|
||||||
let mut map = clients.lock().await;
|
|
||||||
let state = map.entry(client_id).or_insert_with(|| {
|
|
||||||
let (resp_tx, _) = mpsc::channel(64); // placeholder, will be replaced below
|
|
||||||
ClientState {
|
|
||||||
reassembly: HashMap::new(),
|
|
||||||
resp_tx,
|
|
||||||
last_seen: std::time::Instant::now(),
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
state.last_seen = std::time::Instant::now();
|
|
||||||
|
|
||||||
if total_frags == 0 {
|
|
||||||
// Empty poll — no data
|
|
||||||
None
|
|
||||||
} else if total_frags == 1 && payload.is_empty() {
|
|
||||||
// Poll with empty payload
|
|
||||||
None
|
|
||||||
} else {
|
|
||||||
let asm = state.reassembly
|
|
||||||
.entry(msg_id)
|
|
||||||
.or_insert_with(|| ReassemblyState::new(total_frags));
|
|
||||||
|
|
||||||
if asm.insert(frag_idx, payload) {
|
|
||||||
// All fragments received — assemble and remove
|
|
||||||
let complete = state.reassembly.remove(&msg_id)
|
|
||||||
.and_then(|s| s.assemble());
|
|
||||||
complete
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
}
|
Err(e) => {
|
||||||
};
|
tracing::warn!("DNS Transport recv error: {}", e);
|
||||||
|
|
||||||
// ── Create per-query response channel ────────────────────────────────────
|
|
||||||
// We use the stable fake_peer as the routing key in tcp_map.
|
|
||||||
// For each query we create a fresh one-shot channel.
|
|
||||||
let (resp_tx, mut resp_rx) = mpsc::channel::<Bytes>(MAX_RESPONSE_PACKETS);
|
|
||||||
tcp_map.write().await.insert(fake_peer, resp_tx.clone());
|
|
||||||
|
|
||||||
// ── Forward complete OSTP packet to dispatcher ────────────────────────────
|
|
||||||
if let Some(ostp_pkt) = complete_packet {
|
|
||||||
tracing::debug!("DNS: forwarding {}B OSTP packet from client={} to dispatcher",
|
|
||||||
ostp_pkt.len(), hex::encode(&client_id.0));
|
|
||||||
let _ = udp_tx.send((Bytes::from(ostp_pkt), fake_peer)).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Wait for OSTP response(s) ─────────────────────────────────────────────
|
|
||||||
let mut responses: Vec<Bytes> = Vec::new();
|
|
||||||
let deadline = tokio::time::sleep(MAX_RESPONSE_DELAY);
|
|
||||||
tokio::pin!(deadline);
|
|
||||||
|
|
||||||
loop {
|
|
||||||
tokio::select! {
|
|
||||||
_ = &mut deadline => break,
|
|
||||||
resp = resp_rx.recv() => {
|
|
||||||
match resp {
|
|
||||||
Some(r) => {
|
|
||||||
responses.push(r);
|
|
||||||
if responses.len() >= MAX_RESPONSE_PACKETS { break; }
|
|
||||||
}
|
|
||||||
None => break,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only remove if it's still our channel
|
|
||||||
{
|
|
||||||
let mut map = tcp_map.write().await;
|
|
||||||
if let Some(existing_tx) = map.get(&fake_peer) {
|
|
||||||
if existing_tx.same_channel(&resp_tx) {
|
|
||||||
map.remove(&fake_peer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Build DNS TXT response ────────────────────────────────────────────────
|
|
||||||
// Bundle all response packets as length-prefixed data in TXT rdata:
|
|
||||||
// [len_hi][len_lo][data...]...
|
|
||||||
let mut rdata: Vec<u8> = Vec::new();
|
|
||||||
for r in &responses {
|
|
||||||
let len = r.len() as u16;
|
|
||||||
rdata.push((len >> 8) as u8);
|
|
||||||
rdata.push((len & 0xFF) as u8);
|
|
||||||
rdata.extend_from_slice(r);
|
|
||||||
}
|
|
||||||
|
|
||||||
tracing::trace!("DNS: responding to {} with {} OSTP packets ({} bytes rdata)",
|
|
||||||
peer, responses.len(), rdata.len());
|
|
||||||
|
|
||||||
let resp = build_dns_response(&dns_req, &query.name, query.qtype.clone(), rdata);
|
|
||||||
let _ = socket.send_to(&resp, peer).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build a DNS response packet with the given TXT rdata.
|
|
||||||
fn build_dns_response(
|
|
||||||
req: &DnsPacket,
|
|
||||||
name: &str,
|
|
||||||
rtype: DnsRecordType,
|
|
||||||
rdata: Vec<u8>,
|
|
||||||
) -> Vec<u8> {
|
|
||||||
let resp = DnsPacket::new_response(req.id, name, rtype, rdata);
|
|
||||||
resp.encode()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn client_id_to_fake_addr(client_id: &ClientId) -> SocketAddr {
|
|
||||||
let mut ip_bytes = [10, 255, 0, 0];
|
|
||||||
ip_bytes[2] = client_id.0[0];
|
|
||||||
ip_bytes[3] = client_id.0[1];
|
|
||||||
let port = u16::from_be_bytes([client_id.0[2], client_id.0[3]]);
|
|
||||||
let port = if port == 0 { 1 } else { port };
|
|
||||||
SocketAddr::from((ip_bytes, port))
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -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 {
|
||||||
|
|
@ -72,9 +70,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.");
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,3 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
ostp-core = { path = "../ostp-core" }
|
ostp-core = { path = "../ostp-core" }
|
||||||
colored = "2.1"
|
colored = "2.1"
|
||||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] }
|
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] }
|
||||||
pico-args = "0.5.0"
|
|
||||||
clipboard-win = "3.1.1"
|
|
||||||
|
|
||||||
|
|
|
||||||
786
ostp/src/main.rs
786
ostp/src/main.rs
|
|
@ -80,83 +80,6 @@ struct Args {
|
||||||
prober: bool,
|
prober: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn patch_existing_client_config(config_path: &std::path::Path, new_client_inner: serde_json::Value) -> serde_json::Value {
|
|
||||||
let unified_new = serde_json::to_value(UnifiedConfig {
|
|
||||||
mode: AppMode::Client(new_client_inner.clone()),
|
|
||||||
version: Some(env!("CARGO_PKG_VERSION").to_string()),
|
|
||||||
log: Some(serde_json::json!({ "level": "info" })),
|
|
||||||
}).unwrap();
|
|
||||||
|
|
||||||
if !config_path.exists() {
|
|
||||||
return unified_new;
|
|
||||||
}
|
|
||||||
|
|
||||||
let content = match std::fs::read_to_string(config_path) {
|
|
||||||
Ok(c) => c,
|
|
||||||
Err(_) => return unified_new,
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut stripped = json_comments::StripComments::new(content.as_bytes());
|
|
||||||
let mut existing: serde_json::Value = match serde_json::from_reader(&mut stripped) {
|
|
||||||
Ok(v) => v,
|
|
||||||
Err(_) => return unified_new,
|
|
||||||
};
|
|
||||||
|
|
||||||
if existing.get("mode").and_then(|m| m.as_str()) != Some("client") {
|
|
||||||
return unified_new;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut new_proxy = None;
|
|
||||||
if let Some(outbounds) = new_client_inner.get("outbounds").and_then(|o| o.as_array()) {
|
|
||||||
for ob in outbounds {
|
|
||||||
if ob.get("tag").and_then(|t| t.as_str()) == Some("proxy") {
|
|
||||||
new_proxy = Some(ob.clone());
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(new_proxy) = new_proxy {
|
|
||||||
if let Some(existing_outbounds) = existing.get_mut("outbounds").and_then(|o| o.as_array_mut()) {
|
|
||||||
let mut replaced = false;
|
|
||||||
for ob in existing_outbounds.iter_mut() {
|
|
||||||
if ob.get("tag").and_then(|t| t.as_str()) == Some("proxy") {
|
|
||||||
*ob = new_proxy.clone();
|
|
||||||
replaced = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !replaced {
|
|
||||||
existing_outbounds.insert(0, new_proxy);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
existing["outbounds"] = serde_json::json!([new_proxy]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(new_inbounds) = new_client_inner.get("inbounds").and_then(|i| i.as_array()) {
|
|
||||||
for new_ib in new_inbounds {
|
|
||||||
if new_ib.get("type").and_then(|t| t.as_str()) == Some("tun") {
|
|
||||||
if let Some(auto_route) = new_ib.get("auto_route").and_then(|a| a.as_bool()) {
|
|
||||||
if auto_route {
|
|
||||||
if let Some(existing_inbounds) = existing.get_mut("inbounds").and_then(|i| i.as_array_mut()) {
|
|
||||||
for existing_ib in existing_inbounds.iter_mut() {
|
|
||||||
if existing_ib.get("type").and_then(|t| t.as_str()) == Some("tun") {
|
|
||||||
existing_ib["auto_route"] = serde_json::json!(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
existing["version"] = serde_json::json!(env!("CARGO_PKG_VERSION"));
|
|
||||||
|
|
||||||
existing
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_ostp_link(link: &str) -> Result<serde_json::Value> {
|
fn parse_ostp_link(link: &str) -> Result<serde_json::Value> {
|
||||||
let parsed = url::Url::parse(link)
|
let parsed = url::Url::parse(link)
|
||||||
.map_err(|e| anyhow!("Failed to parse share link URL: {e}"))?;
|
.map_err(|e| anyhow!("Failed to parse share link URL: {e}"))?;
|
||||||
|
|
@ -208,7 +131,7 @@ fn parse_ostp_link(link: &str) -> Result<serde_json::Value> {
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(serde_json::json!({
|
Ok(serde_json::json!({
|
||||||
"version": env!("CARGO_PKG_VERSION"),
|
"version": "{}",
|
||||||
"log": {
|
"log": {
|
||||||
"level": "info"
|
"level": "info"
|
||||||
},
|
},
|
||||||
|
|
@ -786,7 +709,7 @@ fn run_setup_wizard(config_path: &std::path::Path) -> Result<()> {
|
||||||
|
|
||||||
let client_json = serde_json::json!({
|
let client_json = serde_json::json!({
|
||||||
"mode": "client",
|
"mode": "client",
|
||||||
"version": env!("CARGO_PKG_VERSION"),
|
"version": "{}",
|
||||||
"log": {
|
"log": {
|
||||||
"level": "info"
|
"level": "info"
|
||||||
},
|
},
|
||||||
|
|
@ -1206,7 +1129,18 @@ async fn run_app() -> Result<()> {
|
||||||
return cmd_migrate(&args.config);
|
return cmd_migrate(&args.config);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if args.config.exists() && !args.uninstall && !args.update {
|
||||||
|
if let Ok(config_content) = fs::read_to_string(&args.config) {
|
||||||
|
let mut stripped = json_comments::StripComments::new(config_content.as_bytes());
|
||||||
|
if let Ok(raw_json) = serde_json::from_reader::<_, serde_json::Value>(&mut stripped) {
|
||||||
|
if raw_json.get("version").and_then(|v| v.as_str()) != Some(env!("CARGO_PKG_VERSION")) {
|
||||||
|
println!("{} Outdated configuration format detected.", "[ostp]".yellow().bold());
|
||||||
|
println!("{} Please run '{}' to update your configuration to the latest modular format.", "[ostp]".yellow().bold(), "ostp --migrate".green());
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ── Setup wizard: explicit flag or first-time (no config) ────────
|
// ── Setup wizard: explicit flag or first-time (no config) ────────
|
||||||
if args.setup {
|
if args.setup {
|
||||||
|
|
@ -1301,8 +1235,12 @@ async fn run_app() -> Result<()> {
|
||||||
println!("{} Importing configuration from share link...", "[ostp]".cyan().bold());
|
println!("{} Importing configuration from share link...", "[ostp]".cyan().bold());
|
||||||
let client_cfg = parse_ostp_link(&import_url)
|
let client_cfg = parse_ostp_link(&import_url)
|
||||||
.map_err(|e| anyhow!("Share Link Error: {e}"))?;
|
.map_err(|e| anyhow!("Share Link Error: {e}"))?;
|
||||||
let patched = patch_existing_client_config(&args.config, client_cfg);
|
let unified = UnifiedConfig {
|
||||||
let content = serde_json::to_string_pretty(&patched)?;
|
mode: AppMode::Client(client_cfg),
|
||||||
|
version: Some("0.3.1".to_string()),
|
||||||
|
log: Some(serde_json::json!({ "level": "info" })),
|
||||||
|
};
|
||||||
|
let content = serde_json::to_string_pretty(&unified)?;
|
||||||
if let Some(parent) = args.config.parent() {
|
if let Some(parent) = args.config.parent() {
|
||||||
if !parent.as_os_str().is_empty() {
|
if !parent.as_os_str().is_empty() {
|
||||||
fs::create_dir_all(parent)?;
|
fs::create_dir_all(parent)?;
|
||||||
|
|
@ -1374,8 +1312,7 @@ async fn run_app() -> Result<()> {
|
||||||
client_cfg["log"]["level"] = serde_json::json!("debug");
|
client_cfg["log"]["level"] = serde_json::json!("debug");
|
||||||
}
|
}
|
||||||
|
|
||||||
let patched = patch_existing_client_config(&args.config, client_cfg);
|
return run_client_directly(client_cfg).await;
|
||||||
return run_client_directly(patched).await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle --check: validate config and exit
|
// Handle --check: validate config and exit
|
||||||
|
|
@ -1614,25 +1551,6 @@ async fn run_app() -> Result<()> {
|
||||||
"sessions": 1
|
"sessions": 1
|
||||||
}}
|
}}
|
||||||
}},
|
}},
|
||||||
{{
|
|
||||||
// DNS Tunneling connection to the remote OSTP server
|
|
||||||
// NOTE: DNS Tunneling is very slow and should be used only when UDP/TCP are blocked.
|
|
||||||
// Read the manual here: https://github.com/ospab/ostp/wiki/DNS-Tunneling
|
|
||||||
"type": "ostp",
|
|
||||||
"tag": "proxy-dns",
|
|
||||||
"server": "1.1.1.1",
|
|
||||||
"port": 53,
|
|
||||||
"access_key": "{key}",
|
|
||||||
"transport": {{
|
|
||||||
"type": "dns",
|
|
||||||
"domain": "tunnel.yourdomain.com",
|
|
||||||
"pubkey": "SERVER_PUBLIC_KEY_HERE"
|
|
||||||
}},
|
|
||||||
"multiplex": {{
|
|
||||||
"enabled": true,
|
|
||||||
"sessions": 5
|
|
||||||
}}
|
|
||||||
}},
|
|
||||||
{{
|
{{
|
||||||
"type": "direct",
|
"type": "direct",
|
||||||
"tag": "direct"
|
"tag": "direct"
|
||||||
|
|
@ -1717,27 +1635,28 @@ async fn run_app() -> Result<()> {
|
||||||
let mut raw_json: serde_json::Value = serde_json::from_reader(&mut stripped)
|
let mut raw_json: serde_json::Value = serde_json::from_reader(&mut stripped)
|
||||||
.map_err(|e| anyhow!("Failed to parse config as JSON: {}", e))?;
|
.map_err(|e| anyhow!("Failed to parse config as JSON: {}", e))?;
|
||||||
|
|
||||||
|
let is_migrated = raw_json.get("version").and_then(|v| v.as_str()) == Some(env!("CARGO_PKG_VERSION"));
|
||||||
// Hard stop if config is not in current format — user must run --migrate explicitly
|
if !is_migrated {
|
||||||
{
|
let is_server = raw_json.get("listen").is_some() || raw_json.get("access_keys").is_some();
|
||||||
let has_new_format = raw_json.get("inbounds").and_then(|v| v.as_array()).is_some()
|
if is_server {
|
||||||
&& raw_json.get("outbounds").and_then(|v| v.as_array()).is_some();
|
raw_json["mode"] = serde_json::json!("server");
|
||||||
let version_ok = raw_json.get("version").and_then(|v| v.as_str()) == Some(env!("CARGO_PKG_VERSION"));
|
|
||||||
if !has_new_format {
|
|
||||||
eprintln!();
|
|
||||||
eprintln!("{} Your configuration file is in an outdated format.", "[ostp]".yellow().bold());
|
|
||||||
eprintln!("{} Run the following command to upgrade it:", "[ostp]".yellow().bold());
|
|
||||||
eprintln!();
|
|
||||||
eprintln!(" {}", "ostp --migrate".green().bold());
|
|
||||||
eprintln!();
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
if !version_ok {
|
|
||||||
// New format but wrong version — silently fix just the version field in memory (no write)
|
|
||||||
raw_json["version"] = serde_json::json!(env!("CARGO_PKG_VERSION"));
|
raw_json["version"] = serde_json::json!(env!("CARGO_PKG_VERSION"));
|
||||||
|
if let Some(log) = raw_json.get("log_level") {
|
||||||
|
raw_json["log"] = serde_json::json!({ "level": log.clone() });
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
let (migrated, _) = ostp_client::config::ClientConfig::migrate_json(raw_json);
|
||||||
|
raw_json = migrated;
|
||||||
|
raw_json["mode"] = serde_json::json!("client");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Save migrated config back
|
||||||
|
let serialized = serde_json::to_string_pretty(&raw_json)?;
|
||||||
|
let header = "// OSTP Configuration v0.3.1\n// DO NOT EDIT THIS COMMENT - Migrator relies on it\n";
|
||||||
|
let final_content = format!("{}{}", header, serialized);
|
||||||
|
let _ = fs::write(&args.config, final_content);
|
||||||
|
println!("{} Configuration automatically migrated to v0.3.1", "[ostp]".cyan().bold());
|
||||||
|
}
|
||||||
|
|
||||||
let config: UnifiedConfig = serde_json::from_value(raw_json)
|
let config: UnifiedConfig = serde_json::from_value(raw_json)
|
||||||
.map_err(|e| anyhow!("Failed to parse config: {}", e))?;
|
.map_err(|e| anyhow!("Failed to parse config: {}", e))?;
|
||||||
|
|
@ -2030,528 +1949,145 @@ fn cmd_migrate(config_path: &std::path::Path) -> Result<()> {
|
||||||
|
|
||||||
let config_content = fs::read_to_string(config_path)?;
|
let config_content = fs::read_to_string(config_path)?;
|
||||||
let mut stripped = json_comments::StripComments::new(config_content.as_bytes());
|
let mut stripped = json_comments::StripComments::new(config_content.as_bytes());
|
||||||
let old: serde_json::Value = serde_json::from_reader(&mut stripped)
|
let mut raw_json: serde_json::Value = serde_json::from_reader(&mut stripped)
|
||||||
.map_err(|e| anyhow!("Failed to parse config as JSON: {}", e))?;
|
.map_err(|e| anyhow!("Failed to parse config as JSON: {}", e))?;
|
||||||
|
|
||||||
// --- Determine config type ---
|
let is_migrated = raw_json.get("version").and_then(|v| v.as_str()) == Some(env!("CARGO_PKG_VERSION"));
|
||||||
let mode = old.get("mode").and_then(|m| m.as_str()).unwrap_or("");
|
if is_migrated {
|
||||||
let is_server = mode == "server"
|
println!("{} Configuration is already up to date (v0.3.5)", "[ostp]".cyan().bold());
|
||||||
|| old.get("listen").is_some()
|
return Ok(());
|
||||||
|| old.get("access_keys").is_some()
|
}
|
||||||
|| old.get("inbounds").and_then(|v| v.as_array()).map(|arr| {
|
|
||||||
arr.iter().any(|i| {
|
|
||||||
i.get("protocol").and_then(|p| p.as_str()) == Some("ostp")
|
|
||||||
|| i.get("type").and_then(|t| t.as_str()) == Some("ostp")
|
|
||||||
})
|
|
||||||
}).unwrap_or(false);
|
|
||||||
let is_relay = mode == "relay" || old.get("upstream_tcp").is_some();
|
|
||||||
let _is_client = !is_server && !is_relay;
|
|
||||||
|
|
||||||
// --- Helper: extract log level ---
|
|
||||||
let log_level = old.get("log").and_then(|l| l.get("level")).and_then(|v| v.as_str())
|
|
||||||
.or_else(|| old.get("log_level").and_then(|v| v.as_str()))
|
|
||||||
.unwrap_or("info");
|
|
||||||
|
|
||||||
// --- Backup original ---
|
|
||||||
let bak_path = config_path.with_extension("json.bak");
|
|
||||||
fs::copy(config_path, &bak_path)?;
|
|
||||||
println!("{} Original config backed up to {:?}", "[ostp]".cyan().bold(), bak_path);
|
|
||||||
|
|
||||||
let new_content: String;
|
|
||||||
|
|
||||||
|
let is_server = raw_json.get("listen").is_some() || raw_json.get("access_keys").is_some() || raw_json.get("mode").and_then(|m| m.as_str()) == Some("server");
|
||||||
if is_server {
|
if is_server {
|
||||||
println!("{} Detected: Server configuration", "[ostp]".cyan().bold());
|
raw_json["mode"] = serde_json::json!("server");
|
||||||
|
raw_json["version"] = serde_json::json!(env!("CARGO_PKG_VERSION"));
|
||||||
|
if let Some(log) = raw_json.get("log_level") {
|
||||||
|
raw_json["log"] = serde_json::json!({ "level": log.clone() });
|
||||||
|
}
|
||||||
|
|
||||||
// --- Extract server data ---
|
let mut inbounds = Vec::new();
|
||||||
// Listen host:port
|
let mut outbounds = Vec::new();
|
||||||
let (listen_host, listen_port) = extract_server_listen(&old);
|
let mut routing = serde_json::json!({
|
||||||
|
"rules": [],
|
||||||
|
"default_outbound": "direct"
|
||||||
|
});
|
||||||
|
|
||||||
// Access keys — support old flat list and new inbounds format
|
// Migrate Ostp inbound
|
||||||
let users_json = extract_server_users(&old);
|
let listen = raw_json.get("listen").and_then(|l| l.as_str()).unwrap_or("0.0.0.0:50000");
|
||||||
|
let parts: Vec<&str> = listen.split(':').collect();
|
||||||
|
let host = parts.get(0).unwrap_or(&"0.0.0.0");
|
||||||
|
let port: u16 = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(50000);
|
||||||
|
|
||||||
// Fallback
|
let mut users = Vec::new();
|
||||||
let (fallback_enabled, fallback_listen, fallback_target) = extract_server_fallback(&old);
|
if let Some(keys) = raw_json.get("access_keys").and_then(|a| a.as_array()) {
|
||||||
|
for k in keys {
|
||||||
|
users.push(serde_json::json!({
|
||||||
|
"key": k.as_str().unwrap_or("")
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// API
|
let mut ostp_inbound = serde_json::json!({
|
||||||
let (api_listen, api_port, api_token, api_webpath, api_username, api_pass_hash) =
|
|
||||||
extract_server_api(&old);
|
|
||||||
|
|
||||||
// DNS transport
|
|
||||||
let (dns_listen, dns_domain, dns_pubkey, dns_privkey) = extract_server_dns(&old);
|
|
||||||
|
|
||||||
// Routing rules (preserve if present)
|
|
||||||
let routing_rules_str = extract_routing_rules_str(&old);
|
|
||||||
let default_outbound = old.get("routing").and_then(|r| r.get("default_outbound"))
|
|
||||||
.and_then(|v| v.as_str()).unwrap_or("direct");
|
|
||||||
|
|
||||||
let users_str = users_json.iter()
|
|
||||||
.map(|k| format!(
|
|
||||||
r#" {{
|
|
||||||
"key": "{}"
|
|
||||||
}}
|
|
||||||
"#, k))
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join(",\n");
|
|
||||||
let users_str = if users_str.is_empty() {
|
|
||||||
format!(r#" {{
|
|
||||||
"key": "{}"
|
|
||||||
}}
|
|
||||||
"#, generate_secure_key("hex"))
|
|
||||||
} else { users_str };
|
|
||||||
|
|
||||||
new_content = format!(r#"{{
|
|
||||||
// OSTP Server Configuration
|
|
||||||
"version": "{ver}",
|
|
||||||
"mode": "server",
|
|
||||||
"log": {{
|
|
||||||
// Log levels: trace, debug, info, warn, error
|
|
||||||
"level": "{log_level}"
|
|
||||||
}},
|
|
||||||
"inbounds": [
|
|
||||||
{{
|
|
||||||
// Primary OSTP protocol listener
|
|
||||||
"protocol": "ostp",
|
"protocol": "ostp",
|
||||||
"tag": "ostp-in",
|
"tag": "ostp-in",
|
||||||
"listen": "{listen_host}",
|
"listen": host,
|
||||||
"port": {listen_port},
|
"port": port,
|
||||||
"users": [
|
"users": users
|
||||||
{users_str} ],
|
});
|
||||||
"fallback": {{
|
|
||||||
// Fallback protection: redirects unauthorized probes to a real website
|
if let Some(fallback) = raw_json.get("fallback") {
|
||||||
"enabled": {fallback_enabled},
|
ostp_inbound["fallback"] = fallback.clone();
|
||||||
"listen": "{fallback_listen}",
|
}
|
||||||
"target": "{fallback_target}"
|
inbounds.push(ostp_inbound);
|
||||||
}}
|
|
||||||
}},
|
// Migrate Api inbound
|
||||||
{{
|
if let Some(api) = raw_json.get("api") {
|
||||||
// Web Administration API
|
let mut api_inbound = api.clone();
|
||||||
"protocol": "api",
|
api_inbound["protocol"] = serde_json::json!("api");
|
||||||
"tag": "api-in",
|
api_inbound["tag"] = serde_json::json!("api-in");
|
||||||
"listen": "{api_listen}",
|
let bind = api.get("bind").and_then(|b| b.as_str()).unwrap_or("127.0.0.1:9090");
|
||||||
"port": {api_port},
|
let parts: Vec<&str> = bind.split(':').collect();
|
||||||
"token": "{api_token}",
|
api_inbound["listen"] = serde_json::json!(parts.get(0).unwrap_or(&"127.0.0.1"));
|
||||||
"webpath": "{api_webpath}",
|
api_inbound["port"] = serde_json::json!(parts.get(1).and_then(|p| p.parse::<u16>().ok()).unwrap_or(9090));
|
||||||
"username": "{api_username}",
|
inbounds.push(api_inbound);
|
||||||
"password_hash": "{api_pass_hash}"
|
}
|
||||||
}},
|
|
||||||
{{
|
// Migrate Outbound
|
||||||
// DNS Tunnel Inbound
|
outbounds.push(serde_json::json!({
|
||||||
// [WARNING] This is a last-resort transport via public DNS.
|
|
||||||
// It requires a dedicated registered domain with NS records pointing to this server.
|
|
||||||
// Full setup guide: https://github.com/ospab/ostp/wiki/DNS-Tunneling
|
|
||||||
"protocol": "dns",
|
|
||||||
"tag": "dns-tunnel",
|
|
||||||
"listen": "{dns_listen}",
|
|
||||||
"domain": "{dns_domain}",
|
|
||||||
"pubkey": "{dns_pubkey}",
|
|
||||||
"privkey": "{dns_privkey}"
|
|
||||||
}}
|
|
||||||
],
|
|
||||||
"outbounds": [
|
|
||||||
{{
|
|
||||||
// Example local SOCKS5 proxy (e.g. for Tor network)
|
|
||||||
"protocol": "socks5",
|
|
||||||
"tag": "socks5-local",
|
|
||||||
"server": "127.0.0.1",
|
|
||||||
"port": 9050
|
|
||||||
}},
|
|
||||||
{{
|
|
||||||
// Default direct internet access
|
|
||||||
"protocol": "direct",
|
"protocol": "direct",
|
||||||
"tag": "direct"
|
"tag": "direct"
|
||||||
}},
|
}));
|
||||||
{{
|
outbounds.push(serde_json::json!({
|
||||||
// Blackhole for blocked connections
|
|
||||||
"protocol": "block",
|
"protocol": "block",
|
||||||
"tag": "block"
|
"tag": "block"
|
||||||
}}
|
}));
|
||||||
],
|
|
||||||
"routing": {{
|
|
||||||
// Rule-based routing of client traffic
|
|
||||||
"rules": [{routing_rules}],
|
|
||||||
// If no rules match, use the default outbound
|
|
||||||
"default_outbound": "{default_outbound}"
|
|
||||||
}},
|
|
||||||
"debug": false
|
|
||||||
}}
|
|
||||||
"#,
|
|
||||||
ver = env!("CARGO_PKG_VERSION"),
|
|
||||||
log_level = log_level,
|
|
||||||
listen_host = listen_host,
|
|
||||||
listen_port = listen_port,
|
|
||||||
users_str = users_str,
|
|
||||||
fallback_enabled = fallback_enabled,
|
|
||||||
fallback_listen = fallback_listen,
|
|
||||||
fallback_target = fallback_target,
|
|
||||||
api_listen = api_listen,
|
|
||||||
api_port = api_port,
|
|
||||||
api_token = api_token,
|
|
||||||
api_webpath = api_webpath,
|
|
||||||
api_username = api_username,
|
|
||||||
api_pass_hash = api_pass_hash,
|
|
||||||
dns_listen = dns_listen,
|
|
||||||
dns_domain = dns_domain,
|
|
||||||
dns_pubkey = dns_pubkey,
|
|
||||||
dns_privkey = dns_privkey,
|
|
||||||
routing_rules = routing_rules_str,
|
|
||||||
default_outbound = default_outbound,
|
|
||||||
);
|
|
||||||
|
|
||||||
} else if is_relay {
|
if let Some(ob) = raw_json.get("outbound") {
|
||||||
println!("{} Detected: Relay configuration", "[ostp]".cyan().bold());
|
if ob.get("enabled").and_then(|e| e.as_bool()).unwrap_or(false) {
|
||||||
|
let tag = "socks5-legacy";
|
||||||
|
let socks = serde_json::json!({
|
||||||
|
"protocol": "socks5",
|
||||||
|
"tag": tag,
|
||||||
|
"server": ob.get("address").and_then(|a| a.as_str()).unwrap_or("127.0.0.1"),
|
||||||
|
"port": ob.get("port").and_then(|p| p.as_u64()).unwrap_or(9050)
|
||||||
|
});
|
||||||
|
outbounds.push(socks);
|
||||||
|
|
||||||
let upstream_tcp = old.get("upstream_tcp").and_then(|v| v.as_str()).unwrap_or("TARGET_SERVER_IP:50000");
|
if let Some(rules) = ob.get("rules").and_then(|r| r.as_array()) {
|
||||||
let upstream_udp = old.get("upstream_udp").and_then(|v| v.as_str()).unwrap_or(upstream_tcp);
|
let mut new_rules = Vec::new();
|
||||||
let api_url = old.get("upstream_api_url").and_then(|v| v.as_str()).unwrap_or("http://TARGET_SERVER_IP:9090");
|
for rule in rules {
|
||||||
let api_token = old.get("upstream_api_token").and_then(|v| v.as_str()).unwrap_or("");
|
let mut new_rule = rule.clone();
|
||||||
let sync_interval = old.get("sync_interval_secs").and_then(|v| v.as_u64()).unwrap_or(30);
|
new_rule["outbound"] = serde_json::json!(tag);
|
||||||
let listen = old.get("listen").and_then(|v| v.as_str()).unwrap_or("0.0.0.0:50000");
|
new_rules.push(new_rule);
|
||||||
|
}
|
||||||
new_content = format!(r#"{{
|
routing["rules"] = serde_json::json!(new_rules);
|
||||||
// OSTP Relay Configuration
|
|
||||||
"version": "{ver}",
|
|
||||||
"mode": "relay",
|
|
||||||
"log": {{
|
|
||||||
// Log levels: trace, debug, info, warn, error
|
|
||||||
"level": "{log_level}"
|
|
||||||
}},
|
|
||||||
// Local port for the relay to listen on
|
|
||||||
"listen": "{listen}",
|
|
||||||
// Upstream server details
|
|
||||||
"upstream_tcp": "{upstream_tcp}",
|
|
||||||
"upstream_udp": "{upstream_udp}",
|
|
||||||
// Upstream Control Panel API for automatic key synchronization
|
|
||||||
"upstream_api_url": "{api_url}",
|
|
||||||
"upstream_api_token": "{api_token}",
|
|
||||||
"sync_interval_secs": {sync_interval},
|
|
||||||
"debug": false
|
|
||||||
}}
|
|
||||||
"#,
|
|
||||||
ver = env!("CARGO_PKG_VERSION"),
|
|
||||||
log_level = log_level,
|
|
||||||
listen = listen,
|
|
||||||
upstream_tcp = upstream_tcp,
|
|
||||||
upstream_udp = upstream_udp,
|
|
||||||
api_url = api_url,
|
|
||||||
api_token = api_token,
|
|
||||||
sync_interval = sync_interval,
|
|
||||||
);
|
|
||||||
|
|
||||||
} else {
|
|
||||||
println!("{} Detected: Client configuration", "[ostp]".cyan().bold());
|
|
||||||
|
|
||||||
// Extract client data
|
|
||||||
let (server_ip, server_port, access_key, transport_type) = extract_client_server(&old);
|
|
||||||
let (socks_listen, socks_port) = extract_client_socks(&old);
|
|
||||||
let tun_enabled = extract_client_tun(&old);
|
|
||||||
let mux_enabled = old.get("mux").and_then(|m| m.get("enabled")).and_then(|v| v.as_bool())
|
|
||||||
.or_else(|| old.get("outbounds").and_then(|o| o.as_array()).and_then(|arr| {
|
|
||||||
arr.iter().find(|o| o.get("type").and_then(|t| t.as_str()) == Some("ostp"))
|
|
||||||
.and_then(|o| o.get("multiplex")).and_then(|m| m.get("enabled")).and_then(|v| v.as_bool())
|
|
||||||
}))
|
|
||||||
.unwrap_or(false);
|
|
||||||
let mux_sessions = old.get("mux").and_then(|m| m.get("sessions")).and_then(|v| v.as_u64())
|
|
||||||
.or_else(|| old.get("outbounds").and_then(|o| o.as_array()).and_then(|arr| {
|
|
||||||
arr.iter().find(|o| o.get("type").and_then(|t| t.as_str()) == Some("ostp"))
|
|
||||||
.and_then(|o| o.get("multiplex")).and_then(|m| m.get("sessions")).and_then(|v| v.as_u64())
|
|
||||||
}))
|
|
||||||
.unwrap_or(1);
|
|
||||||
let routing_rules_str = extract_routing_rules_str(&old);
|
|
||||||
let default_outbound = old.get("routing").and_then(|r| r.get("default_outbound"))
|
|
||||||
.and_then(|v| v.as_str()).unwrap_or("proxy");
|
|
||||||
|
|
||||||
let tun_block = if tun_enabled {
|
|
||||||
r#" {{
|
|
||||||
// Virtual network interface for transparent proxying
|
|
||||||
"type": "tun",
|
|
||||||
"tag": "tun-in",
|
|
||||||
"auto_route": true,
|
|
||||||
"mtu": 1140
|
|
||||||
}},
|
|
||||||
"#
|
|
||||||
} else {
|
|
||||||
r#" // Uncomment below to enable TUN (VPN) mode:
|
|
||||||
// {{ "type": "tun", "tag": "tun-in", "auto_route": true, "mtu": 1140 }},
|
|
||||||
"#
|
|
||||||
};
|
|
||||||
|
|
||||||
new_content = format!(r#"{{
|
|
||||||
// OSTP Client Configuration
|
|
||||||
"version": "{ver}",
|
|
||||||
"mode": "client",
|
|
||||||
"log": {{
|
|
||||||
"level": "{log_level}"
|
|
||||||
}},
|
|
||||||
"inbounds": [
|
|
||||||
{tun_block} {{
|
|
||||||
// Local SOCKS5 proxy server for browser configuration
|
|
||||||
"type": "local_proxy",
|
|
||||||
"tag": "socks-in",
|
|
||||||
"protocol": "socks",
|
|
||||||
"listen": "{socks_listen}",
|
|
||||||
"port": {socks_port}
|
|
||||||
}}
|
|
||||||
],
|
|
||||||
"outbounds": [
|
|
||||||
{{
|
|
||||||
// Connection to the remote OSTP server
|
|
||||||
"type": "ostp",
|
|
||||||
"tag": "proxy",
|
|
||||||
"server": "{server_ip}",
|
|
||||||
"port": {server_port},
|
|
||||||
"access_key": "{access_key}",
|
|
||||||
"transport": {{
|
|
||||||
"type": "{transport_type}"
|
|
||||||
}},
|
|
||||||
"multiplex": {{
|
|
||||||
"enabled": {mux_enabled},
|
|
||||||
"sessions": {mux_sessions}
|
|
||||||
}}
|
|
||||||
}},
|
|
||||||
{{
|
|
||||||
"type": "direct",
|
|
||||||
"tag": "direct"
|
|
||||||
}},
|
|
||||||
{{
|
|
||||||
"type": "block",
|
|
||||||
"tag": "block"
|
|
||||||
}}
|
|
||||||
],
|
|
||||||
"routing": {{
|
|
||||||
"rules": [{routing_rules}],
|
|
||||||
"default_outbound": "{default_outbound}"
|
|
||||||
}}
|
|
||||||
}}
|
|
||||||
"#,
|
|
||||||
ver = env!("CARGO_PKG_VERSION"),
|
|
||||||
log_level = log_level,
|
|
||||||
tun_block = tun_block,
|
|
||||||
socks_listen = socks_listen,
|
|
||||||
socks_port = socks_port,
|
|
||||||
server_ip = server_ip,
|
|
||||||
server_port = server_port,
|
|
||||||
access_key = access_key,
|
|
||||||
transport_type = transport_type,
|
|
||||||
mux_enabled = mux_enabled,
|
|
||||||
mux_sessions = mux_sessions,
|
|
||||||
routing_rules = routing_rules_str,
|
|
||||||
default_outbound = default_outbound,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fs::write(config_path, &new_content)?;
|
let default_action = ob.get("default_action").and_then(|a| a.as_str()).unwrap_or("proxy");
|
||||||
println!("{} Configuration successfully migrated to v{}!", "[ostp]".green().bold(), env!("CARGO_PKG_VERSION"));
|
if default_action == "proxy" {
|
||||||
println!("{} Backup saved at {:?}", "[ostp]".dimmed(), bak_path);
|
routing["default_outbound"] = serde_json::json!(tag);
|
||||||
|
} else if default_action == "block" {
|
||||||
|
routing["default_outbound"] = serde_json::json!("block");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DNS migrate
|
||||||
|
if let Some(dns) = raw_json.get("dns_transport") {
|
||||||
|
let mut dns_inbound = dns.clone();
|
||||||
|
dns_inbound["protocol"] = serde_json::json!("dns");
|
||||||
|
dns_inbound["tag"] = serde_json::json!("dns-tunnel");
|
||||||
|
inbounds.push(dns_inbound);
|
||||||
|
}
|
||||||
|
|
||||||
|
raw_json["inbounds"] = serde_json::json!(inbounds);
|
||||||
|
raw_json["outbounds"] = serde_json::json!(outbounds);
|
||||||
|
raw_json["routing"] = routing;
|
||||||
|
|
||||||
|
// Remove legacy fields
|
||||||
|
let obj = raw_json.as_object_mut().unwrap();
|
||||||
|
obj.remove("listen");
|
||||||
|
obj.remove("access_keys");
|
||||||
|
obj.remove("fallback");
|
||||||
|
obj.remove("api");
|
||||||
|
obj.remove("outbound");
|
||||||
|
obj.remove("log_level");
|
||||||
|
obj.remove("dns_transport");
|
||||||
|
|
||||||
|
println!("{} Detected Server configuration.", "[ostp]".cyan().bold());
|
||||||
|
} else {
|
||||||
|
println!("{} Detected Client configuration.", "[ostp]".cyan().bold());
|
||||||
|
let (migrated, _) = ostp_client::config::ClientConfig::migrate_json(raw_json.clone());
|
||||||
|
raw_json = migrated;
|
||||||
|
raw_json["mode"] = serde_json::json!("client");
|
||||||
|
raw_json["version"] = serde_json::json!(env!("CARGO_PKG_VERSION"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let serialized = serde_json::to_string_pretty(&raw_json)?;
|
||||||
|
let final_content = format!("{}", serialized);
|
||||||
|
fs::write(config_path, final_content)?;
|
||||||
|
|
||||||
|
println!("{} Successfully migrated configuration to v0.3.5!", "[ostp]".green().bold());
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Migration helper extractors
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
/// Extract listen host and port for server from old or new format
|
|
||||||
fn extract_server_listen(old: &serde_json::Value) -> (String, u16) {
|
|
||||||
// New format: inbounds[type=ostp].listen + port
|
|
||||||
if let Some(arr) = old.get("inbounds").and_then(|v| v.as_array()) {
|
|
||||||
for inbound in arr {
|
|
||||||
let proto = inbound.get("protocol").or(inbound.get("type")).and_then(|v| v.as_str()).unwrap_or("");
|
|
||||||
if proto == "ostp" {
|
|
||||||
let h = inbound.get("listen").and_then(|v| v.as_str()).unwrap_or("0.0.0.0").to_string();
|
|
||||||
let p = inbound.get("port").and_then(|v| v.as_u64()).unwrap_or(50000) as u16;
|
|
||||||
return (h, p);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Old format: "listen": "0.0.0.0:50000"
|
|
||||||
if let Some(s) = old.get("listen").and_then(|v| v.as_str()) {
|
|
||||||
let parts: Vec<&str> = s.split(':').collect();
|
|
||||||
let h = parts.get(0).unwrap_or(&"0.0.0.0").to_string();
|
|
||||||
let p = parts.get(1).and_then(|x| x.parse().ok()).unwrap_or(50000);
|
|
||||||
return (h, p);
|
|
||||||
}
|
|
||||||
("0.0.0.0".to_string(), 50000)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extract access keys as list of strings
|
|
||||||
fn extract_server_users(old: &serde_json::Value) -> Vec<String> {
|
|
||||||
// New format: inbounds[type=ostp].users[].key
|
|
||||||
if let Some(arr) = old.get("inbounds").and_then(|v| v.as_array()) {
|
|
||||||
for inbound in arr {
|
|
||||||
let proto = inbound.get("protocol").or(inbound.get("type")).and_then(|v| v.as_str()).unwrap_or("");
|
|
||||||
if proto == "ostp" {
|
|
||||||
if let Some(users) = inbound.get("users").and_then(|v| v.as_array()) {
|
|
||||||
return users.iter().filter_map(|u| {
|
|
||||||
u.get("key").and_then(|k| k.as_str()).map(|s| s.to_string())
|
|
||||||
.or_else(|| u.as_str().map(|s| s.to_string()))
|
|
||||||
}).collect();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Old flat format: "access_keys": ["key1", "key2"]
|
|
||||||
if let Some(keys) = old.get("access_keys").and_then(|v| v.as_array()) {
|
|
||||||
return keys.iter().filter_map(|k| k.as_str().map(|s| s.to_string())).collect();
|
|
||||||
}
|
|
||||||
vec![]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extract fallback config
|
|
||||||
fn extract_server_fallback(old: &serde_json::Value) -> (bool, String, String) {
|
|
||||||
// New format: inbounds[type=ostp].fallback
|
|
||||||
if let Some(arr) = old.get("inbounds").and_then(|v| v.as_array()) {
|
|
||||||
for inbound in arr {
|
|
||||||
let proto = inbound.get("protocol").or(inbound.get("type")).and_then(|v| v.as_str()).unwrap_or("");
|
|
||||||
if proto == "ostp" {
|
|
||||||
if let Some(fb) = inbound.get("fallback") {
|
|
||||||
let enabled = fb.get("enabled").and_then(|v| v.as_bool()).unwrap_or(false);
|
|
||||||
let listen = fb.get("listen").and_then(|v| v.as_str()).unwrap_or("0.0.0.0:443").to_string();
|
|
||||||
let target = fb.get("target").and_then(|v| v.as_str()).unwrap_or("127.0.0.1:8080").to_string();
|
|
||||||
return (enabled, listen, target);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Old flat format
|
|
||||||
if let Some(fb) = old.get("fallback") {
|
|
||||||
let enabled = fb.get("enabled").and_then(|v| v.as_bool()).unwrap_or(false);
|
|
||||||
let listen = fb.get("listen").and_then(|v| v.as_str()).unwrap_or("0.0.0.0:443").to_string();
|
|
||||||
let target = fb.get("target").and_then(|v| v.as_str()).unwrap_or("127.0.0.1:8080").to_string();
|
|
||||||
return (enabled, listen, target);
|
|
||||||
}
|
|
||||||
(false, "0.0.0.0:443".to_string(), "127.0.0.1:8080".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extract API config
|
|
||||||
fn extract_server_api(old: &serde_json::Value) -> (String, u16, String, String, String, String) {
|
|
||||||
let default_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".to_string();
|
|
||||||
// New format: inbounds[protocol=api]
|
|
||||||
if let Some(arr) = old.get("inbounds").and_then(|v| v.as_array()) {
|
|
||||||
for inbound in arr {
|
|
||||||
let proto = inbound.get("protocol").or(inbound.get("type")).and_then(|v| v.as_str()).unwrap_or("");
|
|
||||||
if proto == "api" {
|
|
||||||
let listen = inbound.get("listen").and_then(|v| v.as_str()).unwrap_or("127.0.0.1").to_string();
|
|
||||||
let port = inbound.get("port").and_then(|v| v.as_u64()).unwrap_or(9090) as u16;
|
|
||||||
let token = inbound.get("token").and_then(|v| v.as_str()).unwrap_or("YOUR_SECRET_TOKEN").to_string();
|
|
||||||
let webpath = inbound.get("webpath").and_then(|v| v.as_str()).unwrap_or("/admin").to_string();
|
|
||||||
let username = inbound.get("username").and_then(|v| v.as_str()).unwrap_or("admin").to_string();
|
|
||||||
let pass = inbound.get("password_hash").and_then(|v| v.as_str()).unwrap_or(&default_hash).to_string();
|
|
||||||
return (listen, port, token, webpath, username, pass);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Old format: "api": { "bind": "127.0.0.1:9090", ... }
|
|
||||||
if let Some(api) = old.get("api") {
|
|
||||||
let bind = api.get("bind").and_then(|v| v.as_str()).unwrap_or("127.0.0.1:9090");
|
|
||||||
let parts: Vec<&str> = bind.split(':').collect();
|
|
||||||
let listen = parts.get(0).unwrap_or(&"127.0.0.1").to_string();
|
|
||||||
let port = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(9090);
|
|
||||||
let token = api.get("token").and_then(|v| v.as_str()).unwrap_or("YOUR_SECRET_TOKEN").to_string();
|
|
||||||
let webpath = api.get("webpath").and_then(|v| v.as_str()).unwrap_or("/admin").to_string();
|
|
||||||
let username = api.get("username").and_then(|v| v.as_str()).unwrap_or("admin").to_string();
|
|
||||||
let pass = api.get("password_hash").and_then(|v| v.as_str()).unwrap_or(&default_hash).to_string();
|
|
||||||
return (listen, port, token, webpath, username, pass);
|
|
||||||
}
|
|
||||||
("127.0.0.1".to_string(), 9090, "YOUR_SECRET_TOKEN".to_string(), "/admin".to_string(), "admin".to_string(), default_hash)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extract DNS transport config
|
|
||||||
fn extract_server_dns(old: &serde_json::Value) -> (String, String, String, String) {
|
|
||||||
// New format: inbounds[protocol=dns]
|
|
||||||
if let Some(arr) = old.get("inbounds").and_then(|v| v.as_array()) {
|
|
||||||
for inbound in arr {
|
|
||||||
let proto = inbound.get("protocol").or(inbound.get("type")).and_then(|v| v.as_str()).unwrap_or("");
|
|
||||||
if proto == "dns" {
|
|
||||||
let listen = inbound.get("listen").and_then(|v| v.as_str()).unwrap_or("0.0.0.0:53").to_string();
|
|
||||||
let domain = inbound.get("domain").and_then(|v| v.as_str()).unwrap_or("tunnel.example.com").to_string();
|
|
||||||
let pubkey = inbound.get("pubkey").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
|
||||||
let privkey = inbound.get("privkey").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
|
||||||
return (listen, domain, pubkey, privkey);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Old flat format: "dns_transport": {...}
|
|
||||||
if let Some(dns) = old.get("dns_transport") {
|
|
||||||
let listen = dns.get("listen").and_then(|v| v.as_str()).unwrap_or("0.0.0.0:53").to_string();
|
|
||||||
let domain = dns.get("domain").and_then(|v| v.as_str()).unwrap_or("tunnel.example.com").to_string();
|
|
||||||
let pubkey = dns.get("pubkey").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
|
||||||
let privkey = dns.get("privkey").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
|
||||||
return (listen, domain, pubkey, privkey);
|
|
||||||
}
|
|
||||||
let new_pub = generate_secure_key("base64");
|
|
||||||
let new_priv = generate_secure_key("base64");
|
|
||||||
("0.0.0.0:53".to_string(), "tunnel.example.com".to_string(), new_pub, new_priv)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extract routing rules as a formatted JSON string for embedding in template
|
|
||||||
fn extract_routing_rules_str(old: &serde_json::Value) -> String {
|
|
||||||
if let Some(rules) = old.get("routing").and_then(|r| r.get("rules")).and_then(|v| v.as_array()) {
|
|
||||||
if !rules.is_empty() {
|
|
||||||
let parts: Vec<String> = rules.iter()
|
|
||||||
.filter_map(|r| serde_json::to_string_pretty(r).ok())
|
|
||||||
.collect();
|
|
||||||
return format!("\n {}\n ", parts.join(",\n "));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
String::new()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extract client server address, port, key, transport
|
|
||||||
fn extract_client_server(old: &serde_json::Value) -> (String, u16, String, String) {
|
|
||||||
// New format: outbounds[type=ostp]
|
|
||||||
if let Some(arr) = old.get("outbounds").and_then(|v| v.as_array()) {
|
|
||||||
for ob in arr {
|
|
||||||
let t = ob.get("type").and_then(|v| v.as_str()).unwrap_or("");
|
|
||||||
if t == "ostp" {
|
|
||||||
let server = ob.get("server").and_then(|v| v.as_str()).unwrap_or("YOUR_SERVER_IP").to_string();
|
|
||||||
let port = ob.get("port").and_then(|v| v.as_u64()).unwrap_or(50000) as u16;
|
|
||||||
let key = ob.get("access_key").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
|
||||||
let transport = ob.get("transport").and_then(|t| t.get("type")).and_then(|v| v.as_str()).unwrap_or("udp").to_string();
|
|
||||||
return (server, port, key, transport);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Old flat format
|
|
||||||
let server_full = old.get("server").and_then(|v| v.as_str()).unwrap_or("YOUR_SERVER_IP:50000");
|
|
||||||
let parts: Vec<&str> = server_full.split(':').collect();
|
|
||||||
let server = parts.get(0).unwrap_or(&"YOUR_SERVER_IP").to_string();
|
|
||||||
let port = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(50000);
|
|
||||||
let key = old.get("access_key").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
|
||||||
let transport = old.get("transport").and_then(|t| t.get("mode").or(t.get("type"))).and_then(|v| v.as_str()).unwrap_or("udp").to_string();
|
|
||||||
(server, port, key, transport)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extract client SOCKS listen address and port
|
|
||||||
fn extract_client_socks(old: &serde_json::Value) -> (String, u16) {
|
|
||||||
// New format: inbounds[type=local_proxy]
|
|
||||||
if let Some(arr) = old.get("inbounds").and_then(|v| v.as_array()) {
|
|
||||||
for inbound in arr {
|
|
||||||
let t = inbound.get("type").and_then(|v| v.as_str()).unwrap_or("");
|
|
||||||
if t == "local_proxy" {
|
|
||||||
let listen = inbound.get("listen").and_then(|v| v.as_str()).unwrap_or("127.0.0.1").to_string();
|
|
||||||
let port = inbound.get("port").and_then(|v| v.as_u64()).unwrap_or(1088) as u16;
|
|
||||||
return (listen, port);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Old flat format
|
|
||||||
let bind = old.get("socks5_bind").and_then(|v| v.as_str()).unwrap_or("127.0.0.1:1088");
|
|
||||||
let parts: Vec<&str> = bind.split(':').collect();
|
|
||||||
let listen = parts.get(0).unwrap_or(&"127.0.0.1").to_string();
|
|
||||||
let port = parts.get(1).and_then(|p| p.parse().ok()).unwrap_or(1088);
|
|
||||||
(listen, port)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check if TUN is enabled in old config
|
|
||||||
fn extract_client_tun(old: &serde_json::Value) -> bool {
|
|
||||||
// New format: inbounds[type=tun]
|
|
||||||
if let Some(arr) = old.get("inbounds").and_then(|v| v.as_array()) {
|
|
||||||
for inbound in arr {
|
|
||||||
let t = inbound.get("type").and_then(|v| v.as_str()).unwrap_or("");
|
|
||||||
if t == "tun" {
|
|
||||||
return inbound.get("auto_route").and_then(|v| v.as_bool()).unwrap_or(true);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Old flat format
|
|
||||||
old.get("tun").and_then(|t| t.get("enable")).and_then(|v| v.as_bool()).unwrap_or(false)
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,62 @@
|
||||||
|
{
|
||||||
|
// OSTP Server Configuration
|
||||||
|
"mode": "server",
|
||||||
|
"log_level": "info",
|
||||||
|
|
||||||
|
// The address and port the server listens on for incoming OSTP connections.
|
||||||
|
"listen": "0.0.0.0:50000",
|
||||||
|
|
||||||
|
// List of valid keys. Clients must use one of these to connect.
|
||||||
|
"access_keys": [
|
||||||
|
"a1d8795a93553c08b4e89b017a16ca52"
|
||||||
|
],
|
||||||
|
|
||||||
|
// Optional proxy for outbound traffic.
|
||||||
|
"outbound": {
|
||||||
|
"enabled": false,
|
||||||
|
"protocol": "socks5",
|
||||||
|
"address": "127.0.0.1",
|
||||||
|
"port": 9050,
|
||||||
|
// default_action: 'proxy' (all through proxy) or 'direct' (bypass proxy by default).
|
||||||
|
"default_action": "proxy",
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"domain_suffix": [".onion"],
|
||||||
|
"action": "proxy"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
// Web control panel & Management API
|
||||||
|
"api": {
|
||||||
|
"enabled": false,
|
||||||
|
"bind": "0.0.0.0:9090",
|
||||||
|
// Static API token for Relay servers (optional)
|
||||||
|
"token": "",
|
||||||
|
// Secret URL path to hide panel from scanners (e.g. "mySecret123")
|
||||||
|
"webpath": "",
|
||||||
|
// Login credentials for web panel (password stored as SHA256 hash)
|
||||||
|
"username": "",
|
||||||
|
"password_hash": ""
|
||||||
|
},
|
||||||
|
|
||||||
|
// Fallback TCP proxy: unrecognized connections are proxied to a web server (anti-DPI).
|
||||||
|
"fallback": {
|
||||||
|
"enabled": false,
|
||||||
|
"listen": "0.0.0.0:443",
|
||||||
|
// Target web server (e.g., local nginx or caddy)
|
||||||
|
"target": "127.0.0.1:8080"
|
||||||
|
},
|
||||||
|
|
||||||
|
// Reality (XTLS) / UoT Masquerade parameters
|
||||||
|
"reality": {
|
||||||
|
"enabled": false,
|
||||||
|
"dest": "www.microsoft.com:443",
|
||||||
|
"private_key": "6FVg53jUBTt-dJ52F1Zu1RBCcW1gr9K84WdynBb7i80",
|
||||||
|
"pbk": "c9QjERoaqFGoKBd-9ZpNzj51E8B93fcnEQT_cohEk2E",
|
||||||
|
"sid": "960223edfa174fc5",
|
||||||
|
"sni_list": ["www.microsoft.com"]
|
||||||
|
},
|
||||||
|
"debug": false,
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
{
|
||||||
|
// OSTP Configuration v0.3.1
|
||||||
|
// DO NOT EDIT THIS COMMENT - Migrator relies on it
|
||||||
|
"version": "0.3.1",
|
||||||
|
"mode": "client",
|
||||||
|
"log": {
|
||||||
|
"level": "info"
|
||||||
|
},
|
||||||
|
"inbounds": [
|
||||||
|
{
|
||||||
|
"type": "tun",
|
||||||
|
"tag": "tun-in",
|
||||||
|
"auto_route": true,
|
||||||
|
"mtu": 1140
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "local_proxy",
|
||||||
|
"tag": "socks-in",
|
||||||
|
"protocol": "socks",
|
||||||
|
"listen": "127.0.0.1",
|
||||||
|
"port": 1088
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outbounds": [
|
||||||
|
{
|
||||||
|
"type": "ostp",
|
||||||
|
"tag": "proxy",
|
||||||
|
"server": "YOUR_SERVER_IP",
|
||||||
|
"port": 50000,
|
||||||
|
"access_key": "170756347f1562a4b260f8f4b419009a",
|
||||||
|
"transport": {
|
||||||
|
"type": "udp"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "direct",
|
||||||
|
"tag": "direct"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "block",
|
||||||
|
"tag": "block"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"routing": {
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"domain_suffix": ["localhost"],
|
||||||
|
"outbound": "direct"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"default_outbound": "proxy"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
{
|
||||||
|
// OSTP Configuration v0.3.1
|
||||||
|
// DO NOT EDIT THIS COMMENT - Migrator relies on it
|
||||||
|
"version": "0.3.1",
|
||||||
|
"mode": "server",
|
||||||
|
"log": {
|
||||||
|
"level": "info"
|
||||||
|
},
|
||||||
|
|
||||||
|
// The address and port the server listens on for incoming OSTP connections.
|
||||||
|
"listen": "0.0.0.0:50000",
|
||||||
|
|
||||||
|
// List of valid keys. Clients must use one of these to connect.
|
||||||
|
"access_keys": [
|
||||||
|
"1369293f64ed6382d96cd2c1fa2ee4ee"
|
||||||
|
],
|
||||||
|
|
||||||
|
// Optional proxy for outbound traffic.
|
||||||
|
"outbound": {
|
||||||
|
"enabled": false,
|
||||||
|
"protocol": "socks5",
|
||||||
|
"address": "127.0.0.1",
|
||||||
|
"port": 9050,
|
||||||
|
"default_action": "proxy",
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"domain_suffix": [".onion"],
|
||||||
|
"action": "proxy"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
|
||||||
|
// Fallback TCP proxy: unrecognized connections are proxied to a web server (anti-DPI).
|
||||||
|
"fallback": {
|
||||||
|
"enabled": false,
|
||||||
|
"listen": "0.0.0.0:443",
|
||||||
|
// Target web server (e.g., local nginx or caddy)
|
||||||
|
"target": "127.0.0.1:8080"
|
||||||
|
},
|
||||||
|
|
||||||
|
"debug": false
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue