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        CURRENT_CONN_INFO,
24    },
25    database::db_read_or_wait,
26    http_proxy::http_proxy_serve,
27    pac::pac_serve,
28    route::ExitConstraint,
29    socks5::socks5_loop,
30    vpn::{recv_vpn_packet, send_vpn_packet, vpn_loop},
31    ConnInfo,
32};
33
34#[derive(Serialize, Deserialize, Clone)]
35pub struct Config {
36    pub socks5_listen: Option<SocketAddr>,
37    pub http_proxy_listen: Option<SocketAddr>,
38    pub pac_listen: Option<SocketAddr>,
39
40    pub control_listen: Option<SocketAddr>,
41    pub exit_constraint: ExitConstraint,
42    #[serde(default)]
43    pub bridge_mode: BridgeMode,
44    pub cache: Option<PathBuf>,
45
46    pub broker: Option<BrokerSource>,
47    pub broker_keys: Option<BrokerKeys>,
48
49    #[serde(default)]
50    pub vpn: bool,
51    #[serde(default)]
52    pub vpn_fd: Option<i32>,
53    #[serde(default)]
54    pub spoof_dns: bool,
55    #[serde(default)]
56    pub passthrough_china: bool,
57    #[serde(default)]
58    pub dry_run: bool,
59    #[serde(default)]
60    pub credentials: Credential,
61
62    #[serde(default)]
63    pub sess_metadata: serde_json::Value,
64    pub task_limit: Option<u32>,
65}
66
67#[derive(Serialize, Deserialize, Clone)]
68/// Broker keys, in hexadecimal format.
69pub struct BrokerKeys {
70    pub master: String,
71    pub mizaru_free: String,
72    pub mizaru_plus: String,
73}
74
75impl Config {
76    /// Create an "inert" version of this config that does not start any processes.
77    pub fn inert(&self) -> Self {
78        let mut this = self.clone();
79        this.dry_run = true;
80        this.socks5_listen = None;
81        this.http_proxy_listen = None;
82        this.pac_listen = None;
83        this.control_listen = None;
84        this
85    }
86}
87
88#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug)]
89pub enum BridgeMode {
90    Auto,
91    ForceBridges,
92    ForceDirect,
93}
94
95impl Default for BridgeMode {
96    fn default() -> Self {
97        Self::Auto
98    }
99}
100
101pub struct Client {
102    task: Shared<smol::Task<Result<(), Arc<anyhow::Error>>>>,
103    ctx: AnyCtx<Config>,
104}
105
106impl Client {
107    /// Starts the client logic in the loop, returning the handle.
108    pub fn start(cfg: Config) -> Self {
109        std::env::remove_var("http_proxy");
110        std::env::remove_var("https_proxy");
111        std::env::remove_var("HTTP_PROXY");
112        std::env::remove_var("HTTPS_PROXY");
113        let ctx = AnyCtx::new(cfg.clone());
114
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    #[derive(Serialize)]
247    struct DryRunOutput {
248        auth_token: String,
249        exits: ExitList,
250    }
251
252    if ctx.init().dry_run {
253        smol::future::pending().await
254    } else {
255        let rpc_serve = async {
256            if let Some(control_listen) = ctx.init().control_listen {
257                nanorpc_sillad::rpc_serve(
258                    sillad::tcp::TcpListener::bind(control_listen).await?,
259                    ControlService(ControlProtocolImpl { ctx: ctx.clone() }),
260                )
261                .await?;
262                anyhow::Ok(())
263            } else {
264                smol::future::pending().await
265            }
266        };
267
268        let vpn_loop = vpn_loop(&ctx);
269
270        let _client_loop = Immortal::spawn(client_inner(ctx.clone()));
271
272        socks5_loop(&ctx)
273            .inspect_err(|e| tracing::error!(err = debug(e), "socks5 loop stopped"))
274            .race(vpn_loop.inspect_err(|e| tracing::error!(err = debug(e), "vpn loop stopped")))
275            .race(
276                http_proxy_serve(&ctx)
277                    .inspect_err(|e| tracing::error!(err = debug(e), "http proxy stopped")),
278            )
279            .race(
280                auth_loop(&ctx)
281                    .inspect_err(|e| tracing::error!(err = debug(e), "auth loop stopped")),
282            )
283            .race(rpc_serve)
284            .race(pac_serve(&ctx))
285            .await
286    }
287}