Spaces:
Running

axeronis commited on
Commit
b8370de
·
1 Parent(s): ecc63ec

Fix: Indentation and robust DNS patching for Telegram SNI issues

Browse files
backend/app/services/telegram_service.py CHANGED
@@ -31,21 +31,35 @@ class TelegramService:
31
  return await client.post(url, **kwargs)
32
  except (httpx.ConnectError, OSError) as e:
33
  if "No address associated with hostname" in str(e) or "[Errno -5]" in str(e):
34
- logger.warning(f"⚠️ DNS failure for {url}. Switching to direct IP fallback.")
35
- # Replace hostname with IP
36
- fallback_url = url.replace("api.telegram.org", self.TELEGRAM_API_IP)
37
- # We must disable SSL verification for IP-based requests OR provide the hostname in headers
38
- headers = kwargs.get("headers", {})
39
- headers["Host"] = "api.telegram.org"
40
- kwargs["headers"] = headers
41
-
42
- # Note: verify=False is needed because certificate mismatch (IP vs valid domain)
43
- async with httpx.AsyncClient(timeout=30.0, verify=False) as client:
44
  if method.lower() == 'get':
45
- return await client.get(fallback_url, **kwargs)
46
  else:
47
- return await client.post(fallback_url, **kwargs)
48
  raise e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  def _get_url(self, token: str, method: str) -> str:
51
  return f"{self.base_url}{token}/{method}"
 
31
  return await client.post(url, **kwargs)
32
  except (httpx.ConnectError, OSError) as e:
33
  if "No address associated with hostname" in str(e) or "[Errno -5]" in str(e):
34
+ logger.warning(f"⚠️ DNS failure for {url}. Activating robust DNS patch for HF.")
35
+ self._activate_dns_patch()
36
+ # Retry with original URL (now that DNS is patched)
37
+ async with httpx.AsyncClient(timeout=30.0) as client:
 
 
 
 
 
 
38
  if method.lower() == 'get':
39
+ return await client.get(url, **kwargs)
40
  else:
41
+ return await client.post(url, **kwargs)
42
  raise e
43
+
44
+ def _activate_dns_patch(self):
45
+ """
46
+ Monkeypatch socket.getaddrinfo to resolve api.telegram.org manually.
47
+ This fixes SNI and Host header issues that occur with direct IP URLs.
48
+ """
49
+ if getattr(socket, "_is_patched_by_microfunnel", False):
50
+ return
51
+
52
+ logger.info("🔧 Applying DNS monkeypatch for api.telegram.org -> 149.154.167.220")
53
+ _orig_getaddrinfo = socket.getaddrinfo
54
+
55
+ def _patched_getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
56
+ if host == "api.telegram.org":
57
+ # Return hardcoded valid Telegram IP
58
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (self.TELEGRAM_API_IP, port))]
59
+ return _orig_getaddrinfo(host, port, family, type, proto, flags)
60
+
61
+ socket.getaddrinfo = _patched_getaddrinfo
62
+ socket._is_patched_by_microfunnel = True
63
 
64
  def _get_url(self, token: str, method: str) -> str:
65
  return f"{self.base_url}{token}/{method}"