-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathproxy.rs
More file actions
218 lines (187 loc) · 7.73 KB
/
proxy.rs
File metadata and controls
218 lines (187 loc) · 7.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use serde::{Deserialize, Serialize};
use tauri::State;
use rusqlite::params;
use crate::commands::agents::AgentDb;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ProxySettings {
pub http_proxy: Option<String>,
pub https_proxy: Option<String>,
pub no_proxy: Option<String>,
pub all_proxy: Option<String>,
pub proxy_username: Option<String>,
pub proxy_password: Option<String>,
pub enabled: bool,
}
impl Default for ProxySettings {
fn default() -> Self {
Self {
http_proxy: None,
https_proxy: None,
no_proxy: None,
all_proxy: None,
proxy_username: None,
proxy_password: None,
enabled: false,
}
}
}
/// Get proxy settings from the database
#[tauri::command]
pub async fn get_proxy_settings(db: State<'_, AgentDb>) -> Result<ProxySettings, String> {
let conn = db.0.lock().map_err(|e| e.to_string())?;
let mut settings = ProxySettings::default();
// Query each proxy setting
let keys = vec![
("proxy_enabled", "enabled"),
("proxy_http", "http_proxy"),
("proxy_https", "https_proxy"),
("proxy_no", "no_proxy"),
("proxy_all", "all_proxy"),
("proxy_username", "proxy_username"),
("proxy_password", "proxy_password"),
];
for (db_key, field) in keys {
if let Ok(value) = conn.query_row(
"SELECT value FROM app_settings WHERE key = ?1",
params![db_key],
|row| row.get::<_, String>(0),
) {
match field {
"enabled" => settings.enabled = value == "true",
"http_proxy" => settings.http_proxy = Some(value).filter(|s| !s.is_empty()),
"https_proxy" => settings.https_proxy = Some(value).filter(|s| !s.is_empty()),
"no_proxy" => settings.no_proxy = Some(value).filter(|s| !s.is_empty()),
"all_proxy" => settings.all_proxy = Some(value).filter(|s| !s.is_empty()),
"proxy_username" => settings.proxy_username = Some(value).filter(|s| !s.is_empty()),
"proxy_password" => settings.proxy_password = Some(value).filter(|s| !s.is_empty()),
_ => {}
}
}
}
Ok(settings)
}
/// Save proxy settings to the database
#[tauri::command]
pub async fn save_proxy_settings(
db: State<'_, AgentDb>,
settings: ProxySettings,
) -> Result<(), String> {
let conn = db.0.lock().map_err(|e| e.to_string())?;
// Save each setting
let values = vec![
("proxy_enabled", settings.enabled.to_string()),
("proxy_http", settings.http_proxy.clone().unwrap_or_default()),
("proxy_https", settings.https_proxy.clone().unwrap_or_default()),
("proxy_no", settings.no_proxy.clone().unwrap_or_default()),
("proxy_all", settings.all_proxy.clone().unwrap_or_default()),
("proxy_username", settings.proxy_username.clone().unwrap_or_default()),
("proxy_password", settings.proxy_password.clone().unwrap_or_default()),
];
for (key, value) in values {
conn.execute(
"INSERT OR REPLACE INTO app_settings (key, value) VALUES (?1, ?2)",
params![key, value],
).map_err(|e| format!("Failed to save {}: {}", key, e))?;
}
// Apply the proxy settings immediately to the current process
apply_proxy_settings(&settings);
Ok(())
}
/// Apply proxy settings as environment variables
pub fn apply_proxy_settings(settings: &ProxySettings) {
// Helper function to add authentication to proxy URL if username and password are available
fn add_auth_to_url(url: &str, username: Option<&str>, password: Option<&str>) -> String {
if username.is_none() || username.unwrap().is_empty() {
return url.to_string();
}
if let Ok(mut parsed_url) = url::Url::parse(url) {
// Set username
let _ = parsed_url.set_username(username.unwrap());
// Set password if available
if let Some(pwd) = password {
if !pwd.is_empty() {
let _ = parsed_url.set_password(Some(pwd));
}
}
return parsed_url.to_string();
}
// Return original URL if parsing fails
url.to_string()
}
log::info!("Applying proxy settings: enabled={}", settings.enabled);
if !settings.enabled {
// Clear proxy environment variables if disabled
log::info!("Clearing proxy environment variables");
std::env::remove_var("HTTP_PROXY");
std::env::remove_var("HTTPS_PROXY");
std::env::remove_var("NO_PROXY");
std::env::remove_var("ALL_PROXY");
// Also clear lowercase versions
std::env::remove_var("http_proxy");
std::env::remove_var("https_proxy");
std::env::remove_var("no_proxy");
std::env::remove_var("all_proxy");
return;
}
// Ensure NO_PROXY includes localhost by default
let mut no_proxy_list = vec!["localhost", "127.0.0.1", "::1", "0.0.0.0"];
if let Some(user_no_proxy) = &settings.no_proxy {
if !user_no_proxy.is_empty() {
no_proxy_list.push(user_no_proxy.as_str());
}
}
let no_proxy_value = no_proxy_list.join(",");
// Set proxy environment variables (uppercase is standard)
if let Some(http_proxy) = &settings.http_proxy {
if !http_proxy.is_empty() {
// Add authentication to URL if username/password are available
let auth_url = add_auth_to_url(
http_proxy,
settings.proxy_username.as_deref(),
settings.proxy_password.as_deref()
);
// Log URL without credentials for security
log::info!("Setting HTTP_PROXY={}",
if auth_url.contains('@') { "[authenticated proxy URL]" } else { &auth_url });
std::env::set_var("HTTP_PROXY", auth_url);
}
}
if let Some(https_proxy) = &settings.https_proxy {
if !https_proxy.is_empty() {
// Add authentication to URL if username/password are available
let auth_url = add_auth_to_url(
https_proxy,
settings.proxy_username.as_deref(),
settings.proxy_password.as_deref()
);
// Log URL without credentials for security
log::info!("Setting HTTPS_PROXY={}",
if auth_url.contains('@') { "[authenticated proxy URL]" } else { &auth_url });
std::env::set_var("HTTPS_PROXY", auth_url);
}
}
// Always set NO_PROXY to include localhost
log::info!("Setting NO_PROXY={}", no_proxy_value);
std::env::set_var("NO_PROXY", &no_proxy_value);
if let Some(all_proxy) = &settings.all_proxy {
if !all_proxy.is_empty() {
// Add authentication to URL if username/password are available
let auth_url = add_auth_to_url(
all_proxy,
settings.proxy_username.as_deref(),
settings.proxy_password.as_deref()
);
// Log URL without credentials for security
log::info!("Setting ALL_PROXY={}",
if auth_url.contains('@') { "[authenticated proxy URL]" } else { &auth_url });
std::env::set_var("ALL_PROXY", auth_url);
}
}
// Log current proxy environment variables for debugging
log::info!("Current proxy environment variables:");
for (key, value) in std::env::vars() {
if key.contains("PROXY") || key.contains("proxy") {
log::info!(" {}={}", key, value);
}
}
}