155 lines
4.9 KiB
Python
155 lines
4.9 KiB
Python
import logging
|
|
import socket
|
|
import struct
|
|
import threading
|
|
from typing import Callable, List, Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
GAME_PORT = 5056
|
|
|
|
PROTO_IPV4 = 0x0800
|
|
PROTO_IPV6 = 0x86DD
|
|
PROTO_VLAN = 0x8100
|
|
PROTO_QINQ = 0x88A8
|
|
IPPROTO_UDP = 17
|
|
|
|
ETH_P_ALL = 0x0003
|
|
|
|
MAX_FRAME = 65535
|
|
|
|
|
|
def _extract_udp_payload(frame: bytes) -> Optional[bytes]:
|
|
"""Returns the UDP payload if the ethernet frame carries UDP on port 5056.
|
|
|
|
Handles Ethernet, VLAN tags, IPv4 and IPv6 with basic extension handling.
|
|
"""
|
|
pos = 0
|
|
if len(frame) < 14:
|
|
return None
|
|
ethertype = struct.unpack(">H", frame[12:14])[0]
|
|
pos = 14
|
|
while ethertype in (PROTO_VLAN, PROTO_QINQ):
|
|
if len(frame) < pos + 4:
|
|
return None
|
|
ethertype = struct.unpack(">H", frame[pos + 2:pos + 4])[0]
|
|
pos += 4
|
|
if ethertype == PROTO_IPV4:
|
|
if len(frame) < pos + 20:
|
|
return None
|
|
version_ihl = frame[pos]
|
|
header_len = (version_ihl & 0x0F) * 4
|
|
protocol = frame[pos + 9]
|
|
payload = frame[pos + header_len:]
|
|
elif ethertype == PROTO_IPV6:
|
|
if len(frame) < pos + 40:
|
|
return None
|
|
next_header = frame[pos + 6]
|
|
header_len = 40
|
|
while next_header in (0, 43, 44, 60):
|
|
if len(frame) < pos + header_len + 8:
|
|
return None
|
|
hdr_ext_len = (frame[pos + header_len + 1] + 1) * 8
|
|
if next_header == 44:
|
|
next_header = frame[pos + header_len]
|
|
header_len += 8
|
|
continue
|
|
next_header = frame[pos + header_len]
|
|
header_len += hdr_ext_len
|
|
protocol = next_header
|
|
payload = frame[pos + header_len:]
|
|
else:
|
|
return None
|
|
if protocol != IPPROTO_UDP:
|
|
return None
|
|
if len(payload) < 8:
|
|
return None
|
|
src_port, dst_port, length = struct.unpack(">HHH", payload[0:6])
|
|
if src_port != GAME_PORT and dst_port != GAME_PORT:
|
|
return None
|
|
udp_len = length
|
|
if udp_len < 8 or udp_len > len(payload):
|
|
return None
|
|
return bytes(payload[8:udp_len])
|
|
|
|
|
|
class CaptureEngine:
|
|
"""Listens for Albion Online traffic on all non-loopback interfaces.
|
|
|
|
Mirrors the aoaddons packet sniffer: one AF_PACKET socket per interface,
|
|
forwarding only UDP packets on port 5056 to a shared decode pipeline.
|
|
"""
|
|
|
|
def __init__(self, on_udp: Callable[[bytes], None]):
|
|
self._on_udp = on_udp
|
|
self._sockets: List[socket.socket] = []
|
|
self._threads: List[threading.Thread] = []
|
|
self._stop = threading.Event()
|
|
|
|
@staticmethod
|
|
def interface_names() -> List[str]:
|
|
names = []
|
|
try:
|
|
for _index, name in socket.if_nameindex():
|
|
if name and name != 'lo':
|
|
names.append(name)
|
|
except OSError:
|
|
logger.warning("unable to enumerate network interfaces")
|
|
return names
|
|
|
|
def start(self) -> bool:
|
|
names = self.interface_names()
|
|
if not names:
|
|
logger.warning("no network interfaces available for capture")
|
|
return False
|
|
for name in names:
|
|
try:
|
|
sock = socket.socket(
|
|
socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL))
|
|
sock.bind((name, ETH_P_ALL))
|
|
sock.settimeout(1.0)
|
|
except OSError as e:
|
|
logger.warning("unable to bind %s: %s", name, e)
|
|
continue
|
|
self._sockets.append(sock)
|
|
thread = threading.Thread(
|
|
target=self._run_interface, args=(sock, name), daemon=True)
|
|
thread.start()
|
|
self._threads.append(thread)
|
|
logger.info("capturing on interface %s", name)
|
|
if not self._sockets:
|
|
logger.error("no interfaces could be captured (permissions?)")
|
|
return False
|
|
return True
|
|
|
|
def stop(self):
|
|
self._stop.set()
|
|
for sock in self._sockets:
|
|
try:
|
|
sock.close()
|
|
except OSError:
|
|
pass
|
|
for thread in self._threads:
|
|
thread.join(timeout=2.0)
|
|
self._sockets = []
|
|
self._threads = []
|
|
|
|
def _run_interface(self, sock: socket.socket, interface_name: str):
|
|
logger.debug("capture thread started for %s", interface_name)
|
|
try:
|
|
while not self._stop.is_set():
|
|
try:
|
|
frame = sock.recv(MAX_FRAME)
|
|
except socket.timeout:
|
|
continue
|
|
except OSError:
|
|
break
|
|
payload = _extract_udp_payload(frame)
|
|
if payload is None:
|
|
continue
|
|
try:
|
|
self._on_udp(payload)
|
|
except Exception:
|
|
logger.exception("error handling UDP payload")
|
|
finally:
|
|
logger.debug("capture thread stopped for %s", interface_name) |