Compare commits

..

7 Commits

Author SHA1 Message Date
c30ee50898 add LICENSE 2026-09-11 19:57:14 +02:00
540d990aeb rewrite in rust 2026-08-29 14:36:14 +02:00
aa7f37500f Refactor 2026-03-15 16:55:31 +01:00
67509e9062 Refactor and Bump version to 1.1.0 2026-03-14 12:08:44 +01:00
90b8f3f08a update README 2025-12-14 23:10:52 +01:00
4a8244466e refactor 2025-12-14 23:03:10 +01:00
cc37d6bcb0 use common plugin 2025-12-13 02:01:33 +01:00
33 changed files with 1949 additions and 1060 deletions

View File

@@ -1,43 +0,0 @@
on:
push:
branches:
- main
env:
GIT__TOKEN: ${{ secrets.TOKEN }}
jobs:
release:
runs-on: linux
steps:
- uses: actions/checkout@v4
- uses: actions/cache/restore@v4
with:
key: gradle
path: |
~/.gradle/caches/
~/.gradle/wrapper/
~/.konan/
- uses: actions/setup-java@v4
with:
java-version: '24'
distribution: 'temurin'
- run: |
./gradlew assemble
mv ./build/bin/linuxX64/releaseExecutable/ddns.kexe ./ddns
- uses: actions/upload-artifact@v3
with:
name: ddns
path: ./ddns
- uses: actions/cache/save@v4
with:
key: gradle
path: |
~/.gradle/caches/
~/.gradle/wrapper/
~/.konan/

12
.gitignore vendored
View File

@@ -1,10 +1,2 @@
# IDE
/.idea/
# Gradle
/.gradle/
/gradle.properties
# Kotlin
/.kotlin/
/build/
# Rust
/target/

1747
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

10
Cargo.toml Normal file
View File

@@ -0,0 +1,10 @@
[package]
name = "ddns"
version = "1.0.0"
edition = "2024"
[dependencies]
reqwest = { version = "0.13.4", features = ["json"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
tokio = { version = "1.53.1", features = ["full"] }

View File

@@ -1,50 +0,0 @@
# DDNS
This application enables automatically updating DNS records for various providers.
## Features
* Automatically detect the current IP.
* Both IPv4 and IPv6 are supported.
* IP resolution depends on the selected service.
* ipify (default)
* Update DNS records in the selected provider.
* Porkbun
* Native (Linux)
## Build
Execute `./gradlew assemble`.
The resulting binary will be located in `./build/bin/releaseExecutable/`.
Removing the extension from the binary and adding it to `/usr/local/bin/` enables the use of `ddns` in the terminal.
## Usage
The following command updates all A and AAAA DNS records in Porkbun for `example.com` and `test.example.com`.
```
ddns porkbun \
--key=... \
--secret-key=... \
--domain=example.com \
--subdomain= \
--subdomain=test
```
Optionally, a file can be used to declare one or more configurations.
The above example can be declared as follows.
```
porkbun
key=...
secret-key=...
domain=example.com
subdomain=
subdomain=test
```
To use this config file, execute the command `ddns --config=...`.
By default, the config file is `/etc/ddns.conf`.
This process can be automated using systemd or cron.

View File

@@ -1,35 +0,0 @@
group = "com.infendro"
version = "1.0.0"
repositories {
maven("https://git.infendro.com/api/packages/Infendro/maven")
mavenCentral()
}
plugins {
alias(libs.plugins.multiplatform)
alias(libs.plugins.serialization)
}
kotlin {
linuxX64 {
binaries.executable {
entryPoint = "com.infendro.ddns.main"
}
}
sourceSets {
commonMain.dependencies {
implementation(libs.io)
implementation(libs.serialization.json)
implementation(libs.coroutines)
implementation(libs.cli)
implementation(libs.ktor.client)
implementation(libs.ktor.client.contentNegotiation)
implementation(libs.ktor.client.serialization.json)
}
nativeMain.dependencies {
implementation(libs.ktor.client.curl)
}
}
}

View File

@@ -1,23 +0,0 @@
[versions]
kotlin = "2.1.21"
io = "0.7.0"
coroutines = "1.10.2"
serialization = "1.8.1"
cli = "1.2.2"
ktor = "3.1.2"
[plugins]
multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
[libraries]
io = { module = "org.jetbrains.kotlinx:kotlinx-io-core", version.ref = "io" }
coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }
cli = { module = "com.infendro:cli", version.ref = "cli" }
ktor-client = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-curl = { module = "io.ktor:ktor-client-curl", version.ref = "ktor" }
ktor-client-contentNegotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
ktor-client-serialization-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }

Binary file not shown.

View File

@@ -1,7 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
gradlew vendored
View File

@@ -1,251 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
gradlew.bat vendored
View File

@@ -1,94 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1 +0,0 @@
rootProject.name = "ddns"

View File

@@ -1,13 +0,0 @@
package com.infendro.ddns
import io.ktor.client.HttpClient
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.kotlinx.json.json
object Http {
val client = HttpClient {
install(ContentNegotiation) {
json()
}
}
}

View File

