Add RPC endpoint for adding toml configs

This commit is contained in:
Jett Chen 2024-05-12 00:14:31 +08:00
parent ae8ea8ae54
commit dd3f5d0d92
4 changed files with 14 additions and 5 deletions

View file

@ -17,7 +17,7 @@ use crate::{
ServerConfig,
ServerInfo,
},
database::{get_connection, load_interface},
database::{get_connection, load_interface, dump_interface},
wireguard::{Config, Interface},
};
@ -116,7 +116,10 @@ impl DaemonInstance {
.await?;
Ok(DaemonResponseData::None)
}
DaemonCommand::AddConfigToml(interface_id, config_toml) => {
DaemonCommand::AddConfigToml(config_toml) => {
let conn = get_connection(self.db_path.as_deref())?;
let cfig = Config::from_toml(&config_toml)?;
let _if_id = dump_interface(&conn, &cfig)?;
Ok(DaemonResponseData::None)
}
}

View file

@ -10,7 +10,7 @@ pub enum DaemonCommand {
ServerConfig,
Stop,
ReloadConfig(String),
AddConfigToml(String, String),
AddConfigToml(String),
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]

View file

@ -92,7 +92,7 @@ pub fn load_interface(conn: &Connection, interface_id: &str) -> Result<Config> {
Ok(Config { interface: iface, peers })
}
pub fn dump_interface(conn: &Connection, config: &Config) -> Result<()> {
pub fn dump_interface(conn: &Connection, config: &Config) -> Result<i64> {
let mut stmt = conn.prepare("INSERT INTO wg_interface (private_key, dns, address, listen_port, mtu) VALUES (?, ?, ?, ?, ?)")?;
let cif = &config.interface;
stmt.execute(params![
@ -113,7 +113,7 @@ pub fn dump_interface(conn: &Connection, config: &Config) -> Result<()> {
&peer.endpoint
])?;
}
Ok(())
Ok(interface_id)
}
pub fn get_connection(path: Option<&Path>) -> Result<Connection> {

View file

@ -115,6 +115,12 @@ impl Default for Config {
}
}
impl Config {
pub fn from_toml(toml: &str) -> Result<Self> {
toml::from_str(toml).map_err(Into::into)
}
}
#[cfg(test)]
mod tests {
use super::*;