Moving towards implementing the 0.3.2 featureset

This commit is contained in:
Nadja Reitzenstein
2022-03-11 22:13:54 +01:00
parent 4f36eedf6a
commit 13bfb2fbee
24 changed files with 1062 additions and 599 deletions

View File

@ -1,192 +0,0 @@
use std::default::Default;
use std::path::{Path, PathBuf};
use std::collections::HashMap;
use serde::{Serialize, Deserialize, Deserializer, Serializer};
use std::fmt::Formatter;
use std::net::{SocketAddr, IpAddr, ToSocketAddrs};
use std::str::FromStr;
use serde::de::Error;
use diflouroborane::authorization::permissions::PermRule;
use diflouroborane::authorization::roles::RoleIdentifier;
type Result<T> = std::result::Result<T, serde_dhall::Error>;
pub fn read(path: &Path) -> Result<Config> {
serde_dhall::from_file(path)
.parse()
.map_err(Into::into)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
/// A list of address/port pairs to listen on.
// TODO: This should really be a variant type; that is something that can figure out itself if
// it contains enough information to open a socket (i.e. it checks if it's a valid path (=>
// Unix socket) or IPv4/v6 address)
pub listens: Vec<Listen>,
/// Machine descriptions to load
//pub machines: HashMap<MachineIdentifier, MachineDescription>,
/// Actors to load and their configuration options
pub actors: HashMap<String, ModuleConfig>,
/// Initiators to load and their configuration options
pub initiators: HashMap<String, ModuleConfig>,
pub mqtt_url: String,
pub actor_connections: Vec<(String, String)>,
pub init_connections: Vec<(String, String)>,
pub db_path: PathBuf,
pub roles: HashMap<RoleIdentifier, RoleConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoleConfig {
#[serde(default = "Vec::new")]
pub parents: Vec<RoleIdentifier>,
#[serde(default = "Vec::new")]
pub permissions: Vec<PermRule>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModuleConfig {
pub module: String,
pub params: HashMap<String, String>
}
#[derive(Debug, Clone)]
pub struct Listen {
address: String,
port: Option<u16>,
}
impl std::fmt::Display for Listen {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}", &self.address, self.port.unwrap_or(DEFAULT_PORT))
}
}
impl ToSocketAddrs for Listen {
type Iter = <(String, u16) as ToSocketAddrs>::Iter;
fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
if let Some(port) = self.port {
(self.address.as_str(), port).to_socket_addrs()
} else {
(self.address.as_str(), DEFAULT_PORT).to_socket_addrs()
}
}
}
impl<'de> serde::Deserialize<'de> for Listen {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where D: Deserializer<'de>
{
deserializer.deserialize_str(ListenVisitor)
}
}
impl serde::Serialize for Listen {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where S: Serializer
{
if let Some(port) = self.port {
serializer.serialize_str(&format!("{}:{}", self.address, port))
} else {
serializer.serialize_str(&self.address)
}
}
}
struct ListenVisitor;
impl<'de> serde::de::Visitor<'de> for ListenVisitor {
type Value = Listen;
fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
write!(formatter, "A string encoding a valid IP or Hostname (e.g. 127.0.0.1 or [::1]) with \
or without a defined port")
}
fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
where E: Error
{
let sockaddr = SocketAddr::from_str(v);
if let Ok(address) = sockaddr {
return Ok(Listen {
address: address.ip().to_string(),
port: Some(address.port()),
})
}
let ipaddr = IpAddr::from_str(v);
if let Ok(address) = ipaddr {
return Ok(Listen {
address: address.to_string(),
port: None,
})
}
let mut split = v.split(':');
let address = split.next()
.expect("str::split should always return at least one element")
.to_string();
let port = if let Some(port) = split.next() {
let port: u16 = port.parse()
.map_err(|_| {
E::custom(&format!("Expected valid ip address or hostname with or without \
port. Failed to parse \"{}\".", v))
})?;
Some(port)
} else {
None
};
Ok(Listen { address, port })
}
}
impl Default for Config {
fn default() -> Self {
let mut actors: HashMap::<String, ModuleConfig> = HashMap::new();
let mut initiators: HashMap::<String, ModuleConfig> = HashMap::new();
actors.insert("Actor".to_string(), ModuleConfig {
module: "Shelly".to_string(),
params: HashMap::new(),
});
initiators.insert("Initiator".to_string(), ModuleConfig {
module: "TCP-Listen".to_string(),
params: HashMap::new(),
});
Config {
listens: vec![
Listen {
address: "127.0.0.1".to_string(),
port: None,
}
],
actors,
initiators,
mqtt_url: "tcp://localhost:1883".to_string(),
actor_connections: vec![
("Testmachine".to_string(), "Actor".to_string()),
],
init_connections: vec![
("Initiator".to_string(), "Testmachine".to_string()),
],
db_path: PathBuf::from("/run/bffh/database"),
roles: HashMap::new(),
}
}
}
// The default port in the non-assignable i.e. free-use area
pub const DEFAULT_PORT: u16 = 59661;

