Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! Determine proxy parameters for a URL from the environment.
2 //
3 // Copyright (c) 2016 Ivan Nejgebauer <[email protected]>
4 //
5 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
6 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
7 // http://opensource.org/licenses/MIT>, at your option. This file may not be
8 // copied, modified, or distributed except according to those terms.
9 //!
10 //! Environment variables are one way to request the use of an HTTP proxy server for
11 //! outgoing connections in many command-line applications. _Which_ environment variable
12 //! will be used depends on the target URL and the convention used by the application
13 //! (or, customarily, the connection library that it uses.)
14 //!
15 //! This crate aims to replicate the convention of the __curl__ library and offer it
16 //! behind a simple API: in most cases, a single function, `for_url()`, which accepts
17 //! a target URL and returns the proxy parameters, if applicable. The method for determining
18 //! the parameters is described in detail in that function's documentation.
19 //!
20 //! # Getting Started
21 //!
22 //! Add the following to the `[dependencies]` section of your `Cargo.toml`:
23 //!
24 //! ```toml
25 //! env_proxy = "0.3"
26 //! ```
27 //!
28 //! If you're using the 2015 edition of Rust, import the crate to your crate root:
29 //!
30 //! ```
31 //! extern crate env_proxy;
32 //! ```
33 //!
34 //! # Examples
35 //!
36 //! To determine proxy parameters for `http://www.example.org`:
37 //!
38 //! ```
39 //! # extern crate url;
40 //! # extern crate env_proxy;
41 //! # fn main() {
42 //! use env_proxy;
43 //! use url::Url;
44 //!
45 //! let url = Url::parse("http://www.example.org").unwrap();
46 //! if let Some(proxy) = env_proxy::for_url(&url).host_port() {
47 //! println!("Proxy host: {}", proxy.0);
48 //! println!("Proxy port: {}", proxy.1);
49 //! }
50 //! # }
51 //! ```
52
53
54 #[cfg(test)]
55 use lazy_static::lazy_static;
56 use log::warn;
57
58 use std::env::var_os;
59 use url::{self, Url};
60
61 macro_rules! env_var_pair {
62 ($lc_var:expr, $uc_var:expr) => {
63 var_os($lc_var).or_else(|| var_os($uc_var))
64 .map(|v| v.to_str()
65 .map(str::to_string)
66 .or_else(|| {
67 warn!("non UTF-8 content in {}/{}", $lc_var, $uc_var);
68 None
69 }))
70 .unwrap_or_else(|| None)
71 };
72 }
73
74 fn matches_no_proxy(url: &Url) -> bool {
75 if let Some(no_proxy) = env_var_pair!("no_proxy", "NO_PROXY") {
76 if no_proxy == "*" {
77 return true;
78 }
79 if let Some(host) = url.host_str() {
80 'elems: for elem in no_proxy.split(|c| c == ',' || c == ' ') {
81 if elem == "" || elem == "." {
82 continue;
83 }
84 let ch1 = elem.chars().next().unwrap();
85 let mut elem_iter = elem.chars();
86 if ch1 == '.' {
87 elem_iter.next();
88 }
89 let mut elem_iter = elem_iter.rev();
90 let mut host_iter = host.chars().rev();
91 while let Some(elem_ch) = elem_iter.next() {
92 if let Some(host_ch) = host_iter.next() {
93 let host_ch = host_ch as u32;
94 let elem_ch = match elem_ch as u32 {
95 uppercase @ 0x41 ..= 0x5a => uppercase + 0x20,
96 anything => anything
97 };
98 if elem_ch == host_ch {
99 continue;
100 }
101 continue 'elems;
102 } else {
103 continue 'elems;
104 }
105 }
106 match host_iter.next() {
107 None => return true,
108 Some(host_ch) if host_ch == '.' => return true,
109 _ => ()
110 }
111 }
112 }
113 }
114 false
115 }
116
117 /// A wrapper for the proxy URL retrieved from the environment.
118 ///
119 /// This struct will wrap the raw value of the URL, which is only guaranteed to be valid UTF-8
120 /// when returned. Various methods exist to extract the value as-is, translate it into other forms,
121 /// and provide elements of interest.
122 pub struct ProxyUrl(Option<String>, Option<u16>);
123
124 impl ProxyUrl {
125 /// Return the raw value of the proxy URL.
126 pub fn raw_value(self) -> Option<String> {
127 self.0
128 }
129
130 /// Return `true` if the `None` value is wrapped.
131 pub fn is_none(self) -> bool {
132 self.0.is_none()
133 }
134
135 /// Set the default port to use when transforming the raw URL value if
136 /// the port isn't specified in the URL.
137 ///
138 /// A `ProxyUrl` instance returned by the library will have the default
139 /// port set to __8080__, which corresponds to __http-alt__ in the IANA port
140 /// registry. This is different from __curl__, which uses port 1080 as the default.
141 ///
142 /// To skip the default port substitution, use [`with_no_default_port()`]
143 /// (#method.with_no_default_port) on the instance.
144 pub fn with_default_port(self, port: u16) -> Self {
145 ProxyUrl(self.0, Some(port))
146 }
147
148 /// Don't use the default port value when transforming the raw URL.
149 pub fn with_no_default_port(self) -> Self {
150 ProxyUrl(self.0, None)
151 }
152
153 /// Transform the raw proxy URL into a `Url`.
154 ///
155 /// The transformation will:
156 ///
157 /// * Parse the raw URL as a `Url`. If the raw URL lacks the scheme, `http` is assumed and
158 /// "http://" is prepended to canonicalize the value;
159 /// * Ensure that the host part is not empty;
160 /// * Use the default value for the port (or not, see [`with_default_port()`](#method.with_default_port))
161 /// if one is not specified in the raw URL.
162 /// * Ensure that the port is not empty.
163 ///
164 /// If any of the steps fail, `None` will be returned.
165 pub fn to_url(self) -> Option<Url> {
166 let mut orig_scheme = self.0.as_ref().map(|s|
167 if s.starts_with("http://") {
168 Some("http")
169 } else if s.starts_with("https://") {
170 Some("https")
171 } else {
172 None
173 }
174 ).unwrap_or(None);
175 if let Some(Ok(mut url)) = self.0.map(|mut s| {
176 if !s.contains("://") {
177 s.insert_str(0, "http://");
178 orig_scheme = Some("http");
179 }
180 if orig_scheme.is_some() {
181 s = s.replacen("http", "xttp", 1);
182 }
183 Url::parse(&s).map_err(|e| {
184 warn!("url parse error: {}", e);
185 e
186 })
187 }) {
188 if url.host_str().is_none() {
189 warn!("host part of the URL is empty");
190 return None;
191 }
192 if let Some(orig_scheme) = orig_scheme {
193 let port = url.port();
194 url = match format!("{}{}", orig_scheme, &url[url::Position::AfterScheme..]).parse() {
195 Ok(url) => url,
196 Err(e) => {
197 warn!("could not set URL scheme back to {}: {}", orig_scheme, e);
198 return None;
199 },
200 };
201 if port.is_some() {
202 url.set_port(port).unwrap_or(());
203 return Some(url);
204 }
205 }
206 if url.port().is_some() {
207 return Some(url);
208 } else if self.1.is_none() {
209 warn!("the port of the URL is unknown");
210 return None;
211 }
212 match url.set_port(self.1) {
213 Ok(_) => return Some(url),
214 Err(_) => warn!("could not set URL port"),
215 }
216 }
217 None
218 }
219
220 /// Return the __(host, port)__ tuple of the proxy.
221 ///
222 /// The raw URL will first be transformed into a `Url`, with any errors in the conversion
223 /// producing a `None` (see [`to_url()`](#method.to_url)).
224 pub fn host_port(self) -> Option<(String, u16)> {
225 self.to_url().map(|u| (u.host_str().expect("host_str").to_string(), u.port_or_known_default().expect("port")))
226 }
227
228
229 /// Return the string representation of the proxy URL.
230 ///
231 /// The raw URL will first be transformed into a `Url`, with any errors in the conversion
232 /// producing a `None` (see [`to_url()`](#method.to_url)).
233 pub fn to_string(self) -> Option<String> {
234 self.to_url().map(Url::into_string)
235 }
236 }
237
238 /// Determine proxy parameters for a URL by examining the environment variables.
239 ///
240 /// __Attention__: in a multithreaded program, care should be taken not to change the environment
241 /// in multiple threads simultaneously without some form of serialization.
242 ///
243 /// Most environment variables described here can be defined either with an all-lowercase or an
244 /// all-uppercase name. If both versions are defined, the all-lowercase name takes precedence
245 /// (e.g., __no_proxy__ will be used even if __NO_PROXY__ is defined.) The only exception is
246 /// __http_proxy__, where only the lowercase name is checked for. This text will use the
247 /// lowercase variants for simplicity.
248 ///
249 /// If __no_proxy__ is defined, check the host part of the URL against its components and return
250 /// `None` if there is any match. The value of __no_proxy__ should be a space- or comma-separated
251 /// list of host/domain names or IP addresses for which no proxying should be done, or a single
252 /// '&#8239;__*__&#8239;' (asterisk) which means that proxying is disabled for all hosts. Empty names
253 /// are skipped. Names beginning with a dot are not treated specially; matching is always done
254 /// by full domain name component. A name consisting of a bare dot is skipped (this is different
255 /// from __curl__'s behavior.)
256 ///
257 /// The rules are summarized in the following table, where the two rightmost columns are headed by two
258 /// __no_proxy__ components, the leftmost column contains hostnames, and the symbol inside each cell
259 /// represents the result of checking the hostname against the corresponding component:
260 ///
261 /// | |example.org|.example.org|
262 /// |-------------|:---------:|:----------:|
263 /// |example.org | &#x2714; | &#x2714; |
264 /// |a.example.org| &#x2714; | &#x2714; |
265 /// |xample.org | &#x2718; | &#x2718; |
266 /// |org | &#x2718; | &#x2718; |
267 ///
268 /// For the __ftp__ protocol scheme, __ftp_proxy__ is checked first; for __http__, __http_proxy__
269 /// is checked, and for __https__, it's __https_proxy__. These three schemes will fall back to __all_proxy__
270 /// if the original variable is undefined. For all other schemes only __all_proxy__ is checked. In this
271 /// context, "checked" means that the value of a variable is used if present, and the search for further
272 /// definitions stops.
273 ///
274 /// The return value, if not `None`, is an opaque structure wrapping the value (possibly canonicalized,
275 /// see [`ProxyUrl::to_url()`](struct.ProxyUrl.html#method.to_url)) of the chosen environment variable.
276 ///
277 /// If the target URL matches __no_proxy__, or if the hostname cannot be extracted from the URL,
278 /// the function returns `None`. If the port is not explicitly defined in the proxy URL, the value 8080
279 /// is used.
280 pub fn for_url(url: &Url) -> ProxyUrl {
281 if matches_no_proxy(url) {
282 return ProxyUrl(None, None);
283 }
284
285 let maybe_https_proxy = env_var_pair!("https_proxy", "HTTPS_PROXY");
286 let maybe_ftp_proxy = env_var_pair!("ftp_proxy", "FTP_PROXY");
287 let maybe_http_proxy = env_var_pair!("http_proxy", ""); // ugh, but it works
288 let maybe_all_proxy = env_var_pair!("all_proxy", "ALL_PROXY");
289
290 let url_value = match url.scheme() {
291 "https" => maybe_https_proxy.or(maybe_all_proxy),
292 "http" => maybe_http_proxy.or(maybe_all_proxy),
293 "ftp" => maybe_ftp_proxy.or(maybe_all_proxy),
294 _ => maybe_all_proxy,
295 };
296 ProxyUrl(url_value, Some(8080))
297 }
298
299 /// Determine proxy parameters for a URL given as a string.
300 ///
301 /// Convert the given string to a URL and pass it to [`for_url()`](#method.for_url), returning
302 /// its result. If the conversion of the input argument fails, return `None`.
303 pub fn for_url_str<S: AsRef<str>>(s: S) -> ProxyUrl {
304 let url = match Url::parse(s.as_ref()) {
305 Ok(url) => url,
306 Err(e) => {
307 warn!("error parsing '{}' as Url: {}", s.as_ref(), e);
308 return ProxyUrl(None, None);
309 },
310 };
311 for_url(&url)
312 }
313
314 #[cfg(test)]
315 mod tests {
316 use std::env::{remove_var, set_var};
317 use std::sync::Mutex;
318 use super::*;
319 use url::Url;
320
321 // environment is per-process, and we need it stable per-thread,
322 // hence locking
323 lazy_static! {
324 static ref LOCK: Mutex<()> = Mutex::new(());
325 }
326
327 fn scrub_env() {
328 remove_var("http_proxy");
329 remove_var("https_proxy");
330 remove_var("HTTPS_PROXY");
331 remove_var("ftp_proxy");
332 remove_var("FTP_PROXY");
333 remove_var("all_proxy");
334 remove_var("ALL_PROXY");
335 remove_var("no_proxy");
336 remove_var("NO_PROXY");
337 }
338
339 #[test]
340 fn no_proxy_simple_name() {
341 let _l = LOCK.lock();
342 scrub_env();
343 set_var("no_proxy", "example.org");
344 set_var("http_proxy", "http://proxy.example.com:8080");
345 let u = Url::parse("http://example.org").ok().unwrap();
346 assert!(for_url(&u).is_none());
347 assert!(for_url_str("http://example.org").is_none());
348 }
349
350 #[test]
351 fn no_proxy_global() {
352 let _l = LOCK.lock();
353 scrub_env();
354 set_var("no_proxy", "*");
355 set_var("http_proxy", "http://proxy.example.com:8080");
356 let u = Url::parse("http://example.org").ok().unwrap();
357 assert!(for_url(&u).is_none());
358 assert!(for_url_str("http://example.org").is_none());
359 }
360
361 #[test]
362 fn no_proxy_subdomain() {
363 let _l = LOCK.lock();
364 scrub_env();
365 set_var("no_proxy", "example.org");
366 set_var("http_proxy", "http://proxy.example.com:8080");
367 let u = Url::parse("http://www.example.org").ok().unwrap();
368 assert!(for_url(&u).is_none());
369 }
370
371 #[test]
372 fn no_proxy_subdomain_dot() {
373 let _l = LOCK.lock();
374 scrub_env();
375 set_var("no_proxy", ".example.org");
376 set_var("http_proxy", "http://proxy.example.com:8080");
377 let u = Url::parse("http://www.example.org").ok().unwrap();
378 assert!(for_url(&u).is_none());
379 assert!(for_url_str("http://www.example.org").is_none());
380 }
381
382 #[test]
383 fn no_proxy_multiple_list() {
384 let _l = LOCK.lock();
385 scrub_env();
386 set_var("no_proxy", "com, .example.org, net");
387 set_var("http_proxy", "http://proxy.example.com:8080");
388 let u = Url::parse("http://www.example.org").ok().unwrap();
389 assert!(for_url(&u).is_none());
390 assert!(for_url_str("http://www.example.org").is_none());
391 }
392
393 #[test]
394 fn http_proxy_specific() {
395 let _l = LOCK.lock();
396 scrub_env();
397 set_var("http_proxy", "http://proxy.example.com:8080");
398 set_var("all_proxy", "http://proxy.example.org:8081");
399 let u = Url::parse("http://www.example.org").ok().unwrap();
400 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.com".to_string(), 8080)));
401 assert_eq!(
402 for_url_str("http://www.example.org").to_string(),
403 Some("http://proxy.example.com:8080/".to_string())
404 );
405 }
406
407 #[test]
408 fn default_proxy_url_scheme() {
409 let _l = LOCK.lock();
410 scrub_env();
411 set_var("http_proxy", "proxy.example.com:8080");
412 let u = Url::parse("http://www.example.org").ok().unwrap();
413 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.com".to_string(), 8080)));
414 assert_eq!(
415 for_url_str("http://www.example.org").to_string(),
416 Some("http://proxy.example.com:8080/".to_string())
417 );
418 }
419
420 #[test]
421 fn proxy_url_with_explicit_scheme_port() {
422 let _l = LOCK.lock();
423 scrub_env();
424 set_var("http_proxy", "http://proxy.example.com:80");
425 let u = Url::parse("http://www.example.org").ok().unwrap();
426 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.com".to_string(), 80)));
427 assert_eq!(
428 for_url_str("http://www.example.org").to_string(),
429 Some("http://proxy.example.com/".to_string())
430 );
431 set_var("http_proxy", "https://proxy.example.com:443");
432 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.com".to_string(), 443)));
433 assert_eq!(
434 for_url_str("http://www.example.org").to_string(),
435 Some("https://proxy.example.com/".to_string())
436 );
437 }
438
439 #[test]
440 fn proxy_url_without_port() {
441 let _l = LOCK.lock();
442 scrub_env();
443 set_var("http_proxy", "http://proxy.example.com");
444 let u = Url::parse("http://www.example.org").ok().unwrap();
445 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.com".to_string(), 8080)));
446 }
447
448 #[test]
449 fn http_proxy_fallback() {
450 let _l = LOCK.lock();
451 scrub_env();
452 set_var("ALL_PROXY", "http://proxy.example.com:8080");
453 let u = Url::parse("http://www.example.org").ok().unwrap();
454 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.com".to_string(), 8080)));
455 assert_eq!(
456 for_url_str("http://www.example.org").to_string(),
457 Some("http://proxy.example.com:8080/".to_string())
458 );
459 set_var("all_proxy", "http://proxy.example.org:8081");
460 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.org".to_string(), 8081)));
461 assert_eq!(
462 for_url_str("http://www.example.org").to_string(),
463 Some("http://proxy.example.org:8081/".to_string())
464 );
465 }
466
467 #[test]
468 fn https_proxy_specific() {
469 let _l = LOCK.lock();
470 scrub_env();
471 set_var("HTTPS_PROXY", "http://proxy.example.com:8080");
472 set_var("all_proxy", "http://proxy.example.org:8081");
473 let u = Url::parse("https://www.example.org").ok().unwrap();
474 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.com".to_string(), 8080)));
475 assert_eq!(
476 for_url_str("https://www.example.org").to_string(),
477 Some("http://proxy.example.com:8080/".to_string())
478 );
479 set_var("https_proxy", "http://proxy.example.com:8082");
480 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.com".to_string(), 8082)));
481 assert_eq!(
482 for_url_str("https://www.example.org").to_string(),
483 Some("http://proxy.example.com:8082/".to_string())
484 );
485 }
486
487 #[test]
488 fn https_proxy_fallback() {
489 let _l = LOCK.lock();
490 scrub_env();
491 set_var("ALL_PROXY", "http://proxy.example.org:8081");
492 let u = Url::parse("ftp://www.example.org").ok().unwrap();
493 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.org".to_string(), 8081)));
494 assert_eq!(
495 for_url_str("https://www.example.org").to_string(),
496 Some("http://proxy.example.org:8081/".to_string())
497 );
498 set_var("all_proxy", "http://proxy.example.org:8082");
499 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.org".to_string(), 8082)));
500 assert_eq!(
501 for_url_str("https://www.example.org").to_string(),
502 Some("http://proxy.example.org:8082/".to_string())
503 );
504 }
505
506 #[test]
507 fn ftp_proxy_specific() {
508 let _l = LOCK.lock();
509 scrub_env();
510 set_var("FTP_PROXY", "http://proxy.example.com:8080");
511 set_var("all_proxy", "http://proxy.example.org:8081");
512 let u = Url::parse("ftp://www.example.org").ok().unwrap();
513 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.com".to_string(), 8080)));
514 assert_eq!(
515 for_url_str("ftp://www.example.org").to_string(),
516 Some("http://proxy.example.com:8080/".to_string())
517 );
518 set_var("ftp_proxy", "http://proxy.example.com:8082");
519 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.com".to_string(), 8082)));
520 assert_eq!(
521 for_url_str("ftp://www.example.org").to_string(),
522 Some("http://proxy.example.com:8082/".to_string())
523 );
524 }
525
526 #[test]
527 fn ftp_proxy_fallback() {
528 let _l = LOCK.lock();
529 scrub_env();
530 set_var("ALL_PROXY", "http://proxy.example.org:8081");
531 let u = Url::parse("ftp://www.example.org").ok().unwrap();
532 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.org".to_string(), 8081)));
533 assert_eq!(
534 for_url_str("ftp://www.example.org").to_string(),
535 Some("http://proxy.example.org:8081/".to_string())
536 );
537 set_var("all_proxy", "http://proxy.example.org:8082");
538 assert_eq!(for_url(&u).host_port(), Some(("proxy.example.org".to_string(), 8082)));
539 assert_eq!(
540 for_url_str("ftp://www.example.org").to_string(),
541 Some("http://proxy.example.org:8082/".to_string())
542 );
543 }
544 }