mirror of
https://github.com/sunnypilot/sunnypilot.git
synced 2026-12-04 01:03:43 +08:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e2e137bc23 | |||
| 99d321972d | |||
| 45a2bde6a2 | |||
| 58c521a2e6 |
@@ -7,6 +7,7 @@ See the LICENSE.md file in the root directory for more details.
|
||||
import base64
|
||||
import gzip
|
||||
import json
|
||||
import time
|
||||
|
||||
from openpilot.common.hardware import HARDWARE
|
||||
from openpilot.common.params import ParamKeyType
|
||||
@@ -52,11 +53,12 @@ def _default_wifi():
|
||||
|
||||
|
||||
class Rpc:
|
||||
def __init__(self, params, wifi=None, telemetry=None):
|
||||
def __init__(self, params, wifi=None, telemetry=None, p2p=None):
|
||||
self._params = params
|
||||
self._wifi_factory = wifi or _default_wifi
|
||||
self._wifi_obj = None
|
||||
self._telemetry = telemetry
|
||||
self._p2p_obj = p2p
|
||||
self._pending: list[tuple[str, int, float]] = [] # hotspot.start waiting for the hotspot
|
||||
|
||||
def handle(self, token: str, body: bytes, grants: list[dict], this: str | None, now: float) -> tuple[dict | None, str | None]:
|
||||
@@ -85,6 +87,8 @@ class Rpc:
|
||||
else:
|
||||
waiting.append((token, rid, deadline))
|
||||
self._pending = waiting
|
||||
if self._p2p_obj is not None:
|
||||
self._p2p_obj.poll(now)
|
||||
return done
|
||||
|
||||
def _dispatch(self, token, rid, method, args, grants, this, now):
|
||||
@@ -132,8 +136,44 @@ class Rpc:
|
||||
raise _refused("topics must be a list of names")
|
||||
self._telemetry.unsubscribe(token, topics)
|
||||
return _envelope(rid, result={"ok": True}), None
|
||||
if method == "p2p.capabilities":
|
||||
return _envelope(rid, result=self._p2p().capabilities()), None
|
||||
if method == "p2p.start":
|
||||
transport = args.get("transport")
|
||||
if not isinstance(transport, str):
|
||||
raise _refused("transport must be a string")
|
||||
ttl = args.get("ttl_sec", 90.0)
|
||||
ssid = args.get("ssid") if isinstance(args.get("ssid"), str) else None
|
||||
passphrase = args.get("passphrase") if isinstance(args.get("passphrase"), str) else None
|
||||
try:
|
||||
return _envelope(rid, result=self._p2p().start(transport, ttl_sec=ttl, now=now, ssid=ssid, passphrase=passphrase)), None
|
||||
except (ValueError, RuntimeError, Exception) as e:
|
||||
raise _refused(f"p2p start failed: {e}") from e
|
||||
if method == "p2p.keepalive":
|
||||
sid = args.get("session_id")
|
||||
if not isinstance(sid, str):
|
||||
raise _refused("session_id required")
|
||||
ttl = args.get("ttl_sec", 90.0)
|
||||
try:
|
||||
return _envelope(rid, result=self._p2p().keepalive(sid, ttl_sec=ttl, now=now)), None
|
||||
except KeyError as e:
|
||||
raise _refused(str(e)) from e
|
||||
if method == "p2p.stop":
|
||||
sid = args.get("session_id")
|
||||
self._p2p().stop(sid if isinstance(sid, str) else None)
|
||||
return _envelope(rid, result={"ok": True}), None
|
||||
raise RpcError(METHOD_NOT_FOUND, f"unknown method {method}")
|
||||
|
||||
def _p2p(self):
|
||||
if self._p2p_obj is None:
|
||||
from openpilot.sunnypilot.system.p2p.manager import P2pManager
|
||||
self._p2p_obj = P2pManager(self._wifi, rpc_handler=self._handle_p2p_rpc, telemetry_hub=self._telemetry)
|
||||
return self._p2p_obj
|
||||
|
||||
def _handle_p2p_rpc(self, body: bytes) -> dict | None:
|
||||
resp, _ = self.handle("lan-wifi", body, [], None, time.monotonic())
|
||||
return resp
|
||||
|
||||
def _wifi(self):
|
||||
if self._wifi_obj is None:
|
||||
try:
|
||||
@@ -146,7 +186,7 @@ class Rpc:
|
||||
return {"ssid": wifi.tethering_ssid, "password": wifi.tethering_password}
|
||||
|
||||
def _status(self, grants: list[dict]) -> dict:
|
||||
caps = ["ssh"]
|
||||
caps = ["ssh", "p2p"]
|
||||
if self._telemetry is not None:
|
||||
caps.append("telemetry")
|
||||
return {"version": get_version(), "agnos": HARDWARE.get_os_version(), "dongle_id": self._params.get("DongleId"),
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
@@ -0,0 +1,138 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import secrets
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
from openpilot.sunnypilot.system.p2p.server import P2P_PORT, P2pTlsServer
|
||||
from openpilot.sunnypilot.system.p2p.transports import (
|
||||
ActiveTransport,
|
||||
LanWifiTransport,
|
||||
SoftApTransport,
|
||||
WifiDirectTransport,
|
||||
get_wlan0_ipv4,
|
||||
)
|
||||
|
||||
DEFAULT_TTL_SEC = 90.0
|
||||
MIN_TTL_SEC = 15.0
|
||||
MAX_TTL_SEC = 180.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class _ActiveSession:
|
||||
session_id: str
|
||||
transport: ActiveTransport
|
||||
backend: object
|
||||
server: P2pTlsServer
|
||||
auth_token: str
|
||||
ttl_sec: float
|
||||
expires_at: float
|
||||
|
||||
|
||||
class P2pManager:
|
||||
def __init__(self, wifi_factory, rpc_handler=None, telemetry_hub=None):
|
||||
self._lan = LanWifiTransport()
|
||||
self._direct = WifiDirectTransport()
|
||||
self._softap = SoftApTransport(wifi_factory)
|
||||
self._rpc_handler = rpc_handler
|
||||
self._telemetry = telemetry_hub
|
||||
self._active: _ActiveSession | None = None
|
||||
|
||||
def capabilities(self) -> dict:
|
||||
transports = []
|
||||
wlan0_ip = get_wlan0_ipv4()
|
||||
if wlan0_ip is not None:
|
||||
transports.append("lan_wifi")
|
||||
if self._direct.is_ready():
|
||||
transports.append("wifi_direct")
|
||||
transports.append("softap")
|
||||
return {
|
||||
"transports": transports,
|
||||
"wlan0_ip": wlan0_ip,
|
||||
}
|
||||
|
||||
def start(self, kind: str, ttl_sec: float = DEFAULT_TTL_SEC, now: float | None = None,
|
||||
ssid: str | None = None, passphrase: str | None = None) -> dict:
|
||||
now = time.monotonic() if now is None else now
|
||||
ttl = max(MIN_TTL_SEC, min(MAX_TTL_SEC, float(ttl_sec)))
|
||||
self.stop()
|
||||
|
||||
backend = {"lan_wifi": self._lan, "wifi_direct": self._direct, "softap": self._softap}.get(kind)
|
||||
if backend is None:
|
||||
raise ValueError(f"unsupported transport {kind}")
|
||||
|
||||
session_id = secrets.token_hex(12)
|
||||
auth_token = secrets.token_urlsafe(32)
|
||||
if kind == "wifi_direct":
|
||||
active = backend.start(session_id, ssid=ssid, passphrase=passphrase)
|
||||
else:
|
||||
active = backend.start(session_id)
|
||||
server = P2pTlsServer(
|
||||
bind_host=active.bind_host,
|
||||
port=P2P_PORT,
|
||||
auth_token=auth_token,
|
||||
bind_interface=active.bind_interface,
|
||||
rpc_handler=self._rpc_handler,
|
||||
telemetry_hub=self._telemetry,
|
||||
on_activity=self.touch,
|
||||
)
|
||||
try:
|
||||
server.start()
|
||||
except Exception:
|
||||
backend.stop()
|
||||
raise
|
||||
|
||||
self._active = _ActiveSession(
|
||||
session_id=session_id,
|
||||
transport=active,
|
||||
backend=backend,
|
||||
server=server,
|
||||
auth_token=auth_token,
|
||||
ttl_sec=ttl,
|
||||
expires_at=now + ttl,
|
||||
)
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"transport": active.kind,
|
||||
"peer_host": active.peer_host,
|
||||
"peer_port": P2P_PORT,
|
||||
"auth_token": auth_token,
|
||||
"tls_cert_sha256": server.cert_sha256,
|
||||
"ssid": active.ssid,
|
||||
"passphrase": active.passphrase,
|
||||
"ttl_sec": int(ttl),
|
||||
}
|
||||
|
||||
def touch(self) -> None:
|
||||
if self._active is not None:
|
||||
self._active.expires_at = time.monotonic() + self._active.ttl_sec
|
||||
|
||||
def keepalive(self, session_id: str, ttl_sec: float = DEFAULT_TTL_SEC, now: float | None = None) -> dict:
|
||||
now = time.monotonic() if now is None else now
|
||||
if self._active is None or self._active.session_id != session_id:
|
||||
raise KeyError("unknown p2p session")
|
||||
ttl = max(MIN_TTL_SEC, min(MAX_TTL_SEC, float(ttl_sec)))
|
||||
self._active.ttl_sec = ttl
|
||||
self._active.expires_at = now + ttl
|
||||
return {"session_id": session_id, "ttl_sec": int(ttl)}
|
||||
|
||||
def stop(self, session_id: str | None = None) -> None:
|
||||
if self._active is None:
|
||||
return
|
||||
if session_id is not None and self._active.session_id != session_id:
|
||||
return
|
||||
sess = self._active
|
||||
self._active = None
|
||||
try:
|
||||
sess.server.stop()
|
||||
finally:
|
||||
sess.backend.stop()
|
||||
|
||||
def poll(self, now: float | None = None) -> None:
|
||||
now = time.monotonic() if now is None else now
|
||||
if self._active is not None and now >= self._active.expires_at:
|
||||
self.stop()
|
||||
@@ -0,0 +1,373 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
P2P_PORT = 8443
|
||||
ALLOWED_TUNNEL_PORTS = frozenset({22})
|
||||
WS_MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
|
||||
def generate_ephemeral_tls_cert() -> tuple[str, str, str]:
|
||||
tmp_dir = tempfile.mkdtemp(prefix="sunnylink-p2p-tls-")
|
||||
key_path = os.path.join(tmp_dir, "key.pem")
|
||||
cert_path = os.path.join(tmp_dir, "cert.pem")
|
||||
der_path = os.path.join(tmp_dir, "cert.der")
|
||||
subprocess.run(
|
||||
[
|
||||
"openssl", "req", "-x509", "-newkey", "ec",
|
||||
"-pkeyopt", "ec_paramgen_curve:prime256v1",
|
||||
"-keyout", key_path, "-out", cert_path,
|
||||
"-days", "1", "-nodes", "-subj", "/CN=sunnylink-p2p",
|
||||
],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
subprocess.run(
|
||||
["openssl", "x509", "-in", cert_path, "-outform", "DER", "-out", der_path],
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
with open(der_path, "rb") as f:
|
||||
fingerprint = hashlib.sha256(f.read()).hexdigest()
|
||||
return cert_path, key_path, fingerprint
|
||||
|
||||
|
||||
def _ws_frame(opcode: int, payload: bytes) -> bytes:
|
||||
header = bytearray([0x80 | (opcode & 0x0F)])
|
||||
length = len(payload)
|
||||
if length < 126:
|
||||
header.append(length)
|
||||
elif length < 65536:
|
||||
header.append(126)
|
||||
header.extend(struct.pack("!H", length))
|
||||
else:
|
||||
header.append(127)
|
||||
header.extend(struct.pack("!Q", length))
|
||||
return bytes(header) + payload
|
||||
|
||||
|
||||
async def _read_ws_frame(reader: asyncio.StreamReader) -> tuple[int, bytes] | None:
|
||||
try:
|
||||
b1, b2 = await reader.readexactly(2)
|
||||
except (asyncio.IncompleteReadError, ConnectionError):
|
||||
return None
|
||||
opcode = b1 & 0x0F
|
||||
masked = (b2 & 0x80) != 0
|
||||
length = b2 & 0x7F
|
||||
if length == 126:
|
||||
length = struct.unpack("!H", await reader.readexactly(2))[0]
|
||||
elif length == 127:
|
||||
length = struct.unpack("!Q", await reader.readexactly(8))[0]
|
||||
if length > 1024 * 1024:
|
||||
return None
|
||||
mask_key = await reader.readexactly(4) if masked else b""
|
||||
payload = bytearray(await reader.readexactly(length))
|
||||
if masked:
|
||||
for i in range(length):
|
||||
payload[i] ^= mask_key[i % 4]
|
||||
return opcode, bytes(payload)
|
||||
|
||||
|
||||
class P2pTlsServer:
|
||||
def __init__(
|
||||
self,
|
||||
bind_host: str,
|
||||
port: int,
|
||||
auth_token: str,
|
||||
bind_interface: str | None = None,
|
||||
rpc_handler: Callable[[bytes], dict | None] | None = None,
|
||||
telemetry_hub=None,
|
||||
on_activity: Callable[[], None] | None = None,
|
||||
):
|
||||
self._bind_host = bind_host
|
||||
self._port = port
|
||||
self._auth_token = auth_token
|
||||
self._bind_interface = bind_interface
|
||||
self._rpc_handler = rpc_handler
|
||||
self._telemetry = telemetry_hub
|
||||
self._on_activity = on_activity
|
||||
self._cert_path, self._key_path, self.cert_sha256 = generate_ephemeral_tls_cert()
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
self._server: asyncio.AbstractServer | None = None
|
||||
self._ready = threading.Event()
|
||||
self._error: Exception | None = None
|
||||
|
||||
def start(self) -> None:
|
||||
self._ready.clear()
|
||||
self._error = None
|
||||
self._thread = threading.Thread(target=self._run_loop, name="p2p-tls-server", daemon=True)
|
||||
self._thread.start()
|
||||
if not self._ready.wait(timeout=5.0):
|
||||
raise RuntimeError("P2P TLS server startup timed out")
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
|
||||
def stop(self) -> None:
|
||||
loop = self._loop
|
||||
if loop is not None and loop.is_running():
|
||||
loop.call_soon_threadsafe(self._shutdown_in_loop)
|
||||
if self._thread is not None:
|
||||
self._thread.join(timeout=2.0)
|
||||
self._thread = None
|
||||
for path in (self._cert_path, self._key_path):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _shutdown_in_loop(self) -> None:
|
||||
if self._server is not None:
|
||||
self._server.close()
|
||||
if self._loop is not None:
|
||||
self._loop.stop()
|
||||
|
||||
def _run_loop(self) -> None:
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
self._loop = loop
|
||||
try:
|
||||
loop.run_until_complete(self._start_server())
|
||||
except Exception as e:
|
||||
self._error = e
|
||||
self._ready.set()
|
||||
return
|
||||
self._ready.set()
|
||||
try:
|
||||
loop.run_forever()
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
async def _start_server(self) -> None:
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
ctx.load_cert_chain(self._cert_path, self._key_path)
|
||||
|
||||
host_clean = self._bind_host.split("%")[0]
|
||||
family = socket.AF_INET6 if ":" in host_clean else socket.AF_INET
|
||||
sock = socket.socket(family, socket.SOCK_STREAM)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
||||
if self._bind_interface:
|
||||
try:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, self._bind_interface.encode())
|
||||
except OSError:
|
||||
pass
|
||||
sock.bind((host_clean, self._port))
|
||||
sock.listen(32)
|
||||
sock.setblocking(False)
|
||||
self._server = await asyncio.start_server(self._handle_client, sock=sock, ssl=ctx)
|
||||
|
||||
def _authorized(self, headers: dict[str, str]) -> bool:
|
||||
auth = headers.get("authorization", "")
|
||||
if not auth.startswith("Bearer "):
|
||||
return False
|
||||
return hmac.compare_digest(auth[7:].strip(), self._auth_token)
|
||||
|
||||
async def _handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
|
||||
try:
|
||||
first = True
|
||||
while True:
|
||||
try:
|
||||
head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=10.0 if first else 60.0)
|
||||
except Exception:
|
||||
break
|
||||
first = False
|
||||
|
||||
lines = head.decode("latin1").split("\r\n")
|
||||
parts = lines[0].split(" ")
|
||||
if len(parts) < 2:
|
||||
break
|
||||
method, target = parts[0].upper(), parts[1]
|
||||
headers: dict[str, str] = {}
|
||||
for line in lines[1:]:
|
||||
if ":" in line:
|
||||
k, v = line.split(":", 1)
|
||||
headers[k.strip().lower()] = v.strip()
|
||||
|
||||
if not self._authorized(headers):
|
||||
await self._send_json(writer, 401, {"error": "unauthorized"})
|
||||
break
|
||||
|
||||
if self._on_activity is not None:
|
||||
self._on_activity()
|
||||
|
||||
keep_alive = headers.get("connection", "").lower() != "close"
|
||||
|
||||
try:
|
||||
if method == "GET" and target == "/v1/ping":
|
||||
await self._send_json(writer, 200, {"ok": True}, keep_alive=keep_alive)
|
||||
elif method == "POST" and target == "/v1/rpc":
|
||||
await self._handle_rpc(reader, writer, headers, keep_alive=keep_alive)
|
||||
elif method == "GET" and target == "/v1/telemetry":
|
||||
await self._handle_telemetry_ws(reader, writer, headers)
|
||||
return
|
||||
elif method == "CONNECT" and target.startswith("/v1/tunnel/"):
|
||||
await self._handle_tunnel(reader, writer, target)
|
||||
return
|
||||
else:
|
||||
await self._send_json(writer, 404, {"error": "not found"}, keep_alive=keep_alive)
|
||||
except Exception:
|
||||
break
|
||||
|
||||
if not keep_alive:
|
||||
break
|
||||
finally:
|
||||
if not writer.is_closing():
|
||||
writer.close()
|
||||
|
||||
async def _send_json(self, writer: asyncio.StreamWriter, status: int, body: dict, keep_alive: bool = False) -> None:
|
||||
raw = json.dumps(body, separators=(",", ":")).encode("utf-8")
|
||||
reason = {200: "OK", 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden",
|
||||
404: "Not Found", 502: "Bad Gateway", 503: "Service Unavailable"}.get(status, "Error")
|
||||
conn = "keep-alive" if keep_alive else "close"
|
||||
resp = (
|
||||
f"HTTP/1.1 {status} {reason}\r\n"
|
||||
f"Content-Type: application/json\r\n"
|
||||
f"Content-Length: {len(raw)}\r\n"
|
||||
f"Connection: {conn}\r\n\r\n"
|
||||
).encode("latin1") + raw
|
||||
writer.write(resp)
|
||||
await writer.drain()
|
||||
|
||||
async def _handle_rpc(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter,
|
||||
headers: dict[str, str], keep_alive: bool = False) -> None:
|
||||
if self._rpc_handler is None:
|
||||
await self._send_json(writer, 503, {"error": "rpc unavailable"}, keep_alive=keep_alive)
|
||||
return
|
||||
try:
|
||||
content_len = int(headers.get("content-length", "0"))
|
||||
except ValueError:
|
||||
await self._send_json(writer, 400, {"error": "invalid content-length"})
|
||||
return
|
||||
if content_len <= 0 or content_len > 256 * 1024:
|
||||
await self._send_json(writer, 400, {"error": "invalid body size"})
|
||||
return
|
||||
body = await asyncio.wait_for(reader.readexactly(content_len), timeout=10.0)
|
||||
resp = self._rpc_handler(body)
|
||||
if resp is None:
|
||||
await self._send_json(writer, 503, {"error": "async rpc unsupported over wifi"}, keep_alive=keep_alive)
|
||||
return
|
||||
await self._send_json(writer, 200, resp, keep_alive=keep_alive)
|
||||
|
||||
async def _handle_telemetry_ws(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, headers: dict[str, str]) -> None:
|
||||
key = headers.get("sec-websocket-key")
|
||||
if self._telemetry is None or not key:
|
||||
await self._send_json(writer, 400, {"error": "websocket unavailable"})
|
||||
writer.close()
|
||||
return
|
||||
accept = base64.b64encode(hashlib.sha1((key + WS_MAGIC).encode("latin1")).digest()).decode("latin1")
|
||||
writer.write((
|
||||
"HTTP/1.1 101 Switching Protocols\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
f"Sec-WebSocket-Accept: {accept}\r\n\r\n"
|
||||
).encode("latin1"))
|
||||
await writer.drain()
|
||||
|
||||
dev_id = f"wifi-{id(writer)}"
|
||||
stop = asyncio.Event()
|
||||
|
||||
async def recv_loop() -> None:
|
||||
while not stop.is_set():
|
||||
frame = await _read_ws_frame(reader)
|
||||
if frame is None:
|
||||
break
|
||||
opcode, payload = frame
|
||||
if opcode == 0x8: # close
|
||||
break
|
||||
if opcode == 0x9: # ping
|
||||
writer.write(_ws_frame(0xA, payload))
|
||||
await writer.drain()
|
||||
continue
|
||||
if opcode == 0x1: # text
|
||||
try:
|
||||
msg = json.loads(payload.decode("utf-8"))
|
||||
if isinstance(msg.get("subscribe"), dict):
|
||||
self._telemetry.subscribe(dev_id, msg["subscribe"], time.monotonic())
|
||||
if isinstance(msg.get("unsubscribe"), list):
|
||||
self._telemetry.unsubscribe(dev_id, msg["unsubscribe"])
|
||||
except Exception:
|
||||
pass
|
||||
stop.set()
|
||||
|
||||
async def send_loop() -> None:
|
||||
while not stop.is_set():
|
||||
frames = self._telemetry.drain(time.monotonic())
|
||||
for target_dev, payload in frames:
|
||||
if target_dev == dev_id:
|
||||
writer.write(_ws_frame(0x1, payload))
|
||||
if frames:
|
||||
await writer.drain()
|
||||
if self._on_activity is not None:
|
||||
self._on_activity()
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
try:
|
||||
await asyncio.gather(recv_loop(), send_loop())
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
stop.set()
|
||||
self._telemetry.remove_device(dev_id)
|
||||
if not writer.is_closing():
|
||||
writer.close()
|
||||
|
||||
async def _handle_tunnel(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, target: str) -> None:
|
||||
try:
|
||||
port = int(target.rsplit("/", 1)[-1])
|
||||
except ValueError:
|
||||
await self._send_json(writer, 400, {"error": "invalid port"})
|
||||
writer.close()
|
||||
return
|
||||
if port not in ALLOWED_TUNNEL_PORTS:
|
||||
await self._send_json(writer, 403, {"error": "port forbidden"})
|
||||
writer.close()
|
||||
return
|
||||
|
||||
try:
|
||||
up_r, up_w = await asyncio.open_connection("127.0.0.1", port)
|
||||
except OSError:
|
||||
await self._send_json(writer, 502, {"error": "upstream unavailable"})
|
||||
writer.close()
|
||||
return
|
||||
|
||||
writer.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
await writer.drain()
|
||||
|
||||
async def pipe(src: asyncio.StreamReader, dst: asyncio.StreamWriter) -> None:
|
||||
try:
|
||||
while True:
|
||||
chunk = await src.read(65536)
|
||||
if not chunk:
|
||||
break
|
||||
if self._on_activity is not None:
|
||||
self._on_activity()
|
||||
dst.write(chunk)
|
||||
await dst.drain()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if not dst.is_closing():
|
||||
dst.close()
|
||||
|
||||
await asyncio.gather(pipe(reader, up_w), pipe(up_r, writer))
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from openpilot.sunnypilot.system.p2p.server import P2pTlsServer
|
||||
|
||||
|
||||
class _FakeHub:
|
||||
def subscribe(self, *args): pass
|
||||
def unsubscribe(self, *args): pass
|
||||
def drain(self, *args): return []
|
||||
def remove_device(self, *args): pass
|
||||
def close(self): pass
|
||||
|
||||
|
||||
def _free_port() -> int:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def test_p2p_server_ping_rpc_and_tunnel():
|
||||
port = _free_port()
|
||||
echo_srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
echo_srv.bind(("127.0.0.1", 0))
|
||||
echo_srv.listen(1)
|
||||
|
||||
activity_calls = []
|
||||
hub = _FakeHub()
|
||||
|
||||
def rpc_handler(body: bytes) -> dict:
|
||||
req = json.loads(body)
|
||||
return {"jsonrpc": "2.0", "id": req["id"], "result": {"echo": req["method"]}}
|
||||
|
||||
srv = P2pTlsServer(
|
||||
bind_host="127.0.0.1",
|
||||
port=port,
|
||||
auth_token="secret-token",
|
||||
rpc_handler=rpc_handler,
|
||||
telemetry_hub=hub,
|
||||
on_activity=lambda: activity_calls.append(1),
|
||||
)
|
||||
srv.start()
|
||||
try:
|
||||
ctx = ssl._create_unverified_context()
|
||||
req = urllib.request.Request(
|
||||
f"https://127.0.0.1:{port}/v1/ping",
|
||||
headers={"Authorization": "Bearer secret-token"},
|
||||
)
|
||||
with ctx.wrap_socket(socket.create_connection(("127.0.0.1", port), timeout=3)) as s:
|
||||
assert hashlib.sha256(s.getpeercert(binary_form=True)).hexdigest() == srv.cert_sha256
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=3) as resp:
|
||||
assert resp.status == 200
|
||||
assert json.loads(resp.read()) == {"ok": True}
|
||||
|
||||
rpc_req = urllib.request.Request(
|
||||
f"https://127.0.0.1:{port}/v1/rpc",
|
||||
data=json.dumps({"jsonrpc": "2.0", "id": 7, "method": "status.get", "params": {}}).encode(),
|
||||
headers={"Authorization": "Bearer secret-token", "Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(rpc_req, context=ctx, timeout=3) as resp:
|
||||
assert resp.status == 200
|
||||
assert json.loads(resp.read()) == {"jsonrpc": "2.0", "id": 7, "result": {"echo": "status.get"}}
|
||||
|
||||
bad_req = urllib.request.Request(
|
||||
f"https://127.0.0.1:{port}/v1/ping",
|
||||
headers={"Authorization": "Bearer wrong"},
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(bad_req, context=ctx, timeout=3)
|
||||
raise AssertionError("expected 401")
|
||||
except urllib.error.HTTPError as e:
|
||||
assert e.code == 401
|
||||
|
||||
assert len(activity_calls) >= 2
|
||||
finally:
|
||||
srv.stop()
|
||||
hub.close()
|
||||
echo_srv.close()
|
||||
@@ -0,0 +1,175 @@
|
||||
"""
|
||||
Copyright (c) 2021-, sunnypilot, and a number of other contributors.
|
||||
|
||||
This file is part of sunnypilot and is licensed under the MIT License.
|
||||
See the LICENSE.md file in the root directory for more details.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import subprocess
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
P2P_DIRECT_IP = "192.168.49.1"
|
||||
SOFTAP_GATEWAY_IP = "192.168.43.1"
|
||||
DNSMASQ_PID_FILE = "/tmp/sunnylink-p2p-dnsmasq.pid"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ActiveTransport:
|
||||
kind: str
|
||||
bind_host: str
|
||||
bind_interface: str | None
|
||||
peer_host: str
|
||||
ssid: str | None = None
|
||||
passphrase: str | None = None
|
||||
|
||||
|
||||
def get_wlan0_ipv4() -> str | None:
|
||||
try:
|
||||
out = subprocess.run(
|
||||
["ip", "-4", "-o", "addr", "show", "dev", "wlan0"],
|
||||
capture_output=True, text=True, timeout=3, check=False,
|
||||
).stdout
|
||||
m = re.search(r"\binet\s+(\d+\.\d+\.\d+\.\d+)/", out)
|
||||
ip = m.group(1) if m else None
|
||||
if ip is None or ip == SOFTAP_GATEWAY_IP:
|
||||
return None
|
||||
return ip
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
|
||||
|
||||
def _list_p2p_go_interfaces() -> list[str]:
|
||||
try:
|
||||
out = subprocess.run(["ip", "-o", "link", "show"], capture_output=True, text=True, timeout=3, check=False).stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return []
|
||||
ifaces = []
|
||||
for line in out.splitlines():
|
||||
parts = line.split(": ")
|
||||
if len(parts) >= 2 and parts[1].startswith("p2p-wlan0-"):
|
||||
ifaces.append(parts[1].split("@")[0])
|
||||
return ifaces
|
||||
|
||||
|
||||
def _cleanup_p2p_interface(iface: str) -> None:
|
||||
subprocess.run(["sudo", "wpa_cli", "-i", iface, "p2p_group_remove", iface], capture_output=True, timeout=5, check=False)
|
||||
subprocess.run(["sudo", "iw", "dev", iface, "del"], capture_output=True, timeout=5, check=False)
|
||||
|
||||
|
||||
class LanWifiTransport:
|
||||
def is_ready(self) -> bool:
|
||||
return get_wlan0_ipv4() is not None
|
||||
|
||||
def start(self, session_id: str) -> ActiveTransport:
|
||||
ip = get_wlan0_ipv4()
|
||||
if not ip:
|
||||
raise RuntimeError("wlan0 has no active LAN IPv4 address")
|
||||
return ActiveTransport(
|
||||
kind="lan_wifi",
|
||||
bind_host=ip,
|
||||
bind_interface=None,
|
||||
peer_host=ip,
|
||||
)
|
||||
|
||||
def stop(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class WifiDirectTransport:
|
||||
def __init__(self):
|
||||
self._conn_name: str | None = None
|
||||
|
||||
def is_ready(self) -> bool:
|
||||
try:
|
||||
proc = subprocess.run(["nmcli", "-t", "-f", "DEVICE", "dev", "status"], capture_output=True, text=True, timeout=3, check=False)
|
||||
return "wlan0" in proc.stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return False
|
||||
|
||||
def start(self, session_id: str, ssid: str | None = None, passphrase: str | None = None) -> ActiveTransport:
|
||||
self.stop()
|
||||
if not ssid or not passphrase:
|
||||
raise RuntimeError("Wi-Fi Direct requires phone GO ssid and passphrase")
|
||||
|
||||
self._conn_name = f"sunnylink-p2p-{session_id[:6]}"
|
||||
subprocess.run(["nmcli", "con", "delete", self._conn_name], capture_output=True, timeout=5, check=False)
|
||||
subprocess.run(["nmcli", "dev", "wifi", "rescan", "ifname", "wlan0"], capture_output=True, timeout=8, check=False)
|
||||
|
||||
last_err = ""
|
||||
for _ in range(3):
|
||||
proc = subprocess.run(
|
||||
[
|
||||
"nmcli", "dev", "wifi", "connect", ssid,
|
||||
"password", passphrase,
|
||||
"ifname", "wlan0",
|
||||
"name", self._conn_name,
|
||||
],
|
||||
capture_output=True, text=True, timeout=15, check=False,
|
||||
)
|
||||
if proc.returncode == 0:
|
||||
break
|
||||
last_err = (proc.stderr or proc.stdout).strip()
|
||||
time.sleep(0.5)
|
||||
else:
|
||||
self.stop()
|
||||
raise RuntimeError(f"Wi-Fi Direct join failed: {last_err}")
|
||||
|
||||
ip = None
|
||||
for _ in range(20):
|
||||
ip = get_wlan0_ipv4()
|
||||
if ip and ip.startswith("192.168.49."):
|
||||
break
|
||||
time.sleep(0.25)
|
||||
if not ip:
|
||||
self.stop()
|
||||
raise RuntimeError("Wi-Fi Direct DHCP did not assign an IP")
|
||||
|
||||
return ActiveTransport(
|
||||
kind="wifi_direct",
|
||||
bind_host=ip,
|
||||
bind_interface=None,
|
||||
peer_host=ip,
|
||||
ssid=ssid,
|
||||
passphrase=passphrase,
|
||||
)
|
||||
|
||||
def stop(self) -> None:
|
||||
if self._conn_name:
|
||||
subprocess.run(["nmcli", "con", "delete", self._conn_name], capture_output=True, timeout=5, check=False)
|
||||
self._conn_name = None
|
||||
|
||||
|
||||
class SoftApTransport:
|
||||
def __init__(self, wifi_factory):
|
||||
self._wifi_factory = wifi_factory
|
||||
self._started_by_us = False
|
||||
|
||||
def start(self, session_id: str) -> ActiveTransport:
|
||||
wifi = self._wifi_factory()
|
||||
if not wifi.is_tethering_active():
|
||||
wifi.set_tethering_active(True)
|
||||
self._started_by_us = True
|
||||
deadline = time.monotonic() + 20.0
|
||||
while not wifi.is_tethering_active() and time.monotonic() < deadline:
|
||||
time.sleep(0.25)
|
||||
if not wifi.is_tethering_active():
|
||||
raise RuntimeError("SoftAP hotspot did not start")
|
||||
return ActiveTransport(
|
||||
kind="softap",
|
||||
bind_host="0.0.0.0",
|
||||
bind_interface=None,
|
||||
peer_host=SOFTAP_GATEWAY_IP,
|
||||
ssid=wifi.tethering_ssid,
|
||||
passphrase=wifi.tethering_password,
|
||||
)
|
||||
|
||||
def stop(self) -> None:
|
||||
if self._started_by_us:
|
||||
try:
|
||||
self._wifi_factory().set_tethering_active(False)
|
||||
except Exception:
|
||||
pass
|
||||
self._started_by_us = False
|
||||
Reference in New Issue
Block a user