-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtak_bridge.py
More file actions
406 lines (342 loc) · 13 KB
/
tak_bridge.py
File metadata and controls
406 lines (342 loc) · 13 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
"""
Bidirectional TCP bridge to a TAK Server.
Receives Cursor-on-Target (CoT) events from the TAK Server stream and
upserts them into the local tracks database. Periodically pushes local
tracks back to the TAK Server and sends a self-SA heartbeat.
The bridge is opt-in: it only starts when TAK_HOST is configured.
"""
import logging
import os
import socket
import ssl
import threading
import time
from datetime import datetime, timedelta, timezone
from typing import Any, Callable, Dict, List, Optional
from lxml import etree
log = logging.getLogger("tak_bridge")
SA_INTERVAL = 15 # seconds between self-SA heartbeats
MAX_BUF = 1 << 20 # 1 MB buffer limit before discard
# ---------------------------------------------------------------------------
# TAKBridge
# ---------------------------------------------------------------------------
class TAKBridge:
def __init__(
self,
host: str,
port: int,
tls: bool = False,
tls_insecure_skip_verify: bool = False,
cert_path: str = "",
key_path: str = "",
ca_path: str = "",
callsign: str = "COP-LITE",
push_interval: int = 30,
upsert_fn: Optional[Callable] = None,
list_fn: Optional[Callable] = None,
):
self.host = host
self.port = port
self.tls = tls
self.tls_insecure_skip_verify = tls_insecure_skip_verify
self.cert_path = cert_path
self.key_path = key_path
self.ca_path = ca_path
self.callsign = callsign
self.push_interval = push_interval
self._upsert_track = upsert_fn
self._list_tracks = list_fn
self._lock = threading.Lock()
self._running = False
self._connected = False
self._sock: Optional[socket.socket] = None
self._recv_thread: Optional[threading.Thread] = None
self._send_thread: Optional[threading.Thread] = None
# status counters
self._last_connected_at: Optional[str] = None
self._last_error: Optional[str] = None
self._reconnect_count = 0
self._events_received = 0
self._events_sent = 0
# -- lifecycle -----------------------------------------------------------
def start(self):
if self._running:
return
self._running = True
self._recv_thread = threading.Thread(
target=self._recv_loop, daemon=True, name="tak-recv"
)
self._send_thread = threading.Thread(
target=self._send_loop, daemon=True, name="tak-send"
)
self._recv_thread.start()
self._send_thread.start()
log.info("TAKBridge started -> %s:%s (TLS=%s)", self.host, self.port, self.tls)
def stop(self):
self._running = False
self._close_socket()
if self._recv_thread:
self._recv_thread.join(timeout=3)
if self._send_thread:
self._send_thread.join(timeout=3)
log.info("TAKBridge stopped")
def status(self) -> Dict[str, Any]:
with self._lock:
return {
"connected": self._connected,
"host": self.host,
"port": self.port,
"tls": self.tls,
"callsign": self.callsign,
"last_connected_at": self._last_connected_at,
"last_error": self._last_error,
"reconnect_count": self._reconnect_count,
"events_received": self._events_received,
"events_sent": self._events_sent,
}
# -- connection ----------------------------------------------------------
def _connect(self) -> socket.socket:
raw = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
raw.settimeout(10)
raw.connect((self.host, self.port))
if self.tls:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
if self.ca_path:
ctx.load_verify_locations(self.ca_path)
elif self.tls_insecure_skip_verify:
log.warning("TAK TLS certificate verification is DISABLED")
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
else:
ctx.load_default_certs()
if self.cert_path and self.key_path:
ctx.load_cert_chain(certfile=self.cert_path, keyfile=self.key_path)
raw = ctx.wrap_socket(raw, server_hostname=self.host)
raw.settimeout(None) # blocking for recv
return raw
def _close_socket(self):
with self._lock:
self._connected = False
if self._sock:
try:
self._sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
try:
self._sock.close()
except OSError:
pass
self._sock = None
# -- receive loop --------------------------------------------------------
def _recv_loop(self):
backoff = 1
while self._running:
try:
sock = self._connect()
with self._lock:
self._sock = sock
self._connected = True
self._last_connected_at = datetime.now(timezone.utc).isoformat()
backoff = 1
log.info("Connected to TAK Server %s:%s", self.host, self.port)
self._send_self_sa(sock)
self._stream_recv(sock)
except Exception as e:
with self._lock:
self._connected = False
self._last_error = str(e)
self._reconnect_count += 1
log.warning(
"TAK connection error: %s (reconnect in %ds)", e, backoff
)
self._close_socket()
if not self._running:
break
time.sleep(backoff)
backoff = min(backoff * 2, 60)
def _stream_recv(self, sock: socket.socket):
buf = b""
END_TAG = b"</event>"
while self._running:
try:
chunk = sock.recv(4096)
except socket.timeout:
continue
if not chunk:
log.info("TAK Server closed connection")
return
buf += chunk
# safety: discard oversized buffer (malformed stream)
if len(buf) > MAX_BUF:
log.warning("Buffer exceeded %d bytes, discarding", MAX_BUF)
buf = b""
continue
while END_TAG in buf:
end_idx = buf.index(END_TAG) + len(END_TAG)
raw_event = buf[:end_idx]
buf = buf[end_idx:]
start_idx = raw_event.find(b"<event")
if start_idx < 0:
continue
raw_event = raw_event[start_idx:]
try:
root = etree.fromstring(raw_event)
self._handle_event(root)
with self._lock:
self._events_received += 1
except etree.XMLSyntaxError as xe:
log.debug("Malformed CoT event, skipping: %s", xe)
# -- event handling ------------------------------------------------------
def _handle_event(self, root: etree._Element):
uid = root.get("uid") or root.get("id")
if not uid:
return
# skip our own heartbeat
if uid == self.callsign:
return
cot_type = root.get("type", "")
if cot_type.startswith("a-f"):
side = "friendly"
elif cot_type.startswith("a-h"):
side = "enemy"
elif cot_type.startswith("a-n"):
side = "neutral"
else:
side = "unknown"
if side == "friendly":
layer = "friendly"
elif side == "enemy":
layer = "enemy"
else:
layer = "other"
# derive SIDC
aff = {"friendly": "F", "enemy": "H", "neutral": "N"}.get(side, "U")
dim = "A" if len(cot_type) > 4 and cot_type[4:5] == "A" else "G"
sidc = f"S{aff}{dim}P------*****"
pt = root.find(".//point")
if pt is None:
return
try:
lat = float(pt.get("lat"))
lon = float(pt.get("lon"))
except (TypeError, ValueError):
return
# extract callsign from <detail><contact callsign="..."/>
callsign = uid
contact = root.find(".//detail/contact")
if contact is not None and contact.get("callsign"):
callsign = contact.get("callsign")
meta = {
"cot_type": cot_type,
"how": root.get("how"),
"time": root.get("time"),
"start": root.get("start"),
"stale": root.get("stale"),
"sidc": sidc,
"callsign": callsign,
"source": "tak_server",
}
if self._upsert_track:
self._upsert_track(uid, side, layer, lat, lon, meta)
# -- send loop -----------------------------------------------------------
def _send_loop(self):
last_sa = 0.0
last_push = 0.0
while self._running:
time.sleep(1)
with self._lock:
sock = self._sock
connected = self._connected
if not connected or sock is None:
continue
now = time.monotonic()
if now - last_sa >= SA_INTERVAL:
try:
self._send_self_sa(sock)
last_sa = now
except Exception as e:
log.debug("Error sending self-SA: %s", e)
if now - last_push >= self.push_interval:
try:
self._push_local_tracks(sock)
last_push = now
except Exception as e:
log.debug("Error pushing tracks: %s", e)
# -- self-SA heartbeat ---------------------------------------------------
def _send_self_sa(self, sock: socket.socket):
now = datetime.now(timezone.utc)
stale = now + timedelta(seconds=30)
fmt = "%Y-%m-%dT%H:%M:%SZ"
ev = etree.Element("event")
ev.set("version", "2.0")
ev.set("uid", self.callsign)
ev.set("type", "a-f-G-U-C")
ev.set("how", "h-g-i-g-o")
ev.set("time", now.strftime(fmt))
ev.set("start", now.strftime(fmt))
ev.set("stale", stale.strftime(fmt))
pt = etree.SubElement(ev, "point")
pt.set("lat", "0.0")
pt.set("lon", "0.0")
pt.set("hae", "0")
pt.set("ce", "9999999")
pt.set("le", "9999999")
detail = etree.SubElement(ev, "detail")
contact = etree.SubElement(detail, "contact")
contact.set("callsign", self.callsign)
group = etree.SubElement(detail, "__group")
group.set("name", "Cyan")
group.set("role", "HQ")
takv = etree.SubElement(detail, "takv")
takv.set("os", "COP-Lite")
takv.set("version", "1.0.0")
takv.set("device", "server")
takv.set("platform", "Tactical COP Lite")
sock.sendall(etree.tostring(ev, xml_declaration=True, encoding="UTF-8"))
# -- push local tracks ---------------------------------------------------
def _push_local_tracks(self, sock: socket.socket):
if not self._list_tracks:
return
tracks = self._list_tracks()
if not tracks:
return
now = datetime.now(timezone.utc)
fmt = "%Y-%m-%dT%H:%M:%SZ"
stale_ts = (now + timedelta(seconds=self.push_interval + 15)).strftime(fmt)
ts = now.strftime(fmt)
sent = 0
for t in tracks:
# skip tracks that came from TAK Server (prevent echo loop)
if t.get("meta", {}).get("source") == "tak_server":
continue
side = t["side"]
if side == "friendly":
default_type = "a-f-G-U-C"
elif side == "enemy":
default_type = "a-h-G-U-C"
elif side == "neutral":
default_type = "a-n-G-U-C"
else:
default_type = "a-u-G-U-C"
ev = etree.Element("event")
ev.set("version", "2.0")
ev.set("uid", t["uid"])
ev.set("type", t.get("meta", {}).get("cot_type", default_type))
ev.set("how", "m-g")
ev.set("time", ts)
ev.set("start", ts)
ev.set("stale", stale_ts)
pt = etree.SubElement(ev, "point")
pt.set("lat", str(t["lat"]))
pt.set("lon", str(t["lon"]))
pt.set("hae", "0")
pt.set("ce", "25")
pt.set("le", "25")
detail = etree.SubElement(ev, "detail")
contact = etree.SubElement(detail, "contact")
contact.set("callsign", t.get("meta", {}).get("callsign", t["uid"]))
sock.sendall(etree.tostring(ev, xml_declaration=True, encoding="UTF-8"))
sent += 1
if sent:
with self._lock:
self._events_sent += sent