tun.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. use serde_yaml::{Mapping, Value};
  2. macro_rules! revise {
  3. ($map: expr, $key: expr, $val: expr) => {
  4. let ret_key = Value::String($key.into());
  5. $map.insert(ret_key, Value::from($val));
  6. };
  7. }
  8. // if key not exists then append value
  9. macro_rules! append {
  10. ($map: expr, $key: expr, $val: expr) => {
  11. let ret_key = Value::String($key.into());
  12. if !$map.contains_key(&ret_key) {
  13. $map.insert(ret_key, Value::from($val));
  14. }
  15. };
  16. }
  17. pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
  18. let tun_key = Value::from("tun");
  19. let tun_val = config.get(&tun_key);
  20. if !enable && tun_val.is_none() {
  21. return config;
  22. }
  23. let mut tun_val = tun_val.map_or(Mapping::new(), |val| {
  24. val.as_mapping().cloned().unwrap_or(Mapping::new())
  25. });
  26. revise!(tun_val, "enable", enable);
  27. if enable {
  28. append!(tun_val, "stack", "gvisor");
  29. append!(tun_val, "dns-hijack", vec!["any:53"]);
  30. append!(tun_val, "auto-route", true);
  31. append!(tun_val, "auto-detect-interface", true);
  32. }
  33. revise!(config, "tun", tun_val);
  34. if enable {
  35. use_dns_for_tun(config)
  36. } else {
  37. config
  38. }
  39. }
  40. fn use_dns_for_tun(mut config: Mapping) -> Mapping {
  41. let dns_key = Value::from("dns");
  42. let dns_val = config.get(&dns_key);
  43. let mut dns_val = dns_val.map_or(Mapping::new(), |val| {
  44. val.as_mapping().cloned().unwrap_or(Mapping::new())
  45. });
  46. // 开启tun将同时开启dns
  47. revise!(dns_val, "enable", true);
  48. append!(dns_val, "enhanced-mode", "fake-ip");
  49. append!(dns_val, "fake-ip-range", "198.18.0.1/16");
  50. append!(
  51. dns_val,
  52. "nameserver",
  53. vec!["114.114.114.114", "223.5.5.5", "8.8.8.8"]
  54. );
  55. append!(dns_val, "fallback", vec![] as Vec<&str>);
  56. #[cfg(target_os = "windows")]
  57. append!(
  58. dns_val,
  59. "fake-ip-filter",
  60. vec![
  61. "dns.msftncsi.com",
  62. "www.msftncsi.com",
  63. "www.msftconnecttest.com"
  64. ]
  65. );
  66. revise!(config, "dns", dns_val);
  67. config
  68. }