lib.rs 5.7 KB

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