forked from algesten/ureq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.rs
396 lines (344 loc) · 12.1 KB
/
proxy.rs
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use base64::prelude::BASE64_STANDARD;
use base64::Engine;
use hoot::parser::try_parse_response;
use std::fmt;
use std::io::Write;
use http::{StatusCode, Uri};
use crate::transport::{ConnectionDetails, Connector, Transport, TransportAdapter};
use crate::util::{AuthorityExt, DebugUri, SchemeExt, UriExt};
use crate::Error;
/// Proxy protocol
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub(crate) enum Proto {
Http,
Https,
Socks4,
Socks4A,
Socks5,
}
impl Proto {
pub fn default_port(&self) -> u16 {
match self {
Proto::Http => 80,
Proto::Https => 443,
Proto::Socks4 | Proto::Socks4A | Proto::Socks5 => 1080,
}
}
pub fn is_socks(&self) -> bool {
matches!(self, Self::Socks4 | Self::Socks4A | Self::Socks5)
}
pub(crate) fn is_connect(&self) -> bool {
matches!(self, Self::Http | Self::Https)
}
}
/// Proxy server settings
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct Proxy {
proto: Proto,
uri: Uri,
from_env: bool,
}
impl Proxy {
/// Create a proxy from a uri.
///
/// # Arguments:
///
/// * `proxy` - a str of format `<protocol>://<user>:<password>@<host>:port` . All parts
/// except host are optional.
///
/// ### Protocols
///
/// * `http`: HTTP CONNECT proxy
/// * `https`: HTTPS CONNECT proxy (requires a TLS provider)
/// * `socks4`: SOCKS4 (requires **socks-proxy** feature)
/// * `socks4a`: SOCKS4A (requires **socks-proxy** feature)
/// * `socks5` and `socks`: SOCKS5 (requires **socks-proxy** feature)
///
/// # Examples proxy formats
///
/// * `http://127.0.0.1:8080`
/// * `socks5://john:smith@socks.google.com`
/// * `john:smith@socks.google.com:8000`
/// * `localhost`
pub fn new(proxy: &str) -> Result<Self, Error> {
Self::new_with_flag(proxy, false)
}
fn new_with_flag(proxy: &str, from_env: bool) -> Result<Self, Error> {
let uri = proxy.parse::<Uri>().unwrap();
// The uri must have an authority part (with the host), or
// it is invalid.
let _ = uri.authority().ok_or(Error::InvalidProxyUrl)?;
// The default protocol is Proto::HTTP
let scheme = uri.scheme_str().unwrap_or("http");
let proto = scheme.try_into()?;
Ok(Self {
proto,
uri,
from_env,
})
}
/// Read proxy settings from environment variables.
///
/// The environment variable is expected to contain a proxy URI. The following
/// environment variables are attempted:
///
/// * `ALL_PROXY`
/// * `HTTPS_PROXY`
/// * `HTTP_PROXY`
///
/// Returns `None` if no environment variable is set or the URI is invalid.
pub fn try_from_env() -> Option<Self> {
macro_rules! try_env {
($($env:literal),+) => {
$(
if let Ok(env) = std::env::var($env) {
if let Ok(proxy) = Self::new_with_flag(&env, true) {
return Some(proxy);
}
}
)+
};
}
try_env!(
"ALL_PROXY",
"all_proxy",
"HTTPS_PROXY",
"https_proxy",
"HTTP_PROXY",
"http_proxy"
);
None
}
pub(crate) fn proto(&self) -> Proto {
self.proto
}
/// The proxy uri
pub fn uri(&self) -> &Uri {
&self.uri
}
/// The host part of the proxy uri
pub fn host(&self) -> &str {
self.uri
.authority()
.map(|a| a.host())
.expect("constructor to ensure there is an authority")
}
/// The port of the proxy uri
pub fn port(&self) -> u16 {
self.uri
.authority()
.and_then(|a| a.port_u16())
.unwrap_or_else(|| self.proto.default_port())
}
/// The username of the proxy uri
pub fn username(&self) -> Option<&str> {
self.uri.authority().and_then(|a| a.username())
}
/// The password of the proxy uri
pub fn password(&self) -> Option<&str> {
self.uri.authority().and_then(|a| a.password())
}
/// Whether this proxy setting was created manually or from
/// environment variables.
pub fn is_from_env(&self) -> bool {
self.from_env
}
}
/// Connector for CONNECT proxy settings.
///
/// This operates on the previous chained transport typically a TcpConnector optionally
/// wrapped in TLS.
pub struct ConnectProxyConnector;
impl Connector for ConnectProxyConnector {
fn connect(
&self,
details: &ConnectionDetails,
chained: Option<Box<dyn Transport>>,
) -> Result<Option<Box<dyn Transport>>, Error> {
let Some(transport) = chained else {
return Ok(None);
};
let is_connect_proxy = details.config.connect_proxy_uri().is_some();
if is_connect_proxy {
// unwrap is ok because connect_proxy_uri() above checks it.
let proxy = details.config.proxy.as_ref().unwrap();
let mut w = TransportAdapter::new(transport);
let uri = &details.uri;
uri.ensure_valid_url()?;
// All these unwrap() are ok because ensure_valid_uri() above checks them.
let host = uri.host().unwrap();
let port = uri
.port_u16()
.unwrap_or(uri.scheme().unwrap().default_port().unwrap());
write!(w, "CONNECT {}:{} HTTP/1.1\r\n", host, port)?;
write!(w, "Host: {}:{}\r\n", host, port)?;
write!(w, "User-Agent: {}\r\n", details.config.user_agent)?;
write!(w, "Proxy-Connection: Keep-Alive\r\n")?;
let use_creds = proxy.username().is_some() || proxy.password().is_some();
if use_creds {
let user = proxy.username().unwrap_or_default();
let pass = proxy.password().unwrap_or_default();
let creds = BASE64_STANDARD.encode(format!("{}:{}", user, pass));
write!(w, "Proxy-Authorization: basic {}\r\n", creds)?;
}
write!(w, "\r\n")?;
w.flush()?;
let mut transport = w.into_inner();
let response = loop {
let made_progress = transport.await_input(details.timeout)?;
let buffers = transport.buffers();
let input = buffers.input();
let Some((used_input, response)) = try_parse_response::<20>(input)? else {
if !made_progress {
let reason = "proxy server did not respond".to_string();
return Err(Error::ConnectProxyFailed(reason));
}
continue;
};
buffers.consume(used_input);
break response;
};
match response.status() {
StatusCode::OK => {
trace!("CONNECT proxy connected");
}
x => {
let reason = format!("proxy server responded {}/{}", x.as_u16(), x.as_str());
return Err(Error::ConnectProxyFailed(reason));
}
}
Ok(Some(transport))
} else {
Ok(Some(transport))
}
}
}
impl TryFrom<&str> for Proto {
type Error = Error;
fn try_from(scheme: &str) -> Result<Self, Self::Error> {
match scheme.to_ascii_lowercase().as_str() {
"http" => Ok(Proto::Http),
"https" => Ok(Proto::Https),
"socks4" => Ok(Proto::Socks4),
"socks4a" => Ok(Proto::Socks4A),
"socks" => Ok(Proto::Socks5),
"socks5" => Ok(Proto::Socks5),
_ => Err(Error::InvalidProxyUrl),
}
}
}
impl fmt::Debug for Proxy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Proxy")
.field("proto", &self.proto)
.field("uri", &DebugUri(&self.uri))
.field("from_env", &self.from_env)
.finish()
}
}
impl fmt::Display for Proto {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Proto::Http => write!(f, "HTTP"),
Proto::Https => write!(f, "HTTPS"),
Proto::Socks4 => write!(f, "SOCKS4"),
Proto::Socks4A => write!(f, "SOCKS4a"),
Proto::Socks5 => write!(f, "SOCKS5"),
}
}
}
impl fmt::Debug for ConnectProxyConnector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProxyConnector").finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_proxy_fakeproto() {
assert!(Proxy::new("fakeproto://localhost").is_err());
}
#[test]
fn parse_proxy_http_user_pass_server_port() {
let proxy = Proxy::new("http://user:p@ssw0rd@localhost:9999").unwrap();
assert_eq!(proxy.username(), Some("user"));
assert_eq!(proxy.password(), Some("p@ssw0rd"));
assert_eq!(proxy.host(), "localhost");
assert_eq!(proxy.port(), 9999);
assert_eq!(proxy.proto, Proto::Http);
}
#[test]
fn parse_proxy_http_user_pass_server_port_trailing_slash() {
let proxy = Proxy::new("http://user:p@ssw0rd@localhost:9999/").unwrap();
assert_eq!(proxy.username(), Some("user"));
assert_eq!(proxy.password(), Some("p@ssw0rd"));
assert_eq!(proxy.host(), "localhost");
assert_eq!(proxy.port(), 9999);
assert_eq!(proxy.proto, Proto::Http);
}
#[test]
fn parse_proxy_socks4_user_pass_server_port() {
let proxy = Proxy::new("socks4://user:p@ssw0rd@localhost:9999").unwrap();
assert_eq!(proxy.username(), Some("user"));
assert_eq!(proxy.password(), Some("p@ssw0rd"));
assert_eq!(proxy.host(), "localhost");
assert_eq!(proxy.port(), 9999);
assert_eq!(proxy.proto, Proto::Socks4);
}
#[test]
fn parse_proxy_socks4a_user_pass_server_port() {
let proxy = Proxy::new("socks4a://user:p@ssw0rd@localhost:9999").unwrap();
assert_eq!(proxy.username(), Some("user"));
assert_eq!(proxy.password(), Some("p@ssw0rd"));
assert_eq!(proxy.host(), "localhost");
assert_eq!(proxy.port(), 9999);
assert_eq!(proxy.proto, Proto::Socks4A);
}
#[test]
fn parse_proxy_socks_user_pass_server_port() {
let proxy = Proxy::new("socks://user:p@ssw0rd@localhost:9999").unwrap();
assert_eq!(proxy.username(), Some("user"));
assert_eq!(proxy.password(), Some("p@ssw0rd"));
assert_eq!(proxy.host(), "localhost");
assert_eq!(proxy.port(), 9999);
assert_eq!(proxy.proto, Proto::Socks5);
}
#[test]
fn parse_proxy_socks5_user_pass_server_port() {
let proxy = Proxy::new("socks5://user:p@ssw0rd@localhost:9999").unwrap();
assert_eq!(proxy.username(), Some("user"));
assert_eq!(proxy.password(), Some("p@ssw0rd"));
assert_eq!(proxy.host(), "localhost");
assert_eq!(proxy.port(), 9999);
assert_eq!(proxy.proto, Proto::Socks5);
}
#[test]
fn parse_proxy_user_pass_server_port() {
let proxy = Proxy::new("user:p@ssw0rd@localhost:9999").unwrap();
assert_eq!(proxy.username(), Some("user"));
assert_eq!(proxy.password(), Some("p@ssw0rd"));
assert_eq!(proxy.host(), "localhost");
assert_eq!(proxy.port(), 9999);
assert_eq!(proxy.proto, Proto::Http);
}
#[test]
fn parse_proxy_server_port() {
let proxy = Proxy::new("localhost:9999").unwrap();
assert_eq!(proxy.username(), None);
assert_eq!(proxy.password(), None);
assert_eq!(proxy.host(), "localhost");
assert_eq!(proxy.port(), 9999);
assert_eq!(proxy.proto, Proto::Http);
}
#[test]
fn parse_proxy_server() {
let proxy = Proxy::new("localhost").unwrap();
assert_eq!(proxy.username(), None);
assert_eq!(proxy.password(), None);
assert_eq!(proxy.host(), "localhost");
assert_eq!(proxy.port(), 80);
assert_eq!(proxy.proto, Proto::Http);
}
}