#!/usr/bin/env python3 """Read AdGuard Home summary statistics; never change its settings.""" import argparse import base64 from datetime import datetime, timezone import ipaddress import json import math import os from pathlib import Path import ssl import stat import sys import urllib.error import urllib.parse import urllib.request MAX_RESPONSE_BYTES = 4 * 1024 * 1024 class ReportError(Exception): pass class NoRedirects(urllib.request.HTTPRedirectHandler): def redirect_request(self, request, fp, code, message, headers, new_url): fp.close() raise ReportError("The server redirected the request. Set the exact API base URL; redirects are not followed.") def load_config(path): path = Path(path).expanduser() try: fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) with os.fdopen(fd, "r", encoding="utf-8") as stream: info = os.fstat(stream.fileno()) if not stat.S_ISREG(info.st_mode): raise ReportError("The config must be a regular file.") if os.name == "posix" and (info.st_uid != os.getuid() or info.st_mode & 0o077): raise ReportError("The config must be owned by you and private. Run chmod 600 on the config file.") config = json.loads(stream.read(64 * 1024)) except ReportError: raise except (OSError, ValueError): raise ReportError("Cannot read the config. Check its path, permissions, and JSON syntax.") from None if not isinstance(config, dict): raise ReportError("The config must contain a JSON object.") for field in ("base_url", "username", "password"): if not isinstance(config.get(field), str) or not config[field]: raise ReportError("The config needs nonempty base_url, username, and password fields.") if ":" in config["username"] or any(c in config["username"] for c in "\r\n"): raise ReportError("The configured username is not valid for HTTP Basic authentication.") return config def validate_base_url(url): try: parsed = urllib.parse.urlsplit(url) port = parsed.port hostname = parsed.hostname except ValueError: raise ReportError("The configured API URL is invalid.") from None if parsed.scheme not in ("http", "https") or not hostname or parsed.username is not None or parsed.password is not None or parsed.query or parsed.fragment: raise ReportError("Use an http(s) base URL without credentials, query parameters, or a fragment.") if any(c.isspace() for c in url) or "\\" in url: raise ReportError("The configured API URL contains invalid characters.") if parsed.scheme == "http": try: local = ipaddress.ip_address(hostname).is_loopback except ValueError: local = False if not local: raise ReportError("Plain HTTP is allowed only on a loopback IP. Run this on the Pi, use an SSH tunnel, or configure verified HTTPS.") if port is not None and not 1 <= port <= 65535: raise ReportError("The configured API port is invalid.") path = parsed.path.rstrip("/") if path.endswith("/control"): raise ReportError("Use the web interface base URL without the /control suffix.") return url.rstrip("/") class AdGuardReader: def __init__(self, config, timeout=10): self.base_url = validate_base_url(config["base_url"]) self.timeout = timeout token = base64.b64encode((config["username"] + ":" + config["password"]).encode("utf-8")).decode("ascii") self.headers = {"Authorization": "Basic " + token, "Accept": "application/json", "User-Agent": "HiveNet-report/1.0"} self.opener = urllib.request.build_opener( urllib.request.ProxyHandler({}), NoRedirects(), urllib.request.HTTPSHandler(context=ssl.create_default_context()), ) def get(self, endpoint): request = urllib.request.Request(self.base_url + "/control/" + endpoint, headers=self.headers, method="GET") try: with self.opener.open(request, timeout=self.timeout) as response: if response.status != 200: raise ReportError("The API did not return a successful response.") body = response.read(MAX_RESPONSE_BYTES + 1) if len(body) > MAX_RESPONSE_BYTES: raise ReportError("The API response is too large; no raw data was saved.") result = json.loads(body) if not isinstance(result, dict): raise ReportError("The API returned an unexpected JSON shape.") return result except urllib.error.HTTPError as error: error.close() if error.code in (401, 403): raise ReportError("Authentication failed. Check the locally saved AdGuard credentials.") from None if error.code == 400: raise ReportError("The API rejected the request. Check the requested hours and statistics retention interval.") from None if error.code == 404: raise ReportError("API endpoint not found. Check the base URL and your installed AdGuard Home API version.") from None raise ReportError("The API returned HTTP " + str(error.code) + "; response content was not logged.") from None except ReportError: raise except (OSError, ValueError, urllib.error.URLError): raise ReportError("Could not read the API. Check the service, URL, TLS certificate, and network connection.") from None def number(value, name): if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0: raise ReportError("The API returned an invalid " + name + " value.") return value def boolean(value, name): if not isinstance(value, bool): raise ReportError("The API returned an invalid " + name + " value.") return value def build_report(reader, hours=None): status = reader.get("status") config = reader.get("stats/config") interval = number(config.get("interval"), "statistics interval") enabled = boolean(config.get("enabled"), "statistics enabled") running = boolean(status.get("running"), "DNS running") protection = boolean(status.get("protection_enabled"), "protection enabled") if hours is not None and (hours <= 0 or hours * 3600000 > interval): raise ReportError("Requested hours exceed configured statistics retention. Shorten --hours or omit it to use the configured interval.") result = { "report_version": 1, "collected_at_utc": datetime.now(timezone.utc).isoformat(), "dns_running": running, "protection_enabled": protection, "statistics_enabled": enabled, "period": "Last " + str(hours) + " hours requested from API" if hours is not None else "Configured statistics interval", "period_hours": hours if hours is not None else interval / 3600000, "queries": None, "blocked_by_filtering": None, "blocked_percent": None, "average_processing_ms": None, "warnings": [], } if not running: result["warnings"].append("AdGuard reports that its DNS service is not running.") if not protection: result["warnings"].append("AdGuard reports that protection is disabled.") if not enabled or not interval: result["warnings"].append("Statistics are disabled; counts are unavailable, not zero.") return result endpoint = "stats" + ("?recent=" + str(hours * 3600000) if hours is not None else "") stats = reader.get(endpoint) queries = number(stats.get("num_dns_queries"), "DNS query count") blocked = number(stats.get("num_blocked_filtering"), "filtered query count") average = number(stats.get("avg_processing_time"), "average processing time") if blocked > queries: raise ReportError("The API reported inconsistent query totals; no percentage was calculated.") result.update(queries=queries, blocked_by_filtering=blocked, blocked_percent=round(100 * blocked / queries, 2) if queries else None, average_processing_ms=round(1000 * average, 3)) if not queries: result["warnings"].append("No recorded queries in this interval. This does not prove that clients use this resolver.") return result def render_text(report): show = lambda value: "unavailable" if value is None else str(value) lines = ["HiveNet report", "Collected: " + report["collected_at_utc"], "Period: " + report["period"] + " (" + str(report["period_hours"]) + " h)", "DNS service running: " + str(report["dns_running"]), "Protection enabled: " + str(report["protection_enabled"]), "Queries: " + show(report["queries"]), "Blocked by filtering: " + show(report["blocked_by_filtering"]), "Blocked percentage: " + show(report["blocked_percent"]), "Average processing time (ms): " + show(report["average_processing_ms"])] lines += ["NOTICE: " + notice for notice in report["warnings"]] lines.append("Counts cover traffic recorded by AdGuard, not every connection or tracker on your network.") return "\n".join(lines) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--config", default="~/.config/hivenet/report.json", help="Private JSON config file (default: %(default)s)") parser.add_argument("--hours", type=int, help="Request a whole-hour lookback within configured statistics retention") parser.add_argument("--json", action="store_true", help="Print aggregate JSON instead of text") args = parser.parse_args(argv) try: report = build_report(AdGuardReader(load_config(args.config)), args.hours) except ReportError as error: print("HiveNet: " + str(error), file=sys.stderr) return 1 print(json.dumps(report, indent=2) if args.json else render_text(report)) return 2 if report["warnings"] else 0 if __name__ == "__main__": sys.exit(main())