lib.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. pub mod compress;
  2. #[path = "./protos/message.rs"]
  3. pub mod message_proto;
  4. #[path = "./protos/rendezvous.rs"]
  5. pub mod rendezvous_proto;
  6. pub use bytes;
  7. pub use futures;
  8. pub use protobuf;
  9. use std::{
  10. fs::File,
  11. io::{self, BufRead},
  12. net::{Ipv4Addr, SocketAddr, SocketAddrV4},
  13. path::Path,
  14. time::{self, SystemTime, UNIX_EPOCH},
  15. };
  16. pub use tokio;
  17. pub use tokio_util;
  18. pub mod socket_client;
  19. pub mod tcp;
  20. pub mod udp;
  21. pub use env_logger;
  22. pub use log;
  23. pub mod bytes_codec;
  24. #[cfg(feature = "quic")]
  25. pub mod quic;
  26. pub use anyhow::{self, bail};
  27. pub use futures_util;
  28. pub mod config;
  29. pub mod fs;
  30. #[cfg(not(any(target_os = "android", target_os = "ios")))]
  31. pub use mac_address;
  32. pub use rand;
  33. pub use regex;
  34. pub use sodiumoxide;
  35. pub use tokio_socks;
  36. pub use tokio_socks::IntoTargetAddr;
  37. pub use tokio_socks::TargetAddr;
  38. pub use lazy_static;
  39. #[cfg(feature = "quic")]
  40. pub type Stream = quic::Connection;
  41. #[cfg(not(feature = "quic"))]
  42. pub type Stream = tcp::FramedStream;
  43. #[inline]
  44. pub async fn sleep(sec: f32) {
  45. tokio::time::sleep(time::Duration::from_secs_f32(sec)).await;
  46. }
  47. #[macro_export]
  48. macro_rules! allow_err {
  49. ($e:expr) => {
  50. if let Err(err) = $e {
  51. log::debug!(
  52. "{:?}, {}:{}:{}:{}",
  53. err,
  54. module_path!(),
  55. file!(),
  56. line!(),
  57. column!()
  58. );
  59. } else {
  60. }
  61. };
  62. }
  63. #[inline]
  64. pub fn timeout<T: std::future::Future>(ms: u64, future: T) -> tokio::time::Timeout<T> {
  65. tokio::time::timeout(std::time::Duration::from_millis(ms), future)
  66. }
  67. pub type ResultType<F, E = anyhow::Error> = anyhow::Result<F, E>;
  68. /// Certain router and firewalls scan the packet and if they
  69. /// find an IP address belonging to their pool that they use to do the NAT mapping/translation, so here we mangle the ip address
  70. pub struct AddrMangle();
  71. impl AddrMangle {
  72. pub fn encode(addr: SocketAddr) -> Vec<u8> {
  73. match addr {
  74. SocketAddr::V4(addr_v4) => {
  75. let tm = (SystemTime::now()
  76. .duration_since(UNIX_EPOCH)
  77. .unwrap()
  78. .as_micros() as u32) as u128;
  79. let ip = u32::from_le_bytes(addr_v4.ip().octets()) as u128;
  80. let port = addr.port() as u128;
  81. let v = ((ip + tm) << 49) | (tm << 17) | (port + (tm & 0xFFFF));
  82. let bytes = v.to_le_bytes();
  83. let mut n_padding = 0;
  84. for i in bytes.iter().rev() {
  85. if i == &0u8 {
  86. n_padding += 1;
  87. } else {
  88. break;
  89. }
  90. }
  91. bytes[..(16 - n_padding)].to_vec()
  92. }
  93. _ => {
  94. panic!("Only support ipv4");
  95. }
  96. }
  97. }
  98. pub fn decode(bytes: &[u8]) -> SocketAddr {
  99. let mut padded = [0u8; 16];
  100. padded[..bytes.len()].copy_from_slice(&bytes);
  101. let number = u128::from_le_bytes(padded);
  102. let tm = (number >> 17) & (u32::max_value() as u128);
  103. let ip = (((number >> 49) - tm) as u32).to_le_bytes();
  104. let port = (number & 0xFFFFFF) - (tm & 0xFFFF);
  105. SocketAddr::V4(SocketAddrV4::new(
  106. Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]),
  107. port as u16,
  108. ))
  109. }
  110. }
  111. pub fn get_version_from_url(url: &str) -> String {
  112. let n = url.chars().count();
  113. let a = url
  114. .chars()
  115. .rev()
  116. .enumerate()
  117. .filter(|(_, x)| x == &'-')
  118. .next()
  119. .map(|(i, _)| i);
  120. if let Some(a) = a {
  121. let b = url
  122. .chars()
  123. .rev()
  124. .enumerate()
  125. .filter(|(_, x)| x == &'.')
  126. .next()
  127. .map(|(i, _)| i);
  128. if let Some(b) = b {
  129. if a > b {
  130. if url
  131. .chars()
  132. .skip(n - b)
  133. .collect::<String>()
  134. .parse::<i32>()
  135. .is_ok()
  136. {
  137. return url.chars().skip(n - a).collect();
  138. } else {
  139. return url.chars().skip(n - a).take(a - b - 1).collect();
  140. }
  141. } else {
  142. return url.chars().skip(n - a).collect();
  143. }
  144. }
  145. }
  146. "".to_owned()
  147. }
  148. pub fn gen_version() {
  149. let mut file = File::create("./src/version.rs").unwrap();
  150. for line in read_lines("Cargo.toml").unwrap() {
  151. if let Ok(line) = line {
  152. let ab: Vec<&str> = line.split("=").map(|x| x.trim()).collect();
  153. if ab.len() == 2 && ab[0] == "version" {
  154. use std::io::prelude::*;
  155. file.write_all(format!("pub const VERSION: &str = {};", ab[1]).as_bytes())
  156. .ok();
  157. file.sync_all().ok();
  158. break;
  159. }
  160. }
  161. }
  162. }
  163. fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
  164. where
  165. P: AsRef<Path>,
  166. {
  167. let file = File::open(filename)?;
  168. Ok(io::BufReader::new(file).lines())
  169. }
  170. pub fn is_valid_custom_id(id: &str) -> bool {
  171. regex::Regex::new(r"^[a-zA-Z]\w{5,15}$")
  172. .unwrap()
  173. .is_match(id)
  174. }
  175. pub fn get_version_number(v: &str) -> i64 {
  176. let mut n = 0;
  177. for x in v.split(".") {
  178. n = n * 1000 + x.parse::<i64>().unwrap_or(0);
  179. }
  180. n
  181. }
  182. pub fn get_modified_time(path: &std::path::Path) -> SystemTime {
  183. std::fs::metadata(&path)
  184. .map(|m| m.modified().unwrap_or(UNIX_EPOCH))
  185. .unwrap_or(UNIX_EPOCH)
  186. }
  187. #[cfg(test)]
  188. mod tests {
  189. use super::*;
  190. #[test]
  191. fn test_mangle() {
  192. let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(192, 168, 16, 32), 21116));
  193. assert_eq!(addr, AddrMangle::decode(&AddrMangle::encode(addr)));
  194. }
  195. }