Merge pull request 'public IP address autodiscovery' (#20) from stun into main
Reviewed-on: #20main
commit
05872634a4
@ -1,75 +0,0 @@
|
||||
unstable_features = true
|
||||
|
||||
array_width = 60
|
||||
attr_fn_like_width = 70
|
||||
binop_separator = "Front"
|
||||
blank_lines_lower_bound = 0
|
||||
blank_lines_upper_bound = 1
|
||||
brace_style = "SameLineWhere"
|
||||
chain_width = 60
|
||||
color = "Auto"
|
||||
combine_control_expr = true
|
||||
comment_width = 80
|
||||
condense_wildcard_suffixes = true
|
||||
control_brace_style = "AlwaysSameLine"
|
||||
disable_all_formatting = false
|
||||
empty_item_single_line = true
|
||||
enum_discrim_align_threshold = 0
|
||||
error_on_line_overflow = true
|
||||
error_on_unformatted = true
|
||||
fn_args_layout = "Tall"
|
||||
fn_call_width = 60
|
||||
fn_single_line = true
|
||||
force_explicit_abi = true
|
||||
force_multiline_blocks = false
|
||||
format_code_in_doc_comments = true
|
||||
# format_generated_files = true
|
||||
format_macro_matchers = true
|
||||
format_macro_bodies = true
|
||||
format_strings = true
|
||||
hard_tabs = false
|
||||
#hex_literal_case = "Lower"
|
||||
hide_parse_errors = false
|
||||
ignore = []
|
||||
imports_indent = "Block"
|
||||
imports_layout = "Mixed"
|
||||
indent_style = "Block"
|
||||
inline_attribute_width = 0
|
||||
license_template_path = ""
|
||||
match_arm_blocks = true
|
||||
match_arm_leading_pipes = "Never"
|
||||
match_block_trailing_comma = false
|
||||
max_width = 100
|
||||
merge_derives = true
|
||||
imports_granularity = "Crate"
|
||||
newline_style = "Unix"
|
||||
normalize_comments = true
|
||||
normalize_doc_attributes = true
|
||||
overflow_delimited_expr = false
|
||||
remove_nested_parens = true
|
||||
reorder_impl_items = true
|
||||
reorder_imports = true
|
||||
group_imports = "StdExternalCrate"
|
||||
reorder_modules = true
|
||||
report_fixme = "Unnumbered"
|
||||
report_todo = "Unnumbered"
|
||||
required_version = "1.4.37"
|
||||
skip_children = false
|
||||
single_line_if_else_max_width = 50
|
||||
space_after_colon = true
|
||||
space_before_colon = false
|
||||
#space_around_ranges = false
|
||||
struct_field_align_threshold = 0
|
||||
struct_lit_single_line = true
|
||||
struct_lit_width = 18
|
||||
struct_variant_width = 35
|
||||
tab_spaces = 2
|
||||
trailing_comma = "Vertical"
|
||||
trailing_semicolon = false
|
||||
type_punctuation_density = "Wide"
|
||||
use_field_init_shorthand = false
|
||||
use_small_heuristics = "Off"
|
||||
use_try_shorthand = true
|
||||
version = "Two"
|
||||
where_single_line = true
|
||||
wrap_comments = true
|
File diff suppressed because it is too large
Load Diff
@ -1,151 +1,191 @@
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{anyhow, bail, Result};
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
|
||||
use crate::config::{ConfigOpts, ConfigOptsAcme, ConfigOptsBase, ConfigOptsConsul};
|
||||
use crate::config::{ConfigOpts, ConfigOptsBase, ConfigOptsConsul};
|
||||
|
||||
// This code is inspired by the Trunk crate (https://github.com/thedodd/trunk)
|
||||
|
||||
// In this file, we take ConfigOpts and transform them into ready-to-use
|
||||
// RuntimeConfig. We apply default values and business logic.
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RuntimeConfigAcme {
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RuntimeConfigConsul {
|
||||
pub node_name: String,
|
||||
pub url: String,
|
||||
pub tls: Option<(Option<reqwest::Certificate>, bool, reqwest::Identity)>,
|
||||
pub node_name: String,
|
||||
pub url: String,
|
||||
pub tls: Option<(Option<reqwest::Certificate>, bool, reqwest::Identity)>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RuntimeConfigFirewall {
|
||||
pub refresh_time: Duration,
|
||||
pub ipv6_only: bool,
|
||||
pub refresh_time: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RuntimeConfigIgd {
|
||||
pub private_ip: Option<String>,
|
||||
pub expiration_time: Duration,
|
||||
pub refresh_time: Duration,
|
||||
pub private_ip: Option<Ipv4Addr>,
|
||||
pub expiration_time: Duration,
|
||||
pub refresh_time: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RuntimeConfig {
|
||||
pub acme: Option<RuntimeConfigAcme>,
|
||||
pub consul: RuntimeConfigConsul,
|
||||
pub firewall: RuntimeConfigFirewall,
|
||||
pub igd: RuntimeConfigIgd,
|
||||
pub struct RuntimeConfigStun {
|
||||
pub stun_server_v4: Option<SocketAddr>,
|
||||
pub stun_server_v6: SocketAddr,
|
||||
pub refresh_time: Duration,
|
||||
}
|
||||
|
||||
impl RuntimeConfig {
|
||||
pub fn new(opts: ConfigOpts) -> Result<Self> {
|
||||
let acme = RuntimeConfigAcme::new(opts.acme.clone())?;
|
||||
let consul = RuntimeConfigConsul::new(opts.consul.clone())?;
|
||||
let firewall = RuntimeConfigFirewall::new(opts.base.clone())?;
|
||||
let igd = RuntimeConfigIgd::new(opts.base.clone())?;
|
||||
|
||||
Ok(Self {
|
||||
acme,
|
||||
consul,
|
||||
firewall,
|
||||
igd,
|
||||
})
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct RuntimeConfig {
|
||||
pub consul: RuntimeConfigConsul,
|
||||
pub firewall: RuntimeConfigFirewall,
|
||||
pub igd: Option<RuntimeConfigIgd>,
|
||||
pub stun: RuntimeConfigStun,
|
||||
}
|
||||
|
||||
impl RuntimeConfigAcme {
|
||||
pub fn new(opts: ConfigOptsAcme) -> Result<Option<Self>> {
|
||||
if !opts.enable {
|
||||
return Ok(None);
|
||||
impl RuntimeConfig {
|
||||
pub fn new(opts: ConfigOpts) -> Result<Self> {
|
||||
let consul = RuntimeConfigConsul::new(opts.consul)?;
|
||||
let firewall = RuntimeConfigFirewall::new(&opts.base)?;
|
||||
let igd = match opts.base.ipv6_only {
|
||||
false => Some(RuntimeConfigIgd::new(&opts.base)?),
|
||||
true => None,
|
||||
};
|
||||
let stun = RuntimeConfigStun::new(&opts.base)?;
|
||||
|
||||
Ok(Self {
|
||||
consul,
|
||||
firewall,
|
||||
igd,
|
||||
stun,
|
||||
})
|
||||
}
|
||||
|
||||
let email = opts.email.expect(
|
||||
"'DIPLONAT_ACME_EMAIL' environment variable is required if 'DIPLONAT_ACME_ENABLE' == 'true'",
|
||||
);
|
||||
|
||||
Ok(Some(Self { email }))
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeConfigConsul {
|
||||
pub(super) fn new(opts: ConfigOptsConsul) -> Result<Self> {
|
||||
let node_name = opts
|
||||
.node_name
|
||||
.expect("'DIPLONAT_CONSUL_NODE_NAME' environment variable is required");
|
||||
let url = opts.url.unwrap_or(super::CONSUL_URL.to_string());
|
||||
|
||||
let tls = match (&opts.client_cert, &opts.client_key) {
|
||||
(Some(client_cert), Some(client_key)) => {
|
||||
let cert = match &opts.ca_cert {
|
||||
Some(ca_cert) => {
|
||||
let mut ca_cert_buf = vec![];
|
||||
File::open(ca_cert)?.read_to_end(&mut ca_cert_buf)?;
|
||||
Some(reqwest::Certificate::from_pem(&ca_cert_buf[..])?)
|
||||
}
|
||||
None => None,
|
||||
pub(super) fn new(opts: ConfigOptsConsul) -> Result<Self> {
|
||||
let node_name = opts
|
||||
.node_name
|
||||
.expect("'DIPLONAT_CONSUL_NODE_NAME' environment variable is required");
|
||||
let url = opts.url.unwrap_or(super::CONSUL_URL.to_string());
|
||||
|
||||
let tls = match (&opts.client_cert, &opts.client_key) {
|
||||
(Some(client_cert), Some(client_key)) => {
|
||||
let cert = match &opts.ca_cert {
|
||||
Some(ca_cert) => {
|
||||
let mut ca_cert_buf = vec![];
|
||||
File::open(ca_cert)?.read_to_end(&mut ca_cert_buf)?;
|
||||
Some(reqwest::Certificate::from_pem(&ca_cert_buf[..])?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let mut client_cert_buf = vec![];
|
||||
File::open(client_cert)?.read_to_end(&mut client_cert_buf)?;
|
||||
|
||||
let mut client_key_buf = vec![];
|
||||
File::open(client_key)?.read_to_end(&mut client_key_buf)?;
|
||||
|
||||
let ident = reqwest::Identity::from_pem(
|
||||
&[&client_cert_buf[..], &client_key_buf[..]].concat()[..],
|
||||
)?;
|
||||
|
||||
Some((cert, opts.tls_skip_verify, ident))
|
||||
}
|
||||
(None, None) => None,
|
||||
_ => bail!("Incomplete TLS configuration parameters"),
|
||||
};
|
||||
|
||||
let mut client_cert_buf = vec![];
|
||||
File::open(client_cert)?.read_to_end(&mut client_cert_buf)?;
|
||||
|
||||
let mut client_key_buf = vec![];
|
||||
File::open(client_key)?.read_to_end(&mut client_key_buf)?;
|
||||
|
||||
let ident =
|
||||
reqwest::Identity::from_pem(&[&client_cert_buf[..], &client_key_buf[..]].concat()[..])?;
|
||||
|
||||
Some((cert, opts.tls_skip_verify, ident))
|
||||
}
|
||||
(None, None) => None,
|
||||
_ => bail!("Incomplete TLS configuration parameters"),
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
node_name,
|
||||
url,
|
||||
tls,
|
||||
})
|
||||
}
|
||||
Ok(Self {
|
||||
node_name,
|
||||
url,
|
||||
tls,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeConfigFirewall {
|
||||
pub(super) fn new(opts: ConfigOptsBase) -> Result<Self> {
|
||||
let refresh_time = Duration::from_secs(opts.refresh_time.unwrap_or(super::REFRESH_TIME).into());
|
||||
|
||||
Ok(Self { refresh_time })
|
||||
}
|
||||
pub(super) fn new(opts: &ConfigOptsBase) -> Result<Self> {
|
||||
let refresh_time =
|
||||
Duration::from_secs(opts.refresh_time.unwrap_or(super::REFRESH_TIME).into());
|
||||
|
||||
Ok(Self {
|
||||
refresh_time,
|
||||
ipv6_only: opts.ipv6_only,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeConfigIgd {
|
||||
pub(super) fn new(opts: ConfigOptsBase) -> Result<Self> {
|
||||
let private_ip = opts.private_ip;
|
||||
let expiration_time = Duration::from_secs(
|
||||
opts
|
||||
.expiration_time
|
||||
.unwrap_or(super::EXPIRATION_TIME)
|
||||
.into(),
|
||||
);
|
||||
let refresh_time = Duration::from_secs(opts.refresh_time.unwrap_or(super::REFRESH_TIME).into());
|
||||
|
||||
if refresh_time.as_secs() * 2 > expiration_time.as_secs() {
|
||||
return Err(anyhow!(
|
||||
pub(super) fn new(opts: &ConfigOptsBase) -> Result<Self> {
|
||||
let private_ip = opts
|
||||
.private_ip
|
||||
.as_ref()
|
||||
.map(|x| x.parse())
|
||||
.transpose()
|
||||
.context("parse private_ip")?;
|
||||
let expiration_time = Duration::from_secs(
|
||||
opts.expiration_time
|
||||
.unwrap_or(super::EXPIRATION_TIME)
|
||||
.into(),
|
||||
);
|
||||
let refresh_time =
|
||||
Duration::from_secs(opts.refresh_time.unwrap_or(super::REFRESH_TIME).into());
|
||||
|
||||
if refresh_time.as_secs() * 2 > expiration_time.as_secs() {
|
||||
return Err(anyhow!(
|
||||
"IGD expiration time (currently: {}s) must be at least twice bigger than refresh time \
|
||||
(currently: {}s)",
|
||||
expiration_time.as_secs(),
|
||||
refresh_time.as_secs()
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
private_ip,
|
||||
expiration_time,
|
||||
refresh_time,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
private_ip,
|
||||
expiration_time,
|
||||
refresh_time,
|
||||
})
|
||||
}
|
||||
impl RuntimeConfigStun {
|
||||
pub(super) fn new(opts: &ConfigOptsBase) -> Result<Self> {
|
||||
let mut stun_server_v4 = None;
|
||||
let mut stun_server_v6 = None;
|
||||
for addr in opts
|
||||
.stun_server
|
||||
.as_deref()
|
||||
.unwrap_or(super::STUN_SERVER)
|
||||
.to_socket_addrs()?
|
||||
{
|
||||
if addr.is_ipv4() {
|
||||
stun_server_v4 = Some(addr);
|
||||
}
|
||||
if addr.is_ipv6() {
|
||||
stun_server_v6 = Some(addr);
|
||||
}
|
||||
}
|
||||
|
||||
let refresh_time =
|
||||
Duration::from_secs(opts.refresh_time.unwrap_or(super::REFRESH_TIME).into());
|
||||
|
||||
let stun_server_v4 = match opts.ipv6_only {
|
||||
false => Some(
|
||||
stun_server_v4.ok_or(anyhow!("Unable to resolve STUN server's IPv4 address"))?,
|
||||
),
|
||||
true => None,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
stun_server_v4,
|
||||
stun_server_v6: stun_server_v6
|
||||
.ok_or(anyhow!("Unable to resolve STUN server's IPv6 address"))?,
|
||||
refresh_time,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -1,49 +1,78 @@
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result};
|
||||
use futures::future::FutureExt;
|
||||
use tokio::try_join;
|
||||
|
||||
use crate::{
|
||||
config::ConfigOpts, consul_actor::ConsulActor, fw_actor::FirewallActor, igd_actor::IgdActor,
|
||||
config::ConfigOpts, consul_actor::ConsulActor, fw_actor::FirewallActor, igd_actor::IgdActor,
|
||||
stun_actor::StunActor,
|
||||
};
|
||||
|
||||
pub struct Diplonat {
|
||||
consul: ConsulActor,
|
||||
firewall: FirewallActor,
|
||||
igd: IgdActor,
|
||||
consul: ConsulActor,
|
||||
firewall: FirewallActor,
|
||||
igd: Option<IgdActor>,
|
||||
stun: StunActor,
|
||||
}
|
||||
|
||||
impl Diplonat {
|
||||
pub async fn new() -> Result<Self> {
|
||||
let rt_cfg = ConfigOpts::from_env()?;
|
||||
println!("{:#?}", rt_cfg);
|
||||
|
||||
let ca = ConsulActor::new(&rt_cfg.consul, &rt_cfg.consul.node_name);
|
||||
|
||||
let fw = FirewallActor::new(rt_cfg.firewall.refresh_time, &ca.rx_open_ports).await?;
|
||||
|
||||
let ia = IgdActor::new(
|
||||
rt_cfg.igd.private_ip.as_ref().map(String::as_str),
|
||||
rt_cfg.igd.refresh_time,
|
||||
rt_cfg.igd.expiration_time,
|
||||
&ca.rx_open_ports,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let ctx = Self {
|
||||
consul: ca,
|
||||
igd: ia,
|
||||
firewall: fw,
|
||||
};
|
||||
|
||||
return Ok(ctx);
|
||||
}
|
||||
|
||||
pub async fn listen(&mut self) -> Result<()> {
|
||||
try_join!(
|
||||
self.consul.listen(),
|
||||
self.igd.listen(),
|
||||
self.firewall.listen()
|
||||
)?;
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
pub async fn new() -> Result<Self> {
|
||||
let rt_cfg = ConfigOpts::from_env().context("Parse configuration")?;
|
||||
println!("{:#?}", rt_cfg);
|
||||
|
||||
let ca = ConsulActor::new(&rt_cfg.consul, &rt_cfg.consul.node_name);
|
||||
|
||||
let fw = FirewallActor::new(
|
||||
rt_cfg.firewall.ipv6_only,
|
||||
rt_cfg.firewall.refresh_time,
|
||||
&ca.rx_open_ports,
|
||||
)
|
||||
.await
|
||||
.context("Setup fireall actor")?;
|
||||
|
||||
let ia = match rt_cfg.igd {
|
||||
Some(igdc) => Some(
|
||||
IgdActor::new(
|
||||
igdc.private_ip,
|
||||
igdc.refresh_time,
|
||||
igdc.expiration_time,
|
||||
&ca.rx_open_ports,
|
||||
)
|
||||
.await
|
||||
.context("Setup IGD actor")?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let sa = StunActor::new(&rt_cfg.consul, &rt_cfg.stun, &rt_cfg.consul.node_name);
|
||||
|
||||
let ctx = Self {
|
||||
consul: ca,
|
||||
igd: ia,
|
||||
firewall: fw,
|
||||
stun: sa,
|
||||
};
|
||||
|
||||
Ok(ctx)
|
||||
}
|
||||
|
||||
pub async fn listen(&mut self) -> Result<()> {
|
||||
let igd_opt = &mut self.igd;
|
||||
|
||||
try_join!(
|
||||
self.consul.listen().map(|x| x.context("Run consul actor")),
|
||||
async {
|
||||
if let Some(igd) = igd_opt {
|
||||
igd.listen().await.context("Run IGD actor")
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
},
|
||||
self.firewall
|
||||
.listen()
|
||||
.map(|x| x.context("Run firewall actor")),
|
||||
self.stun.listen().map(|x| x.context("Run STUN actor")),
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|