Repository navigation
Expand file tree
/
Copy pathenrich.py
More file actions
247 lines (195 loc) · 7.11 KB
/
Copy pathenrich.py
File metadata and controls
247 lines (195 loc) · 7.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"""enrich.py – geolocate IPs via ip-api.com, with a persistent SQLite cache
and an optional local GeoLite2 fallback for when the API is rate-limited
or unreachable."""
from __future__ import annotations
import json
import logging
import os
import pathlib
import sqlite3
import sys
import threading
import time
from typing import Dict, Optional, Tuple
import requests
logger = logging.getLogger(__name__)
_CACHE: Dict[str, Tuple[float, Optional[dict]]] = {}
_CACHE_TTL = 3600 # seconds – 1 hour
_GEO_URL = "http://ip-api.com/json/{ip}?fields=status,lat,lon,city,country,org,as,query"
_MY_GEO_URL = "http://ip-api.com/json/?fields=status,lat,lon,city,country,query"
_SESSION = requests.Session()
_SESSION.headers.update({"User-Agent": "NetMapGuard/2.0"})
# ---------------------------------------------------------------------------
# Persistent cache (SQLite) – survives restarts so we don't re-burn the
# ip-api.com free-tier quota (45 req/min) every time NetMapGuard is launched.
# ---------------------------------------------------------------------------
def _user_data_dir() -> pathlib.Path:
"""Writable per-user directory for cache/config data.
A packaged (PyInstaller) build may live in a read-only location (e.g.
Program Files) or run from a temporary extraction dir, so it can't rely
on writing next to its own source file the way a plain script can.
"""
if getattr(sys, "frozen", False):
return pathlib.Path.home() / ".netmapguard"
return pathlib.Path(__file__).parent
_DB_PATH = _user_data_dir() / ".cache" / "geo_cache.sqlite3"
_DB_LOCK = threading.Lock()
def _db_connect() -> sqlite3.Connection:
_DB_PATH.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(_DB_PATH, check_same_thread=False)
conn.execute(
"CREATE TABLE IF NOT EXISTS geo_cache (ip TEXT PRIMARY KEY, data TEXT, ts REAL)"
)
conn.commit()
return conn
_DB = _db_connect()
def _db_get(ip: str) -> Optional[Tuple[float, Optional[dict]]]:
with _DB_LOCK:
row = _DB.execute("SELECT data, ts FROM geo_cache WHERE ip = ?", (ip,)).fetchone()
if row is None:
return None
data_json, ts = row
return ts, json.loads(data_json)
def _db_set(ip: str, result: Optional[dict], ts: float) -> None:
with _DB_LOCK:
_DB.execute(
"INSERT OR REPLACE INTO geo_cache (ip, data, ts) VALUES (?, ?, ?)",
(ip, json.dumps(result), ts),
)
_DB.commit()
def _db_clear() -> None:
with _DB_LOCK:
_DB.execute("DELETE FROM geo_cache")
_DB.commit()
# ---------------------------------------------------------------------------
# Local GeoLite2 fallback (optional) – kicks in when ip-api.com fails or is
# rate-limited, keeping the map populated even offline / over quota.
# Requires the `geoip2` package and a GeoLite2-City.mmdb file (MaxMind
# license required, not bundled) at NETMAPGUARD_GEOIP_DB or one of the
# default locations below.
# ---------------------------------------------------------------------------
try:
import geoip2.database
import geoip2.errors
_GEOIP_AVAILABLE = True
except ImportError:
_GEOIP_AVAILABLE = False
_GEOIP_DB_ENV_VAR = "NETMAPGUARD_GEOIP_DB"
_DEFAULT_GEOIP_PATHS = [
_user_data_dir() / "GeoLite2-City.mmdb",
pathlib.Path.home() / ".netmapguard" / "GeoLite2-City.mmdb",
]
_geoip_reader = None
_geoip_checked = False
def _get_geoip_reader():
"""Lazily open the local GeoLite2 database, if available. Cached after first call."""
global _geoip_reader, _geoip_checked
if _geoip_checked:
return _geoip_reader
_geoip_checked = True
if not _GEOIP_AVAILABLE:
return None
env_path = os.environ.get(_GEOIP_DB_ENV_VAR)
candidates = [pathlib.Path(env_path)] if env_path else _DEFAULT_GEOIP_PATHS
for candidate in candidates:
if candidate.is_file():
try:
_geoip_reader = geoip2.database.Reader(str(candidate))
logger.info("Local GeoLite2 fallback enabled (%s)", candidate)
except Exception:
logger.warning("Failed to open GeoLite2 database at %s", candidate)
break
return _geoip_reader
def _geolocate_local(ip: str) -> Optional[dict]:
reader = _get_geoip_reader()
if reader is None:
return None
try:
resp = reader.city(ip)
except (geoip2.errors.AddressNotFoundError, ValueError):
return None
except Exception:
return None
if resp.location.latitude is None or resp.location.longitude is None:
return None
return {
"ip": ip,
"lat": resp.location.latitude,
"lon": resp.location.longitude,
"city": resp.city.name or "",
"country": resp.country.name or "",
"org": "",
"asn": "",
}
def _fetch_geo(url: str) -> Optional[dict]:
try:
resp = _SESSION.get(url, timeout=2)
resp.raise_for_status()
data = resp.json()
if data.get("status") == "success":
return data
except requests.ConnectTimeout:
# Network timeout - likely due to firewall/DNS block
pass
except requests.ReadTimeout:
# Server timeout
pass
except requests.RequestException:
# Any other request error
pass
except Exception:
# JSON parsing or other errors
pass
return None
def geolocate(ip: str) -> Optional[dict]:
"""Return geolocation dict for *ip*, using a TTL cache backed by SQLite.
Falls back to a local GeoLite2 database (if configured) when ip-api.com
is unreachable or rate-limited.
Returns a dict with keys: lat, lon, city, country, org, asn, ip
or None if lookup failed.
"""
now = time.time()
if ip in _CACHE:
ts, cached = _CACHE[ip]
if now - ts < _CACHE_TTL:
return cached
else:
persisted = _db_get(ip)
if persisted is not None:
ts, cached = persisted
if now - ts < _CACHE_TTL:
_CACHE[ip] = (ts, cached)
return cached
data = _fetch_geo(_GEO_URL.format(ip=ip))
result: Optional[dict] = None
if data:
result = {
"ip": data.get("query", ip),
"lat": data["lat"],
"lon": data["lon"],
"city": data.get("city", ""),
"country": data.get("country", ""),
"org": data.get("org", ""),
"asn": data.get("as", ""),
}
else:
result = _geolocate_local(ip)
_CACHE[ip] = (now, result)
_db_set(ip, result, now)
return result
def get_my_location() -> dict:
"""Return approximate geolocation of this machine's public IP."""
data = _fetch_geo(_MY_GEO_URL)
if data:
return {
"ip": data.get("query", "unknown"),
"lat": data["lat"],
"lon": data["lon"],
"city": data.get("city", ""),
"country": data.get("country", ""),
}
return {"ip": "unknown", "lat": 0.0, "lon": 0.0, "city": "", "country": ""}
def clear_cache() -> None:
"""Clear the geolocation cache (in-memory and persistent), useful for testing."""
_CACHE.clear()
_db_clear()