Skip to content

Commit

Permalink
tproxy: Auto setup wg interface if not already
Browse files Browse the repository at this point in the history
  • Loading branch information
kvinwang committed Dec 12, 2024
1 parent c689909 commit e6c71f7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
43 changes: 41 additions & 2 deletions tproxy/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use anyhow::{anyhow, bail, Result};
use ipnet::Ipv4Net;
use rocket::figment::{
providers::{Format, Toml},
Figment,
};
use serde::{Deserialize, Serialize};
use std::net::Ipv4Addr;
use std::time::Duration;
use std::{net::Ipv4Addr, process::Stdio};
use std::{process::Command, time::Duration};
use tracing::info;

#[derive(Debug, Clone, Deserialize)]
pub struct WgConfig {
Expand Down Expand Up @@ -138,3 +140,40 @@ pub fn load_config_figment(config_file: Option<&str>) -> Figment {
.merge(Toml::file(SYSTEM_CONFIG_FILENAME))
.merge(leaf_config)
}

fn cmd(cmd: &str, args: &[&str]) -> Result<Vec<u8>> {
let output = Command::new(cmd)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.map_err(|e| anyhow!("Failed to run command {cmd}: {e}"))?;
if !output.status.success() {
let error = String::from_utf8_lossy(&output.stderr);
bail!("Failed to run command {cmd}: {error}");
}
Ok(output.stdout)
}

pub fn setup_wireguard(config: &WgConfig) -> Result<()> {
info!("Setting up wireguard interface");

let ifname = &config.interface;

// Check if interface exists by trying to run ip link show
let exists = cmd("ip", &["link", "show", &config.interface]).is_ok();
if exists {
info!("WireGuard interface {ifname} already exists");
return Ok(());
}

let addr = format!("{}/{}", config.ip, config.client_ip_range.prefix_len());
// Interface doesn't exist, create and configure it
cmd("ip", &["link", "add", ifname, "type", "wireguard"])?;
cmd("ip", &["address", "add", &addr, "dev", ifname])?;
cmd("ip", &["link", "set", ifname, "up"])?;

info!("Created and configured WireGuard interface {ifname}");

Ok(())
}
2 changes: 2 additions & 0 deletions tproxy/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ async fn main() -> Result<()> {
let figment = config::load_config_figment(args.config.as_deref());

let config = figment.focus("core").extract::<Config>()?;
config::setup_wireguard(&config.wg)?;

let proxy_config = config.proxy.clone();
let pccs_url = config.pccs_url.clone();
let state = main_service::AppState::new(config)?;
Expand Down

0 comments on commit e6c71f7

Please sign in to comment.