View File

@ -1,48 +1,81 @@
use std::{
io,
io::Write,
path::PathBuf,
};
use clap::{App, Arg, crate_version, crate_description, crate_name};
use std::str::FromStr;
use diflouroborane::{error::Error};
use clap::{Arg, Command};
use diflouroborane::db::{Databases, Dump};
use diflouroborane::{config, Diflouroborane, error::Error};
use std::net::ToSocketAddrs;
use std::os::unix::prelude::AsRawFd;
use std::str::FromStr;
use std::{env, io, io::Write, path::PathBuf};
use anyhow::Context;
use nix::NixPath;
mod config;
fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
fn main() -> anyhow::Result<()> {
// Argument parsing
// values for the name, description and version are pulled from `Cargo.toml`.
let matches = App::new(crate_name!())
.about(crate_description!())
.version(crate_version!())
.arg(Arg::with_name("config")
.help("Path to the config file to use")
.long("config")
.short("c")
.takes_value(true
))
.arg(Arg::with_name("print default")
.help("Print a default config to stdout instead of running")
.long("print-default")
)
.arg(Arg::with_name("check config")
.help("Check config for validity")
.long("check")
)
.arg(Arg::with_name("dump")
.help("Dump all internal databases")
.long("dump")
.conflicts_with("load")
)
.arg(Arg::with_name("load")
.help("Load values into the internal databases")
.long("load")
.conflicts_with("dump")
)
.get_matches();
let matches = Command::new(clap::crate_name!())
.version(clap::crate_version!())
.about(clap::crate_description!())
.arg(
Arg::new("config")
.help("Path to the config file to use")
.long("config")
.short('c')
.takes_value(true),
)
.arg(Arg::new("verbosity")
.help("Increase logging verbosity")
.long("verbose")
.short('v')
.multiple_occurrences(true)
.max_occurrences(3)
.conflicts_with("quiet")
)
.arg(Arg::new("quiet")
.help("Decrease logging verbosity")
.long("quiet")
.conflicts_with("verbosity")
)
.arg(Arg::new("log format")
.help("Use an alternative log formatter. Available: Full, Compact, Pretty")
.long("log-format")
.takes_value(true)
.ignore_case(true)
.possible_values(["Full", "Compact", "Pretty"]))
.arg(
Arg::new("print default")
.help("Print a default config to stdout instead of running")
.long("print-default"),
)
.arg(
Arg::new("check config")
.help("Check config for validity")
.long("check"),
)
.arg(
Arg::new("dump")
.help("Dump all internal databases")
.long("dump")
.conflicts_with("load"),
)
.arg(
Arg::new("load")
.help("Load values into the internal databases")
.long("load")
.conflicts_with("dump"),
)
.arg(Arg::new("keylog")
.help("log TLS keys into PATH. If no path is specified the value of the envvar SSLKEYLOGFILE is used.")
.long("tls-key-log")
.value_name("PATH")
.takes_value(true)
.max_values(1)
.min_values(0)
.default_missing_value("")
)
.get_matches();
let configpath = matches
.value_of("config")
.unwrap_or("/etc/diflouroborane.dhall");
// Check for the --print-default option first because we don't need to do anything else in that
// case.
@ -59,7 +92,6 @@ fn main() -> Result<(), Error> {
// Early return to exit.
return Ok(());
} else if matches.is_present("check config") {
let configpath = matches.value_of("config").unwrap_or("/etc/diflouroborane.dhall");
match config::read(&PathBuf::from_str(configpath).unwrap()) {
Ok(_) => {
//TODO: print a normalized version of the supplied config
@ -71,88 +103,36 @@ fn main() -> Result<(), Error> {
std::process::exit(-1);
}
}
}
// If no `config` option is given use a preset default.
let configpath = matches.value_of("config").unwrap_or("/etc/diflouroborane.dhall");
let config = config::read(&PathBuf::from_str(configpath).unwrap())
.expect("Failed to parse config");
println!("{:#?}", config);
let mut sockaddrs = Vec::new();
for listen in config.listens {
match listen.to_socket_addrs() {
Ok(addrs) => {
sockaddrs.extend(addrs)
},
Err(e) => {
tracing::error!("Invalid listen \"{}\" {}", listen, e);
} else if matches.is_present("dump") {
unimplemented!()
} else if matches.is_present("load") {
unimplemented!()
} else {
let keylog = matches.value_of("keylog");
// When passed an empty string (i.e no value) take the value from the env
let keylog = if let Some("") = keylog {
let v = env::var_os("SSLKEYLOGFILE").map(PathBuf::from);
if v.is_none() || v.as_ref().unwrap().is_empty() {
eprintln!("--tls-key-log set but no path configured!");
return Ok(());
}
}
}
println!("Final listens: {:?}", sockaddrs);
let dbs = Databases::create(config.db_path)?;
if matches.is_present("dump") {
let dump = Dump::new(&dbs)?;
let encoded = serde_json::to_vec(&dump).unwrap();
// Direct writing to fd 1 is faster but also prevents any print-formatting that could
// invalidate the generated TOML
let stdout = io::stdout();
let mut handle = stdout.lock();
handle.write_all(&encoded).unwrap();
}
/*
} else if matches.is_present("load") {
let db = db::Databases::new(&log, &config)?;
let mut dir = PathBuf::from(matches.value_of_os("load").unwrap());
dir.push("users.toml");
let map = db::user::load_file(&dir)?;
for (uid,user) in map.iter() {
db.userdb.put_user(uid, user)?;
}
tracing::debug!("Loaded users: {:?}", map);
dir.pop();
Ok(())
v
} else {
let ex = smol::Executor::new();
let db = db::Databases::new(&log, &config)?;
keylog.map(PathBuf::from)
};
let machines = machine::load(&config)?;
let (actor_map, actors) = actor::load(&log, &config)?;
let (init_map, initiators) = initiator::load(&log, &config, db.userdb.clone(), db.access.clone())?;
let mut config = config::read(&PathBuf::from_str(configpath).unwrap()).unwrap();
let mut network = network::Network::new(machines, actor_map, init_map);
for (a,b) in config.actor_connections.iter() {
if let Err(e) = network.connect_actor(a,b) {
tracing::error!("{}", e);
}
tracing::info!("[Actor] Connected {} to {}", a, b);
}
for (a,b) in config.init_connections.iter() {
if let Err(e) = network.connect_init(a,b) {
tracing::error!("{}", e);
}
tracing::info!("[Initi] Connected {} to {}", a, b);
}
for actor in actors.into_iter() {
ex.spawn(actor).detach();
}
for init in initiators.into_iter() {
ex.spawn(init).detach();
}
capnp::serve_api_connections(log.clone(), config, db, network, ex)
config.tlskeylog = keylog;
config.verbosity = matches.occurrences_of("verbosity") as isize;
if config.verbosity == 0 && matches.is_present("quiet") {
config.verbosity = -1;
}
*/
config.log_format = matches.value_of("log format").unwrap_or("Full").to_string();
let mut bffh = Diflouroborane::new();
bffh.setup(&config);
}
Ok(())
}
}