@@ -1,110 +0,0 @@
package com.infendro.ddns
import com.infendro.cli.argument.string
import com.infendro.cli.argument.stringOrElse
import com.infendro.cli.argument.strings
import com.infendro.cli.cli
import com.infendro.ddns.Argument.CONFIG
import com.infendro.ddns.Argument.DOMAIN
import com.infendro.ddns.Argument.IP_SERVICE
import com.infendro.ddns.Argument.KEY
import com.infendro.ddns.Argument.SECRET_KEY
import com.infendro.ddns.Argument.SUBDOMAIN
import com.infendro.ddns.argument.ipService
import com.infendro.ddns.config.Config
import com.infendro.ddns.dns.DnsService
import com.infendro.ddns.dns.DnsServices.PORKBUN
import com.infendro.ddns.dns.model.DnsRecord
import com.infendro.ddns.dns.porkbun.Porkbun
import com.infendro.ddns.ip.IpService
private object Argument {
val CONFIG = stringOrElse("config", "/etc/ddns.conf")
val DOMAIN = string("domain")
val SUBDOMAIN = strings("subdomain", min = 1)
val IP_SERVICE = ipService("ip-service")
// Porkbun
val KEY = string("key")
val SECRET_KEY = string("secret-key")
}
fun main(
args: Array<String>,
) {
cli {
arguments(CONFIG)
execute {
val config by CONFIG
Config.get(config)
.run {
val domain by DOMAIN
val subdomains by SUBDOMAIN
val ipService by IP_SERVICE
val dnsService = when (name) {
PORKBUN -> {
val key by KEY
val secretkey by SECRET_KEY
Porkbun(key, secretkey)
}
else -> throw Exception()
}
dnsService.update(ipService, domain, subdomains)
}
}
command(PORKBUN) {
arguments(
DOMAIN,
SUBDOMAIN,
IP_SERVICE,
KEY,
SECRET_KEY,
)
execute {
val domain by DOMAIN
val subdomains by SUBDOMAIN
val ipService by IP_SERVICE
val key by KEY
val secretkey by SECRET_KEY
val dnsService = Porkbun(key, secretkey)
dnsService.update(ipService, domain, subdomains)
}
}
}.run(args)
}
fun Config.run(
block: Config.Service.() -> Unit,
) {
for (service in services) {
service.block()
}
}
fun DnsService.update(
ipService: IpService,
domain: String,
subdomains: List<String>,
) {
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)
}

View File

@@ -1,34 +0,0 @@
package com.infendro.ddns.argument
import com.infendro.cli.Command
import com.infendro.cli.argument.Argument
import com.infendro.cli.argument.Parser
import com.infendro.ddns.ip.IpService
import com.infendro.ddns.ip.IpServices
object IpServiceParser : Parser<IpService> {
override fun parse(
text: String?,
): IpService {
return IpServices.get(text!!)
}
}
class IpServiceOrDefaultArgument(
override val name: String,
) : Argument.SingleOrElse<IpService>() {
override val other: IpService
get() = IpServices.DEFAULT
override val parser: Parser<IpService>
get() = IpServiceParser
}
fun ipService(
name: String,
) = IpServiceOrDefaultArgument(name)
fun Command.Builder.ipService(
name: String,
) = IpServiceOrDefaultArgument(name)
.also { argument(it) }

View File

@@ -1,128 +0,0 @@
package com.infendro.ddns.config
import com.infendro.cli.argument.Argument.*
import com.infendro.ddns.config.Regex.ARGUMENT
import com.infendro.ddns.config.Regex.EMPTY_LINES
import kotlin.reflect.KProperty
import kotlinx.io.buffered
import kotlinx.io.files.Path
import kotlinx.io.files.SystemFileSystem
import kotlinx.io.readString
class Config(
val services: List<Service>,
) {
class Service(
val name: String,
val arguments: List<Argument>,
) {
class Argument(
val name: String,
val value: String,
)
operator fun <T> Single<T>.getValue(
thisRef: Any?,
property: KProperty<*>,
): T {
return parser.parse(
arguments
.find { it.name == name }!!
.value
)
}
operator fun <T> SingleOrElse<T>.getValue(
thisRef: Any?,
property: KProperty<*>,
): T {
return arguments
.find { it.name == name }
?.let { parser.parse(it.value) }
?: other
}
operator fun <T> SingleOrNull<T>.getValue(
thisRef: Any?,
property: KProperty<*>,
): T? {
return arguments
.find { it.name == name }
?.let { parser.parse(it.value) }
}
operator fun <T> Multiple<T>.getValue(
thisRef: Any?,
property: KProperty<*>,
): List<T> {
return arguments
.filter { it.name == name }
.map { parser.parse(it.value) }
}
}
companion object {
fun get(
path: String,
): Config {
val path = Path(path)
val source = SystemFileSystem.source(path).buffered()
val text = source
.readString()
.process()
return parse(text)
}
private fun String.process(): String {
val builder = StringBuilder()
for (line in lines()) {
val comment = line.indexOf("""//""")
if (comment != -1) {
builder.appendLine(
line
.slice(0..<comment)
.trim()
)
} else {
builder.appendLine(
line.trim()
)
}
}
return builder.toString().trim()
}
private fun parse(
text: String,
): Config {
val services = text
.split(EMPTY_LINES)
.map { parseService(it) }
return Config(services)
}
private fun parseService(
text: String,
): Service {
val lines = text.lines()
val name = lines[0]
val arguments = lines
.drop(1)
.map { parseArgument(it) }
return Service(name, arguments)
}
private fun parseArgument(
text: String,
): Service.Argument {
val match = ARGUMENT.find(text)!!
val name = match.groups["name"]!!.value
val value = match.groups["value"]!!.value
return Service.Argument(name, value)
}
}
}

