Change to JSONRPC server
This commit is contained in:
parent
17d06a4a35
commit
d1e1944898
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"
|
||||
nest = "1"
|
||||
structopt = "0.2"
|
||||
tokio = { version = "1.5.0", features = ["full"] }
|
||||
tokio-executor = "0.1"
|
||||
tokio-tcp = "0.1.4"
|
||||
tokio-udp = "0.1.4"
|
||||
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"
|
||||
jsonrpc-core = "11"
|
||||
jsonrpc-http-server = "11"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
dotenv = "0.15.0"
|
||||
tera = "1"
|
||||
regex = "1"
|
||||
snafu = "0.6"
|
||||
env_logger = "0.6"
|
||||
|
||||
[package.metadata.deb]
|
||||
depends = "$auto"
|
||||
|
|
|
@ -6,9 +6,9 @@ Type=simple
|
|||
User=peach-dyndns
|
||||
Group=bind
|
||||
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
|
||||
ExecStart=/usr/bin/peach-dyndns-server -vv
|
||||
ExecStart=/usr/bin/peach-dyndns-server
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
|
|
|
@ -1,23 +1,87 @@
|
|||
use std::{error, str};
|
||||
|
||||
use jsonrpc_core::{types::error::Error, ErrorCode};
|
||||
use snafu::Snafu;
|
||||
use std::string::FromUtf8Error;
|
||||
|
||||
pub type BoxError = Box<dyn error::Error>;
|
||||
|
||||
#[derive(Debug, Snafu)]
|
||||
#[snafu(visibility(pub(crate)))]
|
||||
pub enum PeachDynDnsError {
|
||||
|
||||
#[snafu(display("Missing expected parameters: {}", e))]
|
||||
MissingParams { e: Error },
|
||||
|
||||
#[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 }
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PeachDynError {
|
||||
GenerateTsigIoError(std::io::Error),
|
||||
GenerateTsigParseError(std::string::FromUtf8Error),
|
||||
DomainAlreadyExistsError(String),
|
||||
BindConfigurationError(String),
|
||||
InvalidDomainError(String)
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for PeachDynError {
|
||||
fn from(err: std::io::Error) -> PeachDynError {
|
||||
PeachDynError::GenerateTsigIoError(err)
|
||||
|
||||
impl From<PeachDynDnsError> for Error {
|
||||
fn from(err: PeachDynDnsError) -> Self {
|
||||
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: format!("There was a bind configuration error"),
|
||||
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: format!("Error parsing key file"),
|
||||
data: None,
|
||||
},
|
||||
PeachDynDnsError::KeyGenerationError { source: _} => Error {
|
||||
code: ErrorCode::ServerError(-32032),
|
||||
message: format!("Key generation error"),
|
||||
data: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FromUtf8Error> for PeachDynError {
|
||||
fn from(err: std::string::FromUtf8Error) -> PeachDynError {
|
||||
PeachDynError::GenerateTsigParseError(err)
|
||||
}
|
||||
}
|
||||
//#[derive(Debug)]
|
||||
//pub enum PeachDynError {
|
||||
// GenerateTsigIoError(std::io::Error),
|
||||
// GenerateTsigParseError(std::string::FromUtf8Error),
|
||||
// DomainAlreadyExistsError(String),
|
||||
// BindConfigurationError(String),
|
||||
// InvalidDomainError(String)
|
||||
// NetworkError::MissingParams { e } => e.clone(),
|
||||
//}
|
||||
//
|
||||
//impl From<std::io::Error> for PeachDynError {
|
||||
// fn from(err: std::io::Error) -> PeachDynError {
|
||||
// PeachDynError::GenerateTsigIoError(err)
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//impl From<FromUtf8Error> for PeachDynError {
|
||||
// fn from(err: std::string::FromUtf8Error) -> PeachDynError {
|
||||
// PeachDynError::GenerateTsigParseError(err)
|
||||
// }
|
||||
//}
|
|
@ -7,18 +7,20 @@ use std::fs::OpenOptions;
|
|||
use std::io::Write;
|
||||
use std::process::Command;
|
||||
use tera::{Tera, Context};
|
||||
use crate::errors::PeachDynError;
|
||||
use snafu::{ResultExt};
|
||||
use log::{info, error};
|
||||
use crate::errors::*;
|
||||
use crate::constants::DOMAIN_REGEX;
|
||||
|
||||
|
||||
/// 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")
|
||||
.arg("-a")
|
||||
.arg("hmac-md5")
|
||||
.arg(full_domain)
|
||||
.output()?;
|
||||
let key_file_text = String::from_utf8(output.stdout)?;
|
||||
.output().context(KeyGenerationError)?;
|
||||
let key_file_text = String::from_utf8(output.stdout).context(KeyFileParseError)?;
|
||||
Ok(key_file_text)
|
||||
}
|
||||
|
||||
|
@ -65,17 +67,17 @@ 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 minimal zone file to /var/lib/bind/subdomain.dyn.peachcloud.org
|
||||
/// - 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
|
||||
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
|
||||
let is_available = check_domain_available(full_domain);
|
||||
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
|
||||
|
@ -134,7 +136,7 @@ pub fn generate_zone(full_domain: &str) -> Result<String, PeachDynError> {
|
|||
.arg("/usr/bin/reloadbind")
|
||||
.status().expect("error restarting bind9");
|
||||
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
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,152 @@
|
|||
/*
|
||||
* 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
|
||||
*/
|
||||
mod errors;
|
||||
mod generate_zone;
|
||||
mod constants;
|
||||
use crate::generate_zone::{check_domain_available, generate_zone, validate_domain};
|
||||
use std::result::Result;
|
||||
use jsonrpc_core::{types::error::Error, IoHandler, Params, Value};
|
||||
use jsonrpc_http_server::{AccessControlAllowOrigin, DomainsValidation, ServerBuilder};
|
||||
use log::info;
|
||||
use std::env;
|
||||
|
||||
|
||||
use crate::errors::{BoxError, PeachDynDnsError};
|
||||
use serde::{Deserialize};
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct RegisterDomainPost {
|
||||
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) {
|
||||
Ok(_) => Ok(Value::String("success".to_string())),
|
||||
Err(e) => Err(Error::from(e)),
|
||||
},
|
||||
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(())
|
||||
}
|
||||
|
||||
|
||||
|
||||
//
|
||||
//#[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)))
|
||||
// }
|
||||
//}
|
37
src/main.rs
37
src/main.rs
|
@ -1,33 +1,14 @@
|
|||
#![feature(proc_macro_hygiene, decl_macro)]
|
||||
use std::process;
|
||||
|
||||
#[macro_use]
|
||||
extern crate rocket;
|
||||
use log::error;
|
||||
|
||||
use crate::routes::{index, register_domain, check_available};
|
||||
use rocket::figment::{Figment, providers::{Format, Toml, Env}};
|
||||
fn main() {
|
||||
// initalize the logger
|
||||
env_logger::init();
|
||||
|
||||
mod cli;
|
||||
mod routes;
|
||||
mod errors;
|
||||
mod constants;
|
||||
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);
|
||||
// handle errors returned from `run`
|
||||
if let Err(e) = peach_dyndns_server::run() {
|
||||
error!("Application error: {}", e);
|
||||
process::exit(1);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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)))
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue