fabaccess-bffh/src/config.rs

192 lines
5.6 KiB
Rust
Raw Normal View History

2020-12-12 13:58:04 +01:00
use std::default::Default;
2021-09-19 19:47:29 +02:00
use std::path::{Path, PathBuf};
2020-09-15 14:31:10 +02:00
use std::collections::HashMap;
2020-02-18 16:55:19 +01:00
2021-10-20 12:58:05 +02:00
use serde::{Serialize, Deserialize, Deserializer, Serializer};
2020-09-15 14:31:10 +02:00
2021-10-20 12:58:05 +02:00
use std::fmt::Formatter;
use std::net::{SocketAddr, IpAddr, ToSocketAddrs};
use std::str::FromStr;
2021-10-20 13:47:32 +02:00
use crate::permissions::{PermRule, RoleIdentifier};
2021-10-20 12:58:05 +02:00
use serde::de::Error;
2020-09-15 14:31:10 +02:00
2021-10-27 14:49:45 +02:00
type Result<T> = std::result::Result<T, serde_dhall::Error>;
2020-12-12 13:58:04 +01:00
pub fn read(path: &Path) -> Result<Config> {
2020-12-14 11:02:46 +01:00
serde_dhall::from_file(path)
.parse()
.map_err(Into::into)
2020-02-14 12:20:17 +01:00
}
#[derive(Debug, Clone, Serialize, Deserialize)]
2020-12-12 13:58:04 +01:00
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)
2021-10-20 12:58:05 +02:00
pub listens: Vec<Listen>,
2020-02-14 12:20:17 +01:00
2020-12-12 13:58:04 +01:00
/// Machine descriptions to load
2021-10-20 12:58:05 +02:00
//pub machines: HashMap<MachineIdentifier, MachineDescription>,
2020-12-12 13:58:04 +01:00
2020-12-14 11:02:46 +01:00
/// 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,
2020-12-14 12:39:01 +01:00
pub actor_connections: Box<[(String, String)]>,
pub init_connections: Box<[(String, String)]>,
2021-09-19 19:47:29 +02:00
pub db_path: PathBuf,
2021-09-19 22:53:43 +02:00
2021-10-20 13:47:32 +02:00
pub roles: HashMap<RoleIdentifier, RoleConfig>,
2021-09-19 22:53:43 +02:00
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoleConfig {
2021-09-21 07:48:19 +02:00
#[serde(default = "Vec::new")]
2021-10-20 13:47:32 +02:00
pub parents: Vec<RoleIdentifier>,
2021-09-21 07:48:19 +02:00
#[serde(default = "Vec::new")]
pub permissions: Vec<PermRule>,
2020-02-14 12:20:17 +01:00
}
2020-02-18 16:55:19 +01:00
2020-12-14 11:02:46 +01:00
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModuleConfig {
2020-12-14 12:39:01 +01:00
pub module: String,
2020-12-14 11:02:46 +01:00
pub params: HashMap<String, String>
}
2021-10-20 12:58:05 +02:00
#[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 {
2021-10-20 18:37:50 +02:00
write!(formatter, "A string encoding a valid IP or Hostname (e.g. 127.0.0.1 or [::1]) with \
or without a defined port")
2021-10-20 12:58:05 +02:00
}
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 })
}
}
2020-12-14 11:02:46 +01:00
impl Default for Config {
2020-02-18 16:55:19 +01:00
fn default() -> Self {
2020-12-14 11:02:46 +01:00
let mut actors: HashMap::<String, ModuleConfig> = HashMap::new();
let mut initiators: HashMap::<String, ModuleConfig> = HashMap::new();
actors.insert("Actor".to_string(), ModuleConfig {
2020-12-14 12:39:01 +01:00
module: "Shelly".to_string(),
2020-12-14 11:02:46 +01:00
params: HashMap::new(),
});
initiators.insert("Initiator".to_string(), ModuleConfig {
2020-12-14 12:39:01 +01:00
module: "TCP-Listen".to_string(),
2020-12-14 11:02:46 +01:00
params: HashMap::new(),
});
2020-12-12 13:58:04 +01:00
Config {
2021-10-20 12:58:05 +02:00
listens: vec![
2020-12-14 11:02:46 +01:00
Listen {
2021-10-20 12:58:05 +02:00
address: "127.0.0.1".to_string(),
port: None,
2020-12-14 11:02:46 +01:00
}
2021-10-20 12:58:05 +02:00
],
2021-09-19 19:47:29 +02:00
actors,
initiators,
2020-12-14 11:02:46 +01:00
mqtt_url: "tcp://localhost:1883".to_string(),
2020-12-14 12:39:01 +01:00
actor_connections: Box::new([
("Testmachine".to_string(), "Actor".to_string()),
]),
init_connections: Box::new([
("Initiator".to_string(), "Testmachine".to_string()),
]),
2021-09-19 19:47:29 +02:00
db_path: PathBuf::from("/run/bffh/database"),
2021-09-19 22:53:43 +02:00
roles: HashMap::new(),
2020-02-18 16:55:19 +01:00
}
}
}
// The default port in the non-assignable i.e. free-use area
pub const DEFAULT_PORT: u16 = 59661;