"""Clients, DNS query log, domain detail and blocked domains, all backed by AdGuard Home.""" import asyncio import logging import time from collections import Counter, defaultdict from fastapi import APIRouter, HTTPException, Query from pydantic import BaseModel, Field from app.hub import adguard, devices, settings from app.hub.db import db log = logging.getLogger("hub.dns") router = APIRouter() CATEGORIES = ["Computer", "Mobile", "Tablet", "IoT", "Server", "Network", "Media", "Gaming", "Other"] ONLINE_SECONDS = 600 def _decorate(rows: list[dict], index: dict) -> list[dict]: for r in rows: d = index.get(r["client"]) r["device"] = d return rows # ---------------------------------------------------------------- status @router.get("/dns/status") async def dns_status() -> dict: s = settings.get() if not s.adguard_configured: return {"configured": False, "ok": False, "message": "Set ADGUARD_URL in the hub's .env to see clients and DNS queries."} try: st = await adguard.get("/control/status") except adguard.AdGuardError as e: return {"configured": True, "ok": False, "url": s.adguard_url, "message": str(e)} return {"configured": True, "ok": True, "url": s.adguard_url, "version": st.get("version", ""), "protection_enabled": st.get("protection_enabled"), "running": st.get("running")} # ---------------------------------------------------------------- clients class DeviceMeta(BaseModel): name: str | None = Field(default=None, max_length=80) category: str | None = Field(default=None, max_length=40) suspicious: bool | None = None notes: str | None = Field(default=None, max_length=2000) def device_out(r, counts: dict | None = None, now: float | None = None, epoch: float | None = None) -> dict: """epoch: when the hub first saw any device. Devices from that first day aren't "new".""" now = now or time.time() return { "key": r["key"], "mac": r["mac"], "ip": r["ip"], "hostname": r["hostname"] or "", "name": r["name"] or "", "display": r["name"] or r["hostname"] or r["ip"] or r["mac"], "category": r["category"] or "", "suspicious": bool(r["suspicious"]), "notes": r["notes"] or "", "sources": [x for x in r["sources"].split(",") if x], "first_seen": r["first_seen"], "last_seen": r["last_seen"], "online": bool(r["last_seen"]) and now - r["last_seen"] < ONLINE_SECONDS, "new": now - r["first_seen"] < 86400 and (epoch is None or r["first_seen"] - epoch > 86400), "queries": (counts or {}).get(r["ip"]) if r["ip"] else None, } async def _client_counts() -> dict: if not settings.get().adguard_configured: return {} try: return dict(adguard.top_list((await adguard.stats()).get("top_clients"))) except adguard.AdGuardError: return {} @router.get("/clients") async def list_clients() -> dict: counts = await _client_counts() with db() as con: rows = con.execute("SELECT * FROM devices ORDER BY COALESCE(name, hostname, ip, mac) COLLATE NOCASE").fetchall() epoch = min((r["first_seen"] for r in rows), default=None) return {"clients": [device_out(r, counts, epoch=epoch) for r in rows], "categories": CATEGORIES, "adguard": settings.get().adguard_configured} def _device(con, key: str): row = con.execute("SELECT * FROM devices WHERE key = ?", (key,)).fetchone() if not row: raise HTTPException(404, "No client with that id") return row @router.get("/clients/{key}") async def get_client(key: str) -> dict: counts = await _client_counts() with db() as con: row = _device(con, key) ips = devices.ips_for(con, key) out = device_out(row, counts) out["ips"] = ips out["categories"] = CATEGORIES return out @router.put("/clients/{key}") def update_client(key: str, body: DeviceMeta) -> dict: with db() as con: _device(con, key) fields = body.model_dump(exclude_unset=True) if "suspicious" in fields: fields["suspicious"] = int(bool(fields["suspicious"])) for k in ("name", "category", "notes"): if k in fields: fields[k] = (fields[k] or "").strip() or None if fields: con.execute(f"UPDATE devices SET {', '.join(f'{k} = ?' for k in fields)} WHERE key = ?", (*fields.values(), key)) return device_out(_device(con, key)) @router.delete("/clients/{key}", status_code=204) def forget_client(key: str) -> None: with db() as con: _device(con, key) con.execute("DELETE FROM devices WHERE key = ?", (key,)) @router.get("/clients/{key}/summary") async def client_summary(key: str, sample: int = Query(1000, ge=50, le=5000)) -> dict: with db() as con: _device(con, key) ips = devices.ips_for(con, key) if not ips: return {"ips": [], "sample": 0, "top": [], "blocked_top": [], "blocked": 0, "since": None} wanted = set(ips) res = await adguard.collect(search=ips[0] if len(ips) == 1 else "", want=sample, keep=lambda r: r["client"] in wanted, max_rows=sample * 5) rows = res["rows"] top = Counter(r["domain"] for r in rows) blocked = Counter(r["domain"] for r in rows if r["blocked"]) return { "ips": ips, "sample": len(rows), "blocked": sum(blocked.values()), "since": min((r["ts"] for r in rows), default=None), "top": [{"domain": d, "count": c, "blocked": blocked.get(d, 0)} for d, c in top.most_common(25)], "blocked_top": [{"domain": d, "count": c} for d, c in blocked.most_common(10)], } # ---------------------------------------------------------------- query log @router.get("/dns/queries") async def queries(search: str = "", status: str = Query("all", pattern="^(all|blocked|allowed)$"), client: str = "", ip: str = "", domain: str = "", older_than: str = "", limit: int = Query(100, ge=1, le=500)) -> dict: """The AdGuard query log, newest first. `client` is a client id, `ip` a comma list of exact addresses.""" with db() as con: ips = {x.strip() for x in ip.split(",") if x.strip()} if client: ips.update(devices.ips_for(con, client) or ["-"]) index = devices.ip_index(con) domain = domain.strip().lower() def keep(r): if ips and r["client"] not in ips: return False if domain and r["domain"] != domain: return False if status == "allowed" and r["blocked"]: return False return True ag_search = search.strip() or domain or (next(iter(ips)) if len(ips) == 1 else "") res = await adguard.collect(search=ag_search, status="blocked" if status == "blocked" else "all", older_than=older_than, want=limit, keep=keep, max_rows=limit * 20) res["rows"] = _decorate(res["rows"], index) return res # ---------------------------------------------------------------- domains @router.get("/domains") async def top_domains() -> dict: st = await adguard.stats() return { "top_queried": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_queried_domains"))], "top_blocked": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_blocked_domains"))], "num_queries": st.get("num_dns_queries"), "num_blocked": st.get("num_blocked_filtering"), "time_units": st.get("time_units"), } @router.get("/domains/{name}") async def domain_detail(name: str, sample: int = Query(3000, ge=100, le=10000)) -> dict: name = name.strip().rstrip(".").lower() if not name or len(name) > 253: raise HTTPException(400, "Give a domain name, like example.com") base = adguard.base_domain(name) res = await adguard.collect(search=base, want=sample, max_rows=sample, keep=lambda r: r["domain"] == base or r["domain"].endswith("." + base)) rows = res["rows"] exact = [r for r in rows if r["domain"] == name] with db() as con: index = devices.ip_index(con) clients = defaultdict(lambda: {"count": 0, "blocked": 0, "last": 0.0, "name": ""}) for r in exact: c = clients[r["client"]] c["count"] += 1 c["blocked"] += r["blocked"] c["last"] = max(c["last"], r["ts"]) c["name"] = c["name"] or r["client_name"] related = Counter(r["domain"] for r in rows if r["domain"] != name) related_blocked = Counter(r["domain"] for r in rows if r["domain"] != name and r["blocked"]) now = time.time() hours = [0] * 24 blocked_hours = [0] * 24 for r in exact: age = int((now - r["ts"]) // 3600) if 0 <= age < 24: hours[23 - age] += 1 blocked_hours[23 - age] += r["blocked"] lat = [r["elapsed_ms"] for r in exact if r["elapsed_ms"] is not None] st = {} try: st = await adguard.stats() except adguard.AdGuardError: pass stats_count = dict(adguard.top_list(st.get("top_queried_domains"))).get(name) stats_blocked = dict(adguard.top_list(st.get("top_blocked_domains"))).get(name) return { "domain": name, "base": base, "sample_rows": len(rows), "scanned": res["scanned"], "complete": res["done"], "since": min((r["ts"] for r in rows), default=None), "count": len(exact), "blocked": sum(r["blocked"] for r in exact), "first": min((r["ts"] for r in exact), default=None), "last": max((r["ts"] for r in exact), default=None), "avg_ms": round(sum(lat) / len(lat), 2) if lat else None, "types": Counter(r["type"] for r in exact).most_common(), "reasons": Counter(r["reason"] for r in exact).most_common(), "rules": Counter(r["rule"] for r in exact if r["rule"]).most_common(5), "stats_count": stats_count, "stats_blocked": stats_blocked, "hours": hours, "blocked_hours": blocked_hours, "clients": sorted(({"ip": ip, **v, "device": index.get(ip)} for ip, v in clients.items()), key=lambda x: -x["count"]), "related": [{"domain": d, "count": c, "blocked": related_blocked.get(d, 0)} for d, c in related.most_common(50)], "recent": _decorate(exact[:50], index), } @router.get("/dns/blocked") async def blocked(sample: int = Query(1000, ge=50, le=5000)) -> dict: st = await adguard.stats() res = await adguard.collect(status="blocked", want=sample, max_rows=sample, keep=lambda r: r["blocked"]) with db() as con: index = devices.ip_index(con) agg = defaultdict(lambda: {"count": 0, "clients": set(), "last": 0.0, "rule": "", "reason": ""}) for r in res["rows"]: a = agg[r["domain"]] a["count"] += 1 a["clients"].add(r["client"]) a["last"] = max(a["last"], r["ts"]) a["rule"] = a["rule"] or r["rule"] a["reason"] = a["reason"] or r["reason"] recent = [ {"domain": d, "count": a["count"], "last": a["last"], "rule": a["rule"], "reason": a["reason"], "clients": [{"ip": ip, "device": index.get(ip)} for ip in sorted(a["clients"])]} for d, a in sorted(agg.items(), key=lambda kv: -kv[1]["count"]) ] return { "top": [{"domain": d, "count": c} for d, c in adguard.top_list(st.get("top_blocked_domains"))], "num_blocked": st.get("num_blocked_filtering"), "num_queries": st.get("num_dns_queries"), "recent": recent, "sample": len(res["rows"]), "since": min((r["ts"] for r in res["rows"]), default=None), } # ---------------------------------------------------------------- discovery (background) async def discover_once() -> int: """Pull client lists, DHCP leases and recent queries from AdGuard into the device table.""" if not settings.get().adguard_configured: return 0 found: list[dict] = [] clients = await adguard.get("/control/clients") for c in clients.get("clients") or []: ids = c.get("ids") or [] macs = [i for i in ids if devices.norm_mac(i)] ips = [i for i in ids if i.replace(".", "").isdigit() or (":" in i and not devices.norm_mac(i) and "/" not in i)] for ip in ips or [None]: found.append({"ip": ip, "mac": macs[0] if macs else None, "hostname": c.get("name"), "source": "adguard"}) for c in clients.get("auto_clients") or []: found.append({"ip": c.get("ip"), "hostname": c.get("name"), "source": f"adguard-{(c.get('source') or 'auto').lower()}"}) try: dhcp = await adguard.get("/control/dhcp/status") for lease in (dhcp.get("leases") or []) + (dhcp.get("static_leases") or []): found.append({"ip": lease.get("ip"), "mac": lease.get("mac"), "hostname": lease.get("hostname"), "source": "dhcp"}) except adguard.AdGuardError: pass # DHCP not in use recent = await adguard.collect(want=adguard.PAGE, max_rows=adguard.PAGE) last: dict[str, tuple[float, str]] = {} for r in recent["rows"]: if r["client"] and r["ts"] > last.get(r["client"], (0, ""))[0]: last[r["client"]] = (r["ts"], r["client_name"]) def write(): with db() as con: for f in found: devices.sighting(con, ip=f["ip"], mac=f.get("mac"), hostname=f.get("hostname"), source=f["source"]) for ip, (ts, name) in last.items(): devices.sighting(con, ip=ip, hostname=name or None, source="dns", seen=ts) await asyncio.to_thread(write) return len(found) + len(last) async def discovery_loop(every: float = 60) -> None: while True: try: await discover_once() except (adguard.AdGuardError, adguard.NotConfigured) as e: log.warning("client discovery: %s", e) except Exception: log.exception("client discovery failed") await asyncio.sleep(every)