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, ExitList, 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    http_proxy::http_proxy_serve,
25    pac::pac_serve,
26    route::ExitConstraint,
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    ForceDirect,
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    #[derive(Serialize)]
246    struct DryRunOutput {
247        auth_token: String,
248        exits: ExitList,
249    }
250
251    if ctx.init().dry_run {
252        smol::future::pending().await
253    } else {
254        let rpc_serve = async {
255            if let Some(control_listen) = ctx.init().control_listen {
256                nanorpc_sillad::rpc_serve(
257                    sillad::tcp::TcpListener::bind(control_listen).await?,
258                    ControlService(ControlProtocolImpl { ctx: ctx.clone() }),
259                )
260                .await?;
261                anyhow::Ok(())
262            } else {
263                smol::future::pending().await
264            }
265        };
266
267        let vpn_loop = vpn_loop(&ctx);
268
269        let _client_loop = Immortal::spawn(client_inner(ctx.clone()));
270
271        socks5_loop(&ctx)
272            .inspect_err(|e| tracing::error!(err = debug(e), "socks5 loop stopped"))
273            .race(vpn_loop.inspect_err(|e| tracing::error!(err = debug(e), "vpn loop stopped")))
274            .race(
275                http_proxy_serve(&ctx)
276                    .inspect_err(|e| tracing::error!(err = debug(e), "http proxy stopped")),
277            )
278            .race(
279                auth_loop(&ctx)
280                    .inspect_err(|e| tracing::error!(err = debug(e), "auth loop stopped")),
281            )
282            .race(rpc_serve)
283            .race(pac_serve(&ctx))
284            .await
285    }
286}