mirror of
https://github.com/rustdesk/rustdesk.git
synced 2026-05-01 02:53:20 +03:00
Compare commits
6 Commits
43df9fb7a1
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e4b7fca4d | ||
|
|
d135c58ead | ||
|
|
de194417d4 | ||
|
|
d01ce3173f | ||
|
|
010a54d1c9 | ||
|
|
f557fc94fa |
573
src/common.rs
573
src/common.rs
@@ -39,7 +39,7 @@ use hbb_common::{
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
hbbs_http::{create_http_client_async, get_url_for_tls},
|
hbbs_http::{create_http_client_async, get_url_for_tls},
|
||||||
ui_interface::{get_api_server as ui_get_api_server, get_option, is_installed, set_option},
|
ui_interface::{get_option, is_installed, set_option},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Debug, Eq, PartialEq)]
|
#[derive(Debug, Eq, PartialEq)]
|
||||||
@@ -1123,198 +1123,7 @@ pub fn get_audit_server(api: String, custom: String, typ: String) -> String {
|
|||||||
format!("{}/api/audit/{}", url, typ)
|
format!("{}/api/audit/{}", url, typ)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if we should use raw TCP proxy for API calls.
|
pub async fn post_request(url: String, body: String, header: &str) -> ResultType<String> {
|
||||||
/// Returns true if USE_RAW_TCP_FOR_API builtin option is "Y", WebSocket is off,
|
|
||||||
/// and the target URL belongs to the configured non-public API host.
|
|
||||||
#[inline]
|
|
||||||
fn should_use_raw_tcp_for_api(url: &str) -> bool {
|
|
||||||
get_builtin_option(keys::OPTION_USE_RAW_TCP_FOR_API) == "Y"
|
|
||||||
&& !use_ws()
|
|
||||||
&& is_tcp_proxy_api_target(url)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check if we can attempt raw TCP proxy fallback for this target URL.
|
|
||||||
#[inline]
|
|
||||||
fn can_fallback_to_raw_tcp(url: &str) -> bool {
|
|
||||||
!use_ws() && is_tcp_proxy_api_target(url)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn should_use_tcp_proxy_for_api_url(url: &str, api_url: &str) -> bool {
|
|
||||||
if api_url.is_empty() || is_public(api_url) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
let target_host = url::Url::parse(url)
|
|
||||||
.ok()
|
|
||||||
.and_then(|parsed| parsed.host_str().map(|host| host.to_ascii_lowercase()));
|
|
||||||
let api_host = url::Url::parse(api_url)
|
|
||||||
.ok()
|
|
||||||
.and_then(|parsed| parsed.host_str().map(|host| host.to_ascii_lowercase()));
|
|
||||||
|
|
||||||
matches!((target_host, api_host), (Some(target), Some(api)) if target == api)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn is_tcp_proxy_api_target(url: &str) -> bool {
|
|
||||||
should_use_tcp_proxy_for_api_url(url, &ui_get_api_server())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tcp_proxy_log_target(url: &str) -> String {
|
|
||||||
url::Url::parse(url)
|
|
||||||
.ok()
|
|
||||||
.map(|parsed| {
|
|
||||||
let mut redacted = format!("{}://", parsed.scheme());
|
|
||||||
let Some(host) = parsed.host() else {
|
|
||||||
return "<invalid-url>".to_owned();
|
|
||||||
};
|
|
||||||
redacted.push_str(&host.to_string());
|
|
||||||
if let Some(port) = parsed.port() {
|
|
||||||
redacted.push(':');
|
|
||||||
redacted.push_str(&port.to_string());
|
|
||||||
}
|
|
||||||
redacted.push_str(parsed.path());
|
|
||||||
redacted
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|| "<invalid-url>".to_owned())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn get_tcp_proxy_addr() -> String {
|
|
||||||
check_port(Config::get_rendezvous_server(), RENDEZVOUS_PORT)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send an HTTP request via the rendezvous server's TCP proxy using protobuf.
|
|
||||||
/// Connects with `connect_tcp` + `secure_tcp`, sends `HttpProxyRequest`,
|
|
||||||
/// receives `HttpProxyResponse`.
|
|
||||||
async fn tcp_proxy_request(
|
|
||||||
method: &str,
|
|
||||||
url: &str,
|
|
||||||
body: &[u8],
|
|
||||||
headers: Vec<HeaderEntry>,
|
|
||||||
) -> ResultType<HttpProxyResponse> {
|
|
||||||
let tcp_addr = get_tcp_proxy_addr();
|
|
||||||
if tcp_addr.is_empty() {
|
|
||||||
bail!("No rendezvous server configured for TCP proxy");
|
|
||||||
}
|
|
||||||
|
|
||||||
let parsed = url::Url::parse(url)?;
|
|
||||||
let path = if let Some(query) = parsed.query() {
|
|
||||||
format!("{}?{}", parsed.path(), query)
|
|
||||||
} else {
|
|
||||||
parsed.path().to_string()
|
|
||||||
};
|
|
||||||
|
|
||||||
log::debug!(
|
|
||||||
"Sending {} {} via TCP proxy to {}",
|
|
||||||
method,
|
|
||||||
parsed.path(),
|
|
||||||
tcp_addr
|
|
||||||
);
|
|
||||||
|
|
||||||
let mut conn = socket_client::connect_tcp(&*tcp_addr, CONNECT_TIMEOUT).await?;
|
|
||||||
let key = crate::get_key(true).await;
|
|
||||||
secure_tcp_silent(&mut conn, &key).await?;
|
|
||||||
|
|
||||||
let mut req = HttpProxyRequest::new();
|
|
||||||
req.method = method.to_uppercase();
|
|
||||||
req.path = path;
|
|
||||||
req.headers = headers.into();
|
|
||||||
req.body = Bytes::from(body.to_vec());
|
|
||||||
|
|
||||||
let mut msg_out = RendezvousMessage::new();
|
|
||||||
msg_out.set_http_proxy_request(req);
|
|
||||||
conn.send(&msg_out).await?;
|
|
||||||
|
|
||||||
match timeout(READ_TIMEOUT, conn.next()).await? {
|
|
||||||
Some(Ok(bytes)) => {
|
|
||||||
let msg_in = RendezvousMessage::parse_from_bytes(&bytes)?;
|
|
||||||
match msg_in.union {
|
|
||||||
Some(rendezvous_message::Union::HttpProxyResponse(resp)) => Ok(resp),
|
|
||||||
_ => bail!("Unexpected response from TCP proxy"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(Err(e)) => bail!("TCP proxy read error: {}", e),
|
|
||||||
None => bail!("TCP proxy connection closed without response"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build HeaderEntry list from "Key: Value" style header string (used by post_request).
|
|
||||||
fn parse_simple_header(header: &str) -> Vec<HeaderEntry> {
|
|
||||||
let mut entries = vec![HeaderEntry {
|
|
||||||
name: "Content-Type".into(),
|
|
||||||
value: "application/json".into(),
|
|
||||||
..Default::default()
|
|
||||||
}];
|
|
||||||
if !header.is_empty() {
|
|
||||||
let tmp: Vec<&str> = header.splitn(2, ": ").collect();
|
|
||||||
if tmp.len() == 2 {
|
|
||||||
if !tmp[0].eq_ignore_ascii_case("Content-Type") {
|
|
||||||
entries.push(HeaderEntry {
|
|
||||||
name: tmp[0].into(),
|
|
||||||
value: tmp[1].into(),
|
|
||||||
..Default::default()
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
entries
|
|
||||||
}
|
|
||||||
|
|
||||||
/// POST request via TCP proxy.
|
|
||||||
async fn post_request_via_tcp_proxy(url: &str, body: &str, header: &str) -> ResultType<String> {
|
|
||||||
let headers = parse_simple_header(header);
|
|
||||||
let resp = tcp_proxy_request("POST", url, body.as_bytes(), headers).await?;
|
|
||||||
if !resp.error.is_empty() {
|
|
||||||
bail!("TCP proxy error: {}", resp.error);
|
|
||||||
}
|
|
||||||
Ok(String::from_utf8_lossy(&resp.body).to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn http_proxy_response_to_json(resp: HttpProxyResponse) -> ResultType<String> {
|
|
||||||
if !resp.error.is_empty() {
|
|
||||||
bail!("TCP proxy error: {}", resp.error);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut response_headers = Map::new();
|
|
||||||
for entry in resp.headers.iter() {
|
|
||||||
response_headers.insert(entry.name.to_lowercase(), json!(entry.value));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut result = Map::new();
|
|
||||||
result.insert("status_code".to_string(), json!(resp.status));
|
|
||||||
result.insert("headers".to_string(), Value::Object(response_headers));
|
|
||||||
result.insert(
|
|
||||||
"body".to_string(),
|
|
||||||
json!(String::from_utf8_lossy(&resp.body)),
|
|
||||||
);
|
|
||||||
|
|
||||||
serde_json::to_string(&result).map_err(|e| anyhow!("Failed to serialize response: {}", e))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_json_header_entries(header: &str) -> ResultType<Vec<HeaderEntry>> {
|
|
||||||
let v: Value = serde_json::from_str(header)?;
|
|
||||||
if let Value::Object(obj) = v {
|
|
||||||
Ok(obj
|
|
||||||
.iter()
|
|
||||||
.map(|(key, value)| HeaderEntry {
|
|
||||||
name: key.clone(),
|
|
||||||
value: value.as_str().unwrap_or_default().into(),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
} else {
|
|
||||||
Err(anyhow!("HTTP header information parsing failed!"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
|
||||||
fn tcp_proxy_fallback_log_condition() -> &'static str {
|
|
||||||
"failed or 5xx"
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns (status_code, body_text). Separating status so the wrapper can decide on fallback.
|
|
||||||
async fn post_request_http(url: String, body: String, header: &str) -> ResultType<(u16, String)> {
|
|
||||||
let proxy_conf = Config::get_socks();
|
let proxy_conf = Config::get_socks();
|
||||||
let tls_url = get_url_for_tls(&url, &proxy_conf);
|
let tls_url = get_url_for_tls(&url, &proxy_conf);
|
||||||
let tls_type = get_cached_tls_type(tls_url);
|
let tls_type = get_cached_tls_type(tls_url);
|
||||||
@@ -1329,52 +1138,7 @@ async fn post_request_http(url: String, body: String, header: &str) -> ResultTyp
|
|||||||
danger_accept_invalid_cert,
|
danger_accept_invalid_cert,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
let status = response.status().as_u16();
|
Ok(response.text().await?)
|
||||||
let text = response.text().await?;
|
|
||||||
Ok((status, text))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// POST request with raw TCP proxy support.
|
|
||||||
/// - If `USE_RAW_TCP_FOR_API` is "Y" and WS is off, goes directly through TCP proxy.
|
|
||||||
/// - Otherwise tries HTTP first; on connection failure or 5xx status,
|
|
||||||
/// falls back to TCP proxy if WS is off.
|
|
||||||
/// - 4xx responses are returned as-is (server is reachable, business logic error).
|
|
||||||
/// - If fallback also fails, returns the original HTTP result (text or error).
|
|
||||||
pub async fn post_request(url: String, body: String, header: &str) -> ResultType<String> {
|
|
||||||
if should_use_raw_tcp_for_api(&url) {
|
|
||||||
return post_request_via_tcp_proxy(&url, &body, header).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
let http_result = post_request_http(url.clone(), body.clone(), header).await;
|
|
||||||
let should_fallback = match &http_result {
|
|
||||||
Err(_) => true,
|
|
||||||
Ok((status, _)) => *status >= 500,
|
|
||||||
};
|
|
||||||
|
|
||||||
if should_fallback && can_fallback_to_raw_tcp(&url) {
|
|
||||||
log::warn!(
|
|
||||||
"HTTP POST to {} {} (result: {:?}), trying TCP proxy fallback",
|
|
||||||
tcp_proxy_log_target(&url),
|
|
||||||
tcp_proxy_fallback_log_condition(),
|
|
||||||
http_result
|
|
||||||
.as_ref()
|
|
||||||
.map(|(s, _)| *s)
|
|
||||||
.map_err(|e| e.to_string()),
|
|
||||||
);
|
|
||||||
match post_request_via_tcp_proxy(&url, &body, header).await {
|
|
||||||
Ok(resp) => return Ok(resp),
|
|
||||||
Err(tcp_err) => {
|
|
||||||
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
|
|
||||||
// Fall through to return original HTTP result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return original HTTP result
|
|
||||||
match http_result {
|
|
||||||
Ok((_status, text)) => Ok(text),
|
|
||||||
Err(e) => Err(e),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_recursion]
|
#[async_recursion]
|
||||||
@@ -1482,16 +1246,21 @@ async fn get_http_response_async(
|
|||||||
tls_type.unwrap_or(TlsType::Rustls),
|
tls_type.unwrap_or(TlsType::Rustls),
|
||||||
danger_accept_invalid_cert.unwrap_or(false),
|
danger_accept_invalid_cert.unwrap_or(false),
|
||||||
);
|
);
|
||||||
let normalized_method = method.to_ascii_lowercase();
|
let mut http_client = match method {
|
||||||
let mut http_client = match normalized_method.as_str() {
|
|
||||||
"get" => http_client.get(url),
|
"get" => http_client.get(url),
|
||||||
"post" => http_client.post(url),
|
"post" => http_client.post(url),
|
||||||
"put" => http_client.put(url),
|
"put" => http_client.put(url),
|
||||||
"delete" => http_client.delete(url),
|
"delete" => http_client.delete(url),
|
||||||
_ => return Err(anyhow!("The HTTP request method is not supported!")),
|
_ => return Err(anyhow!("The HTTP request method is not supported!")),
|
||||||
};
|
};
|
||||||
for entry in parse_json_header_entries(header)? {
|
let v = serde_json::from_str(header)?;
|
||||||
http_client = http_client.header(entry.name, entry.value);
|
|
||||||
|
if let Value::Object(obj) = v {
|
||||||
|
for (key, value) in obj.iter() {
|
||||||
|
http_client = http_client.header(key, value.as_str().unwrap_or_default());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Err(anyhow!("HTTP header information parsing failed!"));
|
||||||
}
|
}
|
||||||
|
|
||||||
if tls_type.is_some() && danger_accept_invalid_cert.is_some() {
|
if tls_type.is_some() && danger_accept_invalid_cert.is_some() {
|
||||||
@@ -1571,51 +1340,6 @@ async fn get_http_response_async(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns (status_code, json_string) so the caller can inspect the status
|
|
||||||
/// without re-parsing the serialized JSON.
|
|
||||||
async fn http_request_http(
|
|
||||||
url: &str,
|
|
||||||
method: &str,
|
|
||||||
body: Option<String>,
|
|
||||||
header: &str,
|
|
||||||
) -> ResultType<(u16, String)> {
|
|
||||||
let proxy_conf = Config::get_socks();
|
|
||||||
let tls_url = get_url_for_tls(url, &proxy_conf);
|
|
||||||
let tls_type = get_cached_tls_type(tls_url);
|
|
||||||
let danger_accept_invalid_cert = get_cached_tls_accept_invalid_cert(tls_url);
|
|
||||||
let response = get_http_response_async(
|
|
||||||
url,
|
|
||||||
tls_url,
|
|
||||||
method,
|
|
||||||
body,
|
|
||||||
header,
|
|
||||||
tls_type,
|
|
||||||
danger_accept_invalid_cert,
|
|
||||||
danger_accept_invalid_cert,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
// Serialize response headers
|
|
||||||
let mut response_headers = Map::new();
|
|
||||||
for (key, value) in response.headers() {
|
|
||||||
response_headers.insert(key.to_string(), json!(value.to_str().unwrap_or("")));
|
|
||||||
}
|
|
||||||
|
|
||||||
let status_code = response.status().as_u16();
|
|
||||||
let response_body = response.text().await?;
|
|
||||||
|
|
||||||
// Construct the JSON object
|
|
||||||
let mut result = Map::new();
|
|
||||||
result.insert("status_code".to_string(), json!(status_code));
|
|
||||||
result.insert("headers".to_string(), Value::Object(response_headers));
|
|
||||||
result.insert("body".to_string(), json!(response_body));
|
|
||||||
|
|
||||||
// Convert map to JSON string
|
|
||||||
let json_str = serde_json::to_string(&result)
|
|
||||||
.map_err(|e| anyhow!("Failed to serialize response: {}", e))?;
|
|
||||||
Ok((status_code, json_str))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// HTTP request with raw TCP proxy support.
|
|
||||||
#[tokio::main(flavor = "current_thread")]
|
#[tokio::main(flavor = "current_thread")]
|
||||||
pub async fn http_request_sync(
|
pub async fn http_request_sync(
|
||||||
url: String,
|
url: String,
|
||||||
@@ -1623,47 +1347,44 @@ pub async fn http_request_sync(
|
|||||||
body: Option<String>,
|
body: Option<String>,
|
||||||
header: String,
|
header: String,
|
||||||
) -> ResultType<String> {
|
) -> ResultType<String> {
|
||||||
if should_use_raw_tcp_for_api(&url) {
|
let proxy_conf = Config::get_socks();
|
||||||
return http_request_via_tcp_proxy(&url, &method, body.as_deref(), &header).await;
|
let tls_url = get_url_for_tls(&url, &proxy_conf);
|
||||||
}
|
let tls_type = get_cached_tls_type(tls_url);
|
||||||
|
let danger_accept_invalid_cert = get_cached_tls_accept_invalid_cert(tls_url);
|
||||||
let http_result = http_request_http(&url, &method, body.clone(), &header).await;
|
let response = get_http_response_async(
|
||||||
let should_fallback = match &http_result {
|
&url,
|
||||||
Err(_) => true,
|
tls_url,
|
||||||
Ok((status, _)) => *status >= 500,
|
&method,
|
||||||
};
|
body.clone(),
|
||||||
|
&header,
|
||||||
if should_fallback && can_fallback_to_raw_tcp(&url) {
|
tls_type,
|
||||||
log::warn!(
|
danger_accept_invalid_cert,
|
||||||
"HTTP {} to {} {}, trying TCP proxy fallback",
|
danger_accept_invalid_cert,
|
||||||
method,
|
)
|
||||||
tcp_proxy_log_target(&url),
|
.await?;
|
||||||
tcp_proxy_fallback_log_condition()
|
// Serialize response headers
|
||||||
|
let mut response_headers = serde_json::map::Map::new();
|
||||||
|
for (key, value) in response.headers() {
|
||||||
|
response_headers.insert(
|
||||||
|
key.to_string(),
|
||||||
|
serde_json::json!(value.to_str().unwrap_or("")),
|
||||||
);
|
);
|
||||||
match http_request_via_tcp_proxy(&url, &method, body.as_deref(), &header).await {
|
|
||||||
Ok(resp) => return Ok(resp),
|
|
||||||
Err(tcp_err) => {
|
|
||||||
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
http_result.map(|(_status, json_str)| json_str)
|
let status_code = response.status().as_u16();
|
||||||
}
|
let response_body = response.text().await?;
|
||||||
|
|
||||||
/// General HTTP request via TCP proxy. Header is a JSON string (used by http_request_sync).
|
// Construct the JSON object
|
||||||
/// Returns a JSON string with status_code, headers, body (same format as http_request_sync).
|
let mut result = serde_json::map::Map::new();
|
||||||
async fn http_request_via_tcp_proxy(
|
result.insert("status_code".to_string(), serde_json::json!(status_code));
|
||||||
url: &str,
|
result.insert(
|
||||||
method: &str,
|
"headers".to_string(),
|
||||||
body: Option<&str>,
|
serde_json::Value::Object(response_headers),
|
||||||
header: &str,
|
);
|
||||||
) -> ResultType<String> {
|
result.insert("body".to_string(), serde_json::json!(response_body));
|
||||||
let headers = parse_json_header_entries(header)?;
|
|
||||||
let body_bytes = body.unwrap_or("").as_bytes();
|
|
||||||
|
|
||||||
let resp = tcp_proxy_request(method, url, body_bytes, headers).await?;
|
// Convert map to JSON string
|
||||||
http_proxy_response_to_json(resp)
|
serde_json::to_string(&result).map_err(|e| anyhow!("Failed to serialize response: {}", e))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
@@ -1926,7 +1647,7 @@ pub fn check_process(arg: &str, mut same_uid: bool) -> bool {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn secure_tcp_impl(conn: &mut Stream, key: &str, log_on_success: bool) -> ResultType<()> {
|
pub async fn secure_tcp(conn: &mut Stream, key: &str) -> ResultType<()> {
|
||||||
// Skip additional encryption when using WebSocket connections (wss://)
|
// Skip additional encryption when using WebSocket connections (wss://)
|
||||||
// as WebSocket Secure (wss://) already provides transport layer encryption.
|
// as WebSocket Secure (wss://) already provides transport layer encryption.
|
||||||
// This doesn't affect the end-to-end encryption between clients,
|
// This doesn't affect the end-to-end encryption between clients,
|
||||||
@@ -1959,10 +1680,8 @@ async fn secure_tcp_impl(conn: &mut Stream, key: &str, log_on_success: bool) ->
|
|||||||
});
|
});
|
||||||
timeout(CONNECT_TIMEOUT, conn.send(&msg_out)).await??;
|
timeout(CONNECT_TIMEOUT, conn.send(&msg_out)).await??;
|
||||||
conn.set_key(key);
|
conn.set_key(key);
|
||||||
if log_on_success {
|
|
||||||
log::info!("Connection secured");
|
log::info!("Connection secured");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1972,14 +1691,6 @@ async fn secure_tcp_impl(conn: &mut Stream, key: &str, log_on_success: bool) ->
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn secure_tcp(conn: &mut Stream, key: &str) -> ResultType<()> {
|
|
||||||
secure_tcp_impl(conn, key, true).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn secure_tcp_silent(conn: &mut Stream, key: &str) -> ResultType<()> {
|
|
||||||
secure_tcp_impl(conn, key, false).await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn get_pk(pk: &[u8]) -> Option<[u8; 32]> {
|
fn get_pk(pk: &[u8]) -> Option<[u8; 32]> {
|
||||||
if pk.len() == 32 {
|
if pk.len() == 32 {
|
||||||
@@ -2774,198 +2485,6 @@ mod tests {
|
|||||||
assert!(!is_public("rustdesk.comhello.com"));
|
assert!(!is_public("rustdesk.comhello.com"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_should_use_tcp_proxy_for_api_url() {
|
|
||||||
assert!(should_use_tcp_proxy_for_api_url(
|
|
||||||
"https://admin.example.com/api/login",
|
|
||||||
"https://admin.example.com"
|
|
||||||
));
|
|
||||||
assert!(should_use_tcp_proxy_for_api_url(
|
|
||||||
"https://admin.example.com:21114/api/login",
|
|
||||||
"https://admin.example.com"
|
|
||||||
));
|
|
||||||
assert!(!should_use_tcp_proxy_for_api_url(
|
|
||||||
"https://api.telegram.org/bot123/sendMessage",
|
|
||||||
"https://admin.example.com"
|
|
||||||
));
|
|
||||||
assert!(!should_use_tcp_proxy_for_api_url(
|
|
||||||
"https://admin.rustdesk.com/api/login",
|
|
||||||
"https://admin.rustdesk.com"
|
|
||||||
));
|
|
||||||
assert!(!should_use_tcp_proxy_for_api_url(
|
|
||||||
"https://admin.example.com/api/login",
|
|
||||||
"not a url"
|
|
||||||
));
|
|
||||||
assert!(!should_use_tcp_proxy_for_api_url(
|
|
||||||
"not a url",
|
|
||||||
"https://admin.example.com"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_get_tcp_proxy_addr_normalizes_bare_ipv6_host() {
|
|
||||||
struct RestoreCustomRendezvousServer(String);
|
|
||||||
|
|
||||||
impl Drop for RestoreCustomRendezvousServer {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
Config::set_option(
|
|
||||||
keys::OPTION_CUSTOM_RENDEZVOUS_SERVER.to_string(),
|
|
||||||
self.0.clone(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let _restore = RestoreCustomRendezvousServer(Config::get_option(
|
|
||||||
keys::OPTION_CUSTOM_RENDEZVOUS_SERVER,
|
|
||||||
));
|
|
||||||
Config::set_option(
|
|
||||||
keys::OPTION_CUSTOM_RENDEZVOUS_SERVER.to_string(),
|
|
||||||
"1:2".to_string(),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(get_tcp_proxy_addr(), format!("[1:2]:{RENDEZVOUS_PORT}"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn test_http_request_via_tcp_proxy_rejects_invalid_header_json() {
|
|
||||||
let result = http_request_via_tcp_proxy("not a url", "get", None, "{").await;
|
|
||||||
assert!(result.is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn test_http_request_via_tcp_proxy_rejects_non_object_header_json() {
|
|
||||||
let err = http_request_via_tcp_proxy("not a url", "get", None, "[]")
|
|
||||||
.await
|
|
||||||
.unwrap_err()
|
|
||||||
.to_string();
|
|
||||||
assert!(err.contains("HTTP header information parsing failed!"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_parse_json_header_entries_preserves_single_content_type() {
|
|
||||||
let headers = parse_json_header_entries(
|
|
||||||
r#"{"Content-Type":"text/plain","Authorization":"Bearer token"}"#,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
headers
|
|
||||||
.iter()
|
|
||||||
.filter(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
|
|
||||||
.count(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
headers
|
|
||||||
.iter()
|
|
||||||
.find(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
|
|
||||||
.map(|entry| entry.value.as_str()),
|
|
||||||
Some("text/plain")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_parse_json_header_entries_does_not_add_default_content_type() {
|
|
||||||
let headers = parse_json_header_entries(r#"{"Authorization":"Bearer token"}"#).unwrap();
|
|
||||||
|
|
||||||
assert!(!headers
|
|
||||||
.iter()
|
|
||||||
.any(|entry| entry.name.eq_ignore_ascii_case("Content-Type")));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_parse_simple_header_ignores_custom_content_type() {
|
|
||||||
let headers = parse_simple_header("Content-Type: text/plain");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
headers
|
|
||||||
.iter()
|
|
||||||
.filter(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
|
|
||||||
.count(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
headers
|
|
||||||
.iter()
|
|
||||||
.find(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
|
|
||||||
.map(|entry| entry.value.as_str()),
|
|
||||||
Some("application/json")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_parse_simple_header_preserves_non_content_type_header() {
|
|
||||||
let headers = parse_simple_header("Authorization: Bearer token");
|
|
||||||
|
|
||||||
assert!(headers.iter().any(|entry| {
|
|
||||||
entry.name.eq_ignore_ascii_case("Authorization")
|
|
||||||
&& entry.value.as_str() == "Bearer token"
|
|
||||||
}));
|
|
||||||
assert_eq!(
|
|
||||||
headers
|
|
||||||
.iter()
|
|
||||||
.filter(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
|
|
||||||
.count(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
headers
|
|
||||||
.iter()
|
|
||||||
.find(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
|
|
||||||
.map(|entry| entry.value.as_str()),
|
|
||||||
Some("application/json")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_tcp_proxy_fallback_log_condition() {
|
|
||||||
assert_eq!(tcp_proxy_fallback_log_condition(), "failed or 5xx");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_tcp_proxy_log_target_redacts_query_only() {
|
|
||||||
assert_eq!(
|
|
||||||
tcp_proxy_log_target("https://example.com/api/heartbeat?token=secret"),
|
|
||||||
"https://example.com/api/heartbeat"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_tcp_proxy_log_target_brackets_ipv6_host_with_port() {
|
|
||||||
assert_eq!(
|
|
||||||
tcp_proxy_log_target("https://[2001:db8::1]:21114/api/heartbeat?token=secret"),
|
|
||||||
"https://[2001:db8::1]:21114/api/heartbeat"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_http_proxy_response_to_json() {
|
|
||||||
let mut resp = HttpProxyResponse {
|
|
||||||
status: 200,
|
|
||||||
body: br#"{"ok":true}"#.to_vec().into(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
resp.headers.push(HeaderEntry {
|
|
||||||
name: "Content-Type".into(),
|
|
||||||
value: "application/json".into(),
|
|
||||||
..Default::default()
|
|
||||||
});
|
|
||||||
|
|
||||||
let json = http_proxy_response_to_json(resp).unwrap();
|
|
||||||
let value: Value = serde_json::from_str(&json).unwrap();
|
|
||||||
assert_eq!(value["status_code"], 200);
|
|
||||||
assert_eq!(value["headers"]["content-type"], "application/json");
|
|
||||||
assert_eq!(value["body"], r#"{"ok":true}"#);
|
|
||||||
|
|
||||||
let err = http_proxy_response_to_json(HttpProxyResponse {
|
|
||||||
error: "dial failed".into(),
|
|
||||||
..Default::default()
|
|
||||||
})
|
|
||||||
.unwrap_err()
|
|
||||||
.to_string();
|
|
||||||
assert!(err.contains("TCP proxy error: dial failed"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_mouse_event_constants_and_mask_layout() {
|
fn test_mouse_event_constants_and_mask_layout() {
|
||||||
use super::input::*;
|
use super::input::*;
|
||||||
|
|||||||
@@ -741,7 +741,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
|||||||
("keep-awake-during-incoming-sessions-label", "Bildschirm während eingehender Sitzungen aktiv halten"),
|
("keep-awake-during-incoming-sessions-label", "Bildschirm während eingehender Sitzungen aktiv halten"),
|
||||||
("Continue with {}", "Fortfahren mit {}"),
|
("Continue with {}", "Fortfahren mit {}"),
|
||||||
("Display Name", "Anzeigename"),
|
("Display Name", "Anzeigename"),
|
||||||
("password-hidden-tip", ""),
|
("password-hidden-tip", "Ein permanentes Passwort wurde festgelegt (ausgeblendet)."),
|
||||||
("preset-password-in-use-tip", ""),
|
("preset-password-in-use-tip", "Das voreingestellte Passwort wird derzeit verwendet."),
|
||||||
].iter().cloned().collect();
|
].iter().cloned().collect();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -741,7 +741,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
|||||||
("keep-awake-during-incoming-sessions-label", "Mantieni lo schermo attivo durante le sessioni in ingresso"),
|
("keep-awake-during-incoming-sessions-label", "Mantieni lo schermo attivo durante le sessioni in ingresso"),
|
||||||
("Continue with {}", "Continua con {}"),
|
("Continue with {}", "Continua con {}"),
|
||||||
("Display Name", "Visualizza nome"),
|
("Display Name", "Visualizza nome"),
|
||||||
("password-hidden-tip", ""),
|
("password-hidden-tip", "È impostata una password permanente (nascosta)."),
|
||||||
("preset-password-in-use-tip", ""),
|
("preset-password-in-use-tip", "È attualmente in uso la password preimpostata."),
|
||||||
].iter().cloned().collect();
|
].iter().cloned().collect();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -741,7 +741,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
|||||||
("keep-awake-during-incoming-sessions-label", "수신 세션 중 화면 켜짐 유지"),
|
("keep-awake-during-incoming-sessions-label", "수신 세션 중 화면 켜짐 유지"),
|
||||||
("Continue with {}", "{}(으)로 계속"),
|
("Continue with {}", "{}(으)로 계속"),
|
||||||
("Display Name", "표시 이름"),
|
("Display Name", "표시 이름"),
|
||||||
("password-hidden-tip", ""),
|
("password-hidden-tip", "영구 비밀번호가 설정되었습니다 (숨김)."),
|
||||||
("preset-password-in-use-tip", ""),
|
("preset-password-in-use-tip", "현재 사전 설정된 비밀번호가 사용 중입니다."),
|
||||||
].iter().cloned().collect();
|
].iter().cloned().collect();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -666,7 +666,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
|||||||
("Incoming Print Job", "Входящее задание печати"),
|
("Incoming Print Job", "Входящее задание печати"),
|
||||||
("use-the-default-printer-tip", "Использовать принтер по умолчанию"),
|
("use-the-default-printer-tip", "Использовать принтер по умолчанию"),
|
||||||
("use-the-selected-printer-tip", "Использовать выбранный принтер"),
|
("use-the-selected-printer-tip", "Использовать выбранный принтер"),
|
||||||
("auto-print-tip", "Автоматически выполнять печать на выбранном принтере."),
|
("auto-print-tip", "Автоматически выполнять печать на выбранном принтере"),
|
||||||
("print-incoming-job-confirm-tip", "Получено задание на печать с удалённого устройства. Выполнить его локально?"),
|
("print-incoming-job-confirm-tip", "Получено задание на печать с удалённого устройства. Выполнить его локально?"),
|
||||||
("remote-printing-disallowed-tile-tip", "Удалённая печать запрещена"),
|
("remote-printing-disallowed-tile-tip", "Удалённая печать запрещена"),
|
||||||
("remote-printing-disallowed-text-tip", "Настройки разрешений на управляемой стороне запрещают удалённую печать."),
|
("remote-printing-disallowed-text-tip", "Настройки разрешений на управляемой стороне запрещают удалённую печать."),
|
||||||
@@ -741,7 +741,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
|||||||
("keep-awake-during-incoming-sessions-label", "Не отключать экран во время входящих сеансов"),
|
("keep-awake-during-incoming-sessions-label", "Не отключать экран во время входящих сеансов"),
|
||||||
("Continue with {}", "Продолжить с {}"),
|
("Continue with {}", "Продолжить с {}"),
|
||||||
("Display Name", "Отображаемое имя"),
|
("Display Name", "Отображаемое имя"),
|
||||||
("password-hidden-tip", ""),
|
("password-hidden-tip", "Установлен постоянный пароль (скрытый)."),
|
||||||
("preset-password-in-use-tip", ""),
|
("preset-password-in-use-tip", "Установленный пароль сейчас используется."),
|
||||||
].iter().cloned().collect();
|
].iter().cloned().collect();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -741,7 +741,7 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
|||||||
("keep-awake-during-incoming-sessions-label", "Gelen oturumlar süresince ekranı açık tutun"),
|
("keep-awake-during-incoming-sessions-label", "Gelen oturumlar süresince ekranı açık tutun"),
|
||||||
("Continue with {}", "{} ile devam et"),
|
("Continue with {}", "{} ile devam et"),
|
||||||
("Display Name", "Görünen Ad"),
|
("Display Name", "Görünen Ad"),
|
||||||
("password-hidden-tip", ""),
|
("password-hidden-tip", "Şifre gizli"),
|
||||||
("preset-password-in-use-tip", ""),
|
("preset-password-in-use-tip", "Önceden ayarlanmış şifre kullanılıyor"),
|
||||||
].iter().cloned().collect();
|
].iter().cloned().collect();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -740,8 +740,8 @@ pub static ref T: std::collections::HashMap<&'static str, &'static str> =
|
|||||||
("keep-awake-during-outgoing-sessions-label", "在連出工作階段期間保持螢幕喚醒"),
|
("keep-awake-during-outgoing-sessions-label", "在連出工作階段期間保持螢幕喚醒"),
|
||||||
("keep-awake-during-incoming-sessions-label", "在連入工作階段期間保持螢幕喚醒"),
|
("keep-awake-during-incoming-sessions-label", "在連入工作階段期間保持螢幕喚醒"),
|
||||||
("Continue with {}", "使用 {} 登入"),
|
("Continue with {}", "使用 {} 登入"),
|
||||||
("Display Name", ""),
|
("Display Name", "顯示名稱"),
|
||||||
("password-hidden-tip", ""),
|
("password-hidden-tip", "固定密碼已設定(已隱藏)"),
|
||||||
("preset-password-in-use-tip", ""),
|
("preset-password-in-use-tip", "目前正在使用預設密碼"),
|
||||||
].iter().cloned().collect();
|
].iter().cloned().collect();
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user