mdns-termux/lib/mdns_tools/_stdlib_resolve.py

84 lines
2.5 KiB
Python
Raw Normal View History

feat: CLI unificado mdns con browse/reverse/IPv6/cache-TTL Cierra el gap hacia una implementacion mDNS/DNS-SD completa (RFC 6762/6763). CLI nuevo `bin/mdns` con subcomandos: - resolve : hostname -> IP (IPv4 stdlib rapido, IPv6 via zeroconf), cache TTL. - reverse : IP -> hostname (PTR multicast, IPv4/IPv6). - browse : descubrimiento DNS-SD (--list-types o --type _ssh._tcp.local.). - publish : anuncia hostname + servicios (SSH/SMB/HTTP) con probing y goodbye. - cache : list/clear del cache con TTL. Biblioteca lib/mdns_tools/ (cada modulo < 100 lineas): - resolve.py: stdlib-first para IPv4, zeroconf fallback para IPv6/miss. - _stdlib_resolve.py: resolver A puro stdlib, acumula todas las A del host. - _pick.py: elige la IP mas alcanzable ante multi-homing. Descarta rangos virtuales (libvirt 192.168.122/24, docker 172.17/16, link-local) devolviendo None para que el caller caiga a Tailscale en vez de a una IP muerta. - browse.py / publish.py: DNS-SD sobre zeroconf. - reverse.py: PTR stdlib. cache.py: TTL-aware JSON en ~/.cache/mdns. Mejoras de calidad: - IP_ADD_MEMBERSHIP en todos los sockets multicast. - Retries con backoff (timeout dividido). - Imports lazy en el CLI (resolve/cache no cargan zeroconf -> ~1s vs ~4s). Wrappers: - resolve (bash): orden mdns -> mdns-resolve stdlib -> Tailscale -> cache plano. - mdns-publish.py: shim compat sobre `mdns publish`, lee ~/.config/mdns/services.json. - install.sh: symlinks bin/ (updates via git pull), siembra services.json. - ssh_config.example: HostKeyAlias documentado (alias comparte known_hosts con el nombre canonico; evita fallos de verificacion tras reinstalar un host). - bashrc.snippet: aliases mdns-types/ssh/smb/http, mdns-cache, whor. Validado E2E en LAN: browse detecta 13 tipos; dell/movil resuelven a IP LAN real; lenovo (solo publica virbr0 192.168.122.1) cae correctamente a Tailscale; IPv6 de dell via zeroconf; reverse 192.168.1.17 -> dell-latitude3400.local; publish visible desde otro browser. Modulos < 100 lineas salvo el dispatcher. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-07-20 12:06:53 +00:00
"""IPv4 mDNS resolver using only Python stdlib. Used as no-dep fallback."""
import socket
import struct
import select
import time
MDNS_ADDR4 = "224.0.0.251"
MDNS_PORT = 5353
QTYPE_A = 1
def build_query(hostname: str, qtype: int = QTYPE_A) -> bytes:
header = struct.pack(">HHHHHH", 0, 0, 1, 0, 0, 0)
q = b""
for part in hostname.rstrip(".").split("."):
q += bytes([len(part)]) + part.encode()
q += b"\x00" + struct.pack(">HH", qtype, 1)
return header + q
def skip_name(data: bytes, off: int) -> int:
while off < len(data):
b = data[off]
if b == 0:
return off + 1
if b & 0xC0 == 0xC0:
return off + 2
off += b + 1
return off
def parse_all_a(data: bytes) -> list[tuple[str, int]]:
"""Return every A record (ip, ttl) in the response."""
out: list[tuple[str, int]] = []
if len(data) < 12:
return out
qd, an = struct.unpack(">HH", data[4:8])
off = 12
for _ in range(qd):
off = skip_name(data, off) + 4
for _ in range(an):
off = skip_name(data, off)
if off + 10 > len(data):
break
rtype, _, ttl, rdlen = struct.unpack(">HHIH", data[off:off + 10])
off += 10
if rtype == QTYPE_A and rdlen == 4 and off + 4 <= len(data):
out.append((socket.inet_ntoa(data[off:off + 4]), ttl))
off += rdlen
return out
def query_all(hostname: str, timeout: float) -> list[tuple[str, int]]:
"""Collect all A records advertised for hostname during the time window."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
mreq = socket.inet_aton(MDNS_ADDR4) + socket.inet_aton("0.0.0.0")
s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
except OSError:
pass
s.setblocking(False)
try:
s.sendto(build_query(hostname, QTYPE_A), (MDNS_ADDR4, MDNS_PORT))
except OSError:
s.close()
return []
found: list[tuple[str, int]] = []
end = time.time() + timeout
while time.time() < end:
r, _, _ = select.select([s], [], [], min(0.1, max(0.0, end - time.time())))
if r:
try:
data, _ = s.recvfrom(4096)
except OSError:
continue
recs = parse_all_a(data)
if recs:
found.extend(recs)
# Give a brief grace window for additional A packets, then stop.
end = min(end, time.time() + 0.15)
s.close()
return found