"""Root adapter: only the authenticated Node service may manage its own client.""" import json import os import pwd import socket import socketserver import struct import sys from pathlib import Path # Installed, root-owned sources from the same revision as Core. No third-party Python deps. sys.path.insert(0, str(Path(__file__).resolve().parent)) from netbird.client import Client SOCKET = Path("/run/mission-core-netbird/control.sock") def dispatch(client, body): if not isinstance(body, dict): raise ValueError("Некорректный запрос.") action = body.get("action") if action == "status" and set(body) == {"action"}: return client.status() if action == "cancel" and set(body) == {"action"}: return client.cancel() if action == "connect" and set(body) <= {"action", "server_url", "setup_key"}: return client.connect(body.get("server_url", ""), body.get("setup_key", "")) raise ValueError("Неизвестное действие.") class Handler(socketserver.StreamRequestHandler): def handle(self): self.connection.settimeout(20) _, uid, _ = struct.unpack( "3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12) ) if uid != self.server.uid: return try: raw = self.rfile.readline(4097) if len(raw) > 4096 or not raw.endswith(b"\n"): return result = {"ok": True, "result": dispatch(self.server.client, json.loads(raw))} except ValueError as error: result = {"ok": False, "error": str(error)} except Exception: result = {"ok": False, "error": "Служба NetBird недоступна. Повторите подключение."} self.wfile.write(json.dumps(result).encode() + b"\n") def main(): os.umask(0o077) user = pwd.getpwnam("mission-core-node") SOCKET.unlink(missing_ok=True) # Serial requests bound concurrency; connect/cancel themselves are non-blocking. with socketserver.UnixStreamServer(str(SOCKET), Handler) as server: server.uid = user.pw_uid server.client = Client(Path("/var/lib/mission-core-netbird")) os.chown(SOCKET, 0, user.pw_gid) os.chmod(SOCKET, 0o660) try: server.serve_forever() finally: server.client.close() if __name__ == "__main__": main()