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