Change to using jsonrpc instead of reqwest #13
1307
Cargo.lock
generated
1307
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
15
Cargo.toml
15
Cargo.toml
@ -11,18 +11,15 @@ log = "0.4"
|
|||||||
futures = "0.3.1"
|
futures = "0.3.1"
|
||||||
nest = "1"
|
nest = "1"
|
||||||
structopt = "0.2"
|
structopt = "0.2"
|
||||||
tokio = { version = "1.5.0", features = ["full"] }
|
jsonrpc-core = "11"
|
||||||
tokio-executor = "0.1"
|
jsonrpc-http-server = "11"
|
||||||
tokio-tcp = "0.1.4"
|
serde = { version = "1", features = ["derive"] }
|
||||||
tokio-udp = "0.1.4"
|
serde_json = "1"
|
||||||
trust-dns-server = "0.20.2"
|
|
||||||
trust-dns-client = "0.20.2"
|
|
||||||
rocket = { git = "https://github.com/SergioBenitez/Rocket", branch = "master" }
|
|
||||||
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket", branch = "master" }
|
|
||||||
serde = "1.0.125"
|
|
||||||
dotenv = "0.15.0"
|
dotenv = "0.15.0"
|
||||||
tera = "1"
|
tera = "1"
|
||||||
regex = "1"
|
regex = "1"
|
||||||
|
snafu = "0.6"
|
||||||
|
env_logger = "0.6"
|
||||||
|
|
||||||
[package.metadata.deb]
|
[package.metadata.deb]
|
||||||
depends = "$auto"
|
depends = "$auto"
|
||||||
|
4
debian/peach-dyndns-server.service
vendored
4
debian/peach-dyndns-server.service
vendored
@ -6,9 +6,9 @@ Type=simple
|
|||||||
User=peach-dyndns
|
User=peach-dyndns
|
||||||
Group=bind
|
Group=bind
|
||||||
Environment="RUST_LOG=info"
|
Environment="RUST_LOG=info"
|
||||||
Environment="ROCKET_PORT=3002"
|
Environment="PEACH_DYNDNS_SERVER=127.0.0.1:3002"
|
||||||
WorkingDirectory=/srv/peachcloud/peach-dyndns-server/prod-peach-dyndns
|
WorkingDirectory=/srv/peachcloud/peach-dyndns-server/prod-peach-dyndns
|
||||||
ExecStart=/usr/bin/peach-dyndns-server -vv
|
ExecStart=/usr/bin/peach-dyndns-server
|
||||||
Restart=always
|
Restart=always
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
|
0
deploy_prod.sh
Normal file → Executable file
0
deploy_prod.sh
Normal file → Executable file
23
src/cli.rs
23
src/cli.rs
@ -1,23 +0,0 @@
|
|||||||
use structopt::StructOpt;
|
|
||||||
|
|
||||||
#[derive(Debug, StructOpt)]
|
|
||||||
#[structopt(
|
|
||||||
name = "peach-dyndns-host",
|
|
||||||
rename_all = "kebab-case",
|
|
||||||
long_about = "\nTODO",
|
|
||||||
raw(setting = "structopt::clap::AppSettings::ColoredHelp")
|
|
||||||
)]
|
|
||||||
pub struct CliArgs {
|
|
||||||
#[structopt(flatten)]
|
|
||||||
log: clap_log_flag::Log,
|
|
||||||
#[structopt(flatten)]
|
|
||||||
verbose: clap_verbosity_flag::Verbosity,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn args() -> Result<CliArgs, Box<dyn std::error::Error>> {
|
|
||||||
let args = CliArgs::from_args();
|
|
||||||
|
|
||||||
args.log.log_all(Some(args.verbose.log_level()))?;
|
|
||||||
|
|
||||||
Ok(args)
|
|
||||||
}
|
|
@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
// this regex is used to validate that domains are in the correct format
|
// this regex is used to validate that domains are in the correct format
|
||||||
// e.g. blue.dyn.peachcloud.org
|
// e.g. blue.dyn.peachcloud.org
|
||||||
pub const DOMAIN_REGEX: &str = r"^.*\.dyn\.peachcloud\.org$";
|
pub const DOMAIN_REGEX: &str = r"^.*\.dyn\.peachcloud\.org$";
|
||||||
|
@ -1,23 +1,62 @@
|
|||||||
|
use std::{error, str};
|
||||||
|
|
||||||
|
use jsonrpc_core::{types::error::Error, ErrorCode};
|
||||||
|
use snafu::Snafu;
|
||||||
use std::string::FromUtf8Error;
|
use std::string::FromUtf8Error;
|
||||||
|
|
||||||
|
pub type BoxError = Box<dyn error::Error>;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Snafu)]
|
||||||
pub enum PeachDynError {
|
#[snafu(visibility(pub(crate)))]
|
||||||
GenerateTsigIoError(std::io::Error),
|
pub enum PeachDynDnsError {
|
||||||
GenerateTsigParseError(std::string::FromUtf8Error),
|
#[snafu(display("Missing expected parameters: {}", e))]
|
||||||
DomainAlreadyExistsError(String),
|
MissingParams { e: Error },
|
||||||
BindConfigurationError(String),
|
|
||||||
InvalidDomainError(String)
|
#[snafu(display("Domain is in invalid format: {}", domain))]
|
||||||
|
InvalidDomain { domain: String },
|
||||||
|
|
||||||
|
#[snafu(display("There was an error in the bind configuration"))]
|
||||||
|
BindConfigurationError,
|
||||||
|
|
||||||
|
#[snafu(display("This domain was already registered: {}", domain))]
|
||||||
|
DomainAlreadyExistsError { domain: String },
|
||||||
|
|
||||||
|
#[snafu(display("Error parsing key file: {}", source))]
|
||||||
|
KeyFileParseError { source: FromUtf8Error },
|
||||||
|
|
||||||
|
#[snafu(display("Error generating key: {}", source))]
|
||||||
|
KeyGenerationError { source: std::io::Error },
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<std::io::Error> for PeachDynError {
|
impl From<PeachDynDnsError> for Error {
|
||||||
fn from(err: std::io::Error) -> PeachDynError {
|
fn from(err: PeachDynDnsError) -> Self {
|
||||||
PeachDynError::GenerateTsigIoError(err)
|
match &err {
|
||||||
|
PeachDynDnsError::MissingParams { e } => e.clone(),
|
||||||
|
PeachDynDnsError::InvalidDomain { domain } => Error {
|
||||||
|
code: ErrorCode::ServerError(-32028),
|
||||||
|
message: format!("Domain is invalid format: {}", domain),
|
||||||
|
data: None,
|
||||||
|
},
|
||||||
|
PeachDynDnsError::BindConfigurationError => Error {
|
||||||
|
code: ErrorCode::ServerError(-32029),
|
||||||
|
message: "There was a bind configuration error".to_string(),
|
||||||
|
data: None,
|
||||||
|
},
|
||||||
|
PeachDynDnsError::DomainAlreadyExistsError { domain } => Error {
|
||||||
|
code: ErrorCode::ServerError(-32030),
|
||||||
|
message: format!("Can't register domain that already exists: {}", domain),
|
||||||
|
data: None,
|
||||||
|
},
|
||||||
|
PeachDynDnsError::KeyFileParseError { source: _ } => Error {
|
||||||
|
code: ErrorCode::ServerError(-32031),
|
||||||
|
message: "Error parsing key file".to_string(),
|
||||||
|
data: None,
|
||||||
|
},
|
||||||
|
PeachDynDnsError::KeyGenerationError { source: _ } => Error {
|
||||||
|
code: ErrorCode::ServerError(-32032),
|
||||||
|
message: "Key generation error".to_string(),
|
||||||
|
data: None,
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<FromUtf8Error> for PeachDynError {
|
|
||||||
fn from(err: std::string::FromUtf8Error) -> PeachDynError {
|
|
||||||
PeachDynError::GenerateTsigParseError(err)
|
|
||||||
}
|
|
||||||
}
|
|
@ -2,23 +2,25 @@
|
|||||||
* Functions for generating bind9 configurations to enable dynamic dns for a subdomain via TSIG authentication
|
* Functions for generating bind9 configurations to enable dynamic dns for a subdomain via TSIG authentication
|
||||||
* which is unique to that subdomain
|
* which is unique to that subdomain
|
||||||
*/
|
*/
|
||||||
|
use crate::constants::DOMAIN_REGEX;
|
||||||
|
use crate::errors::*;
|
||||||
|
use log::{error, info};
|
||||||
|
use snafu::ResultExt;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::fs::OpenOptions;
|
use std::fs::OpenOptions;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use tera::{Tera, Context};
|
use tera::{Context, Tera};
|
||||||
use crate::errors::PeachDynError;
|
|
||||||
use crate::constants::DOMAIN_REGEX;
|
|
||||||
|
|
||||||
|
|
||||||
/// function to generate the text of a TSIG key file
|
/// function to generate the text of a TSIG key file
|
||||||
pub fn generate_tsig_key(full_domain: &str) -> Result<String, PeachDynError> {
|
pub fn generate_tsig_key(full_domain: &str) -> Result<String, PeachDynDnsError> {
|
||||||
let output = Command::new("/usr/sbin/tsig-keygen")
|
let output = Command::new("/usr/sbin/tsig-keygen")
|
||||||
.arg("-a")
|
.arg("-a")
|
||||||
.arg("hmac-md5")
|
.arg("hmac-md5")
|
||||||
.arg(full_domain)
|
.arg(full_domain)
|
||||||
.output()?;
|
.output()
|
||||||
let key_file_text = String::from_utf8(output.stdout)?;
|
.context(KeyGenerationError)?;
|
||||||
|
let key_file_text = String::from_utf8(output.stdout).context(KeyFileParseError)?;
|
||||||
Ok(key_file_text)
|
Ok(key_file_text)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,23 +40,21 @@ pub fn check_domain_available(full_domain: &str) -> bool {
|
|||||||
let status1 = Command::new("/bin/grep")
|
let status1 = Command::new("/bin/grep")
|
||||||
.arg(full_domain)
|
.arg(full_domain)
|
||||||
.arg("/etc/bind/named.conf.local")
|
.arg("/etc/bind/named.conf.local")
|
||||||
.status().expect("error running grep on /etc/bind/named.conf.local");
|
.status()
|
||||||
|
.expect("error running grep on /etc/bind/named.conf.local");
|
||||||
let code1 = status1.code().expect("error getting code from grep");
|
let code1 = status1.code().expect("error getting code from grep");
|
||||||
let status2 = Command::new("/bin/grep")
|
let status2 = Command::new("/bin/grep")
|
||||||
.arg(full_domain)
|
.arg(full_domain)
|
||||||
.arg("/etc/bind/dyn.peachcloud.org.keys")
|
.arg("/etc/bind/dyn.peachcloud.org.keys")
|
||||||
.status().expect("error running grep on /etc/bind/dyn.peachcloud.org.keys");
|
.status()
|
||||||
|
.expect("error running grep on /etc/bind/dyn.peachcloud.org.keys");
|
||||||
let code2 = status2.code().expect("error getting code from grep");
|
let code2 = status2.code().expect("error getting code from grep");
|
||||||
let condition3 = std::path::Path::new(&format!("/var/lib/bind/{}", full_domain)).exists();
|
let condition3 = std::path::Path::new(&format!("/var/lib/bind/{}", full_domain)).exists();
|
||||||
|
|
||||||
// domain is only available if domain does not exist in either named.conf.local or dyn.peachcloud.orgkeys
|
// domain is only available if domain does not exist in either named.conf.local or dyn.peachcloud.orgkeys
|
||||||
// and a file with that name is not found in /var/lib/bind/
|
// and a file with that name is not found in /var/lib/bind/
|
||||||
// grep returns a status code of 1 if lines are not found, which is why we check that the codes equal 1
|
// grep returns a status code of 1 if lines are not found, which is why we check that the codes equal 1
|
||||||
let domain_available = (code1 == 1) & (code2 == 1) & (!condition3);
|
(code1 == 1) & (code2 == 1) & (!condition3)
|
||||||
|
|
||||||
// return
|
|
||||||
domain_available
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// function which generates all necessary bind configuration to serve the given
|
/// function which generates all necessary bind configuration to serve the given
|
||||||
@ -65,17 +65,20 @@ pub fn check_domain_available(full_domain: &str) -> bool {
|
|||||||
/// - add a zone section to /etc/bind/named.conf.local, associating the key with the subdomain
|
/// - add a zone section to /etc/bind/named.conf.local, associating the key with the subdomain
|
||||||
/// - add a minimal zone file to /var/lib/bind/subdomain.dyn.peachcloud.org
|
/// - add a minimal zone file to /var/lib/bind/subdomain.dyn.peachcloud.org
|
||||||
/// - reload bind and return the secret key to the client
|
/// - reload bind and return the secret key to the client
|
||||||
pub fn generate_zone(full_domain: &str) -> Result<String, PeachDynError> {
|
pub fn generate_zone(full_domain: &str) -> Result<String, PeachDynDnsError> {
|
||||||
|
|
||||||
// first safety check domain is in correct format
|
// first safety check domain is in correct format
|
||||||
if !validate_domain(full_domain) {
|
if !validate_domain(full_domain) {
|
||||||
return Err(PeachDynError::InvalidDomainError(full_domain.to_string()));
|
return Err(PeachDynDnsError::InvalidDomain {
|
||||||
|
domain: full_domain.to_string(),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// safety check if the domain is available
|
// safety check if the domain is available
|
||||||
let is_available = check_domain_available(full_domain);
|
let is_available = check_domain_available(full_domain);
|
||||||
if !is_available {
|
if !is_available {
|
||||||
return Err(PeachDynError::DomainAlreadyExistsError(full_domain.to_string()));
|
return Err(PeachDynDnsError::DomainAlreadyExistsError {
|
||||||
|
domain: full_domain.to_string(),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// generate string with text for TSIG key file
|
// generate string with text for TSIG key file
|
||||||
@ -83,8 +86,10 @@ pub fn generate_zone(full_domain: &str) -> Result<String, PeachDynError> {
|
|||||||
|
|
||||||
// append key_file_text to /etc/bind/dyn.peachcloud.org.keys
|
// append key_file_text to /etc/bind/dyn.peachcloud.org.keys
|
||||||
let key_file_path = "/etc/bind/dyn.peachcloud.org.keys";
|
let key_file_path = "/etc/bind/dyn.peachcloud.org.keys";
|
||||||
let mut file = OpenOptions::new().append(true).open(key_file_path)
|
let mut file = OpenOptions::new()
|
||||||
.expect(&format!("failed to open {}", key_file_path));
|
.append(true)
|
||||||
|
.open(key_file_path)
|
||||||
|
.unwrap_or_else(|_| panic!("failed to open {}", key_file_path));
|
||||||
if let Err(e) = writeln!(file, "{}", key_file_text) {
|
if let Err(e) = writeln!(file, "{}", key_file_text) {
|
||||||
error!("Couldn't write to file: {}", e);
|
error!("Couldn't write to file: {}", e);
|
||||||
}
|
}
|
||||||
@ -94,7 +99,7 @@ pub fn generate_zone(full_domain: &str) -> Result<String, PeachDynError> {
|
|||||||
let mut file = OpenOptions::new()
|
let mut file = OpenOptions::new()
|
||||||
.append(true)
|
.append(true)
|
||||||
.open(bind_conf_path)
|
.open(bind_conf_path)
|
||||||
.expect(&format!("failed to open {}", bind_conf_path));
|
.unwrap_or_else(|_| panic!("failed to open {}", bind_conf_path));
|
||||||
let zone_section_text = format!(
|
let zone_section_text = format!(
|
||||||
"\
|
"\
|
||||||
zone \"{full_domain}\" {{
|
zone \"{full_domain}\" {{
|
||||||
@ -107,7 +112,8 @@ pub fn generate_zone(full_domain: &str) -> Result<String, PeachDynError> {
|
|||||||
",
|
",
|
||||||
full_domain = full_domain
|
full_domain = full_domain
|
||||||
);
|
);
|
||||||
writeln!(file, "{}", zone_section_text).expect(&format!("Couldn't write to file: {}", bind_conf_path));
|
writeln!(file, "{}", zone_section_text)
|
||||||
|
.unwrap_or_else(|_| panic!("Couldn't write to file: {}", bind_conf_path));
|
||||||
|
|
||||||
// use tera to render the zone file
|
// use tera to render the zone file
|
||||||
let tera = match Tera::new("templates/*.tera") {
|
let tera = match Tera::new("templates/*.tera") {
|
||||||
@ -119,22 +125,26 @@ pub fn generate_zone(full_domain: &str) -> Result<String, PeachDynError> {
|
|||||||
};
|
};
|
||||||
let mut context = Context::new();
|
let mut context = Context::new();
|
||||||
context.insert("full_domain", full_domain);
|
context.insert("full_domain", full_domain);
|
||||||
let result = tera.render("zonefile.tera", &context).expect("error loading zonefile.tera");
|
let result = tera
|
||||||
|
.render("zonefile.tera", &context)
|
||||||
|
.expect("error loading zonefile.tera");
|
||||||
|
|
||||||
// write new zone file to /var/lib/bind
|
// write new zone file to /var/lib/bind
|
||||||
let zone_file_path = format!("/var/lib/bind/{}", full_domain);
|
let zone_file_path = format!("/var/lib/bind/{}", full_domain);
|
||||||
let mut file = File::create(&zone_file_path)
|
let mut file = File::create(&zone_file_path)
|
||||||
.expect(&format!("failed to create {}", zone_file_path));
|
.unwrap_or_else(|_| panic!("failed to create {}", zone_file_path));
|
||||||
writeln!(file, "{}", result).expect(&format!("Couldn't write to file: {}", zone_file_path));
|
writeln!(file, "{}", result)
|
||||||
|
.unwrap_or_else(|_| panic!("Couldn't write to file: {}", zone_file_path));
|
||||||
|
|
||||||
// restart bind
|
// restart bind
|
||||||
// we use the /etc/sudoers.d/bindctl to allow peach-dyndns user to restart bind as sudo without entering a password
|
// we use the /etc/sudoers.d/bindctl to allow peach-dyndns user to restart bind as sudo without entering a password
|
||||||
// using a binary at /bin/reloadbind which runs 'systemctl reload bind9'
|
// using a binary at /bin/reloadbind which runs 'systemctl reload bind9'
|
||||||
let status = Command::new("sudo")
|
let status = Command::new("sudo")
|
||||||
.arg("/usr/bin/reloadbind")
|
.arg("/usr/bin/reloadbind")
|
||||||
.status().expect("error restarting bind9");
|
.status()
|
||||||
|
.expect("error restarting bind9");
|
||||||
if !status.success() {
|
if !status.success() {
|
||||||
return Err(PeachDynError::BindConfigurationError("There was an error in the bind configuration".to_string()));
|
return Err(PeachDynDnsError::BindConfigurationError);
|
||||||
// TODO: for extra safety consider to revert bind configurations to whatever they were before
|
// TODO: for extra safety consider to revert bind configurations to whatever they were before
|
||||||
}
|
}
|
||||||
|
|
||||||
|
90
src/lib.rs
Normal file
90
src/lib.rs
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
/*
|
||||||
|
* LIST OF METHODS
|
||||||
|
* register_domain (add a new domain and get back the TSIG key for subsequent updating with nsupdate)
|
||||||
|
* is_domain_available (check if given domain is available and return boolean result)
|
||||||
|
* NOT IMPLEMENTED- register_user (sends an email verification to create a new account)
|
||||||
|
* NOT IMPLEMENTED- verify_user (for clicking the link in the email)
|
||||||
|
*/
|
||||||
|
mod constants;
|
||||||
|
mod errors;
|
||||||
|
mod generate_zone;
|
||||||
|
use crate::generate_zone::{check_domain_available, generate_zone, validate_domain};
|
||||||
|
use jsonrpc_core::{types::error::Error, IoHandler, Params, Value};
|
||||||
|
use jsonrpc_http_server::{AccessControlAllowOrigin, DomainsValidation, ServerBuilder};
|
||||||
|
use log::info;
|
||||||
|
use std::env;
|
||||||
|
use std::result::Result;
|
||||||
|
|
||||||
|
use crate::errors::{BoxError, PeachDynDnsError};
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
#[derive(Deserialize, Debug)]
|
||||||
|
pub struct RegisterDomainPost {
|
||||||
|
domain: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Debug)]
|
||||||
|
pub struct IsDomainAvailablePost {
|
||||||
|
domain: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create JSON-RPC I/O handler, add RPC methods and launch HTTP server.
|
||||||
|
pub fn run() -> Result<(), BoxError> {
|
||||||
|
info!("Starting up.");
|
||||||
|
|
||||||
|
info!("Creating JSON-RPC I/O handler.");
|
||||||
|
let mut io = IoHandler::new();
|
||||||
|
|
||||||
|
io.add_method("ping", |_| Ok(Value::String("success".to_string())));
|
||||||
|
|
||||||
|
io.add_method("register_domain", move |params: Params| {
|
||||||
|
let d: Result<RegisterDomainPost, Error> = params.parse();
|
||||||
|
match d {
|
||||||
|
Ok(d) => match generate_zone(&d.domain) {
|
||||||
|
// returns full TSIG key text to new zone as part of success result
|
||||||
|
Ok(key_text) => Ok(Value::String(key_text)),
|
||||||
|
Err(e) => Err(Error::from(e)),
|
||||||
|
},
|
||||||
|
Err(e) => Err(Error::from(PeachDynDnsError::MissingParams { e })),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
io.add_method("is_domain_available", move |params: Params| {
|
||||||
|
let d: Result<IsDomainAvailablePost, Error> = params.parse();
|
||||||
|
match d {
|
||||||
|
Ok(d) => {
|
||||||
|
// if the domain has an invalid format return an erro
|
||||||
|
if !validate_domain(&d.domain) {
|
||||||
|
Err(Error::from(PeachDynDnsError::InvalidDomain {
|
||||||
|
domain: d.domain,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
// if it has a valid format, check if its available
|
||||||
|
else {
|
||||||
|
let result = check_domain_available(&d.domain);
|
||||||
|
Ok(Value::String(result.to_string()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => Err(Error::from(PeachDynDnsError::MissingParams { e })),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let http_server =
|
||||||
|
env::var("PEACH_DYNDNS_SERVER").unwrap_or_else(|_| "127.0.0.1:3001".to_string());
|
||||||
|
|
||||||
|
info!("Starting JSON-RPC server on {}.", http_server);
|
||||||
|
let server = ServerBuilder::new(io)
|
||||||
|
.cors(DomainsValidation::AllowOnly(vec![
|
||||||
|
AccessControlAllowOrigin::Null,
|
||||||
|
]))
|
||||||
|
.start_http(
|
||||||
|
&http_server
|
||||||
|
.parse()
|
||||||
|
.expect("Invalid HTTP address and port combination"),
|
||||||
|
)
|
||||||
|
.expect("Unable to start RPC server");
|
||||||
|
|
||||||
|
server.wait();
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
37
src/main.rs
37
src/main.rs
@ -1,33 +1,14 @@
|
|||||||
#![feature(proc_macro_hygiene, decl_macro)]
|
use std::process;
|
||||||
|
|
||||||
#[macro_use]
|
use log::error;
|
||||||
extern crate rocket;
|
|
||||||
|
|
||||||
use crate::routes::{index, register_domain, check_available};
|
fn main() {
|
||||||
use rocket::figment::{Figment, providers::{Format, Toml, Env}};
|
// initalize the logger
|
||||||
|
env_logger::init();
|
||||||
|
|
||||||
mod cli;
|
// handle errors returned from `run`
|
||||||
mod routes;
|
if let Err(e) = peach_dyndns_server::run() {
|
||||||
mod errors;
|
error!("Application error: {}", e);
|
||||||
mod constants;
|
process::exit(1);
|
||||||
mod generate_zone;
|
|
||||||
|
|
||||||
#[tokio::main]
|
|
||||||
async fn main() {
|
|
||||||
let _args = cli::args().expect("error parsing args");
|
|
||||||
|
|
||||||
// the following config says to use all default rocket configs
|
|
||||||
// and then override them with any configs specified in Rocket.toml if found
|
|
||||||
// and then override with any configs specified as env variables prefixed with APP_
|
|
||||||
let config = Figment::from(rocket::Config::default())
|
|
||||||
.merge(Toml::file("Rocket.toml").nested()).merge(Env::prefixed("ROCKET_").global());
|
|
||||||
|
|
||||||
let rocket_result = rocket::custom(config)
|
|
||||||
.mount("/", routes![index, register_domain, check_available])
|
|
||||||
.launch()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
if let Err(err) = rocket_result {
|
|
||||||
error!("++ error launching rocket server: {:?}", err);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,94 +0,0 @@
|
|||||||
/*
|
|
||||||
* LIST OF ROUTES
|
|
||||||
* /domain/register (add a new domain and get back the TSIG key for subsequent updating with nsupdate)
|
|
||||||
* /domain/check-available (check if given domain is available)
|
|
||||||
* /user/register sends an email verification to create a new account) NOT IMPLEMENTED
|
|
||||||
* /user/verify (for clicking the link in the email) NOT IMPLEMENTED
|
|
||||||
*/
|
|
||||||
use crate::generate_zone::{check_domain_available, generate_zone, validate_domain};
|
|
||||||
use rocket_contrib::json::{Json, JsonValue};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[get("/")]
|
|
||||||
pub fn index() -> &'static str {
|
|
||||||
"This is the peach-dyndns server."
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
|
||||||
pub struct JsonResponse {
|
|
||||||
pub status: String,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub data: Option<JsonValue>,
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub msg: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// helper function to build a JsonResponse object
|
|
||||||
pub fn build_json_response(
|
|
||||||
status: String,
|
|
||||||
data: Option<JsonValue>,
|
|
||||||
msg: Option<String>,
|
|
||||||
) -> JsonResponse {
|
|
||||||
JsonResponse { status, data, msg }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
|
||||||
pub struct RegisterDomainPost {
|
|
||||||
domain: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[post("/domain/register", data = "<data>")]
|
|
||||||
pub async fn register_domain(data: Json<RegisterDomainPost>) -> Json<JsonResponse> {
|
|
||||||
info!("++ post request to register new domain: {:?}", data);
|
|
||||||
// TODO: grab/create a mutex, so that only one rocket thread is calling register_domain at a time
|
|
||||||
// check if its a valid domain
|
|
||||||
if !validate_domain(&data.domain) {
|
|
||||||
let status = "error".to_string();
|
|
||||||
let msg = "domain is not in a valid format".to_string();
|
|
||||||
Json(build_json_response(status, None, Some(msg)))
|
|
||||||
} else {
|
|
||||||
// check if the domain is available
|
|
||||||
let is_domain_available = check_domain_available(&data.domain);
|
|
||||||
if !is_domain_available {
|
|
||||||
let status = "error".to_string();
|
|
||||||
let msg = "can't register a domain that is already registered".to_string();
|
|
||||||
Json(build_json_response(status, None, Some(msg)))
|
|
||||||
} else {
|
|
||||||
// generate configs for the zone
|
|
||||||
let result = generate_zone(&data.domain);
|
|
||||||
match result {
|
|
||||||
Ok(key_file_text) => {
|
|
||||||
let status = "success".to_string();
|
|
||||||
let msg = key_file_text.to_string();
|
|
||||||
Json(build_json_response(status, None, Some(msg)))
|
|
||||||
}
|
|
||||||
Err(_err) => {
|
|
||||||
let status = "error".to_string();
|
|
||||||
let msg = "there was an error creating the zone file".to_string();
|
|
||||||
Json(build_json_response(status, None, Some(msg)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
|
||||||
pub struct CheckAvailableDomainPost {
|
|
||||||
domain: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
// route which returns a msg of "true" if the domain is available and "false" if it is already taken
|
|
||||||
#[post("/domain/check-available", data = "<data>")]
|
|
||||||
pub async fn check_available(data: Json<CheckAvailableDomainPost>) -> Json<JsonResponse> {
|
|
||||||
info!("post request to check if domain is available {:?}", data);
|
|
||||||
if !validate_domain(&data.domain) {
|
|
||||||
let status = "error".to_string();
|
|
||||||
let msg = "domain is not in a valid format".to_string();
|
|
||||||
Json(build_json_response(status, None, Some(msg)))
|
|
||||||
} else {
|
|
||||||
let status = "success".to_string();
|
|
||||||
let is_available = check_domain_available(&data.domain);
|
|
||||||
let msg = is_available.to_string();
|
|
||||||
Json(build_json_response(status, None, Some(msg)))
|
|
||||||
}
|
|
||||||
}
|
|
Reference in New Issue
Block a user