rewrite in rust

This commit is contained in:
Infendro committed 2026-08-29 14:36:14 +02:00
1 parent aa7f37500f
commit 540d990aeb
35 files changed
+1949 -1557

No files matched your search

@@ -1,11 +0,0 @@
package com.infendro.ddns
import io.ktor.client.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
val http = HttpClient {
install(ContentNegotiation) {
json()
}
}
@@ -1,5 +0,0 @@
package com.infendro.ddns
import com.infendro.ddns.command.ddns
fun main(args: Array<String>) = ddns.run(*args)
@@ -1,12 +0,0 @@
package com.infendro.ddns.command
import com.infendro.cli.command.argument.argument
import com.infendro.cli.command.option.option
import com.infendro.ddns.ip.ipify.Ipify
import com.infendro.ddns.command.parameter.ipService
internal object Parameters {
val DOMAIN = argument.string("domain")
val SUBDOMAINS = argument.string("subdomains").variable(min = 1)
val IP_SERVICE = option.ipService("ip-service").orElse(Ipify)
}
@@ -1,9 +0,0 @@
package com.infendro.ddns.command
import com.infendro.cli.command.command
val ddns = command("ddns") {
execute { help() }
+update
+porkbun
}
@@ -1,25 +0,0 @@
package com.infendro.ddns.command.parameter
import com.infendro.cli.command.argument.ArgumentFactory
import com.infendro.cli.command.argument.argument
import com.infendro.cli.command.option.OptionFactory
import com.infendro.cli.command.option.option
import com.infendro.cli.parser.Parser
import com.infendro.ddns.ip.IpService
import com.infendro.ddns.ip.ipify.Ipify
object IpServiceParser : Parser<IpService>(IpService::class) {
override fun parse(text: String): Result<IpService> {
val service = when (text) {
"ipify" -> Ipify
else -> return failure(text)
}
return success(service)
}
}
fun ArgumentFactory.ipService(name: String, description: String? = null) =
argument(IpServiceParser, name, description)
fun OptionFactory.ipService(vararg names: String, description: String? = null) =
option(IpServiceParser, *names, description = description)
@@ -1,19 +0,0 @@
package com.infendro.ddns.command.parameter
import com.infendro.cli.command.argument.ArgumentFactory
import com.infendro.cli.command.argument.argument
import com.infendro.cli.command.option.OptionFactory
import com.infendro.cli.command.option.option
import com.infendro.cli.parser.Parser
import kotlinx.io.files.Path
object PathParser : Parser<Path>(Path::class) {
override fun parse(text: String) =
success(Path(text))
}
fun ArgumentFactory.path(name: String, description: String? = null) =
argument(PathParser, name, description)
fun OptionFactory.path(vararg names: String, description: String? = null) =
option(PathParser, *names, description = description)
@@ -1,29 +0,0 @@
package com.infendro.ddns.command
import com.infendro.cli.command.command
import com.infendro.cli.command.option.option
import com.infendro.ddns.command.Parameters.DOMAIN
import com.infendro.ddns.command.Parameters.IP_SERVICE
import com.infendro.ddns.command.Parameters.SUBDOMAINS
import com.infendro.ddns.dns.porkbun.Porkbun
val porkbun = command("porkbun") {
execute { help() }
+command("update") {
val key = +option.string("key")
val secretKey = +option.string("secret-key")
register(DOMAIN, SUBDOMAINS)
register(IP_SERVICE)
execute {
val key by key
val secretKey by secretKey
val domain by DOMAIN
val subdomains by SUBDOMAINS
val ipService by IP_SERVICE
Porkbun(key, secretKey).update(domain, subdomains, ipService)
}
}
}
@@ -1,35 +0,0 @@
package com.infendro.ddns.command
import com.infendro.cli.command.command
import com.infendro.cli.command.option.option
import com.infendro.ddns.config.Config
import com.infendro.ddns.ip.ipify.Ipify
import com.infendro.ddns.command.parameter.path
import kotlinx.io.buffered
import kotlinx.io.files.Path
import kotlinx.io.files.SystemFileSystem
import kotlinx.io.readString
import kotlinx.serialization.json.Json
val update = command("update") {
val config = +option.path("config").orElse(Path("/etc/ddns.conf"))
execute {
val config by config
val source = SystemFileSystem.source(config).buffered()
val text = source.readString()
val entries: List<Config.Entry> = Json.decodeFromString(text)
update(entries)
}
}
private fun update(entries: List<Config.Entry>) {
for (entry in entries) {
val domain = entry.domain
val subdomains = entry.subdomains
val ipService = entry.ipService ?: Ipify
entry.dnsService.update(domain, subdomains, ipService)
}
}
@@ -1,29 +0,0 @@
package com.infendro.ddns.config
import com.infendro.ddns.dns.DnsService
import com.infendro.ddns.ip.IpService
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
interface Config {
@Serializable
sealed class Entry {
abstract val domain: String
abstract val subdomains: List<String>
abstract val ipService: IpService?
abstract val dnsService: DnsService
@Serializable
@SerialName("porkbun")
class Porkbun(
val key: String,
val secretKey: String,
override val domain: String,
override val subdomains: List<String>,
@Serializable(with = IpServiceSerializer::class)
override val ipService: IpService? = null,
) : Entry() {
override val dnsService: DnsService = com.infendro.ddns.dns.porkbun.Porkbun(key, secretKey)
}
}
}
@@ -1,25 +0,0 @@
package com.infendro.ddns.config
import com.infendro.ddns.ip.IpService
import com.infendro.ddns.ip.ipify.Ipify
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
object IpServiceSerializer : KSerializer<IpService> {
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("IpService", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: IpService) = throw NotImplementedError()
override fun deserialize(decoder: Decoder): IpService {
val value = decoder.decodeString()
return when (value) {
"ipify" -> Ipify
else -> throw Exception()
}
}
}
@@ -1,30 +0,0 @@
package com.infendro.ddns.dns
import com.infendro.ddns.dns.model.DnsRecord
import com.infendro.ddns.ip.IpService
interface DnsService {
fun getRecords(domain: String, subdomains: List<String>): List<DnsRecord>
fun updateRecord(record: DnsRecord, value: String)
fun updateRecords(records: List<DnsRecord>, value: String) {
for (record in records) {
if (record.value == value) continue
updateRecord(record, value)
}
}
fun update(domain: String, subdomains: List<String>, ipService: IpService) {
val (ipv4, ipv6) = ipService.ip
val records = getRecords(domain, subdomains)
val aRecords = records
.filter { it.type == DnsRecord.Type.A }
val aaaaRecords = records
.filter { it.type == DnsRecord.Type.AAAA }
updateRecords(aRecords, ipv4)
updateRecords(aaaaRecords, ipv6)
}
}
@@ -1,30 +0,0 @@
package com.infendro.ddns.dns.model
data class DnsRecord(
val id: String,
val type: Type,
val domain: Domain,
val value: String,
val ttl: Int,
val priority: Int?,
) {
data class Domain(
val subdomain: String?,
val domain: String,
) {
val full: String
get() = when {
subdomain != null -> "$subdomain.$domain"
else -> domain
}
}
enum class Type {
NS, A, AAAA, CNAME, MX, TXT;
companion object {
val address: List<Type>
get() = listOf(A, AAAA)
}
}
}
@@ -1,64 +0,0 @@
package com.infendro.ddns.dns.porkbun
import com.infendro.ddns.dns.DnsService
import com.infendro.ddns.dns.model.DnsRecord
import com.infendro.ddns.dns.porkbun.dto.request.GetRecordsRequest
import com.infendro.ddns.dns.porkbun.dto.request.UpdateRecordRequest
import com.infendro.ddns.dns.porkbun.dto.response.GetRecordsResponse
import com.infendro.ddns.http
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import kotlinx.coroutines.runBlocking
class Porkbun(
val key: String,
val secretkey: String,
) : DnsService {
override fun getRecords(domain: String, subdomains: List<String>): List<DnsRecord> = runBlocking {
val response = http.post("https://api.porkbun.com/api/json/v3/dns/retrieve/$domain") {
val request = GetRecordsRequest(
apikey = key,
secretapikey = secretkey,
)
contentType(ContentType.Application.Json)
setBody(request)
}
val body = response.body<GetRecordsResponse>()
body.records
.map {
val labels = it.name.split('.')
val subdomain = labels.dropLast(2).joinToString(".")
val domain = labels.takeLast(2).joinToString(".")
DnsRecord(
id = it.id,
type = DnsRecord.Type.valueOf(it.type),
domain = DnsRecord.Domain(
subdomain = subdomain,
domain = domain,
),
value = it.content,
ttl = it.ttl.toInt(),
priority = it.prio?.toInt(),
)
}
.filter { it.type in DnsRecord.Type.address && (it.domain.subdomain ?: "") in subdomains }
}
override fun updateRecord(record: DnsRecord, value: String): Unit = runBlocking {
http.post("https://api.porkbun.com/api/json/v3/dns/edit/${record.domain.domain}/${record.id}") {
val request = UpdateRecordRequest(
apikey = key,
secretapikey = secretkey,
type = record.type.toString(),
name = record.domain.subdomain ?: "",
content = value,
ttl = record.ttl.toString(),
)
contentType(ContentType.Application.Json)
setBody(request)
}
}
}
@@ -1,9 +0,0 @@
package com.infendro.ddns.dns.porkbun.dto.request
import kotlinx.serialization.Serializable
@Serializable
data class GetRecordsRequest(
val apikey: String,
val secretapikey: String,
)
@@ -1,13 +0,0 @@
package com.infendro.ddns.dns.porkbun.dto.request
import kotlinx.serialization.Serializable
@Serializable
data class UpdateRecordRequest(
val apikey: String,
val secretapikey: String,
val type: String,
val name: String,
val content: String,
val ttl: String,
)
@@ -1,21 +0,0 @@
package com.infendro.ddns.dns.porkbun.dto.response
import kotlinx.serialization.Serializable
@Serializable
data class GetRecordsResponse(
val status: String,
val cloudflare: String,
val records: Array<Record>,
) {
@Serializable
data class Record(
val id: String,
val type: String,
val name: String,
val content: String,
val ttl: String,
val prio: String?,
val notes: String?,
)
}
@@ -1,9 +0,0 @@
package com.infendro.ddns.ip
interface IpService {
val ipv4: String
val ipv6: String
val ip: Pair<String, String>
get() = Pair(ipv4, ipv6)
}
@@ -1,24 +0,0 @@
package com.infendro.ddns.ip.ipify
import com.infendro.ddns.http
import com.infendro.ddns.ip.IpService
import com.infendro.ddns.ip.ipify.dto.response.GetIpResponse
import io.ktor.client.call.*
import io.ktor.client.request.*
import kotlinx.coroutines.runBlocking
object Ipify : IpService {
override val ipv4: String
get() = runBlocking {
val response = http.get("https://api4.ipify.org?format=json")
val body = response.body<GetIpResponse>()
body.ip
}
override val ipv6: String
get() = runBlocking {
val response = http.get("https://api6.ipify.org?format=json")
val body = response.body<GetIpResponse>()
body.ip
}
}
@@ -1,8 +0,0 @@
package com.infendro.ddns.ip.ipify.dto.response
import kotlinx.serialization.Serializable
@Serializable
data class GetIpResponse(
val ip: String,
)
+27
View File
@@ -0,0 +1,27 @@
use serde::Deserialize;
use std::{error::Error, fs};
#[derive(Deserialize)]
pub struct Config {
#[serde(flatten)]
pub auth: Auth,
pub entries: Vec<Entry>,
}
#[derive(Deserialize)]
pub struct Auth {
pub key: String,
pub secret_key: String,
}
#[derive(Deserialize)]
pub struct Entry {
pub domain: String,
pub subdomains: Vec<String>,
}
pub fn load(path: &str) -> Result<Config, Box<dyn Error>> {
let raw = fs::read_to_string(&path)?;
let config = serde_json::from_str(&raw)?;
Ok(config)
}
+93
View File
@@ -0,0 +1,93 @@
use std::error::Error;
use reqwest::Client;
use serde::Deserialize;
use serde_json::json;
use crate::config::Auth;
pub struct Record {
pub id: String,
pub record_type: String,
pub domain: String,
pub subdomain: String,
pub value: String,
pub ttl: String,
}
const API: &str = "https://api.porkbun.com/api/json/v3";
#[derive(Deserialize)]
struct RecordsResponse {
records: Vec<RecordResponse>,
}
#[derive(Deserialize)]
struct RecordResponse {
id: String,
#[serde(rename = "type")]
record_type: String,
name: String,
content: String,
ttl: String,
}
impl RecordResponse {
fn into_model(self, domain: &str) -> Record {
let subdomain = self.name
.strip_suffix(domain).unwrap()
.strip_suffix(".").unwrap_or("");
Record {
id: self.id,
record_type: self.record_type,
domain: domain.to_string(),
subdomain: subdomain.to_string(),
value: self.content,
ttl: self.ttl,
}
}
}
pub async fn get_records(
client: &Client,
auth: &Auth,
domain: &str,
) -> Result<Vec<Record>, Box<dyn Error>> {
let body = json!({
"apikey": auth.key,
"secretapikey": auth.secret_key,
});
let request = client.post(format!("{API}/dns/retrieve/{domain}"))
.json(&body)
.send().await?;
let response = request.json::<RecordsResponse>().await?;
let records = response.records
.into_iter()
.map(|it| it.into_model(domain))
.collect();
Ok(records)
}
pub async fn update_record(
client: &Client,
auth: &Auth,
record: &Record,
value: &str,
) -> Result<(), Box<dyn Error>> {
let body = json!({
"apikey": auth.key,
"secretapikey": auth.secret_key,
"type": record.record_type,
"name": record.subdomain,
"content": value,
"ttl": record.ttl,
});
client.post(format!("{API}/dns/edit/{domain}/{id}", domain = record.domain, id = record.id))
.json(&body)
.send().await?;
Ok(())
}
+18
View File
@@ -0,0 +1,18 @@
use reqwest::Client;
use std::error::Error;
pub async fn get_ipv4(client: &Client) -> Result<String, Box<dyn Error>> {
get_ip(client, "https://api4.ipify.org").await
}
pub async fn get_ipv6(client: &Client) -> Result<String, Box<dyn Error>> {
get_ip(client, "https://api6.ipify.org").await
}
async fn get_ip(client: &Client, url: &str) -> Result<String, Box<dyn Error>> {
let request = client.get(url)
.send().await?
.error_for_status()?;
let ip = request.text().await?;
Ok(ip)
}
+52
View File
@@ -0,0 +1,52 @@
use std::error::Error;
use reqwest::Client;
use crate::dns::Record;
mod config;
mod dns;
mod ip;
const CONFIG: &str = "/etc/ddns.json";
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let client = Client::new();
let config = config::load(CONFIG)?;
let ipv4 = ip::get_ipv4(&client).await.ok();
let ipv6 = ip::get_ipv6(&client).await.ok();
for entry in &config.entries {
let records = dns::get_records(&client, &config.auth, &entry.domain).await?;
if let Some(ip) = &ipv4 {
let a_records = find_records(&records, "A", &entry.subdomains, ip);
for record in a_records {
dns::update_record(&client, &config.auth, &record, ip).await?;
}
}
if let Some(ip) = &ipv6 {
let aaaa_records = find_records(&records, "AAAA", &entry.subdomains, ip);
for record in aaaa_records {
dns::update_record(&client, &config.auth, &record, ip).await?;
}
}
}
Ok(())
}
fn find_records<'a>(
records: &'a [Record],
record_type: &str,
subdomains: &[String],
value: &str
) -> Vec<&'a Record> {
records.iter()
.filter(|it| it.record_type == record_type && subdomains.contains(&it.subdomain) && it.value != value)
.collect()
}