v0.1.0
This commit is contained in:
commit
fa432bebda
189 files changed
+26219
No files matched your search
@@ -0,0 +1,37 @@
|
||||
[package]
|
||||
name = "dns-cli"
|
||||
description = "easydns / edns – EasyDNS server and administration CLI"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydns"
|
||||
path = "src/bin/easydns.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "edns"
|
||||
path = "src/bin/edns.rs"
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-authoritative.workspace = true
|
||||
dns-config.workspace = true
|
||||
dns-server.workspace = true
|
||||
dns-api.workspace = true
|
||||
dns-metrics.workspace = true
|
||||
dns-recursive.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
serde_json.workspace = true
|
||||
clap.workspace = true
|
||||
clap_complete.workspace = true
|
||||
clap_mangen.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,11 @@
|
||||
fn main() {
|
||||
let commit = std::process::Command::new("git")
|
||||
.args(["rev-parse", "--short=12", "HEAD"])
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
|
||||
.unwrap_or_else(|| "unknown".into());
|
||||
println!("cargo:rustc-env=EASYDNS_COMMIT={commit}");
|
||||
println!("cargo:rerun-if-changed=../../.git/HEAD");
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_cli::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_cli::main()
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Tiny blocking HTTP/1.1 client for the local admin API (plain HTTP on loopback).
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
pub fn request(method: &str, url: &str, token: Option<&str>, body: Option<&Value>) -> Result<(u16, Value), String> {
|
||||
let rest = url.strip_prefix("http://").ok_or("API URL must start with http:// (use a TLS proxy for remote access)")?;
|
||||
let (hostport, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
|
||||
let path = if path.is_empty() { "/" } else { path };
|
||||
let addr = hostport.to_socket_addrs().map_err(|e| e.to_string())?.next().ok_or("cannot resolve API host")?;
|
||||
let mut s = TcpStream::connect_timeout(&addr, Duration::from_secs(3)).map_err(|e| e.to_string())?;
|
||||
s.set_read_timeout(Some(Duration::from_secs(120))).map_err(|e| e.to_string())?;
|
||||
let body = body.map(|b| b.to_string()).unwrap_or_default();
|
||||
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {hostport}\r\nConnection: close\r\nAccept: application/json\r\n");
|
||||
if let Some(t) = token {
|
||||
req.push_str(&format!("Authorization: Bearer {t}\r\n"));
|
||||
}
|
||||
if !body.is_empty() {
|
||||
req.push_str(&format!("Content-Type: application/json\r\nContent-Length: {}\r\n", body.len()));
|
||||
} else if method != "GET" {
|
||||
req.push_str("Content-Length: 0\r\n");
|
||||
}
|
||||
req.push_str("\r\n");
|
||||
req.push_str(&body);
|
||||
s.write_all(req.as_bytes()).map_err(|e| e.to_string())?;
|
||||
let mut buf = Vec::new();
|
||||
s.read_to_end(&mut buf).map_err(|e| e.to_string())?;
|
||||
let (status, body) = dns_core::tls::parse_http_response_limited(&buf, 64 * 1024 * 1024)
|
||||
.map_err(|e| e.to_string())?
|
||||
.or_else(|| {
|
||||
let p = buf.windows(4).position(|w| w == b"\r\n\r\n")?;
|
||||
let st = std::str::from_utf8(&buf[..p]).ok()?.split_whitespace().nth(1)?.parse().ok()?;
|
||||
Some((st, buf[p + 4..].to_vec()))
|
||||
})
|
||||
.ok_or("invalid HTTP response")?;
|
||||
let v = if body.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
serde_json::from_slice(&body).unwrap_or(Value::String(String::from_utf8_lossy(&body).into()))
|
||||
};
|
||||
Ok((status, v))
|
||||
}
|
||||
@@ -0,0 +1,789 @@
|
||||
//! `easydns` (short: `edns`) – run and administer an EasyDNS server.
|
||||
//!
|
||||
//! Exit codes: 0 ok, 1 runtime/operation error, 2 invalid usage or configuration,
|
||||
//! 3 cannot reach the local API.
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
mod http;
|
||||
mod zonecreate;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::{CommandFactory, Parser, Subcommand};
|
||||
use dns_config::{Config, Overrides};
|
||||
use serde_json::Value;
|
||||
|
||||
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (commit ", env!("EASYDNS_COMMIT"), ")");
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "easydns", version = VERSION, about = "EasyDNS server and administration tool")]
|
||||
struct Cli {
|
||||
/// Configuration file
|
||||
#[arg(short, long, global = true, env = "EASYDNS_CONFIG", default_value = "/etc/easydns/config.yaml")]
|
||||
config: PathBuf,
|
||||
/// API base URL for admin commands (default: from config api.listen)
|
||||
#[arg(long, global = true, env = "EASYDNS_API")]
|
||||
api: Option<String>,
|
||||
/// API bearer token
|
||||
#[arg(long, global = true, env = "EASYDNS_API_TOKEN", hide_env_values = true)]
|
||||
token: Option<String>,
|
||||
/// Output JSON
|
||||
#[arg(long, global = true)]
|
||||
json: bool,
|
||||
#[command(subcommand)]
|
||||
cmd: Cmd,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Cmd {
|
||||
/// Run the server
|
||||
Run {
|
||||
/// Override listen addresses (repeatable)
|
||||
#[arg(long)]
|
||||
listen: Vec<SocketAddr>,
|
||||
#[arg(long)]
|
||||
log_level: Option<String>,
|
||||
#[arg(long)]
|
||||
data_dir: Option<PathBuf>,
|
||||
},
|
||||
/// Validate configuration and zone files offline
|
||||
CheckConfig,
|
||||
/// Configuration helpers
|
||||
Config {
|
||||
#[command(subcommand)]
|
||||
cmd: ConfigCmd,
|
||||
},
|
||||
/// Server status (via API)
|
||||
Status,
|
||||
/// Print version
|
||||
Version,
|
||||
/// Query through the local server (via API)
|
||||
Query {
|
||||
name: String,
|
||||
#[arg(default_value = "A")]
|
||||
rtype: String,
|
||||
},
|
||||
/// Zone management: `zone create` writes files; the rest goes through the API
|
||||
#[command(visible_alias = "zone")]
|
||||
Zones {
|
||||
#[command(subcommand)]
|
||||
cmd: ZonesCmd,
|
||||
},
|
||||
/// Cache management (via API)
|
||||
Cache {
|
||||
#[command(subcommand)]
|
||||
cmd: CacheCmd,
|
||||
},
|
||||
/// Upstream status (via API)
|
||||
Upstreams {
|
||||
#[command(subcommand)]
|
||||
cmd: UpstreamsCmd,
|
||||
},
|
||||
/// Block list maintenance
|
||||
Blocklists {
|
||||
#[command(subcommand)]
|
||||
cmd: BlocklistCmd,
|
||||
},
|
||||
/// Root hints maintenance
|
||||
RootHints {
|
||||
#[command(subcommand)]
|
||||
cmd: RootHintsCmd,
|
||||
},
|
||||
/// DNSSEC key management
|
||||
Dnssec {
|
||||
#[command(subcommand)]
|
||||
cmd: DnssecCmd,
|
||||
},
|
||||
/// Hot-reload configuration (via API)
|
||||
Reload,
|
||||
/// List the EasyDNS diagnostic tools
|
||||
Tools,
|
||||
/// Generate shell completions
|
||||
Completions { shell: clap_complete::Shell },
|
||||
/// Generate a man page
|
||||
Man,
|
||||
/// Print the SHA-256 hash of an API token (for `token: sha256:<hex>`)
|
||||
HashToken { token: String },
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum ConfigCmd {
|
||||
/// Validate (same as check-config)
|
||||
Validate,
|
||||
/// Print the effective configuration (after ENV overrides) as YAML
|
||||
Show,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum ZonesCmd {
|
||||
/// Create a new primary zone with minimal records (SOA, NS, glue) in <data_dir>/zones/
|
||||
Create(zonecreate::CreateArgs),
|
||||
List,
|
||||
Show {
|
||||
zone: String,
|
||||
},
|
||||
Sync {
|
||||
zone: String,
|
||||
},
|
||||
Notify {
|
||||
zone: String,
|
||||
},
|
||||
Transfers {
|
||||
zone: String,
|
||||
},
|
||||
Records {
|
||||
zone: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum CacheCmd {
|
||||
Clear {
|
||||
#[arg(long)]
|
||||
domain: Option<String>,
|
||||
},
|
||||
Stats,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum UpstreamsCmd {
|
||||
List,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum BlocklistCmd {
|
||||
/// Download remote (https) lists into <data_dir>/blocklists and reload
|
||||
Update,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum DnssecCmd {
|
||||
/// Generate a key for a zone (CSK by default)
|
||||
Keygen {
|
||||
#[arg(long)]
|
||||
zone: String,
|
||||
/// Keys directory (zone `dnssec.keys_dir`)
|
||||
#[arg(long)]
|
||||
dir: PathBuf,
|
||||
/// ksk | zsk | csk
|
||||
#[arg(long, default_value = "csk")]
|
||||
role: String,
|
||||
/// ed25519 | ecdsap256 | ecdsap384
|
||||
#[arg(long, default_value = "ed25519")]
|
||||
algorithm: String,
|
||||
},
|
||||
/// Print DS records (for the parent) and DNSKEYs of the keys in a directory
|
||||
Ds {
|
||||
#[arg(long)]
|
||||
zone: String,
|
||||
#[arg(long)]
|
||||
dir: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum RootHintsCmd {
|
||||
/// Download https://www.internic.net/domain/named.root, validate, and replace the hints file
|
||||
Update {
|
||||
#[arg(long, default_value = "https://www.internic.net/domain/named.root")]
|
||||
url: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn load_config(path: &Path) -> Result<Config, ExitCode> {
|
||||
Config::load(path).map_err(|e| {
|
||||
eprintln!("easydns: {e}");
|
||||
ExitCode::from(2)
|
||||
})
|
||||
}
|
||||
|
||||
fn print_check(cfg: &Config, json: bool) -> ExitCode {
|
||||
let findings = dns_server::check::check_config(cfg);
|
||||
let errors = findings.iter().filter(|f| f.severity == "error").count();
|
||||
if json {
|
||||
println!("{}", serde_json::to_string_pretty(&findings).unwrap_or_default());
|
||||
} else {
|
||||
for f in &findings {
|
||||
if f.severity == "error" {
|
||||
eprintln!("{f}");
|
||||
} else {
|
||||
println!("{f}");
|
||||
}
|
||||
}
|
||||
println!("{} error(s), {} warning(s)", errors, findings.iter().filter(|f| f.severity == "warning").count());
|
||||
}
|
||||
if errors > 0 { ExitCode::from(2) } else { ExitCode::SUCCESS }
|
||||
}
|
||||
|
||||
fn running_as_root() -> bool {
|
||||
std::fs::read_to_string("/proc/self/status")
|
||||
.ok()
|
||||
.and_then(|s| s.lines().find(|l| l.starts_with("Uid:")).map(|l| l.split_whitespace().nth(2) == Some("0")))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
async fn run(cli: &Cli, listen: Vec<SocketAddr>, log_level: Option<String>, data_dir: Option<PathBuf>) -> ExitCode {
|
||||
let ov = Overrides { listen, log_level, data_dir, api_listen: None };
|
||||
let cfg = match Config::load_with(&cli.config, &ov) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("easydns: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
dns_metrics::init_logging(&cfg.logging.level, cfg.logging.format == dns_config::LogFormat::Json);
|
||||
if running_as_root() {
|
||||
tracing::warn!("running as root is discouraged: use a dedicated user with CAP_NET_BIND_SERVICE (see deploy/systemd)");
|
||||
}
|
||||
for f in dns_server::check::check_config(&cfg) {
|
||||
match f.severity {
|
||||
"error" => tracing::error!("{f}"),
|
||||
"warning" => tracing::warn!("{f}"),
|
||||
_ => tracing::info!("{f}"),
|
||||
}
|
||||
}
|
||||
let (api_cfg, metrics_cfg) = (cfg.api.clone(), cfg.metrics.clone());
|
||||
let auth = if api_cfg.enabled {
|
||||
match dns_api_auth(&cfg) {
|
||||
Ok(a) => Some(a),
|
||||
Err(e) => {
|
||||
tracing::error!("API configuration: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let server = match dns_server::Server::start(cfg, Some(cli.config.clone()), ov).await {
|
||||
Ok(s) => Arc::new(s),
|
||||
Err(e) => {
|
||||
tracing::error!("startup failed: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
tracing::info!(version = VERSION, "EasyDNS started");
|
||||
if let Some(auth) = auth {
|
||||
let st = Arc::new(dns_api::ApiState { server: Arc::clone(&server), auth });
|
||||
if let Err(e) = dns_api::serve_api(st, api_cfg.listen, server.shutdown_signal()).await {
|
||||
tracing::error!("{e}");
|
||||
server.shutdown().await;
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
}
|
||||
if metrics_cfg.enabled
|
||||
&& let Err(e) = dns_api::serve_metrics(Arc::clone(&server), metrics_cfg.listen, server.shutdown_signal()).await
|
||||
{
|
||||
tracing::error!("{e}");
|
||||
}
|
||||
wait_for_signals(&server).await;
|
||||
tracing::info!("shutting down");
|
||||
server.shutdown().await;
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn dns_api_auth(cfg: &Config) -> Result<dns_api::Auth, String> {
|
||||
dns_api::Auth::from_config(cfg)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
async fn wait_for_signals(server: &dns_server::ServerHandle) {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let (Ok(mut hup), Ok(mut term), Ok(mut int)) =
|
||||
(signal(SignalKind::hangup()), signal(SignalKind::terminate()), signal(SignalKind::interrupt()))
|
||||
else {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
return;
|
||||
};
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = hup.recv() => match server.reload() {
|
||||
Ok(r) => tracing::info!(?r, "reloaded on SIGHUP"),
|
||||
Err(e) => tracing::error!("reload failed, keeping previous configuration: {e}"),
|
||||
},
|
||||
_ = term.recv() => return,
|
||||
_ = int.recv() => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
async fn wait_for_signals(_server: &dns_server::ServerHandle) {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
}
|
||||
|
||||
/// Write a private key: directory 0700, file created 0600 (never briefly readable). When
|
||||
/// run as root, both get the owner of the closest existing parent directory (the
|
||||
/// `easydns` user for `/etc/easydns/data/...`), so the server can read the key.
|
||||
fn write_private_key(dir: &Path, path: &Path, contents: &[u8]) -> std::io::Result<()> {
|
||||
let owner_src = dir.ancestors().find(|a| a.exists()).map(Path::to_path_buf);
|
||||
std::fs::create_dir_all(dir)?;
|
||||
let mut o = std::fs::OpenOptions::new();
|
||||
o.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
o.mode(0o600);
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
|
||||
}
|
||||
std::io::Write::write_all(&mut o.open(path)?, contents)?;
|
||||
#[cfg(unix)]
|
||||
if let Some(meta) = owner_src.and_then(|p| std::fs::metadata(p).ok()) {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
for p in [dir, path] {
|
||||
let _ = std::os::unix::fs::chown(p, Some(meta.uid()), Some(meta.gid()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn api_base(cli: &Cli) -> String {
|
||||
if let Some(a) = &cli.api {
|
||||
return a.trim_end_matches('/').to_string();
|
||||
}
|
||||
let listen = Config::load(&cli.config).map(|c| c.api.listen).unwrap_or_else(|_| SocketAddr::from(([127, 0, 0, 1], 9953)));
|
||||
format!("http://{listen}")
|
||||
}
|
||||
|
||||
/// Token for admin commands: `--token`/`EASYDNS_API_TOKEN`, otherwise the server's local
|
||||
/// control token (`<data_dir>/control.token`, readable by root and the `easydns` group).
|
||||
fn api_token(cli: &Cli) -> Result<Option<String>, ExitCode> {
|
||||
if let Some(t) = &cli.token {
|
||||
return Ok(Some(t.clone()));
|
||||
}
|
||||
let Ok(cfg) = Config::load(&cli.config) else { return Ok(None) };
|
||||
if !cfg.api.local_token {
|
||||
return Ok(None);
|
||||
}
|
||||
let path = cfg.control_token_path();
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(t) => Ok(Some(t.trim().to_string())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
|
||||
eprintln!(
|
||||
"easydns: cannot read {} (permission denied): run with sudo, or add your user to the 'easydns' group",
|
||||
path.display()
|
||||
);
|
||||
Err(ExitCode::from(1))
|
||||
}
|
||||
// server not started yet (token not created) – let the request report the real problem
|
||||
Err(_) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn api(cli: &Cli, method: &str, path: &str, body: Option<&Value>) -> Result<Value, ExitCode> {
|
||||
let url = format!("{}/api/v1{path}", api_base(cli));
|
||||
let token = api_token(cli)?;
|
||||
match http::request(method, &url, token.as_deref(), body) {
|
||||
Ok((status, v)) if (200..300).contains(&status) => Ok(v),
|
||||
Ok((status, v)) => {
|
||||
let msg = v.pointer("/error/message").and_then(Value::as_str).unwrap_or("request failed");
|
||||
eprintln!("easydns: API error {status}: {msg}");
|
||||
Err(ExitCode::from(1))
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("easydns: cannot reach API at {url}: {e}");
|
||||
Err(ExitCode::from(3))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn show(cli: &Cli, v: &Value, human: impl Fn(&Value)) {
|
||||
if cli.json {
|
||||
println!("{}", serde_json::to_string_pretty(v).unwrap_or_default());
|
||||
} else {
|
||||
human(v);
|
||||
}
|
||||
}
|
||||
|
||||
fn s(v: &Value, p: &str) -> String {
|
||||
match v.pointer(p) {
|
||||
Some(Value::String(x)) => x.clone(),
|
||||
Some(Value::Null) | None => "-".into(),
|
||||
Some(o) => o.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn download_blocklists(cli: &Cli) -> ExitCode {
|
||||
let cfg = match load_config(&cli.config) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return e,
|
||||
};
|
||||
let mut rc = ExitCode::SUCCESS;
|
||||
for b in cfg.policy.blocklists.iter().filter(|b| b.enabled) {
|
||||
let Some(url) = &b.url else { continue };
|
||||
match dns_core::tls::https_get(url, Duration::from_secs(60), 64 * 1024 * 1024).await {
|
||||
Ok((200, body)) => {
|
||||
let path = cfg.data_dir().join("blocklists").join(format!("{}.txt", b.name));
|
||||
match dns_core::zonefile::atomic_write(&path, &body) {
|
||||
Ok(()) => println!("{}: {} bytes -> {}", b.name, body.len(), path.display()),
|
||||
Err(e) => {
|
||||
eprintln!("{}: {e}", b.name);
|
||||
rc = ExitCode::from(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((st, _)) => {
|
||||
eprintln!("{}: HTTP {st}", b.name);
|
||||
rc = ExitCode::from(1);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{}: {e}", b.name);
|
||||
rc = ExitCode::from(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if rc == ExitCode::SUCCESS {
|
||||
let _ = api(cli, "POST", "/config/reload", None);
|
||||
}
|
||||
rc
|
||||
}
|
||||
|
||||
async fn update_root_hints(cli: &Cli, url: &str) -> ExitCode {
|
||||
let cfg = match load_config(&cli.config) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return e,
|
||||
};
|
||||
let Some(path) = cfg.recursion.root_hints.as_ref().map(|p| cfg.resolve_path(p)) else {
|
||||
eprintln!("easydns: recursion.root_hints is not set (built-in hints are used)");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
let body = match dns_core::tls::https_get(url, Duration::from_secs(60), 1024 * 1024).await {
|
||||
Ok((200, b)) => b,
|
||||
Ok((st, _)) => {
|
||||
eprintln!("easydns: HTTP {st}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("easydns: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let text = String::from_utf8_lossy(&body).to_string();
|
||||
let servers = match dns_recursive::hints::parse(&text).and_then(|h| dns_recursive::hints::root_servers(&h)) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("easydns: downloaded hints are invalid, keeping the old file: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
if servers.len() < 13 {
|
||||
eprintln!("easydns: only {} root servers in download, refusing to replace hints", servers.len());
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
if let Err(e) = dns_core::zonefile::atomic_write(&path, text.as_bytes()) {
|
||||
eprintln!("easydns: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
println!("root hints updated: {} servers -> {}", servers.len(), path.display());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// Entry point shared by the `easydns` and `edns` binaries.
|
||||
pub fn main() -> ExitCode {
|
||||
let cli = Cli::parse();
|
||||
// one-shot commands only: the server must never exit because of a pipe message
|
||||
if !matches!(cli.cmd, Cmd::Run { .. }) {
|
||||
dns_core::quiet_broken_pipe();
|
||||
}
|
||||
let rt = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
eprintln!("easydns: cannot start runtime: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
rt.block_on(async_main(cli))
|
||||
}
|
||||
|
||||
async fn async_main(cli: Cli) -> ExitCode {
|
||||
match &cli.cmd {
|
||||
Cmd::Run { listen, log_level, data_dir } => run(&cli, listen.clone(), log_level.clone(), data_dir.clone()).await,
|
||||
Cmd::CheckConfig | Cmd::Config { cmd: ConfigCmd::Validate } => match load_config(&cli.config) {
|
||||
Ok(c) => print_check(&c, cli.json),
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Config { cmd: ConfigCmd::Show } => match load_config(&cli.config) {
|
||||
Ok(c) => {
|
||||
println!("{}", serde_json::to_string_pretty(&c).unwrap_or_default());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Version => {
|
||||
println!("easydns {VERSION}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Cmd::Status => match api(&cli, "GET", "/status", None) {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| {
|
||||
println!("EasyDNS {} mode: {} uptime: {}s", s(v, "/version"), s(v, "/mode"), s(v, "/uptime_seconds"));
|
||||
println!("roles: {}", v.pointer("/roles").map(|r| r.to_string()).unwrap_or_default());
|
||||
for z in v.pointer("/zones").and_then(Value::as_array).into_iter().flatten() {
|
||||
println!(
|
||||
" {:<30} {:<10} serial {:<12} {}",
|
||||
s(z, "/name"),
|
||||
s(z, "/kind"),
|
||||
s(z, "/serial"),
|
||||
if z.pointer("/expired") == Some(&Value::Bool(true)) { "EXPIRED" } else { "ok" }
|
||||
);
|
||||
}
|
||||
});
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Query { name, rtype } => match api(&cli, "GET", &format!("/query?name={name}&type={rtype}"), None) {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| {
|
||||
println!(";; rcode {} aa {} ({} ms)", s(v, "/rcode"), s(v, "/aa"), s(v, "/elapsed_ms"));
|
||||
for a in v.pointer("/answers").and_then(Value::as_array).into_iter().flatten() {
|
||||
println!("{}\t{}\tIN\t{}\t{}", s(a, "/name"), s(a, "/ttl"), s(a, "/type"), s(a, "/data"));
|
||||
}
|
||||
});
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Zones { cmd: ZonesCmd::Create(a) } => {
|
||||
let cfg = match Config::load(&cli.config) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
eprintln!("easydns: {e}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
match zonecreate::create(&cfg, &cli.config, a) {
|
||||
Ok(c) => {
|
||||
if a.dry_run {
|
||||
println!("# {} (dry run)\n{}", c.zone_file.display(), c.zone_text);
|
||||
} else {
|
||||
println!("created {}", c.zone_file.display());
|
||||
}
|
||||
match &c.definition_file {
|
||||
Some(f) if !a.dry_run => println!("created {}", f.display()),
|
||||
Some(f) => println!("# {} (dry run)\n{}", f.display(), c.definition),
|
||||
None => println!("\nAdd this to `zones:` in {}:\n{}", cli.config.display(), c.definition),
|
||||
}
|
||||
if a.reload && !a.dry_run {
|
||||
return match api(&cli, "POST", "/config/reload", None) {
|
||||
Ok(_) => {
|
||||
println!("server reloaded");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(code) => code,
|
||||
};
|
||||
}
|
||||
if !a.dry_run {
|
||||
println!("next: easydns check-config && easydns reload");
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("easydns: {e}");
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
Cmd::Zones { cmd } => {
|
||||
let (m, p) = match cmd {
|
||||
ZonesCmd::Create(_) => unreachable!("handled above"),
|
||||
ZonesCmd::List => ("GET", "/zones".to_string()),
|
||||
ZonesCmd::Show { zone } => ("GET", format!("/zones/{zone}")),
|
||||
ZonesCmd::Sync { zone } => ("POST", format!("/zones/{zone}/sync")),
|
||||
ZonesCmd::Notify { zone } => ("POST", format!("/zones/{zone}/notify")),
|
||||
ZonesCmd::Transfers { zone } => ("GET", format!("/zones/{zone}/transfers")),
|
||||
ZonesCmd::Records { zone } => ("GET", format!("/zones/{zone}/records?per_page=1000")),
|
||||
};
|
||||
match api(&cli, m, &p, None) {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| match v.pointer("/items").and_then(Value::as_array) {
|
||||
Some(items) => {
|
||||
for i in items {
|
||||
if i.get("data").is_some() {
|
||||
println!(
|
||||
"{:<18} {}\t{}\t{}\t{}",
|
||||
s(i, "/id"),
|
||||
s(i, "/name"),
|
||||
s(i, "/ttl"),
|
||||
s(i, "/type"),
|
||||
s(i, "/data")
|
||||
);
|
||||
} else if i.get("direction").is_some() {
|
||||
println!(
|
||||
"{} {} {} {} serial {} records {} {}",
|
||||
s(i, "/time_unix"),
|
||||
s(i, "/direction"),
|
||||
s(i, "/kind"),
|
||||
s(i, "/peer"),
|
||||
s(i, "/serial"),
|
||||
s(i, "/records"),
|
||||
if i["ok"] == Value::Bool(true) { "ok".into() } else { s(i, "/error") }
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"{:<30} {:<10} serial {:<12} records {}",
|
||||
s(i, "/name"),
|
||||
s(i, "/kind"),
|
||||
s(i, "/serial"),
|
||||
s(i, "/records")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => println!("{}", serde_json::to_string_pretty(v).unwrap_or_default()),
|
||||
});
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
Cmd::Cache { cmd } => {
|
||||
let r = match cmd {
|
||||
CacheCmd::Clear { domain } => {
|
||||
api(&cli, "DELETE", &domain.as_ref().map(|d| format!("/cache?domain={d}")).unwrap_or_else(|| "/cache".into()), None)
|
||||
}
|
||||
CacheCmd::Stats => api(&cli, "GET", "/cache", None),
|
||||
};
|
||||
match r {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| println!("{}", serde_json::to_string_pretty(v).unwrap_or_default()));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
}
|
||||
}
|
||||
Cmd::Upstreams { cmd: UpstreamsCmd::List } => match api(&cli, "GET", "/upstreams", None) {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| {
|
||||
for g in v.pointer("/items").and_then(Value::as_array).into_iter().flatten() {
|
||||
println!("[{}] strategy {}", s(g, "/group"), s(g, "/strategy"));
|
||||
for sv in g.pointer("/servers").and_then(Value::as_array).into_iter().flatten() {
|
||||
println!(
|
||||
" {:<40} healthy {:<5} rtt {:>8} ms queries {} failures {}",
|
||||
s(sv, "/address"),
|
||||
s(sv, "/stats/healthy"),
|
||||
sv.pointer("/stats/ewma_rtt_ms").and_then(Value::as_f64).map(|x| format!("{x:.1}")).unwrap_or("-".into()),
|
||||
s(sv, "/stats/queries"),
|
||||
s(sv, "/stats/failures")
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Reload => match api(&cli, "POST", "/config/reload", None) {
|
||||
Ok(v) => {
|
||||
show(&cli, &v, |v| println!("reloaded: {v}"));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => e,
|
||||
},
|
||||
Cmd::Blocklists { cmd: BlocklistCmd::Update } => download_blocklists(&cli).await,
|
||||
Cmd::RootHints { cmd: RootHintsCmd::Update { url } } => update_root_hints(&cli, url).await,
|
||||
Cmd::Dnssec { cmd } => dnssec_cmd(cmd),
|
||||
Cmd::Tools => {
|
||||
for (short, long, what) in TOOLS {
|
||||
println!("{short:<8} {long:<14} {what}");
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Cmd::Completions { shell } => {
|
||||
clap_complete::generate(*shell, &mut Cli::command(), "easydns", &mut std::io::stdout());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Cmd::Man => match clap_mangen::Man::new(Cli::command()).render(&mut std::io::stdout()) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(_) => ExitCode::from(1),
|
||||
},
|
||||
Cmd::HashToken { token } => {
|
||||
println!("sha256:{}", dns_api::hash_token(token));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dnssec_cmd(cmd: &DnssecCmd) -> ExitCode {
|
||||
use dns_core::dnssec::{KeyAlgorithm, ZoneKey, key_file_contents, parse_key_file};
|
||||
match cmd {
|
||||
DnssecCmd::Keygen { zone, dir, role, algorithm } => {
|
||||
let Ok(z) = dns_core::names::parse_name(zone) else { return ExitCode::from(2) };
|
||||
let alg: KeyAlgorithm = match serde_json::from_value(Value::String(algorithm.to_ascii_lowercase())) {
|
||||
Ok(a) => a,
|
||||
Err(_) => {
|
||||
eprintln!("easydns: unknown algorithm {algorithm}");
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
let ksk = role != "zsk";
|
||||
let (pk, key) = match ZoneKey::generate(alg, ksk) {
|
||||
Ok(k) => k,
|
||||
Err(e) => {
|
||||
eprintln!("easydns: {e}");
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let prefix = if z.is_root() { "root.".to_string() } else { z.to_ascii().to_ascii_lowercase() };
|
||||
let path = dir.join(format!("{prefix}{}.{}.key", key.tag, role));
|
||||
if let Err(e) = write_private_key(dir, &path, key_file_contents(alg, ksk, &pk).as_bytes()) {
|
||||
eprintln!("easydns: {}: {e}", path.display());
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
println!("created {} (key tag {}, {role})", path.display(), key.tag);
|
||||
if ksk && let Ok(ds) = key.ds_record(&z, 3600) {
|
||||
println!("DS for the parent zone:\n{} {} IN DS {}", ds.name, ds.ttl, ds.data);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
DnssecCmd::Ds { zone, dir } => {
|
||||
let Ok(z) = dns_core::names::parse_name(zone) else { return ExitCode::from(2) };
|
||||
let prefix = if z.is_root() { "root.".to_string() } else { z.to_ascii().to_ascii_lowercase() };
|
||||
let mut found = 0;
|
||||
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
if !name.starts_with(&prefix) || !name.ends_with(".key") {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(e.path()) else { continue };
|
||||
match parse_key_file(&text) {
|
||||
Ok(k) => {
|
||||
found += 1;
|
||||
let dk = k.dnskey_record(&z, 3600);
|
||||
println!("{} {} IN DNSKEY {}", dk.name, dk.ttl, dk.data);
|
||||
if k.ksk
|
||||
&& let Ok(ds) = k.ds_record(&z, 3600)
|
||||
{
|
||||
println!("{} {} IN DS {}", ds.name, ds.ttl, ds.data);
|
||||
}
|
||||
}
|
||||
Err(err) => eprintln!("{}: {err}", e.path().display()),
|
||||
}
|
||||
}
|
||||
if found == 0 {
|
||||
eprintln!("easydns: no keys for {z} in {}", dir.display());
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const TOOLS: &[(&str, &str, &str)] = &[
|
||||
("ed", "easydig", "dig replacement"),
|
||||
("eh", "easyhost", "host replacement"),
|
||||
("ens", "easynslookup", "nslookup replacement (with interactive mode)"),
|
||||
("etrace", "easytrace", "dig +trace: delegation tracing from the root"),
|
||||
("ednssec", "easydnssec", "DNSSEC chain diagnostics (delv-like)"),
|
||||
("eptr", "easyptr", "reverse DNS lookups"),
|
||||
("ezone", "easyzone", "zone file validation (named-checkzone)"),
|
||||
("econf", "easyconf", "configuration validation (named-checkconf)"),
|
||||
("ebench", "easybench", "DNS load testing (dnsperf-like)"),
|
||||
("ewhois", "easywhois", "RDAP/WHOIS lookups"),
|
||||
("edoh", "easydoh", "DNS-over-HTTPS diagnostics"),
|
||||
("edot", "easydot", "DNS-over-TLS diagnostics"),
|
||||
("ediff", "easydiff", "compare answers of several resolvers"),
|
||||
];
|
||||
@@ -0,0 +1,291 @@
|
||||
//! `easydns zone create`: write a minimal, valid primary zone and its definition.
|
||||
//!
|
||||
//! Creates `<data_dir>/zones/<zone>.zone` (SOA, NS, glue for in-zone name servers and
|
||||
//! optional apex addresses) and `<config dir>/zones.d/<zone>.yaml`, which the default
|
||||
//! configuration includes. Nothing is overwritten without `--force`, and the zone is
|
||||
//! parsed and checked before anything is written.
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use dns_config::Config;
|
||||
use dns_core::proto::rr::Name;
|
||||
|
||||
#[derive(clap::Args, Debug, Clone)]
|
||||
pub struct CreateArgs {
|
||||
/// Zone name, e.g. example.com
|
||||
pub zone: String,
|
||||
/// Name server (repeatable). In-zone names need an address: `ns1.example.com=192.0.2.1`.
|
||||
/// Default: ns1.<zone>
|
||||
#[arg(long = "ns", value_name = "NAME[=IP]")]
|
||||
pub ns: Vec<String>,
|
||||
/// Address of the zone apex (`@ A`/`@ AAAA`), repeatable; also used as the glue of a
|
||||
/// default in-zone ns1 without its own address
|
||||
#[arg(long = "ip", value_name = "IP")]
|
||||
pub ip: Vec<IpAddr>,
|
||||
/// Responsible mailbox (`hostmaster@example.com`). Default: hostmaster@<zone>
|
||||
#[arg(long)]
|
||||
pub email: Option<String>,
|
||||
/// Default TTL in seconds
|
||||
#[arg(long, default_value_t = 3600)]
|
||||
pub ttl: u32,
|
||||
/// Secondary allowed to transfer the zone (IP or CIDR, repeatable). No TSIG key needed.
|
||||
#[arg(long = "allow-transfer", value_name = "IP")]
|
||||
pub allow_transfer: Vec<String>,
|
||||
/// Secondary to NOTIFY after changes (IP or IP:port, repeatable)
|
||||
#[arg(long = "notify", value_name = "IP[:PORT]")]
|
||||
pub notify: Vec<String>,
|
||||
/// Allow RFC 2136 updates from these addresses without a key (repeatable)
|
||||
#[arg(long = "allow-update", value_name = "IP")]
|
||||
pub allow_update: Vec<String>,
|
||||
/// Only write the zone file; print the zone definition instead of writing zones.d/
|
||||
#[arg(long)]
|
||||
pub no_config: bool,
|
||||
/// Overwrite existing files
|
||||
#[arg(long)]
|
||||
pub force: bool,
|
||||
/// Print what would be written, change nothing
|
||||
#[arg(long)]
|
||||
pub dry_run: bool,
|
||||
/// Reload the running server afterwards (via the local API)
|
||||
#[arg(long)]
|
||||
pub reload: bool,
|
||||
}
|
||||
|
||||
/// Files produced by `create`.
|
||||
#[derive(Debug)]
|
||||
pub struct Created {
|
||||
pub zone_file: PathBuf,
|
||||
pub zone_text: String,
|
||||
pub definition_file: Option<PathBuf>,
|
||||
pub definition: String,
|
||||
}
|
||||
|
||||
fn fqdn(s: &str) -> Result<Name, String> {
|
||||
let mut n = Name::from_utf8(s.trim()).map_err(|e| format!("invalid name '{s}': {e}"))?;
|
||||
n.set_fqdn(true);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn today_serial() -> u32 {
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
dns_core::serial::next_serial(0, dns_core::serial::SerialStrategy::Date, now).wrapping_add(1)
|
||||
}
|
||||
|
||||
fn notify_addr(s: &str) -> Result<SocketAddr, String> {
|
||||
s.parse::<SocketAddr>()
|
||||
.or_else(|_| s.parse::<IpAddr>().map(|ip| SocketAddr::new(ip, 53)))
|
||||
.map_err(|_| format!("bad --notify address '{s}'"))
|
||||
}
|
||||
|
||||
/// Build the zone text and definition (pure; no file system access).
|
||||
pub fn render(a: &CreateArgs, serial: u32) -> Result<(String, String), String> {
|
||||
let zone = fqdn(&a.zone)?;
|
||||
if zone.is_root() {
|
||||
return Err("refusing to create the root zone".into());
|
||||
}
|
||||
let zname = zone.to_ascii();
|
||||
let bare = zname.trim_end_matches('.');
|
||||
let email = a.email.clone().unwrap_or_else(|| format!("hostmaster@{bare}"));
|
||||
let (local, domain) = email.split_once('@').ok_or("--email must look like user@domain")?;
|
||||
let rname = fqdn(&format!("{}.{}", local.replace('.', "\\."), domain))?;
|
||||
|
||||
let mut ns_list: Vec<(Name, Option<IpAddr>)> = Vec::new();
|
||||
for spec in if a.ns.is_empty() { vec![format!("ns1.{bare}")] } else { a.ns.clone() } {
|
||||
let (n, ip) = match spec.split_once('=') {
|
||||
Some((n, ip)) => (n, Some(ip.parse::<IpAddr>().map_err(|_| format!("bad address in --ns {spec}"))?)),
|
||||
None => (spec.as_str(), None),
|
||||
};
|
||||
ns_list.push((fqdn(n)?, ip));
|
||||
}
|
||||
let mut out = String::new();
|
||||
out.push_str(&format!("; {zname} – created by `easydns zone create`\n$ORIGIN {zname}\n$TTL {}\n", a.ttl));
|
||||
out.push_str(&format!(
|
||||
"@\tIN SOA {} {} (\n\t\t{serial} ; serial\n\t\t3600 ; refresh\n\t\t900 ; retry\n\t\t1209600 ; expire\n\t\t300 ) ; negative TTL\n",
|
||||
ns_list[0].0.to_ascii(),
|
||||
rname.to_ascii()
|
||||
));
|
||||
for (n, _) in &ns_list {
|
||||
out.push_str(&format!("@\tIN NS {}\n", n.to_ascii()));
|
||||
}
|
||||
let mut glue_used_apex = false;
|
||||
for (i, (n, ip)) in ns_list.iter().enumerate() {
|
||||
if !zone.zone_of(n) {
|
||||
continue;
|
||||
}
|
||||
let addrs: Vec<IpAddr> = match ip {
|
||||
Some(ip) => vec![*ip],
|
||||
None if i == 0 && !a.ip.is_empty() => {
|
||||
glue_used_apex = true;
|
||||
a.ip.clone()
|
||||
}
|
||||
None => {
|
||||
return Err(format!(
|
||||
"name server {} is inside the zone and needs an address: --ns {}=<IP>",
|
||||
n.to_ascii().trim_end_matches('.'),
|
||||
n.to_ascii().trim_end_matches('.')
|
||||
));
|
||||
}
|
||||
};
|
||||
let label = if n == &zone { "@".to_string() } else { n.to_ascii().trim_end_matches(&format!(".{zname}")).to_string() };
|
||||
for ip in addrs {
|
||||
out.push_str(&format!("{label}\tIN {} {ip}\n", if ip.is_ipv4() { "A " } else { "AAAA" }));
|
||||
}
|
||||
}
|
||||
for ip in &a.ip {
|
||||
out.push_str(&format!("@\tIN {} {ip}\n", if ip.is_ipv4() { "A " } else { "AAAA" }));
|
||||
}
|
||||
let _ = glue_used_apex;
|
||||
|
||||
let file = format!("zones/{bare}.zone");
|
||||
let mut def = format!("# {bare} – created by `easydns zone create`\n- name: {bare}\n type: primary\n file: {file}\n");
|
||||
let list = |v: &[String]| v.iter().map(|x| format!("\"{x}\"")).collect::<Vec<_>>().join(", ");
|
||||
if !a.allow_transfer.is_empty() {
|
||||
def.push_str(&format!(" transfer_acl: [{}] # IP only; add transfer_tsig_key to require a key\n", list(&a.allow_transfer)));
|
||||
}
|
||||
if !a.notify.is_empty() {
|
||||
let n: Vec<String> = a.notify.iter().map(|s| notify_addr(s).map(|x| x.to_string())).collect::<Result<_, _>>()?;
|
||||
def.push_str(&format!(" notify: [{}]\n", list(&n)));
|
||||
}
|
||||
if !a.allow_update.is_empty() {
|
||||
def.push_str(&format!(" update_acl: [{}] # RFC 2136 without a key\n", list(&a.allow_update)));
|
||||
}
|
||||
Ok((out, def))
|
||||
}
|
||||
|
||||
fn chown_like_parent(path: &Path) {
|
||||
#[cfg(unix)]
|
||||
if let Some(meta) = path.parent().and_then(|p| std::fs::metadata(p).ok()) {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
// as root: give the file to the owner of the directory (the easydns user)
|
||||
let _ = std::os::unix::fs::chown(path, Some(meta.uid()), Some(meta.gid()));
|
||||
}
|
||||
}
|
||||
|
||||
fn write_new(path: &Path, text: &str, force: bool, mode: u32) -> Result<(), String> {
|
||||
if path.exists() && !force {
|
||||
return Err(format!("{} already exists (use --force to overwrite)", path.display()));
|
||||
}
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
dns_core::zonefile::atomic_write(path, text.as_bytes()).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = mode;
|
||||
chown_like_parent(path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create the zone for `cfg` (loaded from `config_path`).
|
||||
pub fn create(cfg: &Config, config_path: &Path, a: &CreateArgs) -> Result<Created, String> {
|
||||
let zone = fqdn(&a.zone)?;
|
||||
let bare = zone.to_ascii().trim_end_matches('.').to_string();
|
||||
if cfg.zones.iter().any(|z| z.name.trim_end_matches('.').eq_ignore_ascii_case(&bare)) && !a.force {
|
||||
return Err(format!("zone {bare} is already defined in the configuration"));
|
||||
}
|
||||
let (text, def) = render(a, today_serial())?;
|
||||
// validate before writing anything
|
||||
let records = dns_core::zonefile::parse_str(&text, &zone, None).map_err(|e| format!("generated zone does not parse: {e}"))?;
|
||||
dns_authoritative::Zone::from_records(&zone, records).map_err(|e| format!("generated zone is invalid: {e}"))?;
|
||||
|
||||
let zone_file = cfg.data_dir().join("zones").join(format!("{bare}.zone"));
|
||||
let conf_dir = config_path.parent().map(Path::to_path_buf).unwrap_or_default();
|
||||
let includes_zones_d = cfg.include.iter().any(|p| p.starts_with("zones.d/"));
|
||||
let definition_file = (!a.no_config && includes_zones_d).then(|| conf_dir.join("zones.d").join(format!("{bare}.yaml")));
|
||||
if !a.dry_run {
|
||||
write_new(&zone_file, &text, a.force, 0o640)?;
|
||||
if let Some(f) = &definition_file {
|
||||
write_new(f, &def, a.force, 0o640)?;
|
||||
}
|
||||
}
|
||||
Ok(Created { zone_file, zone_text: text, definition_file, definition: def })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(zone: &str) -> CreateArgs {
|
||||
CreateArgs {
|
||||
zone: zone.into(),
|
||||
ns: vec![],
|
||||
ip: vec![],
|
||||
email: None,
|
||||
ttl: 3600,
|
||||
allow_transfer: vec![],
|
||||
notify: vec![],
|
||||
allow_update: vec![],
|
||||
no_config: false,
|
||||
force: false,
|
||||
dry_run: false,
|
||||
reload: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn valid(text: &str, zone: &str) -> usize {
|
||||
let z = fqdn(zone).unwrap();
|
||||
let r = dns_core::zonefile::parse_str(text, &z, None).unwrap();
|
||||
let n = r.len();
|
||||
dns_authoritative::Zone::from_records(&z, r).unwrap();
|
||||
n
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_zone_with_glue_from_ip() {
|
||||
let mut a = args("example.com");
|
||||
a.ip = vec!["192.0.2.1".parse().unwrap()];
|
||||
let (t, def) = render(&a, 2026112201).unwrap();
|
||||
assert!(t.contains("@\tIN SOA ns1.example.com. hostmaster.example.com. ("));
|
||||
assert!(t.contains("ns1\tIN A 192.0.2.1"));
|
||||
assert!(t.contains("@\tIN A 192.0.2.1"));
|
||||
assert_eq!(valid(&t, "example.com"), 4); // SOA, NS, glue, apex A
|
||||
assert!(def.contains("file: zones/example.com.zone"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_and_in_zone_name_servers() {
|
||||
let mut a = args("example.org");
|
||||
a.ns = vec!["ns1.example.org=192.0.2.53".into(), "ns2.example.net".into(), "ns3.example.org=2001:db8::53".into()];
|
||||
a.email = Some("dns.admin@example.net".into());
|
||||
a.allow_transfer = vec!["192.0.2.20".into()];
|
||||
a.notify = vec!["192.0.2.20".into()];
|
||||
let (t, def) = render(&a, 1).unwrap();
|
||||
assert!(t.contains("dns\\.admin.example.net."));
|
||||
assert!(t.contains("ns3\tIN AAAA 2001:db8::53"));
|
||||
assert!(!t.contains("ns2\tIN"));
|
||||
assert_eq!(valid(&t, "example.org"), 6);
|
||||
assert!(def.contains("transfer_acl: [\"192.0.2.20\"]") && def.contains("notify: [\"192.0.2.20:53\"]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_zone_ns_without_address_is_an_error() {
|
||||
assert!(render(&args("example.com"), 1).unwrap_err().contains("needs an address"));
|
||||
assert!(render(&args("."), 1).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_files_and_refuses_overwrite() {
|
||||
let d = std::env::temp_dir().join(format!("edns-zc-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let cfgp = d.join("config.yaml");
|
||||
std::fs::write(&cfgp, "include: [\"zones.d/*.yaml\"]\nserver: { data_dir: data }\n").unwrap();
|
||||
let cfg = Config::load(&cfgp).unwrap();
|
||||
let mut a = args("example.com");
|
||||
a.ns = vec!["ns.example.net".into()];
|
||||
let c = create(&cfg, &cfgp, &a).unwrap();
|
||||
assert!(c.zone_file.ends_with("data/zones/example.com.zone") && c.zone_file.is_file());
|
||||
assert!(d.join("zones.d/example.com.yaml").is_file());
|
||||
// the new definition is picked up and the zone loads
|
||||
let cfg2 = Config::load(&cfgp).unwrap();
|
||||
assert_eq!(cfg2.zones.len(), 1);
|
||||
assert!(cfg2.validate().iter().all(|i| !i.is_error()));
|
||||
assert!(create(&cfg, &cfgp, &a).unwrap_err().contains("already exists"));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user