meta: rename wgctrl to wireguard-control

in preparation for publishing on crates.io
pull/153/head
Jake McGinty 2021-09-15 12:29:58 +09:00
parent 454e5458c1
commit 4fa689d400
34 changed files with 153 additions and 122 deletions

54
Cargo.lock generated
View File

@ -180,7 +180,7 @@ dependencies = [
"structopt", "structopt",
"tempfile", "tempfile",
"ureq", "ureq",
"wgctrl", "wireguard-control",
] ]
[[package]] [[package]]
@ -964,9 +964,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_json" name = "serde_json"
version = "1.0.67" version = "1.0.68"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7f9e390c27c3c0ce8bc5d725f6e4d30a29d26659494aa4b17535f7522c5c950" checksum = "0f690853975602e1bfe1ccbf50504d67174e3bcf340f23b5ea9992e0587a52d8"
dependencies = [ dependencies = [
"itoa", "itoa",
"ryu", "ryu",
@ -1003,7 +1003,7 @@ dependencies = [
"tokio", "tokio",
"toml", "toml",
"url", "url",
"wgctrl", "wireguard-control",
] ]
[[package]] [[package]]
@ -1029,8 +1029,8 @@ dependencies = [
"structopt", "structopt",
"toml", "toml",
"url", "url",
"wgctrl", "wireguard-control",
"wgctrl-sys", "wireguard-control-sys",
] ]
[[package]] [[package]]
@ -1358,27 +1358,6 @@ version = "0.10.2+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
[[package]]
name = "wgctrl"
version = "1.5.0-beta.4"
dependencies = [
"base64",
"curve25519-dalek",
"hex",
"libc",
"rand_core",
"wgctrl-sys",
]
[[package]]
name = "wgctrl-sys"
version = "1.5.0-beta.4"
dependencies = [
"bindgen",
"cc",
"libc",
]
[[package]] [[package]]
name = "winapi" name = "winapi"
version = "0.3.9" version = "0.3.9"
@ -1410,6 +1389,27 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "wireguard-control"
version = "1.5.0-beta.4"
dependencies = [
"base64",
"curve25519-dalek",
"hex",
"libc",
"rand_core",
"wireguard-control-sys",
]
[[package]]
name = "wireguard-control-sys"
version = "1.5.0-beta.4"
dependencies = [
"bindgen",
"cc",
"libc",
]
[[package]] [[package]]
name = "wyz" name = "wyz"
version = "0.2.0" version = "0.2.0"

View File

@ -28,7 +28,7 @@ serde_json = "1.0"
shared = { path = "../shared", default-features = false } shared = { path = "../shared", default-features = false }
structopt = "0.3" structopt = "0.3"
ureq = { version = "2", default-features = false, features = ["json"] } ureq = { version = "2", default-features = false, features = ["json"] }
wgctrl = { path = "../wgctrl-rs" } wireguard-control = { path = "../wireguard-control" }
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"

View File

