Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
276 lines
9.8 KiB
Python
276 lines
9.8 KiB
Python
"""Approximate country/city from a fixed, integrity-pinned local DB-IP database.
|
|
|
|
The caller must enforce existing privacy consent and run this synchronous helper
|
|
outside the event loop. Import does not open data. There are no network calls,
|
|
DNS lookups, environment overrides, updates, input/result caches or log messages.
|
|
A missing/changed/broken asset disables lookups until process restart. The data
|
|
file must be deployed read-only and replaced only while the service is stopped.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import atexit
|
|
from contextlib import suppress
|
|
import hashlib
|
|
import ipaddress
|
|
import mmap
|
|
import os
|
|
import stat
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
ATTRIBUTION_TEXT = "IP Geolocation by DB-IP"
|
|
ATTRIBUTION_URL = "https://db-ip.com"
|
|
LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/"
|
|
SOURCE = "DB-IP Lite 2026-10 (https://db-ip.com)"
|
|
|
|
_DATA_PATH = Path(__file__).absolute().parent / "geo" / "dbip-city-lite-2026-10.mmdb"
|
|
_EXPECTED_SIZE = 126998165
|
|
_EXPECTED_SHA256 = "9e250f02722d1ad1780f88192f0e908af285478a33e76b88b349c9181ae9d0f5"
|
|
_HASH_CHUNK_SIZE = 1024 * 1024
|
|
_UNINITIALIZED = object()
|
|
_STATE = _UNINITIALIZED
|
|
_LOCK = threading.Lock()
|
|
|
|
# Conservative, explicit special-purpose exclusions also close classification
|
|
# differences between the Python 3.11 and 3.14 ipaddress registries. IPv6 is
|
|
# limited to allocated global unicast; mapped IPv4 is classified as IPv4 first.
|
|
_SPECIAL_V4 = tuple(
|
|
ipaddress.ip_network(network)
|
|
for network in ("192.0.0.0/24", "192.88.99.0/24")
|
|
)
|
|
_GLOBAL_V6 = ipaddress.ip_network("2000::/3")
|
|
_SPECIAL_V6 = tuple(
|
|
ipaddress.ip_network(network)
|
|
for network in ("2001::/23", "2001:db8::/32", "2002::/16", "3fff::/20")
|
|
)
|
|
|
|
__all__ = ["lookup_ip", "ATTRIBUTION_TEXT", "ATTRIBUTION_URL", "LICENSE_URL", "SOURCE"]
|
|
|
|
|
|
class _ReaderState:
|
|
__slots__ = ("path", "reader", "buffer", "signature")
|
|
|
|
def __init__(self, path, reader, buffer, signature):
|
|
self.path = path
|
|
self.reader = reader
|
|
self.buffer = buffer
|
|
self.signature = signature
|
|
|
|
|
|
def _canonical_public_ip(value):
|
|
if not isinstance(value, str) or not value or len(value) > 45 or "%" in value:
|
|
return None
|
|
try:
|
|
address = ipaddress.ip_address(value)
|
|
except ValueError:
|
|
return None
|
|
if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
|
|
address = address.ipv4_mapped
|
|
if (
|
|
not address.is_global
|
|
or address.is_private
|
|
or address.is_reserved
|
|
or address.is_loopback
|
|
or address.is_link_local
|
|
or address.is_multicast
|
|
or address.is_unspecified
|
|
):
|
|
return None
|
|
if isinstance(address, ipaddress.IPv4Address):
|
|
if any(address in network for network in _SPECIAL_V4):
|
|
return None
|
|
elif address not in _GLOBAL_V6 or any(address in network for network in _SPECIAL_V6):
|
|
return None
|
|
return str(address)
|
|
|
|
|
|
def _signature(info):
|
|
return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
|
|
|
|
|
|
def _regular_file_info(path):
|
|
info = path.stat(follow_symlinks=False)
|
|
if not stat.S_ISREG(info.st_mode):
|
|
raise ValueError("Geo data is not a regular file")
|
|
if getattr(info, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400):
|
|
raise ValueError("Geo data reparse points are not supported")
|
|
if info.st_size != _EXPECTED_SIZE:
|
|
raise ValueError("Geo data size does not match pin")
|
|
return info
|
|
|
|
|
|
def _local_path():
|
|
text = os.fspath(_DATA_PATH)
|
|
# A path override is not a supported interface. Keep even accidental local
|
|
# configuration changes from opening URLs, UNC shares or Windows devices.
|
|
if (
|
|
not isinstance(text, str)
|
|
or not text
|
|
or "\x00" in text
|
|
or "://" in text
|
|
or text.startswith(("\\", "//"))
|
|
or ":" in text[2:]
|
|
):
|
|
raise ValueError("Geo data must use a local absolute path")
|
|
path = Path(text)
|
|
if not path.is_absolute():
|
|
raise ValueError("Geo data path is not absolute")
|
|
return path
|
|
|
|
|
|
def _new_reader(buffer):
|
|
# Use only the inspected pure-Python implementation, not an installed
|
|
# package/extension. Feed the verified mapping directly to the pinned
|
|
# reader, avoiding a pathname re-open between verification and decode.
|
|
from vendor_entry_geo.reader import Reader
|
|
|
|
class _VerifiedMappedReader(Reader):
|
|
def _load_buffer(self, database, mode=0):
|
|
self._buffer = database
|
|
self._buffer_size = len(database)
|
|
return "verified offline DB-IP"
|
|
|
|
return _VerifiedMappedReader(buffer)
|
|
|
|
|
|
def _open_state():
|
|
path = _local_path()
|
|
expected_signature = _signature(_regular_file_info(path))
|
|
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
|
buffer = None
|
|
reader = None
|
|
try:
|
|
with os.fdopen(os.open(path, flags), "rb") as handle:
|
|
info = os.fstat(handle.fileno())
|
|
if not stat.S_ISREG(info.st_mode) or _signature(info) != expected_signature:
|
|
raise ValueError("Geo data changed while opening")
|
|
buffer = mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ)
|
|
if len(buffer) != _EXPECTED_SIZE or buffer.size() != _EXPECTED_SIZE:
|
|
raise ValueError("Geo mapping size does not match pin")
|
|
digest = hashlib.sha256()
|
|
for offset in range(0, _EXPECTED_SIZE, _HASH_CHUNK_SIZE):
|
|
digest.update(buffer[offset : offset + _HASH_CHUNK_SIZE])
|
|
if digest.hexdigest() != _EXPECTED_SHA256:
|
|
raise ValueError("Geo data integrity check failed")
|
|
if (
|
|
_signature(os.fstat(handle.fileno())) != expected_signature
|
|
or _signature(_regular_file_info(path)) != expected_signature
|
|
):
|
|
raise ValueError("Geo data changed while verifying")
|
|
reader = _new_reader(buffer)
|
|
metadata = reader.metadata()
|
|
if (
|
|
metadata.database_type != "DBIP-City-Lite"
|
|
or metadata.binary_format_major_version != 2
|
|
or metadata.ip_version != 6
|
|
):
|
|
raise ValueError("Unexpected geo database metadata")
|
|
state = _ReaderState(path, reader, buffer, expected_signature)
|
|
if not _still_current(state):
|
|
raise ValueError("Geo data changed while initializing")
|
|
return state
|
|
except Exception:
|
|
if reader is not None:
|
|
with suppress(Exception):
|
|
reader.close()
|
|
if buffer is not None:
|
|
with suppress(Exception):
|
|
buffer.close()
|
|
raise
|
|
|
|
|
|
def _still_current(state):
|
|
return (
|
|
_signature(_regular_file_info(state.path)) == state.signature
|
|
and state.buffer.size() == _EXPECTED_SIZE
|
|
)
|
|
|
|
|
|
def _name(value):
|
|
if not isinstance(value, str) or len(value) > 160 or any(not char.isprintable() for char in value):
|
|
return None
|
|
return value.strip()
|
|
|
|
|
|
def _approximate_record(record):
|
|
if not isinstance(record, dict):
|
|
return None
|
|
country = record.get("country")
|
|
city = record.get("city", {})
|
|
if not isinstance(country, dict) or not isinstance(city, dict):
|
|
return None
|
|
iso_code = country.get("iso_code")
|
|
if (
|
|
not isinstance(iso_code, str)
|
|
or len(iso_code) != 2
|
|
or not iso_code.isascii()
|
|
or not iso_code.isalpha()
|
|
or not iso_code.isupper()
|
|
or iso_code in ("ZZ", "XX", "EU", "AP")
|
|
):
|
|
return None
|
|
country_names = country.get("names", {})
|
|
city_names = city.get("names", {})
|
|
if not isinstance(country_names, dict) or not isinstance(city_names, dict):
|
|
return None
|
|
country_name = _name(country_names.get("en", ""))
|
|
city_name = _name(city_names.get("en", ""))
|
|
if country_name is None or city_name is None:
|
|
return None
|
|
# A missing city stays unknown (empty string); do not synthesize one from
|
|
# coordinates, subdivisions, a resolver, registered country or the input.
|
|
return {"country": country_name or iso_code, "city": city_name, "source": SOURCE}
|
|
|
|
|
|
def _disable_locked():
|
|
global _STATE
|
|
state = _STATE
|
|
_STATE = None
|
|
if isinstance(state, _ReaderState):
|
|
with suppress(Exception):
|
|
state.reader.close()
|
|
with suppress(Exception):
|
|
state.buffer.close()
|
|
|
|
|
|
def _close():
|
|
with _LOCK:
|
|
_disable_locked()
|
|
|
|
|
|
def lookup_ip(ip: str) -> dict[str, str] | None:
|
|
"""Return only approximate country/city/source for a public literal, or None.
|
|
|
|
IPv4-mapped IPv6 is canonicalized to IPv4. Non-public and ambiguous inputs
|
|
never initialize the reader. All file/integrity/reader failures are silent
|
|
unknown results, with no raw IP in logs, storage or outbound requests.
|
|
"""
|
|
global _STATE
|
|
canonical = _canonical_public_ip(ip)
|
|
if canonical is None:
|
|
return None
|
|
with _LOCK:
|
|
try:
|
|
if _STATE is _UNINITIALIZED:
|
|
_STATE = _open_state()
|
|
if _STATE is None:
|
|
return None
|
|
state = _STATE
|
|
if not _still_current(state):
|
|
_disable_locked()
|
|
return None
|
|
record = state.reader.get(canonical)
|
|
if not _still_current(state):
|
|
_disable_locked()
|
|
return None
|
|
return _approximate_record(record)
|
|
except Exception:
|
|
# Deliberately do not log exception text: third-party reader errors
|
|
# may include the lookup address. Fail once, closed, until restart.
|
|
_disable_locked()
|
|
return None
|
|
|
|
|
|
atexit.register(_close)
|