smartdns.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*************************************************************************
  2. *
  3. * Copyright (C) 2018-2024 Ruilin Peng (Nick) <[email protected]>.
  4. *
  5. * smartdns is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * smartdns is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #![allow(non_upper_case_globals)]
  19. #![allow(non_camel_case_types)]
  20. #![allow(non_snake_case)]
  21. #![allow(dead_code)]
  22. #![allow(unused_imports)]
  23. mod smartdns_c {
  24. use libc::gid_t;
  25. use libc::in6_addr;
  26. use libc::in_addr;
  27. use libc::sockaddr;
  28. use libc::sockaddr_storage;
  29. use libc::socklen_t;
  30. use libc::time_t;
  31. use libc::timeval;
  32. use libc::tm;
  33. use libc::uid_t;
  34. use u32 as u_int;
  35. include!(concat!(env!("OUT_DIR"), "/smartdns_bindings.rs"));
  36. }
  37. extern crate libc;
  38. use std::error::Error;
  39. use std::ffi::CString;
  40. #[repr(C)]
  41. #[derive(Copy, Clone, Debug, PartialEq)]
  42. #[allow(dead_code)]
  43. pub enum LogLevel {
  44. DEBUG = 0,
  45. INFO = 1,
  46. NOTICE = 2,
  47. WARN = 3,
  48. ERROR = 4,
  49. FATAL = 5,
  50. }
  51. impl TryFrom<u32> for LogLevel {
  52. type Error = ();
  53. fn try_from(value: u32) -> Result<Self, Self::Error> {
  54. match value {
  55. 0 => Ok(LogLevel::DEBUG),
  56. 1 => Ok(LogLevel::INFO),
  57. 2 => Ok(LogLevel::NOTICE),
  58. 3 => Ok(LogLevel::WARN),
  59. 4 => Ok(LogLevel::ERROR),
  60. 5 => Ok(LogLevel::FATAL),
  61. _ => Err(()),
  62. }
  63. }
  64. }
  65. #[macro_export]
  66. macro_rules! dns_log {
  67. ($level:expr, $($arg:tt)*) => {
  68. if $crate::smartdns::dns_can_log($level) {
  69. $crate::smartdns::dns_log_out($level, file!(), line!(), &format!($($arg)*));
  70. }
  71. };
  72. }
  73. pub fn dns_can_log(level: LogLevel) -> bool {
  74. unsafe { smartdns_c::smartdns_plugin_can_log(level as u32) != 0 }
  75. }
  76. pub fn dns_log_set_level(level: LogLevel) {
  77. unsafe {
  78. smartdns_c::smartdns_plugin_log_setlevel(level as u32);
  79. }
  80. }
  81. pub fn dns_log_get_level() -> LogLevel {
  82. unsafe {
  83. let leve = smartdns_c::smartdns_plugin_log_getlevel();
  84. LogLevel::try_from(leve as u32).unwrap()
  85. }
  86. }
  87. pub fn dns_log_out(level: LogLevel, file: &str, line: u32, message: &str) {
  88. let filename_only = std::path::Path::new(file)
  89. .file_name()
  90. .and_then(|s| s.to_str())
  91. .unwrap();
  92. let file_cstring = CString::new(filename_only).expect("Failed to convert to CString");
  93. let message_cstring = CString::new(message).expect("Failed to convert to CString");
  94. unsafe {
  95. smartdns_c::smartdns_plugin_log(
  96. level as u32,
  97. file_cstring.as_ptr(),
  98. line as i32,
  99. std::ptr::null(),
  100. message_cstring.as_ptr(),
  101. );
  102. }
  103. }
  104. pub fn smartdns_version() -> String {
  105. unsafe {
  106. let version = smartdns_c::smartdns_version();
  107. std::ffi::CStr::from_ptr(version)
  108. .to_string_lossy()
  109. .into_owned()
  110. }
  111. }
  112. pub fn smartdns_ui_version() -> String {
  113. env!("CARGO_PKG_VERSION").to_string()
  114. }
  115. pub fn smartdns_server_run(file: &str) -> Result<(), Box<dyn Error>> {
  116. let file = CString::new(file).expect("Failed to convert to CString");
  117. let ret: i32;
  118. unsafe {
  119. ret = smartdns_c::smartdns_server_run(file.as_ptr());
  120. };
  121. if ret != 0 {
  122. return Err("smartdns server run error".into());
  123. }
  124. Ok(())
  125. }
  126. pub fn smartdns_server_stop() {
  127. unsafe {
  128. smartdns_c::smartdns_server_stop();
  129. }
  130. }
  131. pub fn get_utc_time_ms() -> u64 {
  132. unsafe { smartdns_c::get_utc_time_ms() }
  133. }
  134. static SMARTDNS_OPS: smartdns_c::smartdns_operations = smartdns_c::smartdns_operations {
  135. server_recv: None,
  136. server_query_complete: Some(dns_request_complete),
  137. };
  138. #[no_mangle]
  139. extern "C" fn dns_request_complete(request: *mut smartdns_c::dns_request) {
  140. unsafe {
  141. let ops = PLUGIN.ops.as_ref();
  142. if let None = ops {
  143. return;
  144. }
  145. let ops = ops.unwrap();
  146. let mut req = DnsRequest::new(request);
  147. ops.server_query_complete(&mut req);
  148. }
  149. }
  150. #[no_mangle]
  151. extern "C" fn dns_plugin_init(plugin: *mut smartdns_c::dns_plugin) -> i32 {
  152. unsafe {
  153. PLUGIN.parser_args(plugin).unwrap();
  154. smartdns_c::smartdns_operations_register(&SMARTDNS_OPS);
  155. let ret = PLUGIN.ops.as_mut().unwrap().server_init(PLUGIN.get_args());
  156. if let Err(e) = ret {
  157. dns_log!(LogLevel::ERROR, "server init error: {}", e);
  158. return -1;
  159. }
  160. }
  161. return 0;
  162. }
  163. #[no_mangle]
  164. extern "C" fn dns_plugin_exit(_plugin: *mut smartdns_c::dns_plugin) -> i32 {
  165. unsafe {
  166. smartdns_c::smartdns_operations_unregister(&SMARTDNS_OPS);
  167. PLUGIN.ops.as_mut().unwrap().server_exit();
  168. }
  169. return 0;
  170. }
  171. pub struct DnsRequest {
  172. request: *mut smartdns_c::dns_request,
  173. }
  174. #[allow(dead_code)]
  175. impl DnsRequest {
  176. fn new(request: *mut smartdns_c::dns_request) -> DnsRequest {
  177. unsafe {
  178. smartdns_c::dns_server_request_get(request);
  179. }
  180. DnsRequest { request }
  181. }
  182. fn put_ref(&mut self) {
  183. unsafe {
  184. smartdns_c::dns_server_request_put(self.request);
  185. self.request = std::ptr::null_mut();
  186. }
  187. }
  188. pub fn get_group_name(&self) -> String {
  189. unsafe {
  190. let group_name = smartdns_c::dns_server_request_get_group_name(self.request);
  191. std::ffi::CStr::from_ptr(group_name)
  192. .to_string_lossy()
  193. .into_owned()
  194. }
  195. }
  196. pub fn get_domain(&self) -> String {
  197. unsafe {
  198. let domain = smartdns_c::dns_server_request_get_domain(self.request);
  199. std::ffi::CStr::from_ptr(domain)
  200. .to_string_lossy()
  201. .into_owned()
  202. }
  203. }
  204. pub fn get_qtype(&self) -> u32 {
  205. unsafe { smartdns_c::dns_server_request_get_qtype(self.request) as u32 }
  206. }
  207. pub fn get_qclass(&self) -> i32 {
  208. unsafe { smartdns_c::dns_server_request_get_qclass(self.request) }
  209. }
  210. pub fn get_id(&self) -> u16 {
  211. unsafe { smartdns_c::dns_server_request_get_id(self.request) as u16 }
  212. }
  213. pub fn get_rcode(&self) -> u16 {
  214. unsafe { smartdns_c::dns_server_request_get_rcode(self.request) as u16 }
  215. }
  216. pub fn get_query_time(&self) -> u64 {
  217. unsafe { smartdns_c::dns_server_request_get_query_time(self.request) }
  218. }
  219. pub fn get_remote_addr(&self) -> String {
  220. unsafe {
  221. let addr = smartdns_c::dns_server_request_get_remote_addr(self.request);
  222. let mut buf = [0u8; 1024];
  223. let retstr = smartdns_c::get_host_by_addr(
  224. buf.as_mut_ptr(),
  225. buf.len() as i32,
  226. addr as *const libc::sockaddr,
  227. );
  228. if retstr.is_null() {
  229. return String::new();
  230. }
  231. let addr = std::ffi::CStr::from_ptr(retstr)
  232. .to_string_lossy()
  233. .into_owned();
  234. addr
  235. }
  236. }
  237. pub fn get_local_addr(&self) -> String {
  238. unsafe {
  239. let addr = smartdns_c::dns_server_request_get_local_addr(self.request);
  240. let mut buf = [0u8; 1024];
  241. let retstr = smartdns_c::get_host_by_addr(
  242. buf.as_mut_ptr(),
  243. buf.len() as i32,
  244. addr as *const libc::sockaddr,
  245. );
  246. if retstr.is_null() {
  247. return String::new();
  248. }
  249. let addr = std::ffi::CStr::from_ptr(retstr)
  250. .to_string_lossy()
  251. .into_owned();
  252. addr
  253. }
  254. }
  255. }
  256. impl Drop for DnsRequest {
  257. fn drop(&mut self) {
  258. self.put_ref();
  259. }
  260. }
  261. impl Clone for DnsRequest {
  262. fn clone(&self) -> Self {
  263. unsafe {
  264. smartdns_c::dns_server_request_get(self.request);
  265. }
  266. DnsRequest {
  267. request: self.request,
  268. }
  269. }
  270. }
  271. unsafe impl Send for DnsRequest {}
  272. pub trait SmartdnsOperations {
  273. fn server_query_complete(&self, request: &mut DnsRequest);
  274. fn server_init(&mut self, args: &Vec<String>) -> Result<(), Box<dyn Error>>;
  275. fn server_exit(&mut self);
  276. }
  277. pub static mut PLUGIN: Plugin = Plugin {
  278. args: Vec::new(),
  279. ops: None,
  280. };
  281. pub struct Plugin {
  282. args: Vec<String>,
  283. ops: Option<Box<dyn SmartdnsOperations>>,
  284. }
  285. pub struct SmartdnsCert {
  286. pub key: String,
  287. pub cert: String,
  288. pub password: String,
  289. }
  290. #[allow(dead_code)]
  291. impl Plugin {
  292. pub fn get_args(&self) -> &Vec<String> {
  293. &self.args
  294. }
  295. pub fn set_operation(&mut self, ops: Box<dyn SmartdnsOperations>) {
  296. self.ops = Some(ops);
  297. }
  298. pub fn smartdns_exit(status: i32) {
  299. unsafe {
  300. smartdns_c::smartdns_exit(status);
  301. }
  302. }
  303. pub fn smartdns_restart() {
  304. unsafe {
  305. smartdns_c::smartdns_restart();
  306. }
  307. }
  308. pub fn smartdns_get_cert() -> Result<SmartdnsCert, String> {
  309. unsafe {
  310. let mut key = [0u8; 4096];
  311. let mut cert = [0u8; 4096];
  312. let ret = smartdns_c::smartdns_get_cert(
  313. key.as_mut_ptr() as *mut libc::c_char,
  314. cert.as_mut_ptr() as *mut libc::c_char,
  315. );
  316. if ret != 0 {
  317. return Err("get cert error".to_string());
  318. }
  319. let key = std::ffi::CStr::from_ptr(key.as_ptr() as *const libc::c_char)
  320. .to_string_lossy()
  321. .into_owned();
  322. let cert = std::ffi::CStr::from_ptr(cert.as_ptr() as *const libc::c_char)
  323. .to_string_lossy()
  324. .into_owned();
  325. Ok(SmartdnsCert {
  326. key,
  327. cert,
  328. password: "".to_string(),
  329. })
  330. }
  331. }
  332. pub fn dns_cache_flush() {
  333. unsafe {
  334. smartdns_c::dns_cache_flush();
  335. }
  336. }
  337. pub fn dns_cache_total_num() -> i32 {
  338. unsafe { smartdns_c::dns_cache_total_num() }
  339. }
  340. #[allow(dead_code)]
  341. pub fn dns_conf_cache_dir() -> String {
  342. unsafe {
  343. let cache_dir = smartdns_c::dns_conf_get_cache_dir();
  344. std::ffi::CStr::from_ptr(cache_dir)
  345. .to_string_lossy()
  346. .into_owned()
  347. }
  348. }
  349. #[allow(dead_code)]
  350. pub fn dns_conf_data_dir() -> String {
  351. unsafe {
  352. let data_dir = smartdns_c::dns_conf_get_data_dir();
  353. std::ffi::CStr::from_ptr(data_dir)
  354. .to_string_lossy()
  355. .into_owned()
  356. }
  357. }
  358. #[allow(dead_code)]
  359. pub fn dns_conf_plugin_config(key: &str, default: &str) -> String {
  360. let key = CString::new(key).expect("Failed to convert to CString");
  361. unsafe {
  362. let value = smartdns_c::smartdns_plugin_get_config(key.as_ptr());
  363. if value.is_null() {
  364. return default.to_string();
  365. }
  366. std::ffi::CStr::from_ptr(value)
  367. .to_string_lossy()
  368. .into_owned()
  369. }
  370. }
  371. #[allow(dead_code)]
  372. pub fn dns_conf_plugin_clear_all_config() {
  373. unsafe {
  374. smartdns_c::smartdns_plugin_clear_all_config();
  375. }
  376. }
  377. fn parser_args(&mut self, plugin: *mut smartdns_c::dns_plugin) -> Result<(), String> {
  378. let argc = unsafe { smartdns_c::dns_plugin_get_argc(plugin) };
  379. let args: Vec<String> = unsafe {
  380. let argv = smartdns_c::dns_plugin_get_argv(plugin);
  381. let mut args = Vec::new();
  382. for i in 0..argc {
  383. let arg = std::ffi::CStr::from_ptr(*argv.offset(i as isize))
  384. .to_string_lossy()
  385. .into_owned();
  386. args.push(arg);
  387. }
  388. args
  389. };
  390. self.args = args;
  391. Ok(())
  392. }
  393. }
  394. #[cfg(test)]
  395. mod tests {
  396. use super::*;
  397. #[test]
  398. fn test_dns_log() {
  399. dns_log!(LogLevel::DEBUG, "test log");
  400. }
  401. }