1use std::ffi::c_char;
2use std::ffi::c_int;
3use std::ffi::CStr;
4use std::io::Write;
5
6pub use broker::broker_client;
7pub use broker::BrokerSource;
8use bytes::Bytes;
9pub use client::Client;
10pub use client::{BridgeMode, BrokerKeys, Config};
11pub use control_prot::{ConnInfo, ControlClient};
12pub use get_dialer::ExitConstraint;
13use nanorpc::JrpcRequest;
14use nanorpc::RpcTransport;
15use once_cell::sync::OnceCell;
16
17mod auth;
18mod broker;
19mod china;
20mod client;
21mod client_inner;
22mod control_prot;
23mod database;
24mod device_metadata;
25mod http_proxy;
26mod litecopy;
27pub mod logging;
28
29mod get_dialer;
30mod pac;
31mod socks5;
32mod spoof_dns;
33mod stats;
34mod taskpool;
35mod traffcount;
36mod updates;
37mod vpn;
38
39static CLIENT: OnceCell<Client> = OnceCell::new();
42
43#[no_mangle]
44pub unsafe extern "C" fn start_client(cfg: *const c_char) -> libc::c_int {
45 let cfg_str = unsafe { CStr::from_ptr(cfg) }.to_str().unwrap();
46 let cfg: Config = serde_json::from_str(cfg_str).unwrap();
47
48 CLIENT.get_or_init(|| Client::start(cfg));
49
50 0
51}
52
53#[no_mangle]
54pub unsafe extern "C" fn daemon_rpc(
55 jrpc_req: *const c_char,
56 out_buf: *mut c_char,
57 out_buflen: c_int,
58) -> c_int {
59 let req_str = unsafe { CStr::from_ptr(jrpc_req) }.to_str().unwrap();
60 let jrpc: JrpcRequest = serde_json::from_str(req_str).unwrap();
61
62 if let Some(client) = CLIENT.get() {
63 let ctrl = client.control_client().0;
64 if let Ok(response) = smolscale::block_on(async move { ctrl.call_raw(jrpc).await }) {
65 let response_json = serde_json::to_string(&response).unwrap();
66 let response_c = std::ffi::CString::new(response_json).unwrap();
67 let bytes = response_c.as_bytes_with_nul();
68
69 unsafe { fill_buffer(out_buf, out_buflen, bytes) }
70 } else {
71 -2 }
73 } else {
74 -1 }
76}
77
78#[no_mangle]
79pub unsafe extern "C" fn send_pkt(pkt: *const c_char, pkt_len: c_int) -> c_int {
80 let slice: &'static [u8] = std::slice::from_raw_parts(pkt as *mut u8, pkt_len as usize);
81 if let Some(client) = CLIENT.get() {
82 if let Ok(_) = smol::future::block_on(client.send_vpn_packet(Bytes::copy_from_slice(slice)))
83 {
84 return 0;
85 }
86 }
87 -1
88}
89
90#[no_mangle]
91pub unsafe extern "C" fn recv_pkt(out_buf: *mut c_char, out_buflen: c_int) -> c_int {
92 if let Some(client) = CLIENT.get() {
93 if let Ok(pkt) = smol::future::block_on(client.recv_vpn_packet()) {
94 return fill_buffer(out_buf, out_buflen, &pkt);
95 }
96 }
97 -1
98}
99
100unsafe fn fill_buffer(buffer: *mut c_char, buflen: c_int, output: &[u8]) -> c_int {
101 let mut slice = std::slice::from_raw_parts_mut(buffer as *mut u8, buflen as usize);
102 if output.len() < slice.len() {
103 if slice.write_all(output).is_err() {
104 tracing::debug!("writing to buffer failed!");
105 -4
106 } else {
107 output.len() as c_int
108 }
109 } else {
110 tracing::debug!(" buffer not big enough!");
111 -3
112 }
113}
114
115#[cfg(test)]
116mod tests {
117 use smol::Timer;
118
119 use super::*;
120 use std::{
121 ffi::CString,
122 net::{Ipv4Addr, SocketAddr},
123 };
124
125 const CONTROL_ADDR: SocketAddr =
126 SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 12222);
127
128 pub const PAC_ADDR: SocketAddr =
129 SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 12223);
130
131 const SOCKS5_ADDR: SocketAddr =
132 SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 9909);
133
134 pub const HTTP_ADDR: SocketAddr =
135 SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 9910);
136
137 #[test]
138 fn test_clib() {
139 let cfg = super::Config {
140 socks5_listen: Some(SOCKS5_ADDR),
142 http_proxy_listen: Some(HTTP_ADDR),
143 control_listen: Some(CONTROL_ADDR),
144 exit_constraint: super::ExitConstraint::Auto,
145 bridge_mode: BridgeMode::Auto,
146 cache: None,
147 vpn_fd: None,
148 broker: Some(BrokerSource::Race(vec![
149 BrokerSource::Fronted {
150 front: "https://www.cdn77.com/".into(),
151 host: "1826209743.rsc.cdn77.org".into(),
152 },
153 BrokerSource::Fronted {
154 front: "https://vuejs.org/".into(),
155 host: "svitania-naidallszei-2.netlify.app".into(),
156 },
157 ])),
158 broker_keys: Some(BrokerKeys {
159 master: "88c1d2d4197bed815b01a22cadfc6c35aa246dddb553682037a118aebfaa3954".into(),
160 mizaru_free: "0558216cbab7a9c46f298f4c26e171add9af87d0694988b8a8fe52ee932aa754"
161 .into(),
162 mizaru_plus: "cf6f58868c6d9459b3a63bc2bd86165631b3e916bad7f62b578cd9614e0bcb3b"
163 .into(),
164 }),
165 vpn: false,
167 spoof_dns: false,
168 passthrough_china: false,
169 dry_run: false,
170 credentials: geph5_broker_protocol::Credential::Secret(String::new()),
171 sess_metadata: Default::default(),
172 task_limit: None,
173 pac_listen: Some(PAC_ADDR),
174 };
175 let cfg_str = CString::new(serde_json::to_string(&cfg).unwrap()).unwrap();
176 let cfg_ptr = cfg_str.as_ptr();
177
178 let start_client_ret = unsafe { start_client(cfg_ptr) };
179 assert!(start_client_ret == 0);
180
181 for _ in 0..2 {
183 let jrpc_req = JrpcRequest {
184 jsonrpc: "2.0".into(),
185 method: "user_info".into(),
186 params: [].into(),
187 id: nanorpc::JrpcId::Number(1),
188 };
189 let jrpc_req_str = CString::new(serde_json::to_string(&jrpc_req).unwrap()).unwrap();
190 let jrpc_req_ptr = jrpc_req_str.as_ptr();
191 let mut out_buf = vec![0; 1024 * 128]; let out_buf_ptr = out_buf.as_mut_ptr();
194
195 let rpc_ret = unsafe { daemon_rpc(jrpc_req_ptr, out_buf_ptr, out_buf.len() as _) };
196 println!("daemon_rpc retcode = {rpc_ret}");
197 assert!(rpc_ret >= 0);
198 let output = unsafe { CStr::from_ptr(out_buf_ptr) }.to_str().unwrap();
199 println!("daemon_rpc output = {output}");
200 smolscale::block_on(async { Timer::after(std::time::Duration::from_secs(1)).await });
201 }
202 }
203}