aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 17b920de2a4d4fbceea446debcae17c8de090151 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
use std::{env, process::exit};


use anyhow::{Result, anyhow, Context};
use clap::{arg, command, Command};
use serde::Deserialize;
use std::fs::read_to_string;

mod wg;
mod list;
mod rm;
mod add;
mod wgcmd;
mod config;

fn main() {
    let matches = command!()
        .arg(
            arg!(
                -c --config <CONFIG> "wgmgr configuration file path"
            )
            .required(false)
        )
        .subcommand_required(true)

        // "ls"
        .subcommand(
            Command::new("ls")
            .about("List known clients")
        )

        // "config"
        .subcommand(
            Command::new("config")
            .about("Generate the configuration file for a client")
            .arg(
                arg!(
                    -t --type <TYPE> "Type of configuration: \"split\" or \"full\""
                )
                .required(false)
            )
            .arg(arg!(<PEER> "Name of the peer"))
        )

        // "add"
        .subcommand(
            Command::new("add")
            .about("Add a new client to your VPN")
            .arg(
                arg!(
                    <NAME> "Name of the new client"
                )
                .required(true)
            )
            .arg(
                arg!(
                    -i --ip <IP> "IP address (auto-assigned)"
                )
                .required(false)
            )
        )

        // "rm"
        .subcommand(
            Command::new("rm")
            .about("Remove a client from your VPN")
            .arg(
                arg!(
                    <NAME> "Name of the client to remove"
                )
                .required(true)
            )
        )

        // "wg"
        .subcommand(
            Command::new("wg")
            .about("Run 'wg', but with the client names")
        )
        .get_matches();
    
    
    // Find the configuration file for wgmgr
    let wgmgr_conf = match find_configuration_file(matches.get_one::<String>("config")) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Could not find wgmgr configuration file. Place it at /etc/wgmgr.toml or use the --config flag.");
            eprintln!("{:?}", e);
            exit(1);
        }
    };
    

    // Load the Wireguard configuration file
    let mut wg_conf = match wg::config::WireguardConfig::new(&wgmgr_conf.wgconf)  {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Error loading the Wireguard configuration file '{}'.", wgmgr_conf.wgconf);
            eprintln!("{:?}", e);
            exit(1);
        }
    };

    match matches.subcommand() {
        Some(("ls", _)) => {
            list::run(&wg_conf);
        }

        Some(("config", args)) => {
            match args.get_one::<String>("PEER") {
                Some(peer_name) => {
                    let is_full = match args.get_one::<String>("type") {
                        Some(t) => {
                            match t.to_string().as_str() {
                                "split" => false,
                                "full" => true,
                                _ => {
                                    eprintln!("Error: '--type' must be either 'split' or 'full'");
                                    exit(3);
                                }
                            }
                        },
                        None => false
                    };

                    if let Err(e) = config::run(&wg_conf, &wgmgr_conf, peer_name.to_string(), is_full) {
                        eprintln!("Error generating configuration for {}: {:?}", peer_name.to_string(), e);
                        exit(1);
                    }
                },
                None => {}
            }
        },

        Some(("add", args)) => {
            let new_name = args.get_one::<String>("NAME").unwrap().to_string();
            if let Err(e) = add::run(&mut wg_conf, wgmgr_conf.wgconf, &new_name, args.get_one::<String>("ip")) {
                eprintln!("Error adding peer: {:?}", e);
                exit(1);
            }
            else {
                println!("Peer '{}' added successfully. Don't forget to restart your WireGuard server.", new_name);
            }
        },

        Some(("rm", args)) => {
            let rm_name = args.get_one::<String>("NAME").unwrap().to_string();
            if let Err(e) = rm::run(&mut wg_conf, wgmgr_conf.wgconf, &rm_name) {
                eprintln!("Error removing peer: {:?}", e);
                exit(1);
            }

            println!("Client '{}' removed successfully. Don't forget to restart your WireGuard server.", rm_name);
        },

        Some(("wg", _)) => {
            if let Err(e) = wgcmd::run(&wg_conf) {
                eprintln!("{:?}", e);
                exit(1);
            }
        }

        _ => {
            unimplemented!();
        }
    }

}

#[derive(Deserialize)]
pub struct Configuration {
    pub endpoint: String,
    pub wgconf: String,
    pub port: Option<u32>,
    pub dns: Option<String>,
}

pub fn find_configuration_file(argument: Option<&String>) -> Result<Configuration> {
    match argument {
        Some(p) => {
            if let Ok(t) = read_to_string(p) {
                let c: Configuration = toml::from_str(&t).context("parsing configuration file")?;
                return Ok(c)
            }
        },
        None => {
            // Try /etc/wgmgr.toml
            if let Ok(t) = read_to_string("/etc/wgmgr.toml") {
                let c: Configuration = toml::from_str(&t).context("parsing /etc/wgmgr.toml")?;
                return Ok(c)
            }
        },
    };

    Err(anyhow!("Could not find a valid configuration file for wgmgr."))
}