chore: rewrite as service, as CGI caused too many issues

This commit is contained in:
mxmehl committed 2026-10-22 13:49:04 +02:00
1 parent 9314781b08
commit 7a2d7c6650
9 files changed
+413 -107

No files matched your search

+78 -25
View File
@@ -1,26 +1,28 @@
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Snap DynDNS Server: dyndns2-style CGI broker that updates INWX records.
"""Snap DynDNS Server: dyndns2-style HTTP service that updates INWX records.
Clients authenticate with HTTP Basic Auth (user = hostname, password = token).
The INWX credentials never leave this server, and INWX is only contacted when
the IP of a hostname actually changed.
"""
import argparse
import base64
import contextlib
import fcntl
import hashlib
import hmac
import http
import http.client
import http.cookiejar
import http.server
import ipaddress
import json
import os
import ssl
import struct
import sys
import threading
import time
import tomllib
import urllib.parse
@@ -55,8 +57,8 @@ def totp(secret, now=None):
class _IPv4Https(urllib.request.HTTPSHandler):
"""HTTPS that only connects via IPv4.
The INWX API account is restricted to the server's IPv4 address, but a
confined CGI process may prefer IPv6. Binding to 0.0.0.0 makes
The INWX API account is restricted to the server's IPv4 address, but the
process may prefer IPv6 for dual-stack hosts. Binding to 0.0.0.0 makes
socket.create_connection() skip every IPv6 address.
"""
@@ -150,6 +152,9 @@ def _check_auth(env, cfg):
return None
_STATE_LOCK = threading.Lock()
def _load_state(path):
try:
with open(path) as f:
@@ -184,7 +189,11 @@ def handle(env, cfg, update=inwx_update):
ip = ipaddress.ip_address(raw)
except ValueError:
return 400, "badip"
# shortcut: syntax-only check (private/reserved IPs are accepted), reject them if clients misbehave
# Guards against publishing the proxy's address if client_ip_header is wrong
if not given and not ip.is_global:
print(f"snap-dyndns: {host}: connection address {ip} is not global, check client_ip_header", file=sys.stderr)
return 400, "badip"
# shortcut: explicit myip/myipv6 are only syntax-checked (private ranges accepted), tighten if clients misbehave
ips["A" if ip.version == 4 else "AAAA"] = str(ip)
zone = cfg["hosts"][host].get("zone") or ".".join(host.split(".")[-2:])
@@ -192,9 +201,8 @@ def handle(env, cfg, update=inwx_update):
os.makedirs(os.path.dirname(state_path), exist_ok=True)
lines = []
# shortcut: lock is held during the INWX call, fine at this load, split if updates ever get slow
with open(f"{state_path}.lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
# shortcut: one lock held during the INWX call, fine at this load, split per host if updates get slow
with _STATE_LOCK:
state = _load_state(state_path)
for rtype, ip in ips.items():
if state.get(host, {}).get(rtype) == ip:
@@ -216,21 +224,66 @@ def handle(env, cfg, update=inwx_update):
return 200, "\n".join(lines)
def main(env=os.environ, out=sys.stdout):
"""CGI entry point."""
try:
path = os.path.expanduser(env.get("SNAP_DYNDNS_CONFIG", DEFAULT_CONFIG))
class RequestHandler(http.server.BaseHTTPRequestHandler):
timeout = 30 # do not let stalled connections hold a thread forever
def do_GET(self):
url = urllib.parse.urlsplit(self.path)
if url.path != "/nic/update":
return self._reply(404, "not found")
try:
# Read per request, so devices can be added without restarting
with open(self.server.config_path, "rb") as f:
cfg = tomllib.load(f)
env = {
"QUERY_STRING": url.query,
"HTTP_AUTHORIZATION": self.headers.get("Authorization", ""),
"REMOTE_ADDR": self._client_ip(cfg),
}
status, body = handle(env, cfg)
except Exception as e: # noqa: BLE001 - always answer the client
print(f"snap-dyndns: {type(e).__name__}: {e}", file=sys.stderr)
status, body = 500, "911"
self._reply(status, body)
def _client_ip(self, cfg):
"""Address of the device: last entry of client_ip_header (added by our proxy), else the peer."""
name = cfg.get("client_ip_header")
if name:
return self.headers.get(name, "").split(",")[-1].strip()
return self.client_address[0]
def _reply(self, status, body):
data = (body + "\n").encode()
self.send_response(status)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
if status == 401:
self.send_header("WWW-Authenticate", 'Basic realm="Snap DynDNS"')
self.end_headers()
self.wfile.write(data)
def make_server(config_path, port, host="0.0.0.0"):
server = http.server.ThreadingHTTPServer((host, port), RequestHandler)
server.config_path = config_path
return server
def main(argv=None):
parser = argparse.ArgumentParser(description="Snap DynDNS Server (serves /nic/update)")
parser.add_argument("-c", "--config", default=DEFAULT_CONFIG, help=f"config file (default: {DEFAULT_CONFIG})")
parser.add_argument("-p", "--port", type=int, default=8080, help="port to listen on (default: 8080)")
args = parser.parse_args(argv)
path = os.path.expanduser(args.config)
try: # fail fast on a broken config; it is re-read on every request later
with open(path, "rb") as f:
cfg = tomllib.load(f)
status, body = handle(env, cfg)
except Exception as e: # noqa: BLE001 - a CGI must always answer
print(f"snap-dyndns: {type(e).__name__}: {e}", file=sys.stderr)
status, body = 500, "911"
headers = [
f"Status: {status} {http.HTTPStatus(status).phrase}",
"Content-Type: text/plain; charset=utf-8",
"Cache-Control: no-store",
]
if status == 401:
headers.append('WWW-Authenticate: Basic realm="Snap DynDNS"')
out.write("\n".join(headers) + "\n\n" + body + "\n")
tomllib.load(f)
except (OSError, tomllib.TOMLDecodeError) as e:
sys.exit(f"snap-dyndns: cannot use config {path}: {e}")
make_server(path, args.port).serve_forever()
if __name__ == "__main__":
main()