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
198
199
200
201
202
203
204
205
206
207
use std::{
	fs::File,
	io::{BufRead, BufReader, BufWriter, Write},
	net::Ipv4Addr,
	path::Path,
	process::{Child, Command, Stdio},
};

use anyhow::{Context, Result};
use askama::Template;
use tempfile::{NamedTempFile, TempPath};
use util::{ConnectionProtocol, UserConfig};

use crate::utils::LogicalServer;

/// This module contains a wrapper type, [settings::Settings]. It has methods for creating setters, as well as an impl containing special setters for when it is UserConfig being wrapped.
///
/// This module is misplaced, it should be at the top level or under `crate::cli`
pub mod settings;

/// This module declares all the structs that store application state.
pub mod util;

#[derive(Template)] // this will generate the code...
#[template(path = "openvpn_template.j2")]
struct OpenVpnConfig {
	openvpn_protocol: ConnectionProtocol,
	serverlist: Vec<Ipv4Addr>,
	openvpn_ports: Vec<usize>,
	split: bool,
	ip_nm_pairs: Vec<IpNm>,
	ipv6_disabled: bool,
}

/// An IPv4 address and a netmask.
struct IpNm {
	ip: Ipv4Addr,
	nm: Ipv4Addr,
}

/// Stores information about the current connection. Its purpose to prevent the passfile path from being dropped (upon drop the corresponding file is unlinked/deleted)
pub struct VpnConnection {
	pub(crate) openvpn_process: Child,
	pub(crate) passfile: TempPath,
}

fn create_openvpn_config<R, W>(
	servers: &Vec<Ipv4Addr>,
	protocol: &ConnectionProtocol,
	ports: &Vec<usize>,
	split_tunnel: &bool,
	split_tunnel_file: Option<R>,
	output_file: &mut W,
) -> Result<()>
where
	R: BufRead,
	W: Write,
{
	let mut ip_nm_pairs = vec![];

	if *split_tunnel {
		if let Some(split_tunnel_file) = split_tunnel_file {
			for line in split_tunnel_file.lines() {
				let line = line.context("line unwrap")?;
				// TODO String.split_once() once stabilized
				let tokens = line.splitn(2, "/").collect::<Vec<_>>();
				let ip_nm = match tokens.as_slice() {
					[ip, nm] => IpNm {
						ip: ip.parse()?,
						nm: nm.parse()?,
					},
					[ip] => IpNm {
						ip: ip.parse()?,
						nm: "255.255.255.255".parse()?,
					},
					_ => {
						continue;
					}
				};
				ip_nm_pairs.push(ip_nm);
			}
		}
	}

	let ovpn_conf = OpenVpnConfig {
		openvpn_protocol: *protocol,
		serverlist: servers.clone(),
		openvpn_ports: ports.clone(),
		split: *split_tunnel,
		ip_nm_pairs,
		// TODO check if ipv6 is actually disabled
		ipv6_disabled: false,
	};

	let rendered = ovpn_conf.render().context("render template")?;
	let mut out = BufWriter::new(output_file);
	write!(out, "{}", rendered).context("Failed write")?;
	Ok(())
}

fn connect_helper(
	server: &LogicalServer,
	protocol: &ConnectionProtocol,
	passfile: TempPath,
	config: &Path,
	log: &Path,
) -> Result<VpnConnection> {
	create_openvpn_config::<BufReader<File>, File>(
		&server.servers.iter().map(|s| s.entry_ip).collect(),
		protocol,
		&vec![match protocol {
			ConnectionProtocol::TCP => 443,
			ConnectionProtocol::UDP => 1194,
		} as usize],
		&false,
		None,
		&mut File::create(config)?,
	)?;

	let stdout = File::create(log)?;
	let stderr = stdout.try_clone()?;

	let cmd = Command::new("openvpn")
		.arg("--config")
		.arg(config)
		.arg("--auth-user-pass")
		.arg(&passfile)
		.arg("--dev")
		.arg("proton0")
		.arg("--dev-type")
		.arg("tun")
		.stdin(Stdio::null())
		.stdout(stdout)
		.stderr(stderr)
		.spawn()
		.context("couldn't spawn openvpn")?;

	let connection = VpnConnection {
		openvpn_process: cmd,
		passfile,
	};

	Ok(connection)
}

/// This function wraps the helper, first creating the password tempfile and passing it in.
pub fn connect(
	server: &LogicalServer,
	protocol: &ConnectionProtocol,
	user_config: &UserConfig,
	config_path: &Path,
	log_path: &Path,
) -> Result<VpnConnection> {
	let pass_path = create_passfile(user_config)?;
	connect_helper(server, protocol, pass_path, &config_path, &log_path)
}

fn create_passfile(config: &UserConfig) -> Result<TempPath> {
	let f = NamedTempFile::new()?;
	let mut buf = BufWriter::new(f);
	let client_suffix = "plc";

	write!(
		buf,
		"{}+{}\n{}\n",
		config.username, client_suffix, config.password
	)?;

	Ok(buf.into_inner()?.into_temp_path())
}

#[cfg(test)]
mod tests {
	use std::fs::read;

	use super::*;

	#[test]
	fn test_create_ovpn_conf() -> Result<()> {
		let mut output = vec![];

		let res = create_openvpn_config::<BufReader<File>, Vec<u8>>(
			&vec![Ipv4Addr::new(108, 59, 0, 40)],
			&ConnectionProtocol::UDP,
			&vec![1134],
			&false,
			None,
			&mut output,
		)?;
		Ok(res)
	}

	#[test]
	fn test_passfile() -> Result<()> {
		let user = "user";
		let pass = "pass";
		let path = create_passfile(&UserConfig::new(user.into(), pass.into()))?;

		let buf = read(&path)?;
		let s = String::from_utf8(buf)?;
		assert_eq!(s, format!("{}+plc\n{}\n", user, pass));

		let output = Command::new("/usr/bin/cat").arg(&path).output()?;
		assert!(output.status.success());
		Ok(())
	}
}