Really-amin commited on
Commit
a24d8a8
·
verified ·
1 Parent(s): a808cd1

Upload backend/services/exchange_dns_resolver.py with huggingface_hub

Browse files
backend/services/exchange_dns_resolver.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """DoH (DNS-over-HTTPS) resolver — non-US DNS providers for exchange API hosts."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import logging
8
+ import socket
9
+ from typing import Dict, List, Optional
10
+
11
+ import httpx
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ # Prefer EU/global resolvers (not US-centric filtering)
16
+ DOH_PROVIDERS: List[Dict[str, str]] = [
17
+ {"name": "quad9", "url": "https://dns.quad9.net/dns-query"},
18
+ {"name": "cloudflare", "url": "https://cloudflare-dns.com/dns-query"},
19
+ {"name": "adguard", "url": "https://dns.adguard-dns.com/dns-query"},
20
+ {"name": "google", "url": "https://dns.google/resolve"},
21
+ ]
22
+
23
+
24
+ class ExchangeDNSResolver:
25
+ """Resolve exchange hostnames via DoH, cache A records."""
26
+
27
+ def __init__(self) -> None:
28
+ self._cache: Dict[str, List[str]] = {}
29
+
30
+ async def resolve(self, hostname: str) -> Optional[str]:
31
+ if hostname in self._cache and self._cache[hostname]:
32
+ return self._cache[hostname][0]
33
+
34
+ for provider in DOH_PROVIDERS:
35
+ try:
36
+ async with httpx.AsyncClient(timeout=6.0) as client:
37
+ resp = await client.get(
38
+ provider["url"],
39
+ params={"name": hostname, "type": "A"},
40
+ headers={"accept": "application/dns-json"},
41
+ )
42
+ if resp.status_code != 200:
43
+ continue
44
+ data = resp.json()
45
+ answers = data.get("Answer") or []
46
+ ips = [a["data"] for a in answers if a.get("type") == 1 and a.get("data")]
47
+ if ips:
48
+ self._cache[hostname] = ips
49
+ logger.info("DoH %s: %s -> %s", provider["name"], hostname, ips[0])
50
+ return ips[0]
51
+ except Exception as exc:
52
+ logger.debug("DoH %s failed for %s: %s", provider["name"], hostname, exc)
53
+
54
+ try:
55
+ loop = asyncio.get_event_loop()
56
+ ip = await loop.run_in_executor(None, socket.gethostbyname, hostname)
57
+ if ip:
58
+ self._cache[hostname] = [ip]
59
+ return ip
60
+ except Exception:
61
+ pass
62
+
63
+ return None
64
+
65
+ async def fetch_via_doh(
66
+ self,
67
+ base_url: str,
68
+ path: str,
69
+ params: Optional[dict] = None,
70
+ timeout: float = 12.0,
71
+ ) -> Optional[httpx.Response]:
72
+ """HTTP GET to resolved IP with correct Host header (SNI)."""
73
+ hostname = base_url.split("://", 1)[-1].split("/")[0]
74
+ ip = await self.resolve(hostname)
75
+ if not ip:
76
+ return None
77
+
78
+ url = f"https://{ip}{path}"
79
+ headers = {"Host": hostname, "Accept": "application/json"}
80
+ try:
81
+ async with httpx.AsyncClient(
82
+ timeout=timeout,
83
+ verify=False,
84
+ headers=headers,
85
+ ) as client:
86
+ return await client.get(url, params=params)
87
+ except Exception as exc:
88
+ logger.debug("DoH fetch failed %s%s: %s", hostname, path, exc)
89
+ return None