geph5_client/
client.rs

1use anyctx::AnyCtx;
2
3use anyhow::Context;
4use bytes::Bytes;
5use futures_util::{
6    future::Shared, task::noop_waker, AsyncReadExt, AsyncWriteExt, FutureExt, TryFutureExt,
7};
8use geph5_broker_protocol::{Credential, UserInfo};
9use geph5_misc_rpc::client_control::{ControlClient, ControlService};
10use nanorpc::DynRpcTransport;
11use sillad::Pipe;
12use smol::future::FutureExt as _;
13use std::{fs::File, net::SocketAddr, path::PathBuf, sync::Arc};
14
15use serde::{Deserialize, Serialize};
16use smolscale::immortal::Immortal;
17
18use crate::{
19    auth::{auth_loop, get_auth_token},
20    broker::{broker_client, BrokerSource},
21    bw_token::bw_token_refresh_loop,
22    control_prot::{ControlProtocolImpl, DummyControlProtocolTransport},
23    get_dialer::ExitConstraint,
24    http_proxy::http_proxy_serve,
25    logging,
26    pac::pac_serve,
27    session::{open_conn, run_client_sessions},
28    socks5::socks5_loop,
29    vpn::{recv_vpn_packet, send_vpn_packet, vpn_loop},
30};
31
32#[derive(Serialize, Deserialize, Clone)]
33pub struct Config {
34    pub socks5_listen: Option<SocketAddr>,
35    pub http_proxy_listen: Option<SocketAddr>,
36    pub pac_listen: Option<SocketAddr>,
37
38    pub control_listen: Option<SocketAddr>,
39    pub exit_constraint: ExitConstraint,
40    #[serde(default)]
41    pub bridge_mode: BridgeMode,
42    pub cache: Option<PathBuf>,
43
44    pub broker: Option<BrokerSource>,
45    pub broker_keys: Option<BrokerKeys>,
46
47    #[serde(default)]
48    pub vpn: bool,
49    #[serde(default)]
50    pub vpn_fd: Option<i32>,
51    #[serde(default)]
52    pub spoof_dns: bool,
53    #[serde(default)]
54    pub passthrough_china: bool,
55    #[serde(default)]
56    pub dry_run: bool,
57    #[serde(default)]
58    pub credentials: Credential,
59
60    #[serde(default)]
61    pub sess_metadata: serde_json::Value,
62    pub task_limit: Option<u32>,
63}
64
65#[derive(Serialize, Deserialize, Clone)]
66/// Broker keys, in hexadecimal format.
67pub struct BrokerKeys {
68    pub master: String,
69    pub mizaru_free: String,
70    pub mizaru_plus: String,
71    pub mizaru_bw: String,
72}
73
74impl Config {
75    /// Create an "inert" version of this config that does not start any processes.
76    pub fn inert(&self) -> Self {
77        let mut this = self.clone();
78        this.dry_run = true;
79        this.socks5_listen = None;
80        this.http_proxy_listen = None;
81        this.pac_listen = None;
82        this.control_listen = None;
83        this
84    }
85}
86
87#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
88pub enum BridgeMode {
89    #[default]
90    Auto,
91    ForceBridges,
92}
93
94#[derive(Clone)]
95pub struct Client {
96    task: Shared<smol::Task<Result<(), Arc<anyhow::Error>>>>,
97    ctx: AnyCtx<Config>,
98}
99
100impl Client {
101    /// Starts the client logic in the loop, returning the handle.
102    pub fn start(cfg: Config) -> Self {
103        let ctx = AnyCtx::new(cfg.clone());
104        // Initialize logging once we have context so JSON logs go to SQLite
105        let _ = logging::init_logging(&ctx);
106        let ((fd_limit, _), _) = binary_search::binary_search((1, ()), (65536, ()), |lim| {
107            if rlimit::increase_nofile_limit(lim).unwrap_or_default() >= lim {
108                binary_search::Direction::Low(())
109            } else {
110                binary_search::Direction::High(())
111            }
112        });
113        tracing::info!("raised file descriptor limit to {}", fd_limit);
114
115        #[cfg(unix)]
116        if let Some(fd) = cfg.vpn_fd {
117            let ctx_clone = ctx.clone();
118            smolscale::spawn(async move {
119                // Create an async file descriptor from the raw fd
120                let async_fd: smol::Async<File> =
121                    smol::Async::new(unsafe { std::os::fd::FromRawFd::from_raw_fd(fd) })
122                        .expect("could not wrap VPN fd in Async");
123
124                // Split the file descriptor for reading and writingz
125                let (mut reader, mut writer) = async_fd.split();
126
127                // Spawn a task for reading from fd and sending to VPN
128                let read_task = async {
129                    let mut buf = vec![0u8; 65535]; // Buffer for reading packets
130                    loop {
131                        match reader.read(&mut buf).await {
132                            Ok(n) if n > 0 => {
133                                // Send the packet to the VPN
134                                send_vpn_packet(
135                                    &ctx_clone,
136                                    bytes::Bytes::copy_from_slice(&buf[..n]),
137                                )
138                                .await;
139                            }
140                            Ok(0) => {
141                                // EOF
142                                tracing::warn!("VPN fd reached EOF");
143                                break;
144                            }
145                            Err(e) => {
146                                tracing::error!("Error reading from VPN fd: {}", e);
147                                break;
148                            }
149                            _ => break,
150                        }
151                    }
152                    anyhow::Ok(())
153                };
154
155                // Spawn a task for receiving from VPN and writing to fd
156                let write_task = async {
157                    loop {
158                        // Receive a packet from the VPN
159                        let packet = recv_vpn_packet(&ctx_clone).await;
160
161                        // Write the packet to the file descriptor
162                        if let Err(e) = writer.write_all(&packet).await {
163                            tracing::error!("Error writing to VPN fd: {}", e);
164                            break;
165                        }
166
167                        if let Err(e) = writer.flush().await {
168                            tracing::error!("Error flushing VPN fd: {}", e);
169                            break;
170                        }
171                    }
172                    anyhow::Ok(())
173                };
174
175                // Wait for either task to complete (or fail)
176                let _ = read_task.race(write_task).await;
177                tracing::warn!("VPN fd handler exited");
178            })
179            .detach();
180        }
181        let task = smolscale::spawn(client_main(ctx.clone()).map_err(Arc::new));
182        Client {
183            task: task.shared(),
184            ctx,
185        }
186    }
187
188    /// Opens a connection through the tunnel.
189    pub async fn open_conn(&self, remote: &str) -> anyhow::Result<Box<dyn Pipe>> {
190        open_conn(&self.ctx, "tcp", remote).await
191    }
192
193    /// Wait until there's an error.
194    pub async fn wait_until_dead(self) -> anyhow::Result<()> {
195        self.task.await.map_err(|e| anyhow::anyhow!(e))
196    }
197
198    /// Check for an error.
199    pub fn check_dead(&self) -> anyhow::Result<()> {
200        match self
201            .task
202            .clone()
203            .poll(&mut std::task::Context::from_waker(&noop_waker()))
204        {
205            std::task::Poll::Ready(val) => val.map_err(|e| anyhow::anyhow!(e))?,
206            std::task::Poll::Pending => {}
207        }
208
209        Ok(())
210    }
211
212    /// Get the control protocol client.
213    pub fn control_client(&self) -> ControlClient {
214        ControlClient(DynRpcTransport::new(DummyControlProtocolTransport(
215            ControlService(ControlProtocolImpl {
216                ctx: self.ctx.clone(),
217            }),
218        )))
219    }
220
221    /// Gets the user info.
222    pub async fn user_info(&self) -> anyhow::Result<UserInfo> {
223        let auth_token = get_auth_token(&self.ctx).await?;
224        let user_info = broker_client(&self.ctx)?
225            .get_user_info(auth_token)
226            .await??
227            .context("no such user")?;
228        Ok(user_info)
229    }
230
231    /// Force a particular packet to be sent through VPN mode, regardless of whether VPN mode is on.
232    pub async fn send_vpn_packet(&self, bts: Bytes) -> anyhow::Result<()> {
233        send_vpn_packet(&self.ctx, bts).await;
234        Ok(())
235    }
236
237    /// Receive a packet from VPN mode, regardless of whether VPN mode is on.
238    pub async fn recv_vpn_packet(&self) -> anyhow::Result<Bytes> {
239        let packet = recv_vpn_packet(&self.ctx).await;
240        Ok(packet)
241    }
242}
243
244pub type CtxField<T> = fn(&AnyCtx<Config>) -> T;
245
246async fn client_main(ctx: AnyCtx<Config>) -> anyhow::Result<()> {
247    let rpc_serve = async {
248        if let Some(control_listen) = ctx.init().control_listen {
249            nanorpc_sillad::rpc_serve(
250                sillad::tcp::TcpListener::bind(control_listen).await?,
251                ControlService(ControlProtocolImpl { ctx: ctx.clone() }),
252            )
253            .await?;
254            anyhow::Ok(())
255        } else {
256            smol::future::pending().await
257        }
258    };
259    if ctx.init().dry_run {
260        rpc_serve.await
261    } else {
262        let vpn_loop = vpn_loop(&ctx);
263
264        let _client_loop = Immortal::spawn(run_client_sessions(ctx.clone()));
265
266        socks5_loop(&ctx)
267            .inspect_err(|e| tracing::error!(err = debug(e), "socks5 loop stopped"))
268            .race(vpn_loop.inspect_err(|e| tracing::error!(err = debug(e), "vpn loop stopped")))
269            .race(
270                http_proxy_serve(&ctx)
271                    .inspect_err(|e| tracing::error!(err = debug(e), "http proxy stopped")),
272            )
273            .race(
274                auth_loop(&ctx)
275                    .inspect_err(|e| tracing::error!(err = debug(e), "auth loop stopped")),
276            )
277            .race(
278                bw_token_refresh_loop(&ctx)
279                    .inspect_err(|e| tracing::error!(err = debug(e), "bw token loop stopped")),
280            )
281            .race(rpc_serve)
282            .race(pac_serve(&ctx))
283            .await
284    }
285}