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