refactor(dynu): upgrade DDNS monitor to stateful round-robin polling every 30 seconds

- Add `__pycache__` to `.gitignore`.
- Refactor `monitor.py` to maintain a stateful round-robin resolver pool (`/var/lib/dynu/state.json`) across 5 external IP reflection endpoints.
- Increase systemd timer frequency to 30 seconds (`OnUnitActiveSec = "30s"`) while maintaining zero DNS API overhead when IPs remain unchanged.
- Enhance IP parsing with robust regex extraction and range filtering.
- Update documentation in `docs/dynu-ip-monitor.md`.

Rationale: Improves WAN IP rotation detection latency and resilience against provider downtime or rate limiting.
This commit is contained in:
kiskaadee committed 2026-09-08 05:59:54 -05:00
1 parent f8bb112e8d
commit 082b7b0500
6 files changed
+264 -131

No files matched your search

+1
View File
@@ -7,3 +7,4 @@ result-*
.ruff_cache/ .ruff_cache/
__pycache__
+39 -31
View File
@@ -6,38 +6,41 @@ This service manages the Dynamic DNS (DDNS) lifecycle for your host. Instead of
## ⚙️ Architecture and Logic Flow ## ⚙️ Architecture and Logic Flow
The synchronization process runs in the background as a system service completely decoupled from the graphical user session. The synchronization process runs in the background as a system service completely decoupled from the graphical user session. It polls every **30 seconds** using a stateful round-robin resolver pool to minimize load per provider.
```mermaid ```mermaid
graph TD graph TD
A[Timer triggers dynu-monitor.service] --> B[Fetch public IP via HTTP] A[Timer triggers dynu-monitor.service every 30s] --> B[Read /var/lib/dynu/state.json]
B --> C{Verify public IPv4?} B --> C[Query next resolver in round-robin sequence]
C -- No/Timeout --> D[Log warning to journald & Fallback to next provider] C --> D{Verify public IPv4?}
C -- Yes --> E[Read history database log] D -- No/Timeout --> E[Log warning to stderr & Fallback to next resolver]
E --> F{Did IP change?} D -- Yes --> F[Save updated provider index to state.json]
F -- No --> G[Exit cleanly] F --> G{Did IP change vs last_ip?}
F -- Yes --> H[Log rotation in history log] G -- No --> H[Exit 0 cleanly]
H --> I[Trigger systemctl start ddclient.service] G -- Yes --> I[Trigger systemctl start ddclient.service]
I --> J{ddclient success?} I --> J{ddclient success?}
J -- Yes --> K[Record success in ip_history.jsonl] J -- Yes --> K[Save last_ip & Record success in ip_history.jsonl]
J -- No --> L[Record failed_update in ip_history.jsonl & exit 1] J -- No --> L[Record failed_update in ip_history.jsonl & exit 1]
``` ```
--- ---
## 🔍 Public IP Discovery & Validation ## 🔍 Public IP Discovery & Round-Robin Rotation
### 1. HTTP Resolvers with Fallback ### 1. HTTP Resolvers with Stateful Round-Robin
The script queries multiple independent IP reflection endpoints sequentially to handle offline states or service outages: The script maintains a pool of 5 independent IP reflection endpoints:
1. `https://api.ipify.org` 1. `https://api.ipify.org`
2. `https://ifconfig.me/ip` 2. `https://icanhazip.com`
3. `https://icanhazip.com` 3. `https://ifconfig.me/ip`
4. `https://wtfismyip.com/text` 4. `https://checkip.dynu.com`
5. `https://wtfismyip.com/text`
If a provider fails or times out, the script logs the warning to `stderr` and falls back to the next provider. If all providers fail, it exits with a non-zero code to flag a connectivity issue. On each run (every 30 seconds), the monitor loads `/var/lib/dynu/state.json`, selects the next resolver in sequence (`(last_index + 1) % N`), and queries it. If that resolver fails or times out, it immediately cascades to subsequent resolvers in the circular pool until one succeeds.
### 2. IP Address Validation With 5 providers queried at a 30-second interval, each provider is contacted at most **once every 2.5 minutes** (~24 requests/hour), far below free tier rate limits.
Every returned IP must pass a verification check to ensure it is a valid public IPv4 address. The check rejects:
### 2. IP Address Validation & Extraction
Every returned response is parsed with regex extraction and checked to ensure it is a valid public IPv4 address. The check rejects:
* Loopback ranges (`127.0.0.0/8`) * Loopback ranges (`127.0.0.0/8`)
* Private networks / RFC 1918 (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`) * Private networks / RFC 1918 (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`)
* Link-local addresses (`169.254.0.0/16`) * Link-local addresses (`169.254.0.0/16`)
@@ -45,22 +48,27 @@ Every returned IP must pass a verification check to ensure it is a valid public
--- ---
## 📊 Persistent History Registry ## 📊 Persistent History Registry & State
The monitor maintains a historical log of all your public IP assignments in a JSONLines format at `/var/lib/dynu/ip_history.jsonl`. ### 1. State File (`/var/lib/dynu/state.json`)
Stores the current round-robin cursor and the latest confirmed public IP:
Each entry records the timestamp, IP address, and status:
```json ```json
{"timestamp": "2026-06-24T02:00:00Z", "ip": "186.116.231.181", "status": "success"} {
{"timestamp": "2026-06-24T02:30:00Z", "ip": "186.116.231.181", "status": "success"} "last_provider_index": 2,
{"timestamp": "2026-06-24T03:00:00Z", "ip": "186.116.232.40", "status": "success"} "last_ip": "186.168.137.93"
}
``` ```
At each check, the monitor compares the current public IP with the **last recorded successful IP** in the history file. If they match, the monitor exits cleanly without invoking the DNS provider APIs. ### 2. Transition History Log (`/var/lib/dynu/ip_history.jsonl`)
The monitor maintains a historical log of all public IP rotations in JSONLines format:
```json
{"timestamp": "2026-09-07T12:00:00.000000+00:00", "ip": "190.253.250.211", "status": "success", "details": "Provider: https://api.ipify.org"}
{"timestamp": "2026-09-07T12:37:33.000000+00:00", "ip": "186.168.137.93", "status": "success", "details": "Provider: https://icanhazip.com"}
```
--- ---
## 🔑 secrets-management & sops-nix Integration ## 🔑 Secrets Management & sops-nix Integration
### Dynamic User Credentials Access ### Dynamic User Credentials Access
The `ddclient` service in NixOS runs with systemd `DynamicUser=true` for security. Because the dynamic user doesn't exist statically, standard file ownership can prevent access. The `ddclient` service in NixOS runs with systemd `DynamicUser=true` for security. Because the dynamic user doesn't exist statically, standard file ownership can prevent access.
@@ -79,14 +87,14 @@ We resolve this by using systemd **`LoadCredential`**:
## ⏱️ Systemd Timers & Services Configuration ## ⏱️ Systemd Timers & Services Configuration
The updater is divided into two systemd units defined in [dynu.nix](file:///home/kiskaadee/Config/hosts/desktop/dynu.nix): The updater is divided into two systemd units defined in [dynu.nix](file:///home/kiskaadee/Config/hosts/server/dynu.nix):
### 1. `dynu-monitor.timer` ### 1. `dynu-monitor.timer`
Runs every 30 minutes. It triggers the `dynu-monitor.service` which executes the Python script. Runs every 30 seconds. It triggers the `dynu-monitor.service` which executes the Python script.
### 2. `ddclient.service` (On-Demand) ### 2. `ddclient.service` (On-Demand)
The automatic `ddclient.timer` is disabled. The service is only triggered by the Python script using: The automatic `ddclient.timer` is disabled. The service is only triggered by the Python script using:
```bash ```bash
systemctl start ddclient.service systemctl start ddclient.service
``` ```
This ensures your host only makes outbound API calls to Dynu when a rotation actually occurs, maintaining zero overhead. This ensures your host only makes outbound API calls to Dynu when a rotation actually occurs, maintaining zero unnecessary DNS API overhead.
+8 -5
View File
@@ -65,7 +65,10 @@ in
User = "root"; User = "root";
Group = "root"; Group = "root";
StateDirectory = "dynu"; StateDirectory = "dynu";
Environment = "HISTORY_FILE=/var/lib/dynu/ip_history.jsonl"; Environment = [
"HISTORY_FILE=/var/lib/dynu/ip_history.jsonl"
"STATE_FILE=/var/lib/dynu/state.json"
];
ExecStart = "${ipMonitorScript}/bin/dynu-ip-monitor"; ExecStart = "${ipMonitorScript}/bin/dynu-ip-monitor";
TimeoutSec = 30; TimeoutSec = 30;
@@ -78,13 +81,13 @@ in
}; };
}; };
# 5. Run the smart IP change monitor periodically (every 30 minutes) # 5. Run the smart IP change monitor periodically (every 30 seconds)
systemd.timers.dynu-monitor = { systemd.timers.dynu-monitor = {
description = "Run Dynu IP monitor periodically"; description = "Run Dynu IP monitor periodically";
timerConfig = { timerConfig = {
OnBootSec = "5min"; OnBootSec = "10s";
OnUnitActiveSec = "30min"; OnUnitActiveSec = "30s";
AccuracySec = "1min"; AccuracySec = "1s";
Persistent = true; Persistent = true;
}; };
wantedBy = [ "timers.target" ]; wantedBy = [ "timers.target" ];
+104 -45
View File
@@ -2,82 +2,120 @@
Dynu DDNS Smart IP Change Monitor and Updater. Dynu DDNS Smart IP Change Monitor and Updater.
This script determines the current public IPv4 address by querying multiple This script determines the current public IPv4 address by querying multiple
external resolvers sequentially. It compares the discovered IP against the last external resolvers in a stateful round-robin rotation. It compares the
recorded successful IP in a local history log. If a change is detected, it discovered IP against the last recorded successful IP. If a change is
triggers the `ddclient.service` on-demand to perform the DNS record update. detected, it triggers `ddclient.service` on-demand to perform the DNS record
update.
This local-first state verification prevents making redundant API requests to This local-first state verification prevents making redundant API requests to
the DNS provider, avoiding rate-limiting, IP bans, or API abuse flags. the DNS provider, avoiding rate-limiting, IP bans, or API abuse flags while
allowing frequent polling intervals (e.g. every 30 seconds).
""" """
import urllib.request
import re
import json import json
import os import os
import re
import subprocess import subprocess
import sys import sys
from datetime import datetime import urllib.request
from datetime import datetime, timezone
# History file location storing the transition log of public IP states. # History and state file locations managed securely by the systemd service.
# Defaults to a state directory managed securely by the systemd service unit. HISTORY_FILE = os.environ.get(
HISTORY_FILE = os.environ.get("HISTORY_FILE", "/var/lib/dynu/ip_history.jsonl") "HISTORY_FILE", "/var/lib/dynu/ip_history.jsonl"
)
STATE_FILE = os.environ.get(
"STATE_FILE", "/var/lib/dynu/state.json"
)
# Fallback sequence of external services to discover the public WAN IP. # Pool of reputable external resolvers to discover the public WAN IP.
PROVIDERS = [ PROVIDERS = [
"https://api.ipify.org", "https://api.ipify.org",
"https://ifconfig.me/ip",
"https://icanhazip.com", "https://icanhazip.com",
"https://ifconfig.me/ip",
"https://checkip.dynu.com",
"https://wtfismyip.com/text" "https://wtfismyip.com/text"
] ]
def is_valid_public_ipv4(ip): def extract_public_ipv4(text):
""" """
Validates that a string is a properly formatted public IPv4 address. Extracts and validates the first valid public IPv4 address in text.
This function excludes standard private, loopback, link-local, and CGNAT This function excludes standard private, loopback, link-local, and CGNAT
blocks to avoid recording temporary, local, or invalid network states. blocks to avoid recording temporary, local, or invalid network states.
""" """
match = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip) match = re.search(r"\b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b", text)
if not match: if not match:
return False return None
octets = [int(x) for x in match.groups()] octets = [int(x) for x in match.groups()]
if any(x > 255 for x in octets): if any(x > 255 for x in octets):
return False return None
a, b, c, d = octets a, b, c, d = octets
# RFC 1918 Private ranges: 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12 # RFC 1918 Private ranges: 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12
if a == 10: if a == 10:
return False return None
if a == 192 and b == 168: if a == 192 and b == 168:
return False return None
if a == 172 and 16 <= b <= 31: if a == 172 and 16 <= b <= 31:
return False return None
# Carrier-Grade NAT (CGNAT) RFC 6598: 100.64.0.0/10 # Carrier-Grade NAT (CGNAT) RFC 6598: 100.64.0.0/10
if a == 100 and 64 <= b <= 127: if a == 100 and 64 <= b <= 127:
return False return None
# Loopback address range: 127.0.0.0/8 # Loopback address range: 127.0.0.0/8
if a == 127: if a == 127:
return False return None
# Link-local addresses: 169.254.0.0/16 # Link-local addresses: 169.254.0.0/16
if a == 169 and b == 254: if a == 169 and b == 254:
return False return None
return True return ".".join(str(x) for x in octets)
def get_public_ip(): def load_state():
""" """
Queries public IP providers until a valid public IPv4 is returned. Loads runtime state (last provider index and last verified IP).
"""
if not os.path.exists(STATE_FILE):
return {"last_provider_index": -1, "last_ip": None}
try:
with open(STATE_FILE, "r") as f:
return json.load(f)
except Exception as e:
print(f"Warning: Failed to read state file: {e}", file=sys.stderr)
return {"last_provider_index": -1, "last_ip": None}
def save_state(state):
"""
Persists runtime state atomically to disk.
"""
os.makedirs(os.path.dirname(STATE_FILE), exist_ok=True)
tmp_path = f"{STATE_FILE}.tmp"
try:
with open(tmp_path, "w") as f:
json.dump(state, f, indent=2)
os.replace(tmp_path, STATE_FILE)
except Exception as e:
print(f"Error: Failed to write to state file: {e}", file=sys.stderr)
def get_public_ip(start_index=0):
"""
Queries public IP providers in circular sequence starting from start_index.
Returns: Returns:
str: The validated public IP string, or None if all providers fail. tuple: (validated_ip_string, successful_idx) or (None, None).
""" """
errors = [] errors = []
for provider in PROVIDERS: num_providers = len(PROVIDERS)
for i in range(num_providers):
idx = (start_index + i) % num_providers
provider = PROVIDERS[idx]
try: try:
req = urllib.request.Request( req = urllib.request.Request(
provider, provider,
@@ -85,24 +123,29 @@ def get_public_ip():
'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)' 'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)'
} }
) )
# Fetch with 5s timeout to avoid hanging the systemd service
with urllib.request.urlopen(req, timeout=5) as response: with urllib.request.urlopen(req, timeout=5) as response:
ip = response.read().decode('utf-8').strip() raw_text = response.read().decode(
if is_valid_public_ipv4(ip): 'utf-8', errors='replace'
return ip ).strip()
ip = extract_public_ipv4(raw_text)
if ip:
return ip, idx
else: else:
errors.append(f"{provider}: invalid public IPv4 '{ip}'") snippet = raw_text[:50]
errors.append(
f"{provider}: no valid public IPv4 in '{snippet}'"
)
except Exception as e: except Exception as e:
errors.append(f"{provider}: {str(e)}") errors.append(f"{provider}: {e!s}")
print( print(
f"Error: All IP discovery providers failed. Details: {errors}", f"Error: All IP discovery providers failed. Details: {errors}",
file=sys.stderr file=sys.stderr
) )
return None return None, None
def get_last_recorded_ip(): def get_last_recorded_ip_from_history():
""" """
Reads the history log to locate the last successful IP address. Reads the history log to locate the last successful IP address.
@@ -116,7 +159,6 @@ def get_last_recorded_ip():
lines = f.readlines() lines = f.readlines()
if not lines: if not lines:
return None return None
# Search backwards to find the most recent successful transition
for line in reversed(lines): for line in reversed(lines):
try: try:
entry = json.loads(line) entry = json.loads(line)
@@ -135,7 +177,7 @@ def record_ip(ip, status, details=None):
""" """
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True) os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
entry = { entry = {
"timestamp": datetime.utcnow().isoformat() + "Z", "timestamp": datetime.now(timezone.utc).isoformat(),
"ip": ip, "ip": ip,
"status": status "status": status
} }
@@ -156,7 +198,6 @@ def trigger_ddclient():
tuple: (bool, str) representing (success_boolean, error_details_string) tuple: (bool, str) representing (success_boolean, error_details_string)
""" """
try: try:
# Run ddclient as a one-shot activation via systemd to perform API call
res = subprocess.run( res = subprocess.run(
["systemctl", "start", "ddclient.service"], ["systemctl", "start", "ddclient.service"],
capture_output=True, capture_output=True,
@@ -176,27 +217,45 @@ def trigger_ddclient():
def main(): def main():
""" """
Orchestrator logic for DDNS state management. Orchestrator logic for DDNS state management with provider rotation.
""" """
current_ip = get_public_ip() state = load_state()
last_provider_idx = state.get("last_provider_index", -1)
next_provider_idx = (last_provider_idx + 1) % len(PROVIDERS)
current_ip, successful_idx = get_public_ip(start_index=next_provider_idx)
if not current_ip: if not current_ip:
sys.exit(1) sys.exit(1)
last_ip = get_last_recorded_ip() state["last_provider_index"] = successful_idx
last_ip = state.get("last_ip") or get_last_recorded_ip_from_history()
if current_ip == last_ip: if current_ip == last_ip:
# IP matches last recorded working IP; do nothing to conserve quota # State matches; save provider rotation state and exit cleanly
save_state(state)
sys.exit(0) sys.exit(0)
print(f"IP rotation detected! Old: {last_ip}, New: {current_ip}") provider_name = PROVIDERS[successful_idx]
print(
f"IP rotation detected! Old: {last_ip}, New: {current_ip} "
f"(via {provider_name})"
)
# Trigger ddclient to perform the DNS record update # Trigger ddclient to perform the DNS record update
success, error_msg = trigger_ddclient() success, error_msg = trigger_ddclient()
if success: if success:
print("Dynu DDNS update via ddclient triggered successfully.") print("Dynu DDNS update via ddclient triggered successfully.")
record_ip(current_ip, "success") state["last_ip"] = current_ip
save_state(state)
record_ip(
current_ip,
"success",
details=f"Provider: {provider_name}"
)
else: else:
err_msg = f"Error: Failed to trigger ddclient update: {error_msg}" err_msg = f"Error: Failed to trigger ddclient update: {error_msg}"
print(err_msg, file=sys.stderr) print(err_msg, file=sys.stderr)
save_state(state)
record_ip(current_ip, "failed_update", details=error_msg) record_ip(current_ip, "failed_update", details=error_msg)
sys.exit(1) sys.exit(1)
+8 -5
View File
@@ -65,7 +65,10 @@ in
User = "root"; User = "root";
Group = "root"; Group = "root";
StateDirectory = "dynu"; StateDirectory = "dynu";
Environment = "HISTORY_FILE=/var/lib/dynu/ip_history.jsonl"; Environment = [
"HISTORY_FILE=/var/lib/dynu/ip_history.jsonl"
"STATE_FILE=/var/lib/dynu/state.json"
];
ExecStart = "${ipMonitorScript}/bin/dynu-ip-monitor"; ExecStart = "${ipMonitorScript}/bin/dynu-ip-monitor";
TimeoutSec = 30; TimeoutSec = 30;
@@ -78,13 +81,13 @@ in
}; };
}; };
# 5. Run the smart IP change monitor periodically (every 30 minutes) # 5. Run the smart IP change monitor periodically (every 30 seconds)
systemd.timers.dynu-monitor = { systemd.timers.dynu-monitor = {
description = "Run Dynu IP monitor periodically"; description = "Run Dynu IP monitor periodically";
timerConfig = { timerConfig = {
OnBootSec = "5min"; OnBootSec = "10s";
OnUnitActiveSec = "30min"; OnUnitActiveSec = "30s";
AccuracySec = "1min"; AccuracySec = "1s";
Persistent = true; Persistent = true;
}; };
wantedBy = [ "timers.target" ]; wantedBy = [ "timers.target" ];
+104 -45
View File
@@ -2,82 +2,120 @@
Dynu DDNS Smart IP Change Monitor and Updater. Dynu DDNS Smart IP Change Monitor and Updater.
This script determines the current public IPv4 address by querying multiple This script determines the current public IPv4 address by querying multiple
external resolvers sequentially. It compares the discovered IP against the last external resolvers in a stateful round-robin rotation. It compares the
recorded successful IP in a local history log. If a change is detected, it discovered IP against the last recorded successful IP. If a change is
triggers the `ddclient.service` on-demand to perform the DNS record update. detected, it triggers `ddclient.service` on-demand to perform the DNS record
update.
This local-first state verification prevents making redundant API requests to This local-first state verification prevents making redundant API requests to
the DNS provider, avoiding rate-limiting, IP bans, or API abuse flags. the DNS provider, avoiding rate-limiting, IP bans, or API abuse flags while
allowing frequent polling intervals (e.g. every 30 seconds).
""" """
import urllib.request
import re
import json import json
import os import os
import re
import subprocess import subprocess
import sys import sys
from datetime import datetime import urllib.request
from datetime import datetime, timezone
# History file location storing the transition log of public IP states. # History and state file locations managed securely by the systemd service.
# Defaults to a state directory managed securely by the systemd service unit. HISTORY_FILE = os.environ.get(
HISTORY_FILE = os.environ.get("HISTORY_FILE", "/var/lib/dynu/ip_history.jsonl") "HISTORY_FILE", "/var/lib/dynu/ip_history.jsonl"
)
STATE_FILE = os.environ.get(
"STATE_FILE", "/var/lib/dynu/state.json"
)
# Fallback sequence of external services to discover the public WAN IP. # Pool of reputable external resolvers to discover the public WAN IP.
PROVIDERS = [ PROVIDERS = [
"https://api.ipify.org", "https://api.ipify.org",
"https://ifconfig.me/ip",
"https://icanhazip.com", "https://icanhazip.com",
"https://ifconfig.me/ip",
"https://checkip.dynu.com",
"https://wtfismyip.com/text" "https://wtfismyip.com/text"
] ]
def is_valid_public_ipv4(ip): def extract_public_ipv4(text):
""" """
Validates that a string is a properly formatted public IPv4 address. Extracts and validates the first valid public IPv4 address in text.
This function excludes standard private, loopback, link-local, and CGNAT This function excludes standard private, loopback, link-local, and CGNAT
blocks to avoid recording temporary, local, or invalid network states. blocks to avoid recording temporary, local, or invalid network states.
""" """
match = re.match(r"^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$", ip) match = re.search(r"\b(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\b", text)
if not match: if not match:
return False return None
octets = [int(x) for x in match.groups()] octets = [int(x) for x in match.groups()]
if any(x > 255 for x in octets): if any(x > 255 for x in octets):
return False return None
a, b, c, d = octets a, b, c, d = octets
# RFC 1918 Private ranges: 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12 # RFC 1918 Private ranges: 10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12
if a == 10: if a == 10:
return False return None
if a == 192 and b == 168: if a == 192 and b == 168:
return False return None
if a == 172 and 16 <= b <= 31: if a == 172 and 16 <= b <= 31:
return False return None
# Carrier-Grade NAT (CGNAT) RFC 6598: 100.64.0.0/10 # Carrier-Grade NAT (CGNAT) RFC 6598: 100.64.0.0/10
if a == 100 and 64 <= b <= 127: if a == 100 and 64 <= b <= 127:
return False return None
# Loopback address range: 127.0.0.0/8 # Loopback address range: 127.0.0.0/8
if a == 127: if a == 127:
return False return None
# Link-local addresses: 169.254.0.0/16 # Link-local addresses: 169.254.0.0/16
if a == 169 and b == 254: if a == 169 and b == 254:
return False return None
return True return ".".join(str(x) for x in octets)
def get_public_ip(): def load_state():
""" """
Queries public IP providers until a valid public IPv4 is returned. Loads runtime state (last provider index and last verified IP).
"""
if not os.path.exists(STATE_FILE):
return {"last_provider_index": -1, "last_ip": None}
try:
with open(STATE_FILE, "r") as f:
return json.load(f)
except Exception as e:
print(f"Warning: Failed to read state file: {e}", file=sys.stderr)
return {"last_provider_index": -1, "last_ip": None}
def save_state(state):
"""
Persists runtime state atomically to disk.
"""
os.makedirs(os.path.dirname(STATE_FILE), exist_ok=True)
tmp_path = f"{STATE_FILE}.tmp"
try:
with open(tmp_path, "w") as f:
json.dump(state, f, indent=2)
os.replace(tmp_path, STATE_FILE)
except Exception as e:
print(f"Error: Failed to write to state file: {e}", file=sys.stderr)
def get_public_ip(start_index=0):
"""
Queries public IP providers in circular sequence starting from start_index.
Returns: Returns:
str: The validated public IP string, or None if all providers fail. tuple: (validated_ip_string, successful_idx) or (None, None).
""" """
errors = [] errors = []
for provider in PROVIDERS: num_providers = len(PROVIDERS)
for i in range(num_providers):
idx = (start_index + i) % num_providers
provider = PROVIDERS[idx]
try: try:
req = urllib.request.Request( req = urllib.request.Request(
provider, provider,
@@ -85,24 +123,29 @@ def get_public_ip():
'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)' 'User-Agent': 'Mozilla/5.0 (NixOS WAN Monitor)'
} }
) )
# Fetch with 5s timeout to avoid hanging the systemd service
with urllib.request.urlopen(req, timeout=5) as response: with urllib.request.urlopen(req, timeout=5) as response:
ip = response.read().decode('utf-8').strip() raw_text = response.read().decode(
if is_valid_public_ipv4(ip): 'utf-8', errors='replace'
return ip ).strip()
ip = extract_public_ipv4(raw_text)
if ip:
return ip, idx
else: else:
errors.append(f"{provider}: invalid public IPv4 '{ip}'") snippet = raw_text[:50]
errors.append(
f"{provider}: no valid public IPv4 in '{snippet}'"
)
except Exception as e: except Exception as e:
errors.append(f"{provider}: {str(e)}") errors.append(f"{provider}: {e!s}")
print( print(
f"Error: All IP discovery providers failed. Details: {errors}", f"Error: All IP discovery providers failed. Details: {errors}",
file=sys.stderr file=sys.stderr
) )
return None return None, None
def get_last_recorded_ip(): def get_last_recorded_ip_from_history():
""" """
Reads the history log to locate the last successful IP address. Reads the history log to locate the last successful IP address.
@@ -116,7 +159,6 @@ def get_last_recorded_ip():
lines = f.readlines() lines = f.readlines()
if not lines: if not lines:
return None return None
# Search backwards to find the most recent successful transition
for line in reversed(lines): for line in reversed(lines):
try: try:
entry = json.loads(line) entry = json.loads(line)
@@ -135,7 +177,7 @@ def record_ip(ip, status, details=None):
""" """
os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True) os.makedirs(os.path.dirname(HISTORY_FILE), exist_ok=True)
entry = { entry = {
"timestamp": datetime.utcnow().isoformat() + "Z", "timestamp": datetime.now(timezone.utc).isoformat(),
"ip": ip, "ip": ip,
"status": status "status": status
} }
@@ -156,7 +198,6 @@ def trigger_ddclient():
tuple: (bool, str) representing (success_boolean, error_details_string) tuple: (bool, str) representing (success_boolean, error_details_string)
""" """
try: try:
# Run ddclient as a one-shot activation via systemd to perform API call
res = subprocess.run( res = subprocess.run(
["systemctl", "start", "ddclient.service"], ["systemctl", "start", "ddclient.service"],
capture_output=True, capture_output=True,
@@ -176,27 +217,45 @@ def trigger_ddclient():
def main(): def main():
""" """
Orchestrator logic for DDNS state management. Orchestrator logic for DDNS state management with provider rotation.
""" """
current_ip = get_public_ip() state = load_state()
last_provider_idx = state.get("last_provider_index", -1)
next_provider_idx = (last_provider_idx + 1) % len(PROVIDERS)
current_ip, successful_idx = get_public_ip(start_index=next_provider_idx)
if not current_ip: if not current_ip:
sys.exit(1) sys.exit(1)
last_ip = get_last_recorded_ip() state["last_provider_index"] = successful_idx
last_ip = state.get("last_ip") or get_last_recorded_ip_from_history()
if current_ip == last_ip: if current_ip == last_ip:
# IP matches last recorded working IP; do nothing to conserve quota # State matches; save provider rotation state and exit cleanly
save_state(state)
sys.exit(0) sys.exit(0)
print(f"IP rotation detected! Old: {last_ip}, New: {current_ip}") provider_name = PROVIDERS[successful_idx]
print(
f"IP rotation detected! Old: {last_ip}, New: {current_ip} "
f"(via {provider_name})"
)
# Trigger ddclient to perform the DNS record update # Trigger ddclient to perform the DNS record update
success, error_msg = trigger_ddclient() success, error_msg = trigger_ddclient()
if success: if success:
print("Dynu DDNS update via ddclient triggered successfully.") print("Dynu DDNS update via ddclient triggered successfully.")
record_ip(current_ip, "success") state["last_ip"] = current_ip
save_state(state)
record_ip(
current_ip,
"success",
details=f"Provider: {provider_name}"
)
else: else:
err_msg = f"Error: Failed to trigger ddclient update: {error_msg}" err_msg = f"Error: Failed to trigger ddclient update: {error_msg}"
print(err_msg, file=sys.stderr) print(err_msg, file=sys.stderr)
save_state(state)
record_ip(current_ip, "failed_update", details=error_msg) record_ip(current_ip, "failed_update", details=error_msg)
sys.exit(1) sys.exit(1)