细化+上游代理+1.1
This commit is contained in:
Generated
+259
-1
@@ -61,7 +61,7 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
"synstructure",
|
||||
"synstructure 0.13.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -264,6 +264,7 @@ name = "core_vpn"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
"bytes",
|
||||
"http",
|
||||
"http-body-util",
|
||||
@@ -281,6 +282,7 @@ dependencies = [
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tun-rs",
|
||||
"url",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
@@ -422,6 +424,15 @@ dependencies = [
|
||||
"spin",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
@@ -595,6 +606,110 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"potential_utf",
|
||||
"utf8_iter",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_core"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"litemap",
|
||||
"tinystr",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_normalizer_data",
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"smallvec",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer_data"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc"
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_collections",
|
||||
"icu_locale_core",
|
||||
"icu_properties_data",
|
||||
"icu_provider",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties_data"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf"
|
||||
|
||||
[[package]]
|
||||
name = "icu_provider"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_locale_core",
|
||||
"writeable",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
|
||||
dependencies = [
|
||||
"idna_adapter",
|
||||
"smallvec",
|
||||
"utf8_iter",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "idna_adapter"
|
||||
version = "1.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
|
||||
dependencies = [
|
||||
"icu_normalizer",
|
||||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ipnet"
|
||||
version = "2.12.2"
|
||||
@@ -713,6 +828,12 @@ dependencies = [
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
@@ -1003,6 +1124,15 @@ version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
|
||||
dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.1"
|
||||
@@ -1379,6 +1509,12 @@ dependencies = [
|
||||
"lock_api",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
@@ -1418,6 +1554,17 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "system-configuration-sys"
|
||||
version = "0.6.0"
|
||||
@@ -1478,6 +1625,16 @@ dependencies = [
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.54.1"
|
||||
@@ -1597,6 +1754,24 @@ version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "url"
|
||||
version = "2.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"idna",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
@@ -1921,6 +2096,12 @@ version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
|
||||
|
||||
[[package]]
|
||||
name = "x509-parser"
|
||||
version = "0.18.1"
|
||||
@@ -1949,6 +2130,29 @@ dependencies = [
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"
|
||||
dependencies = [
|
||||
"stable_deref_trait",
|
||||
"yoke-derive",
|
||||
"zerofrom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yoke-derive"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.63"
|
||||
@@ -1969,12 +2173,66 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom"
|
||||
version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
|
||||
dependencies = [
|
||||
"zerofrom-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom-derive"
|
||||
version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
"synstructure 0.14.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec"
|
||||
version = "0.11.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40"
|
||||
dependencies = [
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec-derive"
|
||||
version = "0.11.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
|
||||
@@ -26,6 +26,8 @@ hyper-util = { version = "0.1", features = ["tokio", "server", "client"] }
|
||||
http-body-util = "0.1"
|
||||
http = "1.5.0"
|
||||
qstring = "0.7.2"
|
||||
url = "2"
|
||||
base64 = "0.23.1"
|
||||
|
||||
[build-dependencies]
|
||||
rcgen = { version = "0.14", features = ["x509-parser"] }
|
||||
|
||||
+21
-3
@@ -3,7 +3,7 @@ mod mitm;
|
||||
mod tun;
|
||||
mod mut_qstring;
|
||||
|
||||
use crate::mitm::run_capture_async;
|
||||
use crate::mitm::{ProxyConfig, run_capture_async};
|
||||
use jni::objects::{Global, JClass, JObject, JString};
|
||||
use jni::sys::{jint, jstring};
|
||||
use jni::errors::ThrowRuntimeExAndDefault;
|
||||
@@ -89,6 +89,7 @@ pub extern "system" fn Java_net_bluemangoo_indpjsk_vpn_VpnBridge_runCapture(
|
||||
target_host: JString,
|
||||
target_path: JString,
|
||||
save_path: JString,
|
||||
proxy: JString,
|
||||
) -> jstring {
|
||||
let _ = env.with_env(|env: &mut Env| -> Result<(), jni::errors::Error> {
|
||||
init_jvm(env);
|
||||
@@ -118,13 +119,30 @@ pub extern "system" fn Java_net_bluemangoo_indpjsk_vpn_VpnBridge_runCapture(
|
||||
}
|
||||
};
|
||||
|
||||
let proxy_raw: String = if proxy.is_null() {
|
||||
String::new()
|
||||
} else {
|
||||
proxy.to_string()
|
||||
};
|
||||
let proxy_cfg = match ProxyConfig::parse(&proxy_raw) {
|
||||
Ok(cfg) => cfg,
|
||||
Err(e) => {
|
||||
error!("代理配置无效: {e}");
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
};
|
||||
if let Some(cfg) = &proxy_cfg {
|
||||
info!("upstream proxy: {}://{}:{}", if cfg.tls { "https" } else { "http" }, cfg.host, cfg.port);
|
||||
}
|
||||
|
||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
||||
let cancel_token = CancellationToken::new();
|
||||
*CANCLE_TOKEN.write().unwrap() = Some(cancel_token.clone());
|
||||
|
||||
let cancel_token_clone = cancel_token.clone();
|
||||
let result =
|
||||
rt.block_on(async move { run_capture_async(tun_fd, hosts, re, out, cancel_token_clone).await });
|
||||
let result = rt.block_on(async move {
|
||||
run_capture_async(tun_fd, hosts, re, out, proxy_cfg, cancel_token_clone).await
|
||||
});
|
||||
cancel_token.cancel();
|
||||
|
||||
rt.shutdown_timeout(std::time::Duration::from_secs(2));
|
||||
|
||||
+181
-18
@@ -14,6 +14,7 @@ use std::net::SocketAddr;
|
||||
use std::os::fd::RawFd;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Duration;
|
||||
use http::Uri;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
use tokio::net::UdpSocket;
|
||||
use tokio::sync::Mutex;
|
||||
@@ -112,6 +113,7 @@ where
|
||||
async fn handle_tls_connection<S>(
|
||||
tcp: S,
|
||||
dst: SocketAddr,
|
||||
upstream: Upstream,
|
||||
target_hosts: Vec<String>,
|
||||
target_path: Regex,
|
||||
save_path: String,
|
||||
@@ -134,7 +136,8 @@ where
|
||||
let Some((sni, accepted)) = sniffed else {
|
||||
io.rewind();
|
||||
io.stop_recording();
|
||||
return passthrough_cancel_wrapped(io, dst, &cancel).await;
|
||||
// 非 TLS:拿不到 SNI,走代理时只能按 IP CONNECT
|
||||
return passthrough_cancel_wrapped(io, dst, None, upstream, &cancel).await;
|
||||
};
|
||||
|
||||
let host_matched = sni
|
||||
@@ -145,7 +148,7 @@ where
|
||||
if !host_matched {
|
||||
io.rewind();
|
||||
io.stop_recording();
|
||||
let r = passthrough_cancel_wrapped(io, dst, &cancel).await;
|
||||
let r = passthrough_cancel_wrapped(io, dst, sni.as_deref(), upstream, &cancel).await;
|
||||
if r.is_err() {
|
||||
warn!("tcp_passthrough error on {sni:?} {dst:?}");
|
||||
}
|
||||
@@ -159,14 +162,16 @@ where
|
||||
.await?;
|
||||
|
||||
let svc_host = sni.clone().unwrap_or_default();
|
||||
let svc_upstream = upstream;
|
||||
let svc = hyper::service::service_fn(move |req: hyper::Request<Incoming>| {
|
||||
let host = svc_host.clone();
|
||||
let path = target_path.clone();
|
||||
let save = save_path.clone();
|
||||
let result_tx = result_tx.clone();
|
||||
let upstream = svc_upstream.clone();
|
||||
async move {
|
||||
Ok::<_, std::convert::Infallible>(
|
||||
forward_request(req, dst, host, path, save, result_tx).await,
|
||||
forward_request(req, dst, host, path, save, result_tx, upstream).await,
|
||||
)
|
||||
}
|
||||
});
|
||||
@@ -199,6 +204,8 @@ where
|
||||
async fn passthrough_cancel_wrapped<IO>(
|
||||
io: IO,
|
||||
dst: SocketAddr,
|
||||
sni: Option<&str>,
|
||||
upstream: Upstream,
|
||||
cancel: &CancellationToken,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
@@ -206,7 +213,7 @@ where
|
||||
{
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => Ok(()),
|
||||
r = tcp_passthrough(io, dst) => r,
|
||||
r = tcp_passthrough(io, dst, sni, upstream) => r,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,8 +225,9 @@ async fn forward_request(
|
||||
target_path: Regex,
|
||||
save_path: String,
|
||||
result_tx: Arc<Mutex<Option<tokio::sync::oneshot::Sender<String>>>>,
|
||||
upstream: Upstream,
|
||||
) -> hyper::Response<Full<Bytes>> {
|
||||
match forward_request_inner(req, dst, &url_host, &target_path).await {
|
||||
match forward_request_inner(req, dst, &url_host, &target_path, &upstream).await {
|
||||
Ok((response, matched_body)) => {
|
||||
if let Some((url, body)) = matched_body {
|
||||
info!("Target matched! Downloading {} bytes", body.len());
|
||||
@@ -257,6 +265,7 @@ async fn forward_request_inner(
|
||||
dst: SocketAddr,
|
||||
url_host: &str,
|
||||
target_path: &Regex,
|
||||
upstream: &Upstream,
|
||||
) -> anyhow::Result<(hyper::Response<Full<Bytes>>, Option<(String, Bytes)>)> {
|
||||
let (mut parts, body) = req.into_parts();
|
||||
|
||||
@@ -293,7 +302,7 @@ async fn forward_request_inner(
|
||||
client_config.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
let connector = tokio_rustls::TlsConnector::from(Arc::new(client_config));
|
||||
let server_name = rustls::pki_types::ServerName::try_from(url_host.to_string())?;
|
||||
let tcp_to_server = tokio::net::TcpStream::connect(dst).await?;
|
||||
let tcp_to_server = upstream.connect(dst, Some(url_host)).await?;
|
||||
let server_tls = connector.connect(server_name, tcp_to_server).await?;
|
||||
|
||||
let (mut sender, conn) =
|
||||
@@ -335,7 +344,7 @@ async fn forward_request_inner(
|
||||
))
|
||||
}
|
||||
|
||||
fn build_url(host: &str, uri: &http::Uri) -> String {
|
||||
fn build_url(host: &str, uri: &Uri) -> String {
|
||||
if uri.scheme().is_some() && uri.authority().is_some() {
|
||||
return uri.to_string();
|
||||
}
|
||||
@@ -343,15 +352,155 @@ fn build_url(host: &str, uri: &http::Uri) -> String {
|
||||
format!("https://{host}{pq}")
|
||||
}
|
||||
|
||||
fn force_full_mysekai(uri: &http::Uri) -> Option<http::Uri> {
|
||||
if let q = Some(uri.query().is_some()) {
|
||||
let mut query = qstring::QString::from(q);
|
||||
if query.has("isForceAllReloadOnlyMysekai") {
|
||||
query.set("isForceAllReloadOnlyMysekai", "true");
|
||||
return Some(http::Uri::try_from(query.to_string().as_str()).ok()?);
|
||||
/// 把 MySekai 的增量刷新标志强制改成 True(和模块的 URL Rewrite 一致),
|
||||
/// 其它 query 参数原样保留。没有这个参数、或已经是 True 时返回 None。
|
||||
fn force_full_mysekai(uri: &Uri) -> Option<Uri> {
|
||||
const KEY: &str = "isForceAllReloadOnlyMysekai";
|
||||
let mut query = qstring::QString::from(uri.query()?);
|
||||
if !query.has(KEY) || query.get(KEY) == Some("True") {
|
||||
return None;
|
||||
}
|
||||
query.set(KEY, "True");
|
||||
Uri::try_from(format!("{}?{}", uri.path(), query).as_str()).ok()
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ProxyConfig {
|
||||
pub tls: bool,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
pub auth: Option<String>,
|
||||
}
|
||||
|
||||
impl ProxyConfig {
|
||||
pub fn parse(input: &str) -> anyhow::Result<Option<Self>> {
|
||||
let raw = input.trim();
|
||||
if raw.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let url = url::Url::parse(raw)
|
||||
.map_err(|e| anyhow::anyhow!("代理地址不是合法 URL: {raw} ({e})"))?;
|
||||
let tls = match url.scheme() {
|
||||
"http" => false,
|
||||
"https" => true,
|
||||
other => anyhow::bail!("代理只支持 http/https,当前是 {other}://"),
|
||||
};
|
||||
let host = url
|
||||
.host_str()
|
||||
.filter(|h| !h.is_empty())
|
||||
.ok_or_else(|| anyhow::anyhow!("代理地址缺少 host: {raw}"))?
|
||||
.to_string();
|
||||
let port = url
|
||||
.port_or_known_default()
|
||||
.ok_or_else(|| anyhow::anyhow!("代理地址缺少端口: {raw}"))?;
|
||||
let auth = if url.username().is_empty() {
|
||||
None
|
||||
} else {
|
||||
let pass = url.password().unwrap_or("");
|
||||
Some(base64_encode(format!("{}:{}", url.username(), pass).as_bytes()))
|
||||
};
|
||||
Ok(Some(Self { tls, host, port, auth }))
|
||||
}
|
||||
}
|
||||
|
||||
fn base64_encode(data: &[u8]) -> String {
|
||||
use base64::Engine as _;
|
||||
base64::engine::general_purpose::STANDARD.encode(data)
|
||||
}
|
||||
|
||||
type UpstreamIo = Box<dyn AsyncReadWrite + Send + Unpin>;
|
||||
|
||||
trait AsyncReadWrite: AsyncRead + AsyncWrite {}
|
||||
impl<T: AsyncRead + AsyncWrite + ?Sized> AsyncReadWrite for T {}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Upstream {
|
||||
proxy: Option<Arc<ProxyConfig>>,
|
||||
}
|
||||
|
||||
impl Upstream {
|
||||
fn new(proxy: Option<ProxyConfig>) -> Self {
|
||||
Self { proxy: proxy.map(Arc::new) }
|
||||
}
|
||||
|
||||
async fn connect(&self, dst: SocketAddr, host: Option<&str>) -> anyhow::Result<UpstreamIo> {
|
||||
match &self.proxy {
|
||||
None => {
|
||||
let tcp = tokio::net::TcpStream::connect(dst).await?;
|
||||
tcp.set_nodelay(true).ok();
|
||||
Ok(Box::new(tcp))
|
||||
}
|
||||
Some(proxy) => connect_via_proxy(proxy, dst, host).await,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn connect_via_proxy(
|
||||
proxy: &ProxyConfig,
|
||||
dst: SocketAddr,
|
||||
host: Option<&str>,
|
||||
) -> anyhow::Result<UpstreamIo> {
|
||||
let tcp = tokio::net::TcpStream::connect((proxy.host.as_str(), proxy.port))
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("连接代理 {}:{} 失败: {e}", proxy.host, proxy.port))?;
|
||||
tcp.set_nodelay(true).ok();
|
||||
|
||||
let mut io: UpstreamIo = if proxy.tls {
|
||||
let mut cfg = rustls::ClientConfig::builder()
|
||||
.with_root_certificates(root_store())
|
||||
.with_no_client_auth();
|
||||
cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
let connector = tokio_rustls::TlsConnector::from(Arc::new(cfg));
|
||||
let name = rustls::pki_types::ServerName::try_from(proxy.host.clone())?;
|
||||
Box::new(
|
||||
connector
|
||||
.connect(name, tcp)
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("与代理建立 TLS 失败: {e}"))?,
|
||||
)
|
||||
} else {
|
||||
Box::new(tcp)
|
||||
};
|
||||
|
||||
let authority = match host {
|
||||
Some(h) if !h.is_empty() => format!("{h}:{}", dst.port()),
|
||||
_ => dst.to_string(),
|
||||
};
|
||||
let mut req = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n");
|
||||
if let Some(auth) = &proxy.auth {
|
||||
req.push_str(&format!("Proxy-Authorization: Basic {auth}\r\n"));
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
io.write_all(req.as_bytes()).await?;
|
||||
io.flush().await?;
|
||||
|
||||
let mut head = Vec::with_capacity(256);
|
||||
let mut byte = [0u8; 1];
|
||||
loop {
|
||||
let n = io.read(&mut byte).await?;
|
||||
if n == 0 {
|
||||
anyhow::bail!("代理在 CONNECT 阶段直接断开");
|
||||
}
|
||||
head.push(byte[0]);
|
||||
if head.ends_with(b"\r\n\r\n") {
|
||||
break;
|
||||
}
|
||||
if head.len() > 16 * 1024 {
|
||||
anyhow::bail!("代理 CONNECT 响应头过长");
|
||||
}
|
||||
}
|
||||
let head_str = String::from_utf8_lossy(&head);
|
||||
let status_line = head_str.lines().next().unwrap_or("").trim().to_string();
|
||||
let ok = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.map(|code| code == "200")
|
||||
.unwrap_or(false);
|
||||
if !ok {
|
||||
anyhow::bail!("代理 CONNECT 失败: {status_line}");
|
||||
}
|
||||
Ok(io)
|
||||
}
|
||||
|
||||
pub async fn run_capture_async(
|
||||
@@ -359,6 +508,7 @@ pub async fn run_capture_async(
|
||||
target_hosts: Vec<String>,
|
||||
target_path: Regex,
|
||||
save_path: String,
|
||||
proxy: Option<ProxyConfig>,
|
||||
cancel_token: CancellationToken,
|
||||
) -> anyhow::Result<Option<String>> {
|
||||
let device = unsafe { BorrowedAsyncDevice::borrow_raw(tun_fd as RawFd)? };
|
||||
@@ -371,6 +521,7 @@ pub async fn run_capture_async(
|
||||
let mut bridge_tasks = JoinSet::new();
|
||||
|
||||
let tls_acceptor = build_tls_acceptor();
|
||||
let upstream = Upstream::new(proxy);
|
||||
|
||||
let (result_tx, mut result_rx) = tokio::sync::oneshot::channel::<String>();
|
||||
let result_tx = Arc::new(Mutex::new(Some(result_tx)));
|
||||
@@ -442,11 +593,13 @@ pub async fn run_capture_async(
|
||||
let server_config = tls_acceptor.clone();
|
||||
let token = cancel_token.clone();
|
||||
let result_tx = result_tx.clone();
|
||||
let upstream = upstream.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
match handle_tls_connection(
|
||||
app_io,
|
||||
dst,
|
||||
upstream,
|
||||
hosts,
|
||||
path,
|
||||
save,
|
||||
@@ -460,8 +613,11 @@ pub async fn run_capture_async(
|
||||
});
|
||||
}else{
|
||||
let pump_token = cancel_token.clone();
|
||||
let upstream = upstream.clone();
|
||||
bridge_tasks.spawn(async move {
|
||||
let _ = tcp_passthrough_cancellable(tcp, dst, pump_token).await;
|
||||
let _ =
|
||||
tcp_passthrough_cancellable(tcp, dst, None, upstream, pump_token)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -481,11 +637,16 @@ pub async fn run_capture_async(
|
||||
result
|
||||
}
|
||||
|
||||
async fn tcp_passthrough<IO>(mut client: IO, dst: SocketAddr) -> anyhow::Result<()>
|
||||
async fn tcp_passthrough<IO>(
|
||||
mut client: IO,
|
||||
dst: SocketAddr,
|
||||
sni: Option<&str>,
|
||||
upstream: Upstream,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
IO: AsyncRead + AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
let mut server = tokio::net::TcpStream::connect(dst).await?;
|
||||
let mut server = upstream.connect(dst, sni).await?;
|
||||
tokio::io::copy_bidirectional(&mut client, &mut server).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -493,12 +654,14 @@ where
|
||||
async fn tcp_passthrough_cancellable<IO>(
|
||||
mut client: IO,
|
||||
dst: SocketAddr,
|
||||
sni: Option<&str>,
|
||||
upstream: Upstream,
|
||||
cancel: CancellationToken,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
IO: AsyncRead + AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
let mut server = tokio::net::TcpStream::connect(dst).await?;
|
||||
let mut server = upstream.connect(dst, sni).await?;
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => {
|
||||
let _ = tokio::time::timeout(
|
||||
|
||||
Reference in New Issue
Block a user