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