refactor(dynu): deprecate local IP monitor in favor of NixOS host config
This commit removes the imperative bash scripts and local systemd units previously used for Dynu DDNS synchronization. As defined in the new ADR 002, this responsibility has been fully migrated to the declarative host OS configuration (nixos-config) to improve secret management, reduce redundant polling, and establish a single source of truth. - Add ADR 002 detailing the migration to NixOS declarative state - Delete legacy scripts/dynu directory (installer, monitor, units, env) - Delete redundant infra/nixos/dynu-ddns.nix module - Update architecture, roadmap, and protocol docs to reflect deprecation
This commit is contained in:
1 parent
868a0190be
commit
a6e27d522e
11 files changed
+39
-571
No files matched your search
@@ -0,0 +1,32 @@
|
||||
# ADR 002: Migrate Dynu DDNS IP Discovery to Host NixOS Configuration
|
||||
|
||||
* **Status**: Accepted & Implemented
|
||||
* **Date**: 2026-06-24
|
||||
* **Decider**: User & Antigravity
|
||||
|
||||
## Context
|
||||
Previously, we managed dynamic DNS IP synchronization using custom bash scripts (`ip-monitor.sh`) and systemd unit configurations in the `homeserver` scripts directory. The service checked the WAN IP and pushed updates to Dynu every 5 minutes.
|
||||
|
||||
However, this design introduced several structural problems:
|
||||
1. **Imperative Secrets Leakage**: Credentials were stored in a cleartext out-of-band environment file (`/etc/conf.d/dynu-environment`). This required manual setup on target hosts and broke the declarative reproducibility goal.
|
||||
2. **Redundant Logic**: The desktop machine (`desktop`) and server machine shared the same router (external public IP), but operated separate, duplicated cron/timer implementations.
|
||||
3. **Inefficient Polling**: Checking the external IP and calling the Dynu APIs every 5 minutes from multiple endpoints generated unnecessary network traffic and risked API bans.
|
||||
|
||||
## Decision
|
||||
We decided to **deprecate and remove all native Dynu IP updater scripts and systemd definitions** from the `homeserver` codebase.
|
||||
|
||||
Instead, the Dynu IP monitoring and DDNS update lifecycle is now managed directly by the host operating system's configuration repository ([nixos-config](https://github.com/kiskaadee/nixos-config)).
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive
|
||||
* **Single Source of Truth**: All WAN IP discovery, validation, and update logic is handled declaratively in the [nixos-config](https://github.com/kiskaadee/nixos-config) repository.
|
||||
* **Cryptographic Secrets**: Credentials are encrypted inside Git using `sops-nix` and `age`, allowing safe storage in public dotfiles repositories.
|
||||
* **Smart Change Detection**: A lightweight background Python script (`monitor.py`) checks the public IP every 30 minutes, keeping a local historical log (`ip_history.jsonl`) and triggering updates via `ddclient` *only* when a WAN IP rotation actually occurs.
|
||||
* **Clean Repository**: Removed bloat and deprecated files from this service-level repo.
|
||||
|
||||
### Negative / Required Actions
|
||||
* None. The deployment process is simplified as secrets and services are now handled automatically during the system-wide NixOS activation phase.
|
||||
|
||||
## References
|
||||
* This decision was implemented in the [nixos-config commits](https://github.com/kiskaadee/nixos-config/commits/main/) under hash `c7acc2b0a3bb262dfd5577989d8d7f0218f2721e` (and subsequent hardening adjustments).
|
||||
@@ -33,7 +33,7 @@
|
||||
<div class="layer-box">
|
||||
<ul>
|
||||
<li><strong>OS:</strong> Linux (Generic).</li>
|
||||
<li><strong>IP Sync:</strong> A host-level systemd service (<code>scripts/dynu/</code>) monitors the public IP and updates Dynu DDNS records.</li>
|
||||
<li><strong>IP Sync:</strong> <span style="color: #cc0000; font-weight: bold;">[DEPRECATED/MOVED]</span> Dynu DDNS updates are now handled declaratively by the host's NixOS configuration repository (<a href="https://github.com/kiskaadee/nixos-config">nixos-config</a>).</li>
|
||||
<li><strong>Docker Engine:</strong> Orchestrates all containerized services.</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -9,6 +9,11 @@
|
||||
<body>
|
||||
|
||||
<main>
|
||||
<header style="background: #ffe6e6; border: 1px solid #ff9999; padding: 15px; border-radius: 5px; margin-bottom: 25px; color: #cc0000;">
|
||||
<strong>⚠️ DEPRECATED</strong>
|
||||
<p>This script-based DDNS implementation has been deprecated and removed from the homeserver repository. The Dynamic DNS update service and IP monitor are now handled declaratively by the host's NixOS configuration repository. See the nixos-config repository commit <a href="https://github.com/kiskaadee/nixos-config/commit/c7acc2b0a3bb262dfd5577989d8d7f0218f2721e" target="_blank">c7acc2b0a3b</a> for implementation details.</p>
|
||||
</header>
|
||||
|
||||
<header>
|
||||
<h1>📡 Dynu IP Monitor & Updater</h1>
|
||||
<p>Design and architecture of the DDNS synchronization mechanism.</p>
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@
|
||||
<h2>✅ Phase 1: Core Gateway & Infrastructure</h2>
|
||||
<p><span class="badge badge-success">COMPLETE</span> Stable external access, identity management, and core security.</p>
|
||||
<ul class="status-list">
|
||||
<li class="status-item"><span>[x]</span> <strong>Dynamic DNS:</strong> Reliable IP synchronization via systemd-based Dynu updater.</li>
|
||||
<li class="status-item"><span>[x]</span> <strong>Dynamic DNS:</strong> IP synchronization migrated to host NixOS configuration (<a href="https://github.com/kiskaadee/nixos-config">nixos-config</a>).</li>
|
||||
<li class="status-item"><span>[x]</span> <strong>Edge Routing:</strong> Traefik v3 with Let's Encrypt (DNS-01) automation.</li>
|
||||
<li class="status-item"><span>[x]</span> <strong>Layered Architecture:</strong> Separation of control plane and decoupled data plane folders.</li>
|
||||
<li class="status-item"><span>[x]</span> <strong>Identity & SSO:</strong> Authelia integration with 2FA/OIDC support.</li>
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
|
||||
with lib;
|
||||
|
||||
let
|
||||
cfg = config.services.dynu-ddns;
|
||||
in {
|
||||
options.services.dynu-ddns = {
|
||||
enable = mkEnableOption "Dynu DDNS IP monitor and updater service";
|
||||
|
||||
scriptPath = mkOption {
|
||||
type = types.path;
|
||||
default = ../../scripts/dynu/ip-monitor.sh;
|
||||
description = "Path to the ip-monitor.sh script.";
|
||||
};
|
||||
|
||||
environmentFile = mkOption {
|
||||
type = types.path;
|
||||
default = /etc/conf.d/dynu-environment;
|
||||
description = ''
|
||||
Path to the environment file containing the Dynu credentials.
|
||||
The file must define:
|
||||
DYNU_HOST=your-domain.mywire.org
|
||||
DYNU_USER=your-dynu-username
|
||||
DYNU_PASSWORD=your-dynu-password
|
||||
'';
|
||||
};
|
||||
|
||||
interval = mkOption {
|
||||
type = types.str;
|
||||
default = "5min";
|
||||
description = "Interval at which to run the updater service.";
|
||||
};
|
||||
};
|
||||
|
||||
config = mkIf cfg.enable {
|
||||
systemd.services.dynu-ddns = {
|
||||
description = "Dynu IP Monitor & Updater";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
path = with pkgs; [
|
||||
bash
|
||||
curl
|
||||
coreutils
|
||||
dnsutils # provides dig
|
||||
util-linux # provides flock
|
||||
gawk
|
||||
];
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
User = "root";
|
||||
Group = "root";
|
||||
StateDirectory = "dynu";
|
||||
EnvironmentFile = cfg.environmentFile;
|
||||
ExecStart = "${pkgs.bash}/bin/bash ${cfg.scriptPath}";
|
||||
TimeoutSec = 30;
|
||||
|
||||
# Hardening
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
ReadWritePaths = "/var/lib/dynu";
|
||||
};
|
||||
};
|
||||
|
||||
systemd.timers.dynu-ddns = {
|
||||
description = "Run Dynu updater periodically";
|
||||
timerConfig = {
|
||||
OnBootSec = "30s";
|
||||
OnUnitActiveSec = cfg.interval;
|
||||
AccuracySec = "10s";
|
||||
Persistent = true;
|
||||
};
|
||||
wantedBy = [ "timers.target" ];
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# --- argument parsing ---
|
||||
DYNU_HOST=""
|
||||
DYNU_USER=""
|
||||
DYNU_PASSWORD=""
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--host) DYNU_HOST="$2"; shift 2 ;;
|
||||
--user) DYNU_USER="$2"; shift 2 ;;
|
||||
--password) DYNU_PASSWORD="$2"; shift 2 ;;
|
||||
*)
|
||||
echo "Unknown argument: $1"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# --- validation ---
|
||||
: "${DYNU_HOST:?--host required}"
|
||||
: "${DYNU_USER:?--user required}"
|
||||
: "${DYNU_PASSWORD:?--password required}"
|
||||
|
||||
# --- root check ---
|
||||
if [[ $EUID -ne 0 ]]; then
|
||||
echo "Run as root"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- paths ---
|
||||
BIN_PATH="/usr/local/bin/ip-monitor.sh"
|
||||
SERVICE_PATH="/etc/systemd/system/dynu.service"
|
||||
TIMER_PATH="/etc/systemd/system/dynu.timer"
|
||||
ENV_PATH="/etc/conf.d/dynu-environment"
|
||||
|
||||
# --- install files ---
|
||||
install -m 755 "$(dirname "$0")/ip-monitor.sh" "$BIN_PATH"
|
||||
install -m 644 "$(dirname "$0")/install/dynu.service" "$SERVICE_PATH"
|
||||
install -m 644 "$(dirname "$0")/install/dynu.timer" "$TIMER_PATH"
|
||||
|
||||
# --- write env file atomically ---
|
||||
TMP_ENV=$(mktemp)
|
||||
|
||||
cat > "$TMP_ENV" <<EOF
|
||||
DYNU_HOST=$DYNU_HOST
|
||||
DYNU_USER=$DYNU_USER
|
||||
DYNU_PASSWORD=$DYNU_PASSWORD
|
||||
EOF
|
||||
|
||||
install -m 600 "$TMP_ENV" "$ENV_PATH"
|
||||
rm -f "$TMP_ENV"
|
||||
|
||||
# --- systemd reload ---
|
||||
systemctl daemon-reload
|
||||
|
||||
# --- enable + start timer ---
|
||||
systemctl enable --now dynu.timer
|
||||
|
||||
echo "Installation complete"
|
||||
echo "Check logs with: journalctl -u dynu.service -f"
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
# Example Dynu DDNS credentials
|
||||
# Don't use your main account password. Use the IP update password or its hash instead.
|
||||
# Secure the env file from local users read:
|
||||
# chmod 600 /etc/conf.d/dynu-environment
|
||||
# chown root:root /etc/conf.d/dynu-environment
|
||||
|
||||
# No quotes/spaces
|
||||
# Your Dynu hostname (e.g., subdomain you registered)
|
||||
DYNU_HOST=your-subdomain.dynu.net
|
||||
|
||||
# Dynu username (account login)
|
||||
DYNU_USER=your-username
|
||||
|
||||
# Dynu DDNS IP Update Password (not account password): Dynu API supports passwords as plain text or MD5 hashes
|
||||
DYNU_PASSWORD=ip-update-password-or-hash
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
# Dynu IP Monitor & Updater
|
||||
|
||||
This component keeps your Dynu DNS record in sync with your current public IPv4 address.
|
||||
|
||||
It runs as a **systemd timer-driven probe**, not a daemon.
|
||||
|
||||
## Execution Flow
|
||||
|
||||
```
|
||||
timer → service → script
|
||||
├─ lock (skip if overlapping run)
|
||||
├─ DNS discovery (fast path)
|
||||
├─ HTTP fallback (multi-provider)
|
||||
├─ strict validation
|
||||
├─ compare with last known IP
|
||||
├─ update Dynu (only on change)
|
||||
├─ atomic state write
|
||||
└─ structured logs (journald)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
Run the setup script as root:
|
||||
|
||||
```bash
|
||||
sudo ./api-update-installer.sh \
|
||||
--host your-domain.mywire.org \
|
||||
--user your-dynu-username \
|
||||
--password your-dynu-password
|
||||
```
|
||||
|
||||
This will:
|
||||
|
||||
* Install the script to `/usr/local/bin/ip-monitor.sh`
|
||||
* Install systemd units (from the `install/` directory):
|
||||
|
||||
* `/etc/systemd/system/dynu.service`
|
||||
* `/etc/systemd/system/dynu.timer`
|
||||
* Store credentials in:
|
||||
|
||||
* `/etc/conf.d/dynu-environment` (mode `600`)
|
||||
* Enable and start the timer
|
||||
|
||||
---
|
||||
|
||||
## Runtime Behavior
|
||||
|
||||
* Runs every **5 minutes** (configurable via `dynu.timer`)
|
||||
* Skips execution if a previous run is still active
|
||||
* Only updates Dynu **when IP changes**
|
||||
* Never writes state unless the update succeeds
|
||||
|
||||
---
|
||||
|
||||
## State Management
|
||||
|
||||
* Directory: `/var/lib/dynu/` (managed by systemd)
|
||||
* Files:
|
||||
|
||||
* `last_ip` → last successfully synced public IP
|
||||
* `lock` → used for concurrency control
|
||||
|
||||
State updates are **atomic**:
|
||||
|
||||
* write → temp file
|
||||
* move → final file
|
||||
|
||||
---
|
||||
|
||||
## Logs & Monitoring
|
||||
|
||||
View logs:
|
||||
|
||||
```bash
|
||||
journalctl -u dynu.service -f
|
||||
```
|
||||
|
||||
### Log Types
|
||||
|
||||
* `event=discovered` → IP successfully detected
|
||||
* `event=change` → IP changed
|
||||
* `event=state_updated` → Dynu successfully updated
|
||||
* `event=degraded` → fallback or partial failure
|
||||
* `event=error` → hard failure (no state change)
|
||||
* `event=skip` → concurrent run avoided
|
||||
|
||||
---
|
||||
|
||||
## Manual Testing
|
||||
|
||||
Force an update:
|
||||
|
||||
```bash
|
||||
echo "1.1.1.1" > /var/lib/dynu/last_ip
|
||||
systemctl start dynu.service
|
||||
```
|
||||
|
||||
Check state:
|
||||
|
||||
```bash
|
||||
cat /var/lib/dynu/last_ip
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### Timer
|
||||
|
||||
```ini
|
||||
OnBootSec=30s
|
||||
OnUnitActiveSec=5min
|
||||
Persistent=true
|
||||
```
|
||||
|
||||
### Service
|
||||
|
||||
* Runs as `root`
|
||||
* Uses systemd sandboxing:
|
||||
|
||||
* `ProtectSystem=strict`
|
||||
* `NoNewPrivileges=true`
|
||||
* limited write access to `/var/lib/dynu`
|
||||
@@ -1,28 +0,0 @@
|
||||
# This service is responsible for updating the Dynu DDNS record with the current IP address
|
||||
# Copy this to /etc/systemd/system/dynu.service
|
||||
# This script is intended to run via systemd
|
||||
[Unit]
|
||||
Description=Dynu IP Monitor & Updater
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=root
|
||||
Group=root
|
||||
|
||||
StateDirectory=dynu
|
||||
EnvironmentFile=/etc/conf.d/dynu-environment
|
||||
|
||||
ExecStart=/usr/local/bin/ip-monitor.sh
|
||||
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
TimeoutSec=30
|
||||
|
||||
# Optional hardening (safe defaults)
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/var/lib/dynu
|
||||
@@ -1,13 +0,0 @@
|
||||
# This timer is used to run the dynu.service
|
||||
# Copy this to /etc/systemd/system/dynu.timer
|
||||
[Unit]
|
||||
Description=Run Dynu updater periodically
|
||||
|
||||
[Timer]
|
||||
OnBootSec=30s
|
||||
OnUnitActiveSec=5min
|
||||
AccuracySec=10s
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -1,246 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Dynu DDNS IP monitor and updater
|
||||
|
||||
# Design notes:
|
||||
# - Execution is periodic (systemd timer), not continuous: this is a probe, not a daemon
|
||||
# - Discovery and update are intentionally coupled to guarantee consistency:
|
||||
# we only persist state after a successful external sync
|
||||
# - Failure is classified:
|
||||
# * degraded → partial failure with fallback (DNS → HTTP, provider errors)
|
||||
# * error → no valid IP or API failure (no state mutation allowed)
|
||||
# - Logs are structured for journald filtering (event=, reason=, cause=)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# --- invariants ---
|
||||
: "${STATE_DIRECTORY:?must be run via systemd (StateDirectory missing)}"
|
||||
: "${DYNU_HOST:?missing}"
|
||||
: "${DYNU_USER:?missing}"
|
||||
: "${DYNU_PASSWORD:?missing}"
|
||||
|
||||
STATE_DIR="$STATE_DIRECTORY"
|
||||
LAST_IP_FILE="$STATE_DIR/last_ip"
|
||||
|
||||
# --- logging ---
|
||||
# Logging strategy:
|
||||
# - Only log meaningful transitions:
|
||||
# * discovery
|
||||
# * degradation
|
||||
# * change
|
||||
# * failure
|
||||
# - Suppress noise (e.g., no_change)
|
||||
# - Structured logs for journald filtering
|
||||
log() {
|
||||
printf '%s dynu-monitor %s\n' "$(date -Iseconds)" "$*"
|
||||
}
|
||||
|
||||
# --- dependencies checks ---
|
||||
# Hard dependency validation:
|
||||
# curl → required for all network operations
|
||||
# md5sum → required because Dynu rejects plain-text passwords in practice
|
||||
# We fail early here to avoid partial execution later
|
||||
CURL_CMD="$(command -v curl)" || {
|
||||
log "event=error reason=dependency_check cause=missing_tool tool=curl"
|
||||
exit 1
|
||||
}
|
||||
|
||||
MD5_CMD="$(command -v md5sum)" || {
|
||||
log "event=error reason=dependency_check cause=missing_tool tool=md5sum"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# dig remains optional but tracked (used as fast-path provider)
|
||||
DIG_CMD="$(command -v dig || true)"
|
||||
|
||||
# --- concurrency control ---
|
||||
# Concurrency control:
|
||||
# Non-blocking lock ensures idempotent timer behavior.
|
||||
# If a previous run overlaps, we skip instead of queueing.
|
||||
exec 9>"$STATE_DIR/lock"
|
||||
flock -n 9 || {
|
||||
log "event=skip reason=concurrency_check cause=lock_held"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# --- validation ---
|
||||
is_valid_ipv4() {
|
||||
local ip=$1
|
||||
[[ $ip =~ ^((0|[1-9][0-9]{0,2})\.){3}(0|[1-9][0-9]{0,2})$ ]] || return 1
|
||||
local IFS='.'
|
||||
read -r a b c d <<< "$ip"
|
||||
(( 10#$a <= 255 && 10#$b <= 255 && 10#$c <= 255 && 10#$d <= 255 ))
|
||||
}
|
||||
|
||||
is_public_ipv4() {
|
||||
local ip=$1 a b
|
||||
local IFS='.'
|
||||
read -r a b _ <<< "$ip"
|
||||
|
||||
# Reject RFC1918 + CGNAT ranges
|
||||
if (( a == 10 )) || \
|
||||
(( a == 192 && b == 168 )) || \
|
||||
(( a == 172 && b >= 16 && b <= 31 )) || \
|
||||
(( a == 100 && b >= 64 && b <= 127 )); then
|
||||
return 1
|
||||
fi
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# --- providers ---
|
||||
get_ip_from_dns() {
|
||||
"$DIG_CMD" +short +time=2 +tries=1 myip.opendns.com @resolver1.opendns.com \
|
||||
| head -n1 | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
get_ip_from_http() {
|
||||
local providers=(
|
||||
"https://api.ipify.org"
|
||||
"https://ifconfig.me"
|
||||
"https://wtfismyip.com/text"
|
||||
)
|
||||
|
||||
for url in "${providers[@]}"; do
|
||||
local ip err_file
|
||||
err_file=$(mktemp)
|
||||
|
||||
if ip="$("$CURL_CMD" -s --fail --max-time 2 "$url" 2>"$err_file")"; then
|
||||
ip="$(head -n1 <<< "$ip" | tr -d '[:space:]')"
|
||||
rm -f "$err_file"
|
||||
|
||||
# Provider validation tightened:
|
||||
# Reject invalid or private IPs before accepting
|
||||
if is_valid_ipv4 "$ip" && is_public_ipv4 "$ip"; then
|
||||
echo "$ip"
|
||||
return 0
|
||||
else
|
||||
log "event=degraded reason=http_provider_rejected cause=invalid_or_private source=http url='$url' value='$ip'"
|
||||
fi
|
||||
else
|
||||
local exit_code=$? err
|
||||
err="$(head -c 120 "$err_file")"
|
||||
log "event=degraded reason=http_provider_failed source=http url='$url' exit_code=$exit_code err='${err:-none}'"
|
||||
rm -f "$err_file"
|
||||
fi
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# --- discovery ---
|
||||
RAW_IP=""
|
||||
SOURCE="dns"
|
||||
DNS_UNUSABLE=false
|
||||
|
||||
# DNS evaluation is explicit:
|
||||
# classify DNS as usable/unusable instead of implicit fallback
|
||||
if [[ -z "$DIG_CMD" ]]; then
|
||||
log "event=degraded reason=dns_unavailable fallback=http"
|
||||
DNS_UNUSABLE=true
|
||||
else
|
||||
DNS_ERR_FILE=$(mktemp)
|
||||
if ! RAW_IP="$(get_ip_from_dns 2>"$DNS_ERR_FILE")"; then
|
||||
DNS_EXIT=$?
|
||||
DNS_ERR="$(head -c 120 "$DNS_ERR_FILE")"
|
||||
log "event=degraded reason=dns_provider_failed fallback=http source=dns exit_code=$DNS_EXIT err='${DNS_ERR:-none}'"
|
||||
DNS_UNUSABLE=true
|
||||
fi
|
||||
rm -f "$DNS_ERR_FILE"
|
||||
fi
|
||||
|
||||
# Validate DNS result before accepting
|
||||
if [[ "$DNS_UNUSABLE" == "false" ]]; then
|
||||
if ! is_valid_ipv4 "$RAW_IP"; then
|
||||
log "event=degraded reason=dns_unusable fallback=http cause=invalid_format"
|
||||
DNS_UNUSABLE=true
|
||||
elif ! is_public_ipv4 "$RAW_IP"; then
|
||||
log "event=degraded reason=dns_unusable fallback=http cause=private_address"
|
||||
DNS_UNUSABLE=true
|
||||
fi
|
||||
fi
|
||||
|
||||
# Fallback to HTTP providers if DNS is unusable
|
||||
if [[ "$DNS_UNUSABLE" == "true" ]]; then
|
||||
SOURCE="http"
|
||||
if ! RAW_IP="$(get_ip_from_http)"; then
|
||||
log "event=error reason=all_providers_failed source=http"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- final validation ---
|
||||
# Final validation is repeated intentionally as a safety gate
|
||||
if ! is_valid_ipv4 "$RAW_IP"; then
|
||||
log "event=error reason=validation_failed cause=invalid_format source=$SOURCE value='$RAW_IP'"
|
||||
exit 1
|
||||
elif ! is_public_ipv4 "$RAW_IP"; then
|
||||
log "event=error reason=validation_failed cause=private_address source=$SOURCE value='$RAW_IP'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CURRENT_IP="$RAW_IP"
|
||||
log "event=discovered source=$SOURCE ip=$CURRENT_IP"
|
||||
|
||||
# --- state load ---
|
||||
# State invariant:
|
||||
# last_ip is only updated after successful external sync
|
||||
LAST_IP=""
|
||||
if [[ -f "$LAST_IP_FILE" ]]; then
|
||||
LAST_IP="$(tr -d '[:space:]' < "$LAST_IP_FILE" || true)"
|
||||
if ! is_valid_ipv4 "$LAST_IP"; then
|
||||
log "event=degraded reason=state_load_failed cause=invalid_format value='$LAST_IP'"
|
||||
LAST_IP=""
|
||||
fi
|
||||
fi
|
||||
|
||||
# --- compare ---
|
||||
if [[ "$CURRENT_IP" == "$LAST_IP" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log "event=change old_ip=${LAST_IP:-none} new_ip=$CURRENT_IP"
|
||||
|
||||
# --- credentials preparation ---
|
||||
# Deferred hashing:
|
||||
# Only compute hash if an update is actually needed
|
||||
if [[ "$DYNU_PASSWORD" =~ ^[a-fA-F0-9]{32}$ ]]; then
|
||||
DYNU_PASSWORD_HASH="$DYNU_PASSWORD"
|
||||
else
|
||||
DYNU_PASSWORD_HASH="$(printf '%s' "$DYNU_PASSWORD" | "$MD5_CMD" | awk '{print $1}')"
|
||||
fi
|
||||
|
||||
# --- update Dynu ---
|
||||
RESP_FILE=$(mktemp)
|
||||
|
||||
HTTP_CODE="$(
|
||||
"$CURL_CMD" -s --max-time 2 \
|
||||
-w "%{http_code}" \
|
||||
-o "$RESP_FILE" \
|
||||
"https://api.dynu.com/nic/update?hostname=${DYNU_HOST}&username=${DYNU_USER}&password=${DYNU_PASSWORD_HASH}&myip=${CURRENT_IP}" \
|
||||
|| echo "000"
|
||||
)"
|
||||
|
||||
# Response normalization:
|
||||
# - strip CRLF
|
||||
# - normalize case
|
||||
UPDATE_RESPONSE="$(head -c 200 "$RESP_FILE" 2>/dev/null | tr -d '\r\n' | tr '[:upper:]' '[:lower:]' || true)"
|
||||
rm -f "$RESP_FILE"
|
||||
|
||||
# Transport layer validation
|
||||
if [[ "$HTTP_CODE" != "200" ]]; then
|
||||
log "event=error reason=api_transport_failed cause=http_transport_error code=$HTTP_CODE response='$UPDATE_RESPONSE'"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Semantic layer validation
|
||||
if [[ "$UPDATE_RESPONSE" == good* || "$UPDATE_RESPONSE" == nochg* ]]; then
|
||||
TMP_FILE=$(mktemp -p "$STATE_DIR" last_ip.XXXXXX)
|
||||
|
||||
printf '%s\n' "$CURRENT_IP" > "$TMP_FILE"
|
||||
mv "$TMP_FILE" "$LAST_IP_FILE"
|
||||
|
||||
log "event=state_updated ip=$CURRENT_IP"
|
||||
else
|
||||
log "event=error reason=api_semantic_failed cause=invalid_response response='$UPDATE_RESPONSE'"
|
||||
exit 1
|
||||
fi
|
||||
Reference in new issue
Block a user