View File

@@ -1,6 +0,0 @@
package com.infendro.ddns.config
object Regex {
val EMPTY_LINES = Regex("""\n{2,}""")
val ARGUMENT = Regex("""(?<name>[a-z]+(?:-[a-z]+)*)(?:=(?<value>.*))?""")
}

View File

@@ -1,25 +0,0 @@
package com.infendro.ddns.dns
import com.infendro.ddns.dns.model.DnsRecord
abstract class DnsService {
abstract fun getRecords(
domain: String,
subdomains: List<String>,
): List<DnsRecord>
abstract 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)
}
}
}

View File

@@ -1,5 +0,0 @@
package com.infendro.ddns.dns
object DnsServices {
const val PORKBUN = "porkbun"
}

View File

@@ -1,5 +0,0 @@
package com.infendro.ddns.dns
object Regex {
val DOMAIN = Regex("""(?:(?<subdomain>(?:\w+\.)*\w+)\.)?(?<domain>\w+\.\w+)""")
}

View File

@@ -1,31 +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() = if (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)
}
}
}

View File

@@ -1,88 +0,0 @@
package com.infendro.ddns.dns.porkbun
import com.infendro.ddns.Http.client
import com.infendro.ddns.dns.Regex.DOMAIN
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 io.ktor.client.call.body
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.contentType
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 = client.post("https://api.porkbun.com/api/json/v3/dns/retrieve/$domain") {
val request = getRecordsRequest()
contentType(ContentType.Application.Json)
setBody(request)
}
val body = response.body<GetRecordsResponse>()
body.records
.map { model(it) }
.filter { it.type in DnsRecord.Type.address && (it.domain.subdomain ?: "") in subdomains }
}
override fun updateRecord(
record: DnsRecord,
value: String,
): Unit = runBlocking {
client.post("https://api.porkbun.com/api/json/v3/dns/edit/${record.domain.domain}/${record.id}") {
val request = updateRecordRequest(record, value)
contentType(ContentType.Application.Json)
setBody(request)
}
}
private fun model(
record: GetRecordsResponse.Record,
): DnsRecord {
val match = DOMAIN.matchEntire(record.name)!!
val domain = match.groups["domain"]!!.value
val subdomain = match.groups["subdomain"]?.value
return DnsRecord(
id = record.id,
type = DnsRecord.Type.valueOf(record.type),
domain = DnsRecord.Domain(
subdomain = subdomain,
domain = domain,
),
value = record.content,
ttl = record.ttl.toInt(),
priority = record.prio?.toInt(),
)
}
private fun getRecordsRequest(): GetRecordsRequest {
return GetRecordsRequest(
apikey = key,
secretapikey = secretkey,
)
}
private fun updateRecordRequest(
record: DnsRecord,
ip: String,
): UpdateRecordRequest {
return UpdateRecordRequest(
apikey = key,
secretapikey = secretkey,
type = record.type.toString(),
name = record.domain.subdomain ?: "",
content = ip,
ttl = record.ttl.toString(),
)
}
}

View File

@@ -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,
)

View File

@@ -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,
)

View File

@@ -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?,
)
}

View File

@@ -1,9 +0,0 @@
package com.infendro.ddns.ip
abstract class IpService {
abstract val ipv4: String
abstract val ipv6: String
val ip: List<String>
get() = listOf(ipv4, ipv6)
}

View File

@@ -1,17 +0,0 @@
package com.infendro.ddns.ip
import com.infendro.ddns.ip.ipify.Ipify
object IpServices {
const val IPIFY = "ipify"
val DEFAULT = Ipify
fun get(
name: String,
): IpService {
return when (name) {
IPIFY -> Ipify
else -> throw Exception()
}
}
}

View File

@@ -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.body
import io.ktor.client.request.get
import kotlinx.coroutines.runBlocking
object Ipify : IpService() {
override val ipv4: String
get() = runBlocking {
val response = Http.client.get("https://api.ipify.org?format=json")
val body = response.body<GetIpResponse>()
body.ip
}
override val ipv6: String
get() = runBlocking {
val response = Http.client.get("https://api64.ipify.org?format=json")
val body = response.body<GetIpResponse>()
body.ip
}
}

View File

@@ -1,8 +0,0 @@
package com.infendro.ddns.ip.ipify.dto.response
import kotlinx.serialization.Serializable
@Serializable
data class GetIpResponse(
val ip: String,
)

27
src/config.rs Normal file
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
src/dns.rs Normal file
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
src/ip.rs Normal file
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
src/main.rs Normal file
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()
}