@ -9,7 +9,7 @@ use std::{
io::{self, Read, Seek, SeekFrom, Write}, io::{self, Read, Seek, SeekFrom, Write},
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use wgctrl::InterfaceName; use wireguard_control::InterfaceName;
#[derive(Debug)] #[derive(Debug)]
pub struct DataStore { pub struct DataStore {

View File

@ -21,7 +21,7 @@ use std::{
time::Duration, time::Duration,
}; };
use structopt::{clap::AppSettings, StructOpt}; use structopt::{clap::AppSettings, StructOpt};
use wgctrl::{Device, DeviceUpdate, InterfaceName, PeerConfigBuilder, PeerInfo}; use wireguard_control::{Device, DeviceUpdate, InterfaceName, PeerConfigBuilder, PeerInfo};
mod data_store; mod data_store;
mod nat; mod nat;
@ -428,7 +428,7 @@ fn redeem_invite(
.with_str(iface.to_string())?; .with_str(iface.to_string())?;
log::info!("Generating new keypair."); log::info!("Generating new keypair.");
let keypair = wgctrl::KeyPair::generate(); let keypair = wireguard_control::KeyPair::generate();
log::info!( log::info!(
"Registering keypair with server (at {}).", "Registering keypair with server (at {}).",

View File

@ -10,7 +10,7 @@ use shared::{
wg::{DeviceExt, PeerInfoExt}, wg::{DeviceExt, PeerInfoExt},
Endpoint, Peer, PeerDiff, Endpoint, Peer, PeerDiff,
}; };
use wgctrl::{Backend, Device, DeviceUpdate, InterfaceName, Key, PeerConfigBuilder}; use wireguard_control::{Backend, Device, DeviceUpdate, InterfaceName, Key, PeerConfigBuilder};
const STEP_INTERVAL: Duration = Duration::from_secs(5); const STEP_INTERVAL: Duration = Duration::from_secs(5);

View File

@ -40,7 +40,7 @@ thiserror = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] } tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
toml = "0.5" toml = "0.5"
url = "2" url = "2"
wgctrl = { path = "../wgctrl-rs" } wireguard-control = { path = "../wireguard-control" }
[target.'cfg(target_os = "linux")'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
socket2 = { version = "0.4", features = ["all"] } socket2 = { version = "0.4", features = ["all"] }

View File

@ -8,7 +8,7 @@ use crate::{
}; };
use hyper::{Body, Method, Request, Response, StatusCode}; use hyper::{Body, Method, Request, Response, StatusCode};
use shared::PeerContents; use shared::PeerContents;
use wgctrl::DeviceUpdate; use wireguard_control::DeviceUpdate;
pub async fn routes( pub async fn routes(
req: Request<Body>, req: Request<Body>,

View File

@ -8,7 +8,7 @@ use crate::{
}; };
use hyper::{Body, Method, Request, Response, StatusCode}; use hyper::{Body, Method, Request, Response, StatusCode};
use shared::{EndpointContents, PeerContents, RedeemContents, State, REDEEM_TRANSITION_WAIT}; use shared::{EndpointContents, PeerContents, RedeemContents, State, REDEEM_TRANSITION_WAIT};
use wgctrl::DeviceUpdate; use wireguard_control::DeviceUpdate;
pub async fn routes( pub async fn routes(
req: Request<Body>, req: Request<Body>,
@ -86,7 +86,7 @@ mod handlers {
let conn = session.context.db.lock(); let conn = session.context.db.lock();
let mut selected_peer = DatabasePeer::get(&conn, session.peer.id)?; let mut selected_peer = DatabasePeer::get(&conn, session.peer.id)?;
let old_public_key = wgctrl::Key::from_base64(&selected_peer.public_key) let old_public_key = wireguard_control::Key::from_base64(&selected_peer.public_key)
.map_err(|_| ServerError::WireGuard)?; .map_err(|_| ServerError::WireGuard)?;
selected_peer.redeem(&conn, &form.public_key)?; selected_peer.redeem(&conn, &form.public_key)?;

View File

@ -6,7 +6,7 @@ use indoc::printdoc;
use publicip::Preference; use publicip::Preference;
use rusqlite::{params, Connection}; use rusqlite::{params, Connection};
use shared::{prompts, CidrContents, Endpoint, PeerContents, PERSISTENT_KEEPALIVE_INTERVAL_SECS}; use shared::{prompts, CidrContents, Endpoint, PeerContents, PERSISTENT_KEEPALIVE_INTERVAL_SECS};
use wgctrl::KeyPair; use wireguard_control::KeyPair;
fn create_database<P: AsRef<Path>>( fn create_database<P: AsRef<Path>>(
database_path: P, database_path: P,

View File

@ -25,7 +25,7 @@ use std::{
}; };
use structopt::{clap::AppSettings, StructOpt}; use structopt::{clap::AppSettings, StructOpt};
use subtle::ConstantTimeEq; use subtle::ConstantTimeEq;
use wgctrl::{Backend, Device, DeviceUpdate, InterfaceName, Key, PeerConfigBuilder}; use wireguard_control::{Backend, Device, DeviceUpdate, InterfaceName, Key, PeerConfigBuilder};
pub mod api; pub mod api;
pub mod db; pub mod db;
@ -523,7 +523,7 @@ async fn serve(
num_candidates num_candidates
); );
let public_key = wgctrl::Key::from_base64(&config.private_key)?.generate_public(); let public_key = wireguard_control::Key::from_base64(&config.private_key)?.generate_public();
let db = Arc::new(Mutex::new(conn)); let db = Arc::new(Mutex::new(conn));
let endpoints = spawn_endpoint_refresher(interface, network); let endpoints = spawn_endpoint_refresher(interface, network);
spawn_expired_invite_sweeper(db.clone()); spawn_expired_invite_sweeper(db.clone());

View File

@ -12,7 +12,7 @@ use serde::Serialize;
use shared::{Cidr, CidrContents, Error, PeerContents}; use shared::{Cidr, CidrContents, Error, PeerContents};
use std::{collections::HashMap, net::SocketAddr, path::PathBuf, sync::Arc}; use std::{collections::HashMap, net::SocketAddr, path::PathBuf, sync::Arc};
use tempfile::TempDir; use tempfile::TempDir;
use wgctrl::{Backend, InterfaceName, Key, KeyPair}; use wireguard_control::{Backend, InterfaceName, Key, KeyPair};
#[cfg(not(feature = "v6-test"))] #[cfg(not(feature = "v6-test"))]
mod v4 { mod v4 {

View File

@ -22,13 +22,13 @@ serde = { version = "1", features = ["derive"] }
structopt = "0.3" structopt = "0.3"
toml = "0.5" toml = "0.5"
url = "2" url = "2"
wgctrl = { path = "../wgctrl-rs" } wireguard-control = { path = "../wireguard-control" }
[target.'cfg(target_os = "linux")'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
netlink-sys = "0.7" netlink-sys = "0.7"
netlink-packet-core = "0.2" netlink-packet-core = "0.2"
netlink-packet-route = "0.7" netlink-packet-route = "0.7"
wgctrl-sys = { path = "../wgctrl-sys" } wireguard-control-sys = { path = "../wireguard-control-sys" }
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
nix = "0.22" nix = "0.22"

View File

@ -10,7 +10,7 @@ use std::{
net::SocketAddr, net::SocketAddr,
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use wgctrl::InterfaceName; use wireguard_control::InterfaceName;
#[derive(Clone, Deserialize, Serialize, Debug)] #[derive(Clone, Deserialize, Serialize, Debug)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
@ -133,7 +133,7 @@ impl InterfaceConfig {
impl InterfaceInfo { impl InterfaceInfo {
pub fn public_key(&self) -> Result<String, Error> { pub fn public_key(&self) -> Result<String, Error> {
Ok(wgctrl::Key::from_base64(&self.private_key)? Ok(wireguard_control::Key::from_base64(&self.private_key)?
.generate_public() .generate_public()
.to_base64()) .to_base64())
} }

View File

@ -11,7 +11,7 @@ use netlink_packet_route::{
}; };
use netlink_sys::{protocols::NETLINK_ROUTE, Socket, SocketAddr}; use netlink_sys::{protocols::NETLINK_ROUTE, Socket, SocketAddr};
use std::{io, net::IpAddr}; use std::{io, net::IpAddr};
use wgctrl::InterfaceName; use wireguard_control::InterfaceName;
fn if_nametoindex(interface: &InterfaceName) -> Result<u32, io::Error> { fn if_nametoindex(interface: &InterfaceName) -> Result<u32, io::Error> {
match unsafe { libc::if_nametoindex(interface.as_ptr()) } { match unsafe { libc::if_nametoindex(interface.as_ptr()) } {

View File

@ -17,7 +17,7 @@ use std::{
str::FromStr, str::FromStr,
time::SystemTime, time::SystemTime,
}; };
use wgctrl::{InterfaceName, KeyPair}; use wireguard_control::{InterfaceName, KeyPair};
lazy_static! { lazy_static! {
pub static ref THEME: ColorfulTheme = ColorfulTheme::default(); pub static ref THEME: ColorfulTheme = ColorfulTheme::default();

View File

@ -15,7 +15,7 @@ use std::{
}; };
use structopt::StructOpt; use structopt::StructOpt;
use url::Host; use url::Host;
use wgctrl::{ use wireguard_control::{
AllowedIp, Backend, InterfaceName, InvalidInterfaceName, Key, PeerConfig, PeerConfigBuilder, AllowedIp, Backend, InterfaceName, InvalidInterfaceName, Key, PeerConfig, PeerConfigBuilder,
PeerInfo, PeerInfo,
}; };
@ -753,7 +753,7 @@ impl std::error::Error for WrappedIoError {}
mod tests { mod tests {
use super::*; use super::*;
use std::net::IpAddr; use std::net::IpAddr;
use wgctrl::{Key, PeerConfigBuilder, PeerStats}; use wireguard_control::{Key, PeerConfigBuilder, PeerStats};
#[test] #[test]
fn test_peer_no_diff() { fn test_peer_no_diff() {

View File

@ -5,7 +5,9 @@ use std::{
net::{IpAddr, SocketAddr}, net::{IpAddr, SocketAddr},
time::Duration, time::Duration,
}; };
use wgctrl::{Backend, Device, DeviceUpdate, InterfaceName, Key, PeerConfigBuilder, PeerInfo}; use wireguard_control::{
Backend, Device, DeviceUpdate, InterfaceName, Key, PeerConfigBuilder, PeerInfo,
};
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
fn cmd(bin: &str, args: &[&str]) -> Result<std::process::Output, io::Error> { fn cmd(bin: &str, args: &[&str]) -> Result<std::process::Output, io::Error> {
@ -31,7 +33,7 @@ fn cmd(bin: &str, args: &[&str]) -> Result<std::process::Output, io::Error> {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub fn set_addr(interface: &InterfaceName, addr: IpNetwork) -> Result<(), io::Error> { pub fn set_addr(interface: &InterfaceName, addr: IpNetwork) -> Result<(), io::Error> {
let real_interface = wgctrl::backends::userspace::resolve_tun(interface)?; let real_interface = wireguard_control::backends::userspace::resolve_tun(interface)?;
if addr.is_ipv4() { if addr.is_ipv4() {
cmd( cmd(
@ -56,7 +58,7 @@ pub fn set_addr(interface: &InterfaceName, addr: IpNetwork) -> Result<(), io::Er
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub fn set_up(interface: &InterfaceName, mtu: u32) -> Result<(), io::Error> { pub fn set_up(interface: &InterfaceName, mtu: u32) -> Result<(), io::Error> {
let real_interface = wgctrl::backends::userspace::resolve_tun(interface)?; let real_interface = wireguard_control::backends::userspace::resolve_tun(interface)?;
cmd("ifconfig", &[&real_interface, "mtu", &mtu.to_string()])?; cmd("ifconfig", &[&real_interface, "mtu", &mtu.to_string()])?;
Ok(()) Ok(())
} }
@ -78,23 +80,24 @@ pub fn up(
let mut device = DeviceUpdate::new(); let mut device = DeviceUpdate::new();
if let Some((public_key, address, endpoint)) = peer { if let Some((public_key, address, endpoint)) = peer {
let prefix = if address.is_ipv4() { 32 } else { 128 }; let prefix = if address.is_ipv4() { 32 } else { 128 };
let peer_config = let peer_config = PeerConfigBuilder::new(
PeerConfigBuilder::new(&wgctrl::Key::from_base64(public_key).map_err(|_| { &wireguard_control::Key::from_base64(public_key).map_err(|_| {
io::Error::new( io::Error::new(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"failed to parse base64 public key", "failed to parse base64 public key",
) )
})?) })?,
.add_allowed_ip(address, prefix) )
.set_persistent_keepalive_interval(25) .add_allowed_ip(address, prefix)
.set_endpoint(endpoint); .set_persistent_keepalive_interval(25)
.set_endpoint(endpoint);
device = device.add_peer(peer_config); device = device.add_peer(peer_config);
} }
if let Some(listen_port) = listen_port { if let Some(listen_port) = listen_port {
device = device.set_listen_port(listen_port); device = device.set_listen_port(listen_port);
} }
device device
.set_private_key(wgctrl::Key::from_base64(private_key).unwrap()) .set_private_key(wireguard_control::Key::from_base64(private_key).unwrap())
.apply(interface, network.backend)?; .apply(interface, network.backend)?;
set_addr(interface, address)?; set_addr(interface, address)?;
set_up( set_up(
@ -137,7 +140,7 @@ pub fn down(interface: &InterfaceName, backend: Backend) -> Result<(), Error> {
/// true if the route was changed, false if the route already exists. /// true if the route was changed, false if the route already exists.
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub fn add_route(interface: &InterfaceName, cidr: IpNetwork) -> Result<bool, io::Error> { pub fn add_route(interface: &InterfaceName, cidr: IpNetwork) -> Result<bool, io::Error> {
let real_interface = wgctrl::backends::userspace::resolve_tun(interface)?; let real_interface = wireguard_control::backends::userspace::resolve_tun(interface)?;
let output = cmd( let output = cmd(
"route", "route",
&[ &[

View File

@ -3,10 +3,9 @@ authors = ["K900 <me@0upti.me>", "Jake McGinty <jake@tonari.no>"]
categories = ["external-ffi-bindings", "os::unix-apis"] categories = ["external-ffi-bindings", "os::unix-apis"]
description = "Raw bindings to the WireGuard embeddable C library" description = "Raw bindings to the WireGuard embeddable C library"
license = "LGPL-2.1-or-later" license = "LGPL-2.1-or-later"
name = "wgctrl-sys" name = "wireguard-control-sys"
publish = false readme = "README.md"
readme = "../README.md" repository = "https://github.com/tonarino/innernet"
repository = "https://gitlab.com/K900/wgctrl-rs"
version = "1.5.0-beta.4" version = "1.5.0-beta.4"
[dependencies] [dependencies]

View File

@ -0,0 +1,5 @@
# `wireguard-control-sys`
A low-level FFI around the [`embaddable-wg-library`](https://git.zx2c4.com/wireguard-tools/tree/contrib/embeddable-wg-library) WireGuard C library, which in turn communicates with the Linux kernel WireGuard via Netlink.
You *probably* want to use the [`wireguard-control`](https://crates.io/crates/wireguard-control) crate instead.

View File

@ -1,12 +1,12 @@
[package] [package]
authors = ["K900 <me@0upti.me>"] authors = ["K900 <me@0upti.me>", "Jake McGinty <jake@tonari.no>"]
categories = ["os::unix-apis"] categories = ["os::unix-apis"]
description = "High level bindings to the WireGuard embeddable C library" description = "High level bindings to the WireGuard embeddable C library"
edition = "2018" edition = "2018"
license = "LGPL-2.1-or-later" license = "LGPL-2.1-or-later"
name = "wgctrl" name = "wireguard-control"
publish = false readme = "README.md"
readme = "../README.md" repository = "https://github.com/tonarino/innernet"
version = "1.5.0-beta.4" version = "1.5.0-beta.4"
[dependencies] [dependencies]
@ -15,7 +15,7 @@ hex = "0.4"
libc = "0.2" libc = "0.2"
[target.'cfg(target_os = "linux")'.dependencies] [target.'cfg(target_os = "linux")'.dependencies]
wgctrl-sys = { path = "../wgctrl-sys" } wireguard-control-sys = { path = "../wireguard-control-sys", version = "1.5.0-beta.1" }
[target.'cfg(not(target_os = "linux"))'.dependencies] [target.'cfg(not(target_os = "linux"))'.dependencies]
rand_core = "0.6" rand_core = "0.6"

View File

@ -0,0 +1,12 @@
# `wireguard-control`
A high-level control library to get and set configurations for WireGuard interfaces.
It's a heavily-modified fork of [K900's `wgctrl-rs`](https://gitlab.com/K900/wgctrl-rs), and was made for [innernet](https://github.com/tonarino/innernet).
Currently supports:
* Linux kernel WireGuard implementation
* Userspace WireGuard implementations (tested against `wireguard-go` on macOS and Linux)
Versioning is held in lockstep with innernet, although this may change in the future.

View File

@ -2,7 +2,7 @@ use crate::{
device::AllowedIp, Backend, Device, DeviceUpdate, InterfaceName, InvalidInterfaceName, device::AllowedIp, Backend, Device, DeviceUpdate, InterfaceName, InvalidInterfaceName,
InvalidKey, PeerConfig, PeerConfigBuilder, PeerInfo, PeerStats, InvalidKey, PeerConfig, PeerConfigBuilder, PeerInfo, PeerStats,
}; };
use wgctrl_sys::{timespec64, wg_device_flags as wgdf, wg_peer_flags as wgpf}; use wireguard_control_sys::{timespec64, wg_device_flags as wgdf, wg_peer_flags as wgpf};
use std::{ use std::{
ffi::{CStr, CString}, ffi::{CStr, CString},
@ -13,8 +13,8 @@ use std::{
time::{Duration, SystemTime}, time::{Duration, SystemTime},
}; };
impl<'a> From<&'a wgctrl_sys::wg_allowedip> for AllowedIp { impl<'a> From<&'a wireguard_control_sys::wg_allowedip> for AllowedIp {
fn from(raw: &wgctrl_sys::wg_allowedip) -> AllowedIp { fn from(raw: &wireguard_control_sys::wg_allowedip) -> AllowedIp {
let addr = match i32::from(raw.family) { let addr = match i32::from(raw.family) {
libc::AF_INET => IpAddr::V4(unsafe { raw.__bindgen_anon_1.ip4.s_addr }.to_be().into()), libc::AF_INET => IpAddr::V4(unsafe { raw.__bindgen_anon_1.ip4.s_addr }.to_be().into()),
libc::AF_INET6 => { libc::AF_INET6 => {
@ -30,8 +30,8 @@ impl<'a> From<&'a wgctrl_sys::wg_allowedip> for AllowedIp {
} }
} }
impl<'a> From<&'a wgctrl_sys::wg_peer> for PeerInfo { impl<'a> From<&'a wireguard_control_sys::wg_peer> for PeerInfo {
fn from(raw: &wgctrl_sys::wg_peer) -> PeerInfo { fn from(raw: &wireguard_control_sys::wg_peer) -> PeerInfo {
PeerInfo { PeerInfo {
config: PeerConfig { config: PeerConfig {
public_key: Key::from_raw(raw.public_key), public_key: Key::from_raw(raw.public_key),
@ -63,8 +63,8 @@ impl<'a> From<&'a wgctrl_sys::wg_peer> for PeerInfo {
} }
} }
impl<'a> From<&'a wgctrl_sys::wg_device> for Device { impl<'a> From<&'a wireguard_control_sys::wg_device> for Device {
fn from(raw: &wgctrl_sys::wg_device) -> Device { fn from(raw: &wireguard_control_sys::wg_device) -> Device {
// SAFETY: The name string buffer came directly from wgctrl so its NUL terminated. // SAFETY: The name string buffer came directly from wgctrl so its NUL terminated.
let name = unsafe { InterfaceName::from_wg(raw.name) }; let name = unsafe { InterfaceName::from_wg(raw.name) };
Device { Device {
@ -95,7 +95,7 @@ impl<'a> From<&'a wgctrl_sys::wg_device> for Device {
} }
} }
fn parse_peers(dev: &wgctrl_sys::wg_device) -> Vec<PeerInfo> { fn parse_peers(dev: &wireguard_control_sys::wg_device) -> Vec<PeerInfo> {
let mut result = Vec::new(); let mut result = Vec::new();
let mut current_peer = dev.first_peer; let mut current_peer = dev.first_peer;
@ -118,10 +118,10 @@ fn parse_peers(dev: &wgctrl_sys::wg_device) -> Vec<PeerInfo> {
result result
} }
fn parse_allowed_ips(peer: &wgctrl_sys::wg_peer) -> Vec<AllowedIp> { fn parse_allowed_ips(peer: &wireguard_control_sys::wg_peer) -> Vec<AllowedIp> {
let mut result = Vec::new(); let mut result = Vec::new();
let mut current_ip: *mut wgctrl_sys::wg_allowedip = peer.first_allowedip; let mut current_ip: *mut wireguard_control_sys::wg_allowedip = peer.first_allowedip;
if current_ip.is_null() { if current_ip.is_null() {
return result; return result;
@ -141,7 +141,7 @@ fn parse_allowed_ips(peer: &wgctrl_sys::wg_peer) -> Vec<AllowedIp> {
result result
} }
fn parse_endpoint(endpoint: &wgctrl_sys::wg_peer__bindgen_ty_1) -> Option<SocketAddr> { fn parse_endpoint(endpoint: &wireguard_control_sys::wg_peer__bindgen_ty_1) -> Option<SocketAddr> {
let addr = unsafe { endpoint.addr }; let addr = unsafe { endpoint.addr };
match i32::from(addr.sa_family) { match i32::from(addr.sa_family) {
libc::AF_INET => { libc::AF_INET => {
@ -166,16 +166,19 @@ fn parse_endpoint(endpoint: &wgctrl_sys::wg_peer__bindgen_ty_1) -> Option<Socket
fn encode_allowedips( fn encode_allowedips(
allowed_ips: &[AllowedIp], allowed_ips: &[AllowedIp],
) -> (*mut wgctrl_sys::wg_allowedip, *mut wgctrl_sys::wg_allowedip) { ) -> (
*mut wireguard_control_sys::wg_allowedip,
*mut wireguard_control_sys::wg_allowedip,
) {
if allowed_ips.is_empty() { if allowed_ips.is_empty() {
return (ptr::null_mut(), ptr::null_mut()); return (ptr::null_mut(), ptr::null_mut());
} }
let mut first_ip = ptr::null_mut(); let mut first_ip = ptr::null_mut();
let mut last_ip: *mut wgctrl_sys::wg_allowedip = ptr::null_mut(); let mut last_ip: *mut wireguard_control_sys::wg_allowedip = ptr::null_mut();
for ip in allowed_ips { for ip in allowed_ips {
let mut wg_allowedip = Box::new(wgctrl_sys::wg_allowedip { let mut wg_allowedip = Box::new(wireguard_control_sys::wg_allowedip {
family: 0, family: 0,
__bindgen_anon_1: Default::default(), __bindgen_anon_1: Default::default(),
cidr: ip.cidr, cidr: ip.cidr,
@ -202,13 +205,13 @@ fn encode_allowedips(
(first_ip, last_ip) (first_ip, last_ip)
} }
fn encode_endpoint(endpoint: Option<SocketAddr>) -> wgctrl_sys::wg_peer__bindgen_ty_1 { fn encode_endpoint(endpoint: Option<SocketAddr>) -> wireguard_control_sys::wg_peer__bindgen_ty_1 {
match endpoint { match endpoint {
Some(SocketAddr::V4(s)) => { Some(SocketAddr::V4(s)) => {
let mut peer = wgctrl_sys::wg_peer__bindgen_ty_1::default(); let mut peer = wireguard_control_sys::wg_peer__bindgen_ty_1::default();
peer.addr4 = wgctrl_sys::sockaddr_in { peer.addr4 = wireguard_control_sys::sockaddr_in {
sin_family: libc::AF_INET as u16, sin_family: libc::AF_INET as u16,
sin_addr: wgctrl_sys::in_addr { sin_addr: wireguard_control_sys::in_addr {
s_addr: u32::from_be((*s.ip()).into()), s_addr: u32::from_be((*s.ip()).into()),
}, },
sin_port: u16::to_be(s.port()), sin_port: u16::to_be(s.port()),
@ -217,35 +220,38 @@ fn encode_endpoint(endpoint: Option<SocketAddr>) -> wgctrl_sys::wg_peer__bindgen
peer peer
}, },
Some(SocketAddr::V6(s)) => { Some(SocketAddr::V6(s)) => {
let mut peer = wgctrl_sys::wg_peer__bindgen_ty_1::default(); let mut peer = wireguard_control_sys::wg_peer__bindgen_ty_1::default();
let in6_addr = wgctrl_sys::in6_addr__bindgen_ty_1 { let in6_addr = wireguard_control_sys::in6_addr__bindgen_ty_1 {
__u6_addr8: s.ip().octets(), __u6_addr8: s.ip().octets(),
}; };
peer.addr6 = wgctrl_sys::sockaddr_in6 { peer.addr6 = wireguard_control_sys::sockaddr_in6 {
sin6_family: libc::AF_INET6 as u16, sin6_family: libc::AF_INET6 as u16,
sin6_addr: wgctrl_sys::in6_addr { __in6_u: in6_addr }, sin6_addr: wireguard_control_sys::in6_addr { __in6_u: in6_addr },
sin6_port: u16::to_be(s.port()), sin6_port: u16::to_be(s.port()),
sin6_flowinfo: 0, sin6_flowinfo: 0,
sin6_scope_id: 0, sin6_scope_id: 0,
}; };
peer peer
}, },
None => wgctrl_sys::wg_peer__bindgen_ty_1::default(), None => wireguard_control_sys::wg_peer__bindgen_ty_1::default(),
} }
} }
fn encode_peers( fn encode_peers(
peers: &[PeerConfigBuilder], peers: &[PeerConfigBuilder],
) -> (*mut wgctrl_sys::wg_peer, *mut wgctrl_sys::wg_peer) { ) -> (
*mut wireguard_control_sys::wg_peer,
*mut wireguard_control_sys::wg_peer,
) {
let mut first_peer = ptr::null_mut(); let mut first_peer = ptr::null_mut();
let mut last_peer: *mut wgctrl_sys::wg_peer = ptr::null_mut(); let mut last_peer: *mut wireguard_control_sys::wg_peer = ptr::null_mut();
for peer in peers { for peer in peers {
let (first_allowedip, last_allowedip) = encode_allowedips(&peer.allowed_ips); let (first_allowedip, last_allowedip) = encode_allowedips(&peer.allowed_ips);
let mut wg_peer = Box::new(wgctrl_sys::wg_peer { let mut wg_peer = Box::new(wireguard_control_sys::wg_peer {
public_key: peer.public_key.0, public_key: peer.public_key.0,
preshared_key: wgctrl_sys::wg_key::default(), preshared_key: wireguard_control_sys::wg_key::default(),
endpoint: encode_endpoint(peer.endpoint), endpoint: encode_endpoint(peer.endpoint),
last_handshake_time: timespec64 { last_handshake_time: timespec64 {
tv_sec: 0, tv_sec: 0,
@ -288,7 +294,7 @@ fn encode_peers(
} }
pub fn enumerate() -> Result<Vec<InterfaceName>, io::Error> { pub fn enumerate() -> Result<Vec<InterfaceName>, io::Error> {
let base = unsafe { wgctrl_sys::wg_list_device_names() }; let base = unsafe { wireguard_control_sys::wg_list_device_names() };
if base.is_null() { if base.is_null() {
return Err(io::Error::last_os_error()); return Err(io::Error::last_os_error());
@ -323,17 +329,17 @@ pub fn enumerate() -> Result<Vec<InterfaceName>, io::Error> {
pub fn apply(builder: &DeviceUpdate, iface: &InterfaceName) -> io::Result<()> { pub fn apply(builder: &DeviceUpdate, iface: &InterfaceName) -> io::Result<()> {
let (first_peer, last_peer) = encode_peers(&builder.peers); let (first_peer, last_peer) = encode_peers(&builder.peers);
let result = unsafe { wgctrl_sys::wg_add_device(iface.as_ptr()) }; let result = unsafe { wireguard_control_sys::wg_add_device(iface.as_ptr()) };
match result { match result {
0 | -17 => {}, 0 | -17 => {},
_ => return Err(io::Error::last_os_error()), _ => return Err(io::Error::last_os_error()),
}; };
let mut wg_device = Box::new(wgctrl_sys::wg_device { let mut wg_device = Box::new(wireguard_control_sys::wg_device {
name: iface.into_inner(), name: iface.into_inner(),
ifindex: 0, ifindex: 0,
public_key: wgctrl_sys::wg_key::default(), public_key: wireguard_control_sys::wg_key::default(),
private_key: wgctrl_sys::wg_key::default(), private_key: wireguard_control_sys::wg_key::default(),
fwmark: 0, fwmark: 0,
listen_port: 0, listen_port: 0,
first_peer, first_peer,
@ -366,9 +372,9 @@ pub fn apply(builder: &DeviceUpdate, iface: &InterfaceName) -> io::Result<()> {
} }
let ptr = Box::into_raw(wg_device); let ptr = Box::into_raw(wg_device);
let result = unsafe { wgctrl_sys::wg_set_device(ptr) }; let result = unsafe { wireguard_control_sys::wg_set_device(ptr) };
unsafe { wgctrl_sys::wg_free_device(ptr) }; unsafe { wireguard_control_sys::wg_free_device(ptr) };
if result == 0 { if result == 0 {
Ok(()) Ok(())
@ -378,11 +384,11 @@ pub fn apply(builder: &DeviceUpdate, iface: &InterfaceName) -> io::Result<()> {
} }
pub fn get_by_name(name: &InterfaceName) -> Result<Device, io::Error> { pub fn get_by_name(name: &InterfaceName) -> Result<Device, io::Error> {
let mut device: *mut wgctrl_sys::wg_device = ptr::null_mut(); let mut device: *mut wireguard_control_sys::wg_device = ptr::null_mut();
let result = unsafe { let result = unsafe {
wgctrl_sys::wg_get_device( wireguard_control_sys::wg_get_device(
(&mut device) as *mut _ as *mut *mut wgctrl_sys::wg_device, (&mut device) as *mut _ as *mut *mut wireguard_control_sys::wg_device,
name.as_ptr(), name.as_ptr(),
) )
}; };
@ -393,13 +399,13 @@ pub fn get_by_name(name: &InterfaceName) -> Result<Device, io::Error> {
Err(io::Error::last_os_error()) Err(io::Error::last_os_error())
}; };
unsafe { wgctrl_sys::wg_free_device(device) }; unsafe { wireguard_control_sys::wg_free_device(device) };
result result
} }
pub fn delete_interface(iface: &InterfaceName) -> io::Result<()> { pub fn delete_interface(iface: &InterfaceName) -> io::Result<()> {
let result = unsafe { wgctrl_sys::wg_del_device(iface.as_ptr()) }; let result = unsafe { wireguard_control_sys::wg_del_device(iface.as_ptr()) };
if result == 0 { if result == 0 {
Ok(()) Ok(())
@ -418,21 +424,21 @@ pub fn delete_interface(iface: &InterfaceName) -> io::Result<()> {
/// `Key`s, especially ones created from external data. /// `Key`s, especially ones created from external data.
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
#[derive(PartialEq, Eq, Clone)] #[derive(PartialEq, Eq, Clone)]
pub struct Key(wgctrl_sys::wg_key); pub struct Key(wireguard_control_sys::wg_key);
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
impl Key { impl Key {
/// Creates a new `Key` from raw bytes. /// Creates a new `Key` from raw bytes.
pub fn from_raw(key: wgctrl_sys::wg_key) -> Self { pub fn from_raw(key: wireguard_control_sys::wg_key) -> Self {
Self(key) Self(key)
} }
/// Generates and returns a new private key. /// Generates and returns a new private key.
pub fn generate_private() -> Self { pub fn generate_private() -> Self {
let mut private_key = wgctrl_sys::wg_key::default(); let mut private_key = wireguard_control_sys::wg_key::default();
unsafe { unsafe {
wgctrl_sys::wg_generate_private_key(private_key.as_mut_ptr()); wireguard_control_sys::wg_generate_private_key(private_key.as_mut_ptr());
} }
Self(private_key) Self(private_key)
@ -440,10 +446,10 @@ impl Key {
/// Generates and returns a new preshared key. /// Generates and returns a new preshared key.
pub fn generate_preshared() -> Self { pub fn generate_preshared() -> Self {
let mut preshared_key = wgctrl_sys::wg_key::default(); let mut preshared_key = wireguard_control_sys::wg_key::default();
unsafe { unsafe {
wgctrl_sys::wg_generate_preshared_key(preshared_key.as_mut_ptr()); wireguard_control_sys::wg_generate_preshared_key(preshared_key.as_mut_ptr());
} }
Self(preshared_key) Self(preshared_key)
@ -451,10 +457,10 @@ impl Key {
/// Generates a public key for this private key. /// Generates a public key for this private key.
pub fn generate_public(&self) -> Self { pub fn generate_public(&self) -> Self {
let mut public_key = wgctrl_sys::wg_key::default(); let mut public_key = wireguard_control_sys::wg_key::default();
unsafe { unsafe {
wgctrl_sys::wg_generate_public_key( wireguard_control_sys::wg_generate_public_key(
public_key.as_mut_ptr(), public_key.as_mut_ptr(),
&self.0 as *const u8 as *mut u8, &self.0 as *const u8 as *mut u8,
); );
@ -465,7 +471,7 @@ impl Key {
/// Generates an all-zero key. /// Generates an all-zero key.
pub fn zero() -> Self { pub fn zero() -> Self {
Self(wgctrl_sys::wg_key::default()) Self(wireguard_control_sys::wg_key::default())
} }
pub fn as_bytes(&self) -> &[u8] { pub fn as_bytes(&self) -> &[u8] {
@ -474,9 +480,12 @@ impl Key {
/// Converts the key to a standardized base64 representation, as used by the `wg` utility and `wg-quick`. /// Converts the key to a standardized base64 representation, as used by the `wg` utility and `wg-quick`.
pub fn to_base64(&self) -> String { pub fn to_base64(&self) -> String {
let mut key_b64: wgctrl_sys::wg_key_b64_string = [0; 45]; let mut key_b64: wireguard_control_sys::wg_key_b64_string = [0; 45];
unsafe { unsafe {
wgctrl_sys::wg_key_to_base64(key_b64.as_mut_ptr(), &self.0 as *const u8 as *mut u8); wireguard_control_sys::wg_key_to_base64(
key_b64.as_mut_ptr(),
&self.0 as *const u8 as *mut u8,
);
str::from_utf8_unchecked(&*(&key_b64[..44] as *const [c_char] as *const [u8])).into() str::from_utf8_unchecked(&*(&key_b64[..44] as *const [c_char] as *const [u8])).into()
} }
@ -487,11 +496,14 @@ impl Key {
/// This can fail, as not all text input is valid base64 - in this case /// This can fail, as not all text input is valid base64 - in this case
/// `Err(InvalidKey)` is returned. /// `Err(InvalidKey)` is returned.
pub fn from_base64(key: &str) -> Result<Self, InvalidKey> { pub fn from_base64(key: &str) -> Result<Self, InvalidKey> {
let mut decoded = wgctrl_sys::wg_key::default(); let mut decoded = wireguard_control_sys::wg_key::default();
let key_str = CString::new(key)?; let key_str = CString::new(key)?;
let result = unsafe { let result = unsafe {
wgctrl_sys::wg_key_from_base64(decoded.as_mut_ptr(), key_str.as_ptr() as *mut _) wireguard_control_sys::wg_key_from_base64(
decoded.as_mut_ptr(),
key_str.as_ptr() as *mut _,
)
}; };
if result == 0 { if result == 0 {

View File

@ -18,7 +18,7 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
/// ///
/// # Example /// # Example
/// ```rust /// ```rust
/// # use wgctrl::*; /// # use wireguard_control::*;
/// # use std::net::AddrParseError; /// # use std::net::AddrParseError;
/// # fn try_main() -> Result<(), AddrParseError> { /// # fn try_main() -> Result<(), AddrParseError> {
/// let peer_keypair = KeyPair::generate(); /// let peer_keypair = KeyPair::generate();

View File

@ -273,7 +273,7 @@ impl Device {
/// ///
/// # Example /// # Example
/// ```rust /// ```rust
/// # use wgctrl::*; /// # use wireguard_control::*;
/// # use std::net::AddrParseError; /// # use std::net::AddrParseError;
/// # fn try_main() -> Result<(), AddrParseError> { /// # fn try_main() -> Result<(), AddrParseError> {
/// let our_keypair = KeyPair::generate(); /// let our_keypair = KeyPair::generate();