mirror of
https://github.com/sunnypilot/sunnypilot.git
synced 2026-12-01 05:33:42 +08:00
Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a6e313bb9a | |||
| cb95d65923 | |||
| 2bdcb77ed2 | |||
| 5f86bd34dc | |||
| e675689ded | |||
| 4f8d054cf3 | |||
| 1c9fa16a9a | |||
| 0c8e4665a1 | |||
| 59ac80f0d9 | |||
| 87167d7403 | |||
| 8004e0305e | |||
| 3343e9fde8 | |||
| 9b514ae0a7 | |||
| 7d93cd16cd | |||
| cb6b5d6913 | |||
| 3c4f6b5e0e | |||
| 3fb02ca1f6 | |||
| 1f15111e33 | |||
| 368ea8c3d9 | |||
| 202ee8d64e | |||
| 4023e5d616 | |||
| 035f5ce655 | |||
| ec2edb34f7 | |||
| 74f99e04e4 | |||
| 85c794547a | |||
| 9caada9700 | |||
| f733eba7f6 | |||
| 2b203a5237 | |||
| efe7b30b4c | |||
| 74c14722be | |||
| edaf055284 | |||
| 1527c52bf1 | |||
| c78f4c4549 |
+1
-1
@@ -16,7 +16,7 @@ export VECLIB_MAXIMUM_THREADS=1
|
||||
export QCOM_PRIORITY=12
|
||||
|
||||
if [ -z "$AGNOS_VERSION" ]; then
|
||||
export AGNOS_VERSION="19.9"
|
||||
export AGNOS_VERSION="19.9-sunnypilot.2-dae64af"
|
||||
fi
|
||||
|
||||
export STAGING_ROOT="/data/safe_staging"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[
|
||||
{
|
||||
"name": "xbl",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/xbl-e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb.img.xz",
|
||||
"hash": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
|
||||
"hash_raw": "e8acf2a9cc7f0ce84cb803bfea9477f765c0d7b4daf26048e59651b9e6a7bfbb",
|
||||
"size": 3282256,
|
||||
@@ -12,7 +12,7 @@
|
||||
},
|
||||
{
|
||||
"name": "xbl_config",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/xbl_config-758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85.img.xz",
|
||||
"hash": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
|
||||
"hash_raw": "758552ecf92b5569677197783bf0ccb73d7f961685308e45d3276ac9dd974f85",
|
||||
"size": 98124,
|
||||
@@ -23,7 +23,7 @@
|
||||
},
|
||||
{
|
||||
"name": "abl",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/abl-29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35.img.xz",
|
||||
"hash": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
|
||||
"hash_raw": "29fd7ed1c012e599420764840f9f11286d34dbff4adaf102a447f06d8c5e0b35",
|
||||
"size": 274432,
|
||||
@@ -34,7 +34,7 @@
|
||||
},
|
||||
{
|
||||
"name": "aop",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/aop-78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1.img.xz",
|
||||
"hash": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
|
||||
"hash_raw": "78b2287ca219a0811b3004c523fa0f4749e4d1fd92be3aba61699305b7943ad1",
|
||||
"size": 184364,
|
||||
@@ -45,7 +45,7 @@
|
||||
},
|
||||
{
|
||||
"name": "devcfg",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/devcfg-f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc.img.xz",
|
||||
"hash": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
|
||||
"hash_raw": "f71df3a86958c093ba3969254c4db025187eef9385427f1ade946742939b43cc",
|
||||
"size": 40336,
|
||||
@@ -56,28 +56,28 @@
|
||||
},
|
||||
{
|
||||
"name": "boot",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/boot-b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615.img.xz",
|
||||
"hash": "b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615",
|
||||
"hash_raw": "b9c9b9261fca0cef9e6d9b198fa4b563767e6342afc7a61ab137b2b519260615",
|
||||
"size": 46962688,
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/boot-6c8ea96dde9402be6ebccd4f11f0cd31a75113704b614a8c3f23e15cff06d30b.img.xz",
|
||||
"hash": "6c8ea96dde9402be6ebccd4f11f0cd31a75113704b614a8c3f23e15cff06d30b",
|
||||
"hash_raw": "6c8ea96dde9402be6ebccd4f11f0cd31a75113704b614a8c3f23e15cff06d30b",
|
||||
"size": 47859712,
|
||||
"sparse": false,
|
||||
"full_check": true,
|
||||
"has_ab": true,
|
||||
"ondevice_hash": "3ef4769bb1cc73bfc31f96f073b46af42dcc0bad4ab2dde32d11929745d0cd28"
|
||||
"ondevice_hash": "71f49de9dcb8b8181a47695a4390d5a934ac59e92ce398bbfe5767ce01f78e4f"
|
||||
},
|
||||
{
|
||||
"name": "system",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/system-80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7.img.xz",
|
||||
"hash": "9aebca09b9d142718e71efbfe44b723010eec6e70067c043c63186067291739d",
|
||||
"hash_raw": "80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/system-db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86.img.xz",
|
||||
"hash": "b959d05e5000ba590b0d47f8394a4024d3d5d348eadb8cc85f4aa7c15f8b7c20",
|
||||
"hash_raw": "db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86",
|
||||
"size": 4718592000,
|
||||
"sparse": true,
|
||||
"full_check": false,
|
||||
"has_ab": true,
|
||||
"ondevice_hash": "270b76c5c5568828e3883390b83ea445425a104dd42119d68f06093ce6b6fcef",
|
||||
"ondevice_hash": "872ca1b96c0d26d8fdaa74ab019b8c58de36c66afb4fc765681d265d17e80e9d",
|
||||
"alt": {
|
||||
"hash": "80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7",
|
||||
"url": "https://commadist.azureedge.net/agnosupdate/system-80d9373348ddff2a5d1f534fab3420383939c96f3eba60baab6b15339fc602c7.img",
|
||||
"hash": "db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86",
|
||||
"url": "https://huggingface.co/sunnypilot/agnos-ci/resolve/main/pr-16/system-db741feb64d22927df45788f78caf0a97743a71346e64ba61e4bb9e3b9451e86.img",
|
||||
"size": 4718592000
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +156,8 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"BlinkerLateralReengageDelay", {PERSISTENT | BACKUP, INT, "0"}}, // seconds
|
||||
{"BlinkerMinLateralControlSpeed", {PERSISTENT | BACKUP, INT, "20"}}, // MPH or km/h
|
||||
{"BlinkerPauseLateralControl", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"BluetoothAllowed", {PERSISTENT, BOOL, "1"}},
|
||||
{"BluetoothEnabled", {CLEAR_ON_MANAGER_START, BOOL, "0"}},
|
||||
{"Brightness", {PERSISTENT | BACKUP, INT, "0"}},
|
||||
{"CarList", {PERSISTENT, JSON}},
|
||||
{"CarParamsSP", {CLEAR_ON_MANAGER_START | CLEAR_ON_ONROAD_TRANSITION, BYTES}},
|
||||
@@ -232,6 +234,11 @@ inline static std::unordered_map<std::string, ParamKeyAttributes> keys = {
|
||||
{"SunnylinkDongleId", {PERSISTENT, STRING}},
|
||||
{"SunnylinkdPid", {PERSISTENT, INT}},
|
||||
{"SunnylinkEnabled", {PERSISTENT, BOOL, "1"}},
|
||||
{"SunnylinkLocalConnectPhoneRequest", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}},
|
||||
{"SunnylinkLocalConnectPhoneWindow", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}},
|
||||
{"SunnylinkLocalBleGrants", {PERSISTENT | DONT_LOG, JSON}},
|
||||
{"SunnylinkLocalBleKey", {PERSISTENT | DONT_LOG, BYTES}},
|
||||
{"SunnylinkLocalBluetoothStatus", {CLEAR_ON_MANAGER_START | DONT_LOG, JSON}},
|
||||
{"SunnylinkTempFault", {CLEAR_ON_MANAGER_START | CLEAR_ON_OFFROAD_TRANSITION, BOOL, "0"}},
|
||||
|
||||
// Backup Manager params
|
||||
|
||||
@@ -101,6 +101,8 @@ class Sidebar(Widget, SidebarSP):
|
||||
|
||||
self._draw_buttons(rect)
|
||||
self._draw_network_indicator(rect)
|
||||
if gui_app.sunnypilot_ui():
|
||||
SidebarSP._draw_bluetooth_indicator(self, rect)
|
||||
self._draw_metrics(rect)
|
||||
|
||||
def _update_state(self):
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
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 time
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.connect_phone import ConnectPhoneLayout
|
||||
from openpilot.sunnypilot.system.ble import grants
|
||||
from openpilot.sunnypilot.system.connect_phone import write_request
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.lib.text_measure import measure_text_cached
|
||||
from openpilot.system.ui.sunnypilot.widgets.list_view import button_item_sp, simple_button_item_sp, toggle_item_sp
|
||||
from openpilot.system.ui.widgets import DialogResult, Widget
|
||||
from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog
|
||||
from openpilot.system.ui.widgets.list_view import ITEM_TEXT_FONT_SIZE
|
||||
from openpilot.system.ui.widgets.scroller_tici import Scroller
|
||||
|
||||
POLL_INTERVAL = 1.0
|
||||
NAME_MAX_WIDTH = 1000 # px at the list font: leaves room for REMOVE in the settings panel
|
||||
|
||||
|
||||
def _fit_name(name: str) -> str:
|
||||
# a phone name is up to 80 bytes; list titles are single line and never elided by stock
|
||||
font = gui_app.font(FontWeight.NORMAL)
|
||||
if measure_text_cached(font, name, ITEM_TEXT_FONT_SIZE).x <= NAME_MAX_WIDTH:
|
||||
return name
|
||||
while name and measure_text_cached(font, name + "...", ITEM_TEXT_FONT_SIZE).x > NAME_MAX_WIDTH:
|
||||
name = name[:-1]
|
||||
return name.rstrip() + "..."
|
||||
|
||||
|
||||
class BluetoothLayout(Widget):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._params = Params()
|
||||
|
||||
self._bluetooth_toggle = toggle_item_sp(
|
||||
title=lambda: tr("Bluetooth"),
|
||||
description=lambda: tr("Allow phones to connect to this device over Bluetooth."),
|
||||
param="BluetoothAllowed",
|
||||
)
|
||||
self._connect_phone_button = simple_button_item_sp(
|
||||
button_text=lambda: tr("Connect phone"),
|
||||
callback=lambda: gui_app.push_widget(ConnectPhoneLayout()),
|
||||
enabled=lambda: self._bluetooth_toggle.action_item.get_state(),
|
||||
)
|
||||
|
||||
self._phone_items = []
|
||||
self._grants: list[dict] | None = None
|
||||
self._last_poll = float("-inf")
|
||||
|
||||
self._scroller = Scroller([self._bluetooth_toggle, self._connect_phone_button], line_separator=True, spacing=0)
|
||||
|
||||
def _bluetooth_on(self) -> bool:
|
||||
return self._bluetooth_toggle.action_item.get_state()
|
||||
|
||||
def _update_state(self):
|
||||
now = time.monotonic()
|
||||
if now - self._last_poll < POLL_INTERVAL:
|
||||
return
|
||||
self._last_poll = now
|
||||
phones = grants.load(self._params)
|
||||
if phones != self._grants:
|
||||
self._grants = phones
|
||||
self._rebuild_phone_items()
|
||||
|
||||
def _rebuild_phone_items(self):
|
||||
for item in self._phone_items:
|
||||
self._scroller._items.remove(item)
|
||||
self._phone_items = [self._phone_item(phone) for phone in self._grants or []]
|
||||
for item in self._phone_items:
|
||||
item.set_visible(self._bluetooth_on)
|
||||
self._scroller.add_widget(item)
|
||||
|
||||
def _phone_item(self, phone: dict):
|
||||
spki, name = phone["spki"], _fit_name(phone["name"])
|
||||
return button_item_sp(title=name, button_text=lambda: tr("REMOVE"), callback=lambda: self._remove(spki, name))
|
||||
|
||||
def _remove(self, spki: str, name: str):
|
||||
def done(result: DialogResult):
|
||||
if result == DialogResult.CONFIRM:
|
||||
write_request(self._params, "remove", phone=spki)
|
||||
gui_app.push_widget(ConfirmDialog(tr("Remove \"{}\"?").format(name), tr("Remove"), tr("Cancel"), callback=done))
|
||||
|
||||
def _render(self, rect):
|
||||
self._scroller.render(rect)
|
||||
@@ -0,0 +1,205 @@
|
||||
"""
|
||||
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 math
|
||||
import time
|
||||
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.selfdrive.ui.ui_state import device
|
||||
from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog
|
||||
from openpilot.sunnypilot.system.connect_phone import WINDOW_SECONDS, display_name, format_code, read_window, write_request
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr, tr_noop
|
||||
from openpilot.system.ui.lib.text_measure import measure_text_cached
|
||||
from openpilot.system.ui.lib.wrap_text import wrap_text
|
||||
from openpilot.system.ui.widgets import DialogResult
|
||||
from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog
|
||||
|
||||
POLL_INTERVAL = 0.25
|
||||
START_TIMEOUT = 15
|
||||
STALE_SECONDS = 3
|
||||
CLOSE_REASON_MESSAGES = {
|
||||
"granted": tr_noop("Phone connected."),
|
||||
"denied": tr_noop("Phone not connected."),
|
||||
"no_answer": tr_noop("Phone not connected: Allow was not tapped in time."),
|
||||
"phone_left": tr_noop("Phone not connected: the phone disconnected."),
|
||||
"wrong_codes": tr_noop("Phone not connected: too many wrong codes. Try again."),
|
||||
"limit": tr_noop("Phone not connected: 8 phones are already connected. Remove one first."),
|
||||
"timeout": tr_noop("The connect window timed out. Try again."),
|
||||
"bluetooth_off": tr_noop("Bluetooth is off. Turn Bluetooth on to connect a phone."),
|
||||
"no_key": tr_noop("The device key is unavailable. Reboot and try again."),
|
||||
}
|
||||
|
||||
|
||||
class ConnectPhoneLayout(PairingDialog):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._params = Params()
|
||||
self._name = display_name(self._params)
|
||||
self._close_btn.set_click_callback(self._close_screen)
|
||||
self._started = False
|
||||
self._closed = False
|
||||
self._seq = 0
|
||||
self._opened_at = 0.0
|
||||
self._matched_at = 0.0
|
||||
self._window: dict | None = None
|
||||
self._last_poll = float("-inf")
|
||||
self._qr_source = ""
|
||||
self._check_dialog: ConfirmDialog | None = None
|
||||
self._check_shown_for: float | None = None
|
||||
|
||||
def show_event(self):
|
||||
super().show_event()
|
||||
device.set_override_interactive_timeout(WINDOW_SECONDS + 10)
|
||||
# a tick, not _update_state: it has to keep polling while the Allow dialog is on top
|
||||
gui_app.add_nav_stack_tick(self._tick)
|
||||
if not self._started:
|
||||
self._started = True
|
||||
self._seq = write_request(self._params, "open")
|
||||
self._opened_at = time.monotonic()
|
||||
|
||||
def hide_event(self):
|
||||
super().hide_event()
|
||||
gui_app.remove_nav_stack_tick(self._tick)
|
||||
device.set_override_interactive_timeout(None)
|
||||
if self._seq and not self._closed:
|
||||
write_request(self._params, "cancel")
|
||||
self._closed = True
|
||||
|
||||
def _update_state(self):
|
||||
pass # stock closes itself once the device is paired to comma connect
|
||||
|
||||
def _tick(self):
|
||||
if self._closed:
|
||||
return
|
||||
now = time.monotonic()
|
||||
if now - self._last_poll >= POLL_INTERVAL:
|
||||
self._last_poll = now
|
||||
window = read_window(self._params)
|
||||
if window and window.get("seq") == self._seq:
|
||||
self._window = window
|
||||
self._matched_at = now
|
||||
if window.get("state") == "closed":
|
||||
self._on_closed(window.get("reason", ""))
|
||||
return
|
||||
self._sync_check_dialog(window.get("prompt") or {})
|
||||
|
||||
if self._window is not None and self._window.get("state") == "open":
|
||||
if not self._window.get("held") and now >= self._window.get("deadline", 0.0):
|
||||
self._on_closed("timeout")
|
||||
elif self._matched_at and now - self._matched_at > STALE_SECONDS:
|
||||
self._finish(None)
|
||||
elif now - self._opened_at > START_TIMEOUT:
|
||||
write_request(self._params, "cancel")
|
||||
self._finish(tr("Bluetooth did not start"))
|
||||
|
||||
def _sync_check_dialog(self, prompt: dict):
|
||||
if prompt.get("step") == "allow" and self._check_shown_for != prompt.get("until"):
|
||||
self._check_shown_for = prompt.get("until")
|
||||
text = tr("Code {}\nIs the same code on your phone?").format(prompt.get("check", ""))
|
||||
self._check_dialog = ConfirmDialog(text, tr("Allow"), tr("Deny"), callback=self._answer)
|
||||
gui_app.push_widget(self._check_dialog)
|
||||
elif prompt.get("step") != "allow" and self._check_dialog is not None:
|
||||
gui_app.pop_widgets_to(self, instant=True)
|
||||
self._check_dialog = None
|
||||
|
||||
def _answer(self, result: DialogResult):
|
||||
self._check_dialog = None
|
||||
write_request(self._params, "allow" if result == DialogResult.CONFIRM else "deny")
|
||||
|
||||
def _on_closed(self, reason: str):
|
||||
message = CLOSE_REASON_MESSAGES.get(reason)
|
||||
self._finish(tr(message) if message else None)
|
||||
|
||||
def _finish(self, message: str | None):
|
||||
self._closed = True
|
||||
gui_app.pop_widgets_to(self, instant=True)
|
||||
self._close_screen()
|
||||
if message:
|
||||
gui_app.push_widget(ConfirmDialog(message, tr("OK"), cancel_text=""))
|
||||
|
||||
def _close_screen(self):
|
||||
if gui_app.get_active_widget() is self:
|
||||
gui_app.pop_widget()
|
||||
|
||||
def _get_pairing_url(self) -> str:
|
||||
return self._qr_source
|
||||
|
||||
def _check_qr_refresh(self):
|
||||
qr = (self._window or {}).get("qr", "") if self._is_open() else ""
|
||||
if qr and qr != self._qr_source:
|
||||
self._qr_source = qr
|
||||
self._generate_qr_code()
|
||||
|
||||
def _is_open(self) -> bool:
|
||||
return self._window is not None and self._window.get("state") == "open" and not self._window.get("held")
|
||||
|
||||
def _render(self, rect: rl.Rectangle) -> int:
|
||||
# copied from PairingDialog._render: stock hardcodes its title and steps there
|
||||
rl.clear_background(rl.Color(224, 224, 224, 255))
|
||||
self._check_qr_refresh()
|
||||
|
||||
margin = 70
|
||||
content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - 2 * margin, rect.height - 2 * margin)
|
||||
y = content_rect.y
|
||||
close_size = 80
|
||||
pad = 20
|
||||
self._close_btn.render(rl.Rectangle(content_rect.x - pad, y - pad, close_size + pad * 2, close_size + pad * 2))
|
||||
y += close_size + 40
|
||||
|
||||
title_font = gui_app.font(FontWeight.NORMAL)
|
||||
left_width = int(content_rect.width * 0.5 - 15)
|
||||
title_wrapped = wrap_text(title_font, tr("Connect a phone to {}").format(self._name), 75, left_width)
|
||||
rl.draw_text_ex(title_font, "\n".join(title_wrapped), rl.Vector2(content_rect.x, y), 75, 0.0, rl.BLACK)
|
||||
y += len(title_wrapped) * 75 + 60
|
||||
|
||||
remaining_height = content_rect.height - (y - content_rect.y)
|
||||
right_width = content_rect.width // 2 - 20
|
||||
self._render_instructions(rl.Rectangle(content_rect.x, y, left_width, remaining_height))
|
||||
|
||||
qr_size = min(right_width, content_rect.height) - 40
|
||||
qr_rect = rl.Rectangle(content_rect.x + left_width + 40 + (right_width - qr_size) // 2, content_rect.y, qr_size, qr_size)
|
||||
if self._is_open():
|
||||
self._render_qr_code(qr_rect)
|
||||
else:
|
||||
text = tr("Connecting phone") if self._window is not None and self._window.get("held") else tr("Starting Bluetooth")
|
||||
rl.draw_rectangle_rounded(qr_rect, 0.1, 20, rl.Color(240, 240, 240, 255))
|
||||
font = gui_app.font(FontWeight.BOLD)
|
||||
size = measure_text_cached(font, text, 47)
|
||||
rl.draw_text_ex(font, text, rl.Vector2(qr_rect.x + (qr_rect.width - size.x) / 2, qr_rect.y + (qr_rect.height - size.y) / 2), 47, 0,
|
||||
rl.BLACK)
|
||||
return -1
|
||||
|
||||
def _render_instructions(self, rect: rl.Rectangle) -> None:
|
||||
window = self._window if self._is_open() else None
|
||||
instructions = [
|
||||
tr("Open the sunnylink app and tap Connect phone"),
|
||||
tr("Scan the QR code on the right, or type {}").format(format_code(int(window["code"]))) if window else tr("Scan the QR code on the right"),
|
||||
tr("Check that both screens show the same code, then tap Allow"),
|
||||
]
|
||||
font = gui_app.font(FontWeight.BOLD)
|
||||
y = rect.y
|
||||
for i, text in enumerate(instructions):
|
||||
circle_radius = 25
|
||||
circle_x = rect.x + circle_radius + 15
|
||||
text_x = rect.x + circle_radius * 2 + 40
|
||||
wrapped = wrap_text(font, text, 47, int(rect.width - (circle_radius * 2 + 40)))
|
||||
text_height = len(wrapped) * 47
|
||||
circle_y = y + text_height // 2
|
||||
rl.draw_circle(int(circle_x), int(circle_y), circle_radius, rl.Color(70, 70, 70, 255))
|
||||
number = str(i + 1)
|
||||
number_size = measure_text_cached(font, number, 30)
|
||||
rl.draw_text_ex(font, number, (int(circle_x - number_size.x // 2), int(circle_y - number_size.y // 2)), 30, 0, rl.WHITE)
|
||||
rl.draw_text_ex(font, "\n".join(wrapped), rl.Vector2(text_x, y), 47, 0.0, rl.BLACK)
|
||||
y += text_height + 50
|
||||
|
||||
if window:
|
||||
remaining = max(0, math.ceil(window.get("deadline", 0.0) - time.monotonic()))
|
||||
rl.draw_text_ex(gui_app.font(FontWeight.NORMAL), tr("Time left {}:{:02d}").format(remaining // 60, remaining % 60),
|
||||
rl.Vector2(rect.x, y), 47, 0.0, rl.Color(70, 70, 70, 255))
|
||||
@@ -149,7 +149,8 @@ class DeviceLayoutSP(DeviceLayout):
|
||||
def _do_reset(result: int):
|
||||
if result == DialogResult.CONFIRM:
|
||||
for _key in ui_state.params.all_keys():
|
||||
ui_state.params.remove(_key)
|
||||
if not _key.startswith("SunnylinkLocal"):
|
||||
ui_state.params.remove(_key)
|
||||
HARDWARE.reboot()
|
||||
|
||||
def _second_confirm(result: int):
|
||||
|
||||
@@ -11,6 +11,7 @@ import pyray as rl
|
||||
from openpilot.selfdrive.ui.layouts.settings import settings as OP
|
||||
from openpilot.selfdrive.ui.layouts.settings.firehose import FirehoseLayout
|
||||
from openpilot.selfdrive.ui.layouts.settings.toggles import TogglesLayout
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.bluetooth import BluetoothLayout
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.cruise import CruiseLayout
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.developer import DeveloperLayoutSP
|
||||
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.device import DeviceLayoutSP
|
||||
@@ -50,6 +51,7 @@ OP.PanelType = IntEnum( # type: ignore[assignment] # ty: ignore[invalid-assignm
|
||||
"NAVIGATION",
|
||||
"TRIPS",
|
||||
"VEHICLE",
|
||||
"BLUETOOTH",
|
||||
],
|
||||
start=0,
|
||||
)
|
||||
@@ -111,6 +113,7 @@ class SettingsLayoutSP(OP.SettingsLayout):
|
||||
self._panels = {
|
||||
OP.PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_home.png"),
|
||||
OP.PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUISP(wifi_manager), icon="icons/network.png"),
|
||||
OP.PanelType.BLUETOOTH: PanelInfo(tr_noop("Bluetooth"), BluetoothLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png"),
|
||||
OP.PanelType.SUNNYLINK: PanelInfo(tr_noop("sunnylink"), SunnylinkLayout(), icon="icons/wifi_strength_full.png"),
|
||||
OP.PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"),
|
||||
OP.PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_software.png"),
|
||||
|
||||
@@ -11,6 +11,7 @@ import time
|
||||
from dataclasses import dataclass
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
|
||||
from openpilot.sunnypilot.sunnylink.api import UNREGISTERED_SUNNYLINK_DONGLE_ID
|
||||
from openpilot.sunnypilot.system.connect_phone import phone_indicator, read_status
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr_noop
|
||||
|
||||
@@ -23,6 +24,11 @@ HOME_BTN = rl.Rectangle(60, 860, 180, 180)
|
||||
|
||||
CHESTNUT_ICON_WIDTH = 180
|
||||
CHESTNUT_ICON_HEIGHT = 133
|
||||
BT_ICON_SIZE = 30
|
||||
BT_ICON_X = 250 # right of the signal dots, clear of the mic indicator
|
||||
BT_ICON_Y = 195
|
||||
BT_POLL_SECONDS = 1.0
|
||||
BT_WAITING_OPACITY = 0.35
|
||||
|
||||
|
||||
# Color scheme
|
||||
@@ -62,6 +68,19 @@ class SidebarSP:
|
||||
self._chestnut_green_img = gui_app.texture("icons_mici/chestnut_green.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
|
||||
self._chestnut_default_img = gui_app.texture("icons_mici/chestnut.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
|
||||
self._chestnut_orange_img = gui_app.texture("icons_mici/chestnut_orange.png", CHESTNUT_ICON_WIDTH, CHESTNUT_ICON_HEIGHT)
|
||||
self._bt_img = gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", BT_ICON_SIZE, BT_ICON_SIZE)
|
||||
self._bt_state = "hidden"
|
||||
self._bt_polled_at = float("-inf")
|
||||
|
||||
def _draw_bluetooth_indicator(self, rect: rl.Rectangle):
|
||||
now = time.monotonic()
|
||||
if now - self._bt_polled_at >= BT_POLL_SECONDS:
|
||||
self._bt_polled_at = now
|
||||
self._bt_state = phone_indicator(read_status(ui_state.params))
|
||||
if self._bt_state == "hidden":
|
||||
return
|
||||
alpha = 255 if self._bt_state == "connected" else int(255 * BT_WAITING_OPACITY)
|
||||
rl.draw_texture_ex(self._bt_img, rl.Vector2(rect.x + BT_ICON_X, rect.y + BT_ICON_Y), 0.0, 1.0, rl.Color(255, 255, 255, alpha))
|
||||
|
||||
def _update_sunnylink_status(self):
|
||||
if not ui_state.params.get_bool("SunnylinkEnabled"):
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
"""
|
||||
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 time
|
||||
|
||||
from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigParamControl
|
||||
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.connect_phone import start_connect_phone
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.sunnypilot.system.ble import grants
|
||||
from openpilot.sunnypilot.system.connect_phone import display_name, write_request
|
||||
from openpilot.system.ui.lib.application import gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.widgets.scroller import NavScroller
|
||||
|
||||
POLL_SECONDS = 1.0
|
||||
|
||||
|
||||
def _phone_count(n: int) -> str:
|
||||
return tr("none connected") if n == 0 else tr("{} connected").format(n)
|
||||
|
||||
|
||||
class BluetoothLayoutMici(NavScroller):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self._bluetooth_on = ui_state.params.get_bool("BluetoothAllowed")
|
||||
|
||||
def bluetooth_callback(checked: bool):
|
||||
self._bluetooth_on = checked
|
||||
|
||||
self._bluetooth_toggle = BigParamControl(tr("bluetooth"), "BluetoothAllowed", toggle_callback=bluetooth_callback)
|
||||
|
||||
self._connect_phone_btn = BigButton(tr("connect phone"), display_name(ui_state.params))
|
||||
self._connect_phone_btn.set_click_callback(start_connect_phone)
|
||||
self._connect_phone_btn.set_enabled(lambda: self._bluetooth_on)
|
||||
|
||||
self._phones_page = ConnectedPhonesMici()
|
||||
self._phones_btn = BigButton(tr("phones"), "")
|
||||
self._phones_btn.set_click_callback(lambda: gui_app.push_widget(self._phones_page))
|
||||
self._phones_btn.set_visible(lambda: self._bluetooth_on)
|
||||
self._last_poll = float("-inf")
|
||||
|
||||
self._scroller.add_widgets([self._bluetooth_toggle, self._connect_phone_btn, self._phones_btn])
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
now = time.monotonic()
|
||||
if now - self._last_poll >= POLL_SECONDS:
|
||||
self._last_poll = now
|
||||
self._phones_btn.set_value(_phone_count(len(grants.load(ui_state.params))))
|
||||
|
||||
|
||||
class ConnectedPhonesMici(NavScroller):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._phone_items: list[BigButton] = []
|
||||
self._grants: list[dict] | None = None
|
||||
self._last_poll = float("-inf")
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
now = time.monotonic()
|
||||
if now - self._last_poll < POLL_SECONDS:
|
||||
return
|
||||
self._last_poll = now
|
||||
phones = grants.load(ui_state.params)
|
||||
if phones != self._grants:
|
||||
self._grants = phones
|
||||
for item in self._phone_items:
|
||||
self._scroller._items.remove(item)
|
||||
self._phone_items = [self._phone_item(phone) for phone in phones] or [BigButton(tr("no phones connected yet"), "")]
|
||||
self._scroller.add_widgets(self._phone_items)
|
||||
|
||||
def _phone_item(self, phone: dict) -> BigButton:
|
||||
spki = phone["spki"]
|
||||
item = BigButton(phone["name"], tr("remove"), scroll=True)
|
||||
item.set_click_callback(lambda: self._remove(spki))
|
||||
return item
|
||||
|
||||
def _remove(self, spki: str) -> None:
|
||||
icon = gui_app.texture("icons_mici/settings/network/new/trash.png", 54, 64)
|
||||
gui_app.push_widget(BigConfirmationDialog(tr("slide to remove"), icon, lambda: write_request(ui_state.params, "remove", phone=spki), red=True))
|
||||
@@ -0,0 +1,202 @@
|
||||
"""
|
||||
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 time
|
||||
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.common.qrcode import make_texture
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationCircleButton, BigDialog
|
||||
from openpilot.selfdrive.ui.ui_state import device, ui_state
|
||||
from openpilot.sunnypilot.system.connect_phone import WINDOW_SECONDS, format_code, read_window, write_request
|
||||
from openpilot.system.ui.lib.application import FontWeight, gui_app
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
from openpilot.system.ui.mici_setup import GreyBigButton
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
from openpilot.system.ui.widgets.nav_widget import NavWidget
|
||||
from openpilot.system.ui.widgets.scroller import NavScroller
|
||||
|
||||
POLL_SECONDS = 0.25
|
||||
START_TIMEOUT = 15 # seconds from open to the first window for this request
|
||||
LOST_SECONDS = 3 # the daemon restarted mid-window and no longer reports our seq
|
||||
INTERACTIVE_TIMEOUT = WINDOW_SECONDS + 10 # the offroad idle timeout would pop the screen mid-window
|
||||
|
||||
|
||||
def _closed_message(reason: str) -> str | None:
|
||||
messages = {
|
||||
"granted": tr("phone connected"),
|
||||
"denied": tr("phone not connected"),
|
||||
"no_answer": tr("allow not tapped in time"),
|
||||
"phone_left": tr("phone disconnected"),
|
||||
"wrong_codes": tr("too many wrong codes"),
|
||||
"limit": tr("8 phones already connected"),
|
||||
"timeout": tr("connect timed out"),
|
||||
"bluetooth_off": tr("turn on bluetooth"),
|
||||
"no_key": tr("device key unavailable"),
|
||||
}
|
||||
return messages.get(reason)
|
||||
|
||||
|
||||
def start_connect_phone() -> None:
|
||||
gui_app.push_widget(ConnectPhoneDialog())
|
||||
|
||||
|
||||
class ConnectPhoneDialog(NavWidget):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._params = ui_state.params
|
||||
self._seq = write_request(self._params, "open")
|
||||
self._opened_at = time.monotonic()
|
||||
self._next_poll = 0.0
|
||||
self._was_open = False
|
||||
self._lost_since: float | None = None
|
||||
self._window: dict | None = None
|
||||
self._closing = False
|
||||
self._check_shown_for: float | None = None
|
||||
self._qr_source = ""
|
||||
self._qr_texture: rl.Texture | None = None
|
||||
|
||||
self._title = UnifiedLabel(tr("connect phone"), font_size=48, font_weight=FontWeight.BOLD,
|
||||
text_color=rl.Color(255, 255, 255, int(255 * 0.9)), line_height=0.8)
|
||||
self._status = UnifiedLabel("", font_size=36, font_weight=FontWeight.ROMAN,
|
||||
text_color=rl.Color(255, 255, 255, int(255 * 0.65)))
|
||||
self._code = UnifiedLabel("", font_size=48, font_weight=FontWeight.BOLD,
|
||||
text_color=rl.Color(255, 255, 255, int(255 * 0.9)))
|
||||
|
||||
self.set_back_callback(self._cancel)
|
||||
|
||||
def show_event(self):
|
||||
super().show_event()
|
||||
device.set_override_interactive_timeout(INTERACTIVE_TIMEOUT)
|
||||
|
||||
def hide_event(self):
|
||||
super().hide_event()
|
||||
device.set_override_interactive_timeout(None)
|
||||
if not self._closing:
|
||||
self._cancel()
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
if self._closing:
|
||||
return
|
||||
now = time.monotonic()
|
||||
if now < self._next_poll:
|
||||
return
|
||||
self._next_poll = now + POLL_SECONDS
|
||||
|
||||
window = read_window(self._params)
|
||||
# the request seq guards against a window left over from an earlier open
|
||||
if window is None or window.get("seq") != self._seq:
|
||||
self._window = None
|
||||
if self._was_open:
|
||||
# a daemon restart writes seq 0 and never reports our window again
|
||||
if self._lost_since is None:
|
||||
self._lost_since = now
|
||||
if now - self._lost_since > LOST_SECONDS:
|
||||
self._finish(None)
|
||||
elif now - self._opened_at > START_TIMEOUT:
|
||||
self._cancel()
|
||||
self._finish(tr("bluetooth did not start"))
|
||||
return
|
||||
self._lost_since = None
|
||||
self._window = window
|
||||
prompt = window.get("prompt") or {}
|
||||
if prompt.get("step") == "allow" and self._check_shown_for != prompt.get("until"):
|
||||
self._check_shown_for = prompt.get("until")
|
||||
gui_app.push_widget(ConnectPhoneCheckDialog(prompt.get("check", ""), self._params))
|
||||
if window.get("state") == "closed":
|
||||
self._finish(_closed_message(window.get("reason", "")))
|
||||
elif window.get("state") == "open":
|
||||
self._was_open = True
|
||||
if not window.get("held") and now >= window["deadline"]:
|
||||
self._finish(_closed_message("timeout"))
|
||||
|
||||
def _cancel(self) -> None:
|
||||
if not self._closing:
|
||||
self._closing = True
|
||||
write_request(self._params, "cancel")
|
||||
|
||||
def _finish(self, message: str | None) -> None:
|
||||
self._closing = True
|
||||
gui_app.pop_widgets_to(self, instant=True)
|
||||
if message is None:
|
||||
self.dismiss(lambda: None)
|
||||
else:
|
||||
self.dismiss(lambda: gui_app.push_widget(BigDialog(message, "")))
|
||||
|
||||
def _render(self, _):
|
||||
window = self._window
|
||||
held = window is not None and window.get("held", False)
|
||||
show_code = window is not None and window.get("state") == "open" and not held
|
||||
|
||||
if show_code:
|
||||
if window["qr"] != self._qr_source:
|
||||
self._load_qr(window["qr"])
|
||||
self._draw_qr()
|
||||
|
||||
label_x = self._rect.x + 8 + self._rect.height + 24 if show_code else self._rect.x + 20
|
||||
max_width = int(self._rect.x + self._rect.width - label_x)
|
||||
y = self._rect.y + 16
|
||||
self._title.set_text(tr("scan or type") if show_code else tr("connect phone"))
|
||||
self._title.set_max_width(max_width)
|
||||
self._title.set_position(label_x, y)
|
||||
self._title.render()
|
||||
y += self._title.get_content_height(max_width) + 16
|
||||
|
||||
if show_code:
|
||||
remaining = max(0, int(window["deadline"] - time.monotonic()))
|
||||
self._code.set_text(format_code(int(window["code"])))
|
||||
self._code.set_max_width(max_width)
|
||||
self._code.set_position(label_x, y)
|
||||
self._code.render()
|
||||
y += self._code.get_content_height(max_width) + 12
|
||||
self._status.set_text(f"{tr('expires in')} {remaining // 60}:{remaining % 60:02d}")
|
||||
elif held:
|
||||
self._status.set_text(tr("connecting phone"))
|
||||
else:
|
||||
self._status.set_text("" if self._closing else tr("starting bluetooth"))
|
||||
self._status._shimmer = not show_code and not self._closing
|
||||
self._status.set_max_width(max_width)
|
||||
self._status.set_position(label_x, y)
|
||||
self._status.render()
|
||||
|
||||
def _load_qr(self, text: str) -> None:
|
||||
self._unload_qr()
|
||||
self._qr_source = text
|
||||
try:
|
||||
self._qr_texture = make_texture(text, inverted=True)
|
||||
except Exception:
|
||||
cloudlog.exception("connect phone QR generation failed")
|
||||
self._qr_texture = None
|
||||
|
||||
def _draw_qr(self) -> None:
|
||||
if self._qr_texture is None:
|
||||
return
|
||||
scale = self._rect.height / self._qr_texture.height
|
||||
rl.draw_texture_ex(self._qr_texture, rl.Vector2(round(self._rect.x + 8), round(self._rect.y)), 0.0, scale, rl.WHITE)
|
||||
|
||||
def _unload_qr(self) -> None:
|
||||
if self._qr_texture and self._qr_texture.id != 0:
|
||||
rl.unload_texture(self._qr_texture)
|
||||
self._qr_texture = None
|
||||
|
||||
def __del__(self):
|
||||
self._unload_qr()
|
||||
|
||||
|
||||
class ConnectPhoneCheckDialog(NavScroller):
|
||||
def __init__(self, check: str, params):
|
||||
super().__init__()
|
||||
self._params = params
|
||||
allow = BigConfirmationCircleButton(tr("allow\nthis phone"), gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 64, 64),
|
||||
lambda: self._answer("allow"))
|
||||
deny = BigConfirmationCircleButton(tr("deny"), gui_app.texture("icons_mici/setup/cancel.png", 64, 64), lambda: self._answer("deny"))
|
||||
self._scroller.add_widgets([GreyBigButton(check, tr("same code on your phone?"), gui_app.texture("icons_mici/setup/green_info.png", 64, 64)),
|
||||
allow, deny])
|
||||
|
||||
def _answer(self, action: str) -> None:
|
||||
self.dismiss(lambda: write_request(self._params, action))
|
||||
@@ -5,19 +5,38 @@ 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 math
|
||||
import time
|
||||
|
||||
import pyray as rl
|
||||
|
||||
from openpilot.selfdrive.ui.mici.layouts.home import MiciHomeLayout
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state, ChestnutState
|
||||
from openpilot.sunnypilot.system.connect_phone import phone_indicator, read_status
|
||||
from openpilot.system.ui.lib.application import FontWeight
|
||||
from openpilot.system.ui.widgets.icon_widget import IconWidget
|
||||
from openpilot.system.ui.widgets.label import UnifiedLabel
|
||||
|
||||
BT_POLL_SECONDS = 1.0
|
||||
BT_WAITING_OPACITY = 0.35
|
||||
|
||||
|
||||
class MiciHomeLayoutSP(MiciHomeLayout):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._openpilot_label = UnifiedLabel("sunnypilot", font_size=88, font_weight=FontWeight.AUDIOWIDE, max_width=480, wrap_text=False)
|
||||
self._bluetooth_icon = IconWidget("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", (40, 40))
|
||||
self._bluetooth_icon.set_visible(False)
|
||||
self._bt_polled_at = float("-inf")
|
||||
self._status_bar_layout.add_widget(self._bluetooth_icon)
|
||||
|
||||
def _update_state(self):
|
||||
super()._update_state()
|
||||
now = time.monotonic()
|
||||
if now - self._bt_polled_at >= BT_POLL_SECONDS:
|
||||
self._bt_polled_at = now
|
||||
state = phone_indicator(read_status(ui_state.params))
|
||||
self._bluetooth_icon.set_visible(state != "hidden")
|
||||
self._bluetooth_icon.set_opacity(1.0 if state == "connected" else BT_WAITING_OPACITY)
|
||||
|
||||
def _set_chestnut_visibility(self):
|
||||
usb_connected = ui_state.usb_connected
|
||||
|
||||
@@ -11,6 +11,7 @@ from openpilot.selfdrive.ui.mici.widgets.button import BigCircleButton
|
||||
from openpilot.selfdrive.ui.mici.widgets.dialog import BigConfirmationDialog, BigDialog
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.sunnylink import SunnylinkLayoutMici
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.models import ModelsLayoutMici
|
||||
from openpilot.selfdrive.ui.sunnypilot.mici.layouts.bluetooth import BluetoothLayoutMici
|
||||
from openpilot.selfdrive.ui.ui_state import ui_state
|
||||
from openpilot.system.ui.lib.application import gui_app, FontWeight
|
||||
from openpilot.system.ui.lib.multilang import tr
|
||||
@@ -50,6 +51,12 @@ class SettingsLayoutSP(OP.SettingsLayout):
|
||||
models_btn = SettingsBigButton(tr("models"), "", gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_models.png", ICON_SIZE, ICON_SIZE))
|
||||
models_btn.set_click_callback(lambda: gui_app.push_widget(models_panel))
|
||||
|
||||
network_btn = self._scroller._items[1]
|
||||
bluetooth_panel = BluetoothLayoutMici()
|
||||
bluetooth_btn = SettingsBigButton(tr("bluetooth"), "",
|
||||
gui_app.texture("../../sunnypilot/selfdrive/assets/offroad/icon_bluetooth.png", ICON_SIZE, ICON_SIZE))
|
||||
bluetooth_btn.set_click_callback(lambda: gui_app.push_widget(bluetooth_panel))
|
||||
|
||||
# onroad: enable button sits at the front (left of toggles)
|
||||
self._enable_offroad_btn_onroad = BigCircleButton(self.icon_offroad_enable, red=True)
|
||||
self._enable_offroad_btn_onroad.set_click_callback(lambda: self._handle_always_offroad(True))
|
||||
@@ -68,6 +75,7 @@ class SettingsLayoutSP(OP.SettingsLayout):
|
||||
|
||||
items.insert(1, models_btn)
|
||||
items.insert(5, sunnylink_btn)
|
||||
items.insert(items.index(network_btn) + 1, bluetooth_btn)
|
||||
|
||||
# front slots (only one ever visible at a time): exit-always-offroad, then enable-onroad
|
||||
items.insert(0, self._enable_offroad_btn_onroad)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:f7df0485754b51731fc60b4cb324d75c7058c0e20c7c979ac84aa5273e29aa83
|
||||
size 5956
|
||||
@@ -0,0 +1,25 @@
|
||||
"""
|
||||
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.
|
||||
"""
|
||||
# Parameters that should never be remotely modified
|
||||
BLOCKED_PARAMS = {
|
||||
"AdbEnabled",
|
||||
"BluetoothAllowed",
|
||||
"BluetoothEnabled",
|
||||
"CompletedSunnylinkConsentVersion",
|
||||
"CompletedTrainingVersion",
|
||||
"GithubUsername", # Could grant SSH access
|
||||
"GithubSshKeys", # Direct SSH key injection
|
||||
"HasAcceptedTerms",
|
||||
"HasAcceptedTermsSP",
|
||||
"OnroadCycleRequested", # Prevent remote cycle trigger
|
||||
"ParamsVersion", # Device-managed version counter
|
||||
}
|
||||
|
||||
|
||||
def is_local_param(key: str) -> bool:
|
||||
return key.startswith("SunnylinkLocal")
|
||||
|
||||
@@ -44,18 +44,7 @@ DISALLOW_LOG_UPLOAD = threading.Event()
|
||||
|
||||
params = Params()
|
||||
|
||||
# Parameters that should never be remotely modified
|
||||
BLOCKED_PARAMS = {
|
||||
"AdbEnabled",
|
||||
"CompletedSunnylinkConsentVersion",
|
||||
"CompletedTrainingVersion",
|
||||
"GithubUsername", # Could grant SSH access
|
||||
"GithubSshKeys", # Direct SSH key injection
|
||||
"HasAcceptedTerms",
|
||||
"HasAcceptedTermsSP",
|
||||
"OnroadCycleRequested", # Prevent remote cycle trigger
|
||||
"ParamsVersion", # Device-managed version counter
|
||||
}
|
||||
from openpilot.sunnypilot.sunnylink.athena.params_guard import BLOCKED_PARAMS, is_local_param
|
||||
|
||||
|
||||
def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None:
|
||||
@@ -166,7 +155,7 @@ def toggleLogUpload(enabled: bool):
|
||||
@dispatcher.add_method
|
||||
def getParamsAllKeys() -> list[str]:
|
||||
keys: list[str] = [k.decode('utf-8') for k in Params().all_keys()]
|
||||
return keys
|
||||
return [key for key in keys if not is_local_param(key)]
|
||||
|
||||
|
||||
@dispatcher.add_method
|
||||
@@ -208,7 +197,7 @@ def getParams(params_keys: list[str], compression: bool = False) -> str | dict[s
|
||||
ParamKeyType.BYTES.value: b"",
|
||||
}
|
||||
|
||||
param_keys_validated = [key for key in params_keys if key in available_keys]
|
||||
param_keys_validated = [key for key in params_keys if key in available_keys and not is_local_param(key)]
|
||||
params_dict: dict[str, list[dict[str, str | bool | int]]] = {"params": []}
|
||||
for key in param_keys_validated:
|
||||
value = get_param_as_byte(key)
|
||||
@@ -238,7 +227,7 @@ def getParams(params_keys: list[str], compression: bool = False) -> str | dict[s
|
||||
def saveParams(params_to_update: dict[str, str], compression: bool = False) -> None:
|
||||
for key, value in params_to_update.items():
|
||||
# disallow modifications to blocked parameters
|
||||
if key in BLOCKED_PARAMS:
|
||||
if key in BLOCKED_PARAMS or is_local_param(key):
|
||||
cloudlog.warning(f"sunnylinkd.saveParams.blocked: Attempted to modify blocked parameter '{key}'")
|
||||
continue
|
||||
|
||||
|
||||
@@ -58,3 +58,24 @@ class TestSunnylinkdMethods(OpenpilotTestCase):
|
||||
assert len(self.saved_params) == 1
|
||||
assert self.saved_params[0][0] == "SpeedLimitOffset"
|
||||
assert self.saved_params[0][1] == "10"
|
||||
|
||||
def test_saveParams_refuses_local_and_bluetooth_params(self):
|
||||
sunnylinkd.saveParams({
|
||||
"SunnylinkLocalBleGrants": "e30=",
|
||||
"SunnylinkLocalConnectPhoneRequest": "e30=",
|
||||
"BluetoothAllowed": "MQ==",
|
||||
"BluetoothEnabled": "MQ==",
|
||||
"SpeedLimitOffset": "5",
|
||||
})
|
||||
|
||||
assert [p[0] for p in self.saved_params] == ["SpeedLimitOffset"]
|
||||
|
||||
def test_local_params_are_hidden(self, mocker):
|
||||
params = mocker.patch.object(sunnylinkd, "Params").return_value
|
||||
params.all_keys.return_value = [b"SunnylinkEnabled", b"SunnylinkLocalBleGrants", b"SunnylinkLocalConnectPhoneWindow"]
|
||||
mocker.patch.object(sunnylinkd, "get_param_as_byte", return_value=b"1")
|
||||
|
||||
assert sunnylinkd.getParamsAllKeys() == ["SunnylinkEnabled"]
|
||||
response = sunnylinkd.getParams(["SunnylinkEnabled", "SunnylinkLocalBleGrants", "SunnylinkLocalConnectPhoneWindow"])
|
||||
assert set(response) == {"SunnylinkEnabled", "params"}
|
||||
assert "SunnylinkLocal" not in response["params"]
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
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 hmac
|
||||
import secrets
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
|
||||
|
||||
# draft-irtf-cfrg-cpace-21, CPACE-X25519-SHA512 (the same test vectors as -20)
|
||||
PAKE_SUITE = 1
|
||||
DSI = b"CPace255"
|
||||
CI = b"sunnylink-ble-connect-v1"
|
||||
|
||||
P = 2**255 - 19
|
||||
J = 486662
|
||||
C2 = pow(2, (P + 3) // 8, P)
|
||||
C3 = pow(2, (P - 1) // 4, P) # sqrt(-1)
|
||||
C4 = (P - 5) // 8
|
||||
|
||||
|
||||
class CpaceError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def lv(data: bytes) -> bytes:
|
||||
# LEB128 length prefix, as the draft's prepend_len
|
||||
n = len(data)
|
||||
head = bytearray()
|
||||
while True:
|
||||
head.append((n & 0x7F) | (0x80 if n >> 7 else 0))
|
||||
n >>= 7
|
||||
if not n:
|
||||
return bytes(head) + data
|
||||
|
||||
|
||||
def _cmov(a: int, b: int, cond: bool) -> int:
|
||||
# b if cond else a, as a mask select; Python bigints are not constant time regardless
|
||||
mask = -int(cond)
|
||||
return (a & ~mask) | (b & mask)
|
||||
|
||||
|
||||
def map_to_curve_elligator2_curve25519(u: int) -> int:
|
||||
# RFC 9380 G.2.1 straight-line map, Z = 2. Only x is returned: the RFC's y, x2 sign fix and y2 steps
|
||||
# feed nothing CPace uses, and x only depends on e3 (which needs y1).
|
||||
tv1 = 2 * u * u % P
|
||||
xd = (tv1 + 1) % P
|
||||
x1n = -J % P
|
||||
tv2 = xd * xd % P
|
||||
gxd = tv2 * xd % P
|
||||
gx1 = J * tv1 % P * x1n % P
|
||||
gx1 = (gx1 + tv2) % P * x1n % P
|
||||
tv3 = gxd * gxd % P
|
||||
tv2 = tv3 * tv3 % P
|
||||
tv3 = tv3 * gxd % P
|
||||
tv3 = tv3 * gx1 % P
|
||||
tv2 = tv2 * tv3 % P
|
||||
y11 = pow(tv2, C4, P) * tv3 % P
|
||||
y12 = y11 * C3 % P
|
||||
e1 = (y11 * y11 % P * gxd - gx1) % P == 0
|
||||
y1 = _cmov(y12, y11, e1)
|
||||
x2n = x1n * tv1 % P
|
||||
e3 = (y1 * y1 % P * gxd - gx1) % P == 0
|
||||
xn = _cmov(x2n, x1n, e3)
|
||||
return xn * pow(xd, P - 2, P) % P
|
||||
|
||||
|
||||
def generator(prs: bytes, ci: bytes, sid: bytes) -> bytes:
|
||||
zpad = max(0, 128 - len(lv(prs)) - len(lv(DSI)) - 1)
|
||||
gen_str = lv(DSI) + lv(prs) + lv(bytes(zpad)) + lv(ci) + lv(sid)
|
||||
u = int.from_bytes(hashlib.sha512(gen_str).digest()[:32], "little") & ((1 << 255) - 1)
|
||||
return map_to_curve_elligator2_curve25519(u % P).to_bytes(32, "little")
|
||||
|
||||
|
||||
def _scalar_mult(scalar: bytes, point: bytes) -> bytes:
|
||||
try:
|
||||
k = X25519PrivateKey.from_private_bytes(scalar).exchange(X25519PublicKey.from_public_bytes(point))
|
||||
except ValueError as e:
|
||||
raise CpaceError("low-order or malformed point") from e
|
||||
if k == bytes(32):
|
||||
raise CpaceError("low-order point")
|
||||
return k
|
||||
|
||||
|
||||
def _tag(isk: bytes, sid: bytes, share: bytes, ad: bytes) -> bytes:
|
||||
mac_key = hashlib.sha512(b"CPaceMac" + sid + isk).digest()
|
||||
return hmac.new(mac_key, lv(share) + lv(ad), hashlib.sha512).digest()
|
||||
|
||||
|
||||
class Cpace:
|
||||
def __init__(self, initiator: bool, prs: bytes, sid: bytes, ad_a: bytes, ad_b: bytes, *, scalar: bytes | None = None):
|
||||
self._initiator = initiator
|
||||
self._sid = sid
|
||||
self._ad_a, self._ad_b = ad_a, ad_b
|
||||
self._scalar = scalar if scalar is not None else secrets.token_bytes(32)
|
||||
self.public = _scalar_mult(self._scalar, generator(prs, CI, sid))
|
||||
|
||||
def isk(self, peer_share: bytes) -> bytes:
|
||||
k = _scalar_mult(self._scalar, peer_share)
|
||||
ya, yb = (self.public, peer_share) if self._initiator else (peer_share, self.public)
|
||||
transcript = lv(ya) + lv(self._ad_a) + lv(yb) + lv(self._ad_b)
|
||||
return hashlib.sha512(lv(DSI + b"_ISK") + lv(self._sid) + lv(k) + transcript).digest()
|
||||
|
||||
def tag(self, isk: bytes) -> bytes:
|
||||
own_ad = self._ad_a if self._initiator else self._ad_b
|
||||
return _tag(isk, self._sid, self.public, own_ad)
|
||||
|
||||
def check(self, isk: bytes, peer_share: bytes, peer_tag: bytes) -> bool:
|
||||
peer_ad = self._ad_b if self._initiator else self._ad_a
|
||||
return hmac.compare_digest(_tag(isk, self._sid, peer_share, peer_ad), peer_tag)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
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 base64
|
||||
import secrets
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
|
||||
|
||||
GRANTS_KEY = "SunnylinkLocalBleGrants"
|
||||
KEY_KEY = "SunnylinkLocalBleKey"
|
||||
MAX_PHONES = 8
|
||||
|
||||
|
||||
def b64(data: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def unb64(text: str) -> bytes:
|
||||
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
||||
|
||||
|
||||
def load(params) -> list[dict]:
|
||||
grants = params.get(GRANTS_KEY)
|
||||
return grants if isinstance(grants, list) else []
|
||||
|
||||
|
||||
def save(params, grants: list[dict]):
|
||||
params.put(GRANTS_KEY, grants, block=True)
|
||||
|
||||
|
||||
def static_private(params) -> X25519PrivateKey:
|
||||
raw = params.get(KEY_KEY)
|
||||
if not isinstance(raw, bytes) or len(raw) != 32:
|
||||
raw = secrets.token_bytes(32)
|
||||
params.put(KEY_KEY, raw, block=True)
|
||||
return X25519PrivateKey.from_private_bytes(raw)
|
||||
@@ -0,0 +1,141 @@
|
||||
"""
|
||||
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
|
||||
|
||||
from cryptography.exceptions import InvalidSignature, InvalidTag
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
|
||||
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
||||
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||
|
||||
MORE = 0x01
|
||||
PAKE_SUITE = 1 # CPACE-X25519-SHA512; 0 is a development build with no PAKE
|
||||
MTU_MIN = 23
|
||||
FRAME_HEADER = 3
|
||||
MAX_ATT_VALUE = 512 # Bluetooth caps an attribute value at 512 bytes whatever the MTU
|
||||
PRE_SESSION_CAP = 1024
|
||||
SESSION_CAP = 16384
|
||||
RECORD_TYPE = 0x20
|
||||
REKEY_INTERVAL = 65536
|
||||
KEYS_INFO = b"sunnylink-ble-connect-v1 keys"
|
||||
KEYS_SIGNED_TAG = b"sunnylink-ble-keys-v1\x00"
|
||||
|
||||
|
||||
class LinkError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def frames(message: bytes, link_id: int, max_frame: int) -> list[bytes]:
|
||||
# max_frame is the ATT payload (MTU - 3); each frame carries 3 header bytes of it
|
||||
max_frame = min(max_frame, MAX_ATT_VALUE)
|
||||
if not 1 <= link_id <= 0xFFFF:
|
||||
raise LinkError("link id")
|
||||
if max_frame < MTU_MIN - 3 or not message:
|
||||
raise LinkError("frame size or empty message")
|
||||
size = max_frame - FRAME_HEADER
|
||||
chunks = [message[i:i + size] for i in range(0, len(message), size)]
|
||||
return [bytes([MORE if i < len(chunks) - 1 else 0]) + link_id.to_bytes(2, "big") + c for i, c in enumerate(chunks)]
|
||||
|
||||
|
||||
class Reassembler:
|
||||
def __init__(self, link_id: int, cap: int = PRE_SESSION_CAP):
|
||||
self.link_id = link_id
|
||||
self.cap = cap # set to SESSION_CAP once the session is up
|
||||
self._buf = bytearray()
|
||||
|
||||
def feed(self, frame: bytes) -> bytes | None:
|
||||
if len(frame) <= FRAME_HEADER or frame[0] & ~MORE or int.from_bytes(frame[1:3], "big") != self.link_id:
|
||||
self._buf.clear()
|
||||
raise LinkError("malformed frame")
|
||||
self._buf += frame[FRAME_HEADER:]
|
||||
if len(self._buf) > self.cap:
|
||||
self._buf.clear()
|
||||
raise LinkError("message over cap")
|
||||
if frame[0] & MORE:
|
||||
return None
|
||||
message, self._buf = bytes(self._buf), bytearray()
|
||||
return message
|
||||
|
||||
|
||||
def _nonce(n: int) -> bytes:
|
||||
return b"\x00" * 4 + n.to_bytes(8, "little")
|
||||
|
||||
|
||||
def _rekey(key: bytes) -> bytes:
|
||||
return ChaCha20Poly1305(key).encrypt(_nonce(2**64 - 1), bytes(32), b"")[:32]
|
||||
|
||||
|
||||
class Records:
|
||||
def __init__(self, send_key: bytes, recv_key: bytes, link_id: int, *, rekey_interval: int = REKEY_INTERVAL):
|
||||
self._send, self._recv = send_key, recv_key
|
||||
self._aad = bytes([RECORD_TYPE]) + link_id.to_bytes(2, "big")
|
||||
self._interval = rekey_interval
|
||||
self._ns = 0
|
||||
self._nr = 0
|
||||
|
||||
def seal(self, inner: bytes) -> bytes:
|
||||
if self._ns and self._ns % self._interval == 0:
|
||||
self._send = _rekey(self._send)
|
||||
ct = ChaCha20Poly1305(self._send).encrypt(_nonce(self._ns), inner, self._aad)
|
||||
self._ns += 1
|
||||
return bytes([RECORD_TYPE]) + ct
|
||||
|
||||
def open(self, record: bytes) -> bytes:
|
||||
if len(record) < 1 + 1 + 16 or record[0] != RECORD_TYPE:
|
||||
raise LinkError("not a record")
|
||||
if self._nr and self._nr % self._interval == 0:
|
||||
self._recv = _rekey(self._recv)
|
||||
try:
|
||||
inner = ChaCha20Poly1305(self._recv).decrypt(_nonce(self._nr), record[1:], self._aad)
|
||||
except InvalidTag as e:
|
||||
raise LinkError("record authentication failed") from e
|
||||
self._nr += 1
|
||||
return inner
|
||||
|
||||
|
||||
def transcript(*bodies: bytes) -> bytes:
|
||||
# connect_start, connect_window, pake_a, pake_b, confirm_a, confirm_b: clear bodies, fixed sizes, no separators
|
||||
if len(bodies) != 6:
|
||||
raise ValueError("transcript takes six bodies")
|
||||
return hashlib.sha256(b"".join(bodies)).digest()
|
||||
|
||||
|
||||
def session_keys(isk: bytes, sid: bytes) -> tuple[bytes, bytes, str]:
|
||||
okm = HKDF(algorithm=hashes.SHA256(), length=68, salt=sid, info=KEYS_INFO).derive(isk)
|
||||
check = int.from_bytes(okm[64:68], "big") % 1_000_000
|
||||
return okm[:32], okm[32:64], f"{check:06d}"
|
||||
|
||||
|
||||
def signed_bytes(role: str, th: bytes, spki: bytes, static: bytes) -> bytes:
|
||||
if role not in ("D", "P") or len(th) != 32 or len(static) != 32:
|
||||
raise ValueError("signed bytes")
|
||||
return KEYS_SIGNED_TAG + role.encode() + th + hashlib.sha256(spki).digest() + static
|
||||
|
||||
|
||||
def sign(key, data: bytes) -> tuple[str, bytes]:
|
||||
if isinstance(key, rsa.RSAPrivateKey):
|
||||
return "RS256", key.sign(data, padding.PKCS1v15(), hashes.SHA256())
|
||||
if isinstance(key, ec.EllipticCurvePrivateKey) and key.curve.name == "secp256r1":
|
||||
return "ES256", key.sign(data, ec.ECDSA(hashes.SHA256()))
|
||||
raise ValueError("unsupported key")
|
||||
|
||||
|
||||
def verify(alg: str, spki: bytes, data: bytes, sig: bytes) -> bool:
|
||||
try:
|
||||
pub = serialization.load_der_public_key(spki)
|
||||
except ValueError:
|
||||
return False
|
||||
try:
|
||||
if alg == "RS256" and isinstance(pub, rsa.RSAPublicKey):
|
||||
pub.verify(sig, data, padding.PKCS1v15(), hashes.SHA256())
|
||||
elif alg == "ES256" and isinstance(pub, ec.EllipticCurvePublicKey) and pub.curve.name == "secp256r1":
|
||||
pub.verify(sig, data, ec.ECDSA(hashes.SHA256()))
|
||||
else:
|
||||
return False
|
||||
except InvalidSignature:
|
||||
return False
|
||||
return True
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
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 hmac
|
||||
|
||||
from cryptography.exceptions import InvalidTag
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
|
||||
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
||||
|
||||
# Noise revision 34, pattern KK only
|
||||
PROTOCOL = b"Noise_KK_25519_ChaChaPoly_SHA256" # exactly 32 bytes, so h starts as the name itself
|
||||
PROLOGUE = b"sunnylink-ble-v1"
|
||||
|
||||
|
||||
class NoiseError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _hkdf2(ck: bytes, ikm: bytes) -> tuple[bytes, bytes]:
|
||||
temp = hmac.new(ck, ikm, hashlib.sha256).digest()
|
||||
out1 = hmac.new(temp, b"\x01", hashlib.sha256).digest()
|
||||
return out1, hmac.new(temp, out1 + b"\x02", hashlib.sha256).digest()
|
||||
|
||||
|
||||
def _nonce(n: int) -> bytes:
|
||||
return b"\x00" * 4 + n.to_bytes(8, "little")
|
||||
|
||||
|
||||
def _dh(priv: X25519PrivateKey, pub: bytes) -> bytes:
|
||||
try:
|
||||
return priv.exchange(X25519PublicKey.from_public_bytes(pub))
|
||||
except ValueError as e:
|
||||
raise NoiseError("low-order or malformed key") from e
|
||||
|
||||
|
||||
class KKHandshake:
|
||||
# Messages: -> e, es, ss <- e, ee, se (initiator = phone, responder = comma)
|
||||
def __init__(self, initiator: bool, s: X25519PrivateKey, rs: bytes, *, e: X25519PrivateKey | None = None,
|
||||
prologue: bytes = PROLOGUE):
|
||||
self._initiator = initiator
|
||||
self._s = s
|
||||
self._rs = rs
|
||||
self._e = e
|
||||
self._re: bytes | None = None
|
||||
self._step = 0 # 0 first message, 1 second, 2 done
|
||||
self._h = PROTOCOL
|
||||
self._ck = PROTOCOL
|
||||
self._k: bytes | None = None
|
||||
self._n = 0
|
||||
s_pub = s.public_key().public_bytes_raw()
|
||||
self._mix_hash(prologue)
|
||||
# pre-messages, initiator's static key first
|
||||
self._mix_hash(s_pub if initiator else rs)
|
||||
self._mix_hash(rs if initiator else s_pub)
|
||||
|
||||
def _mix_hash(self, data: bytes):
|
||||
self._h = hashlib.sha256(self._h + data).digest()
|
||||
|
||||
def _mix_key(self, ikm: bytes):
|
||||
self._ck, temp = _hkdf2(self._ck, ikm)
|
||||
self._k, self._n = temp, 0
|
||||
|
||||
def _encrypt(self, plaintext: bytes) -> bytes:
|
||||
ct = ChaCha20Poly1305(self._k).encrypt(_nonce(self._n), plaintext, self._h)
|
||||
self._n += 1
|
||||
self._mix_hash(ct)
|
||||
return ct
|
||||
|
||||
def _decrypt(self, ciphertext: bytes) -> bytes:
|
||||
try:
|
||||
pt = ChaCha20Poly1305(self._k).decrypt(_nonce(self._n), ciphertext, self._h)
|
||||
except InvalidTag as e:
|
||||
raise NoiseError("handshake authentication failed") from e
|
||||
self._n += 1
|
||||
self._mix_hash(ciphertext)
|
||||
return pt
|
||||
|
||||
def _local_e(self) -> bytes:
|
||||
if self._e is None:
|
||||
self._e = X25519PrivateKey.generate()
|
||||
e_pub = self._e.public_key().public_bytes_raw()
|
||||
self._mix_hash(e_pub)
|
||||
return e_pub
|
||||
|
||||
def write(self, payload: bytes = b"") -> bytes:
|
||||
if self._initiator and self._step == 0:
|
||||
e_pub = self._local_e()
|
||||
self._mix_key(_dh(self._e, self._rs)) # es
|
||||
self._mix_key(_dh(self._s, self._rs)) # ss
|
||||
elif not self._initiator and self._step == 1:
|
||||
e_pub = self._local_e()
|
||||
self._mix_key(_dh(self._e, self._re)) # ee
|
||||
self._mix_key(_dh(self._e, self._rs)) # se
|
||||
else:
|
||||
raise NoiseError("write out of order")
|
||||
self._step += 1
|
||||
return e_pub + self._encrypt(payload)
|
||||
|
||||
def read(self, message: bytes) -> bytes:
|
||||
if len(message) < 32 + 16:
|
||||
raise NoiseError("short handshake message")
|
||||
e_pub, body = message[:32], message[32:]
|
||||
if not self._initiator and self._step == 0:
|
||||
self._re = e_pub
|
||||
self._mix_hash(e_pub)
|
||||
self._mix_key(_dh(self._s, e_pub)) # es
|
||||
self._mix_key(_dh(self._s, self._rs)) # ss
|
||||
elif self._initiator and self._step == 1:
|
||||
self._mix_hash(e_pub)
|
||||
self._mix_key(_dh(self._e, e_pub)) # ee
|
||||
self._mix_key(_dh(self._s, e_pub)) # se
|
||||
else:
|
||||
raise NoiseError("read out of order")
|
||||
self._step += 1
|
||||
return self._decrypt(body)
|
||||
|
||||
def split(self) -> tuple[bytes, bytes]:
|
||||
if self._step != 2:
|
||||
raise NoiseError("handshake not finished")
|
||||
k1, k2 = _hkdf2(self._ck, b"")
|
||||
return (k1, k2) if self._initiator else (k2, k1)
|
||||
@@ -0,0 +1,176 @@
|
||||
"""
|
||||
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 json
|
||||
|
||||
from openpilot.common.hardware import HARDWARE
|
||||
from openpilot.common.params import ParamKeyType
|
||||
from openpilot.common.version import get_version
|
||||
from openpilot.sunnypilot.sunnylink.athena.params_guard import BLOCKED_PARAMS, is_local_param
|
||||
|
||||
# what sunnylink's getParams reports for a key that was never set and has no default
|
||||
UNSET_VALUES = {ParamKeyType.BOOL: False, ParamKeyType.INT: 0, ParamKeyType.FLOAT: 0.0, ParamKeyType.STRING: "", ParamKeyType.JSON: {}}
|
||||
|
||||
METHOD_NOT_FOUND = -32601
|
||||
INVALID_REQUEST = -32600
|
||||
REFUSED = -32001
|
||||
MAX_PARAM_KEYS = 32
|
||||
HOTSPOT_WAIT = 30.0 # seconds for the hotspot to come up after hotspot.start
|
||||
|
||||
|
||||
class RpcError(Exception):
|
||||
def __init__(self, code: int, message: str):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def _refused(message: str) -> RpcError:
|
||||
return RpcError(REFUSED, message)
|
||||
|
||||
|
||||
def _wifi_status() -> dict:
|
||||
# wpa_supplicant answers at once; a fresh WifiManager reports no SSID until its own thread catches up
|
||||
try:
|
||||
from openpilot.common.hardware.comma.hardware import wpa_supplicant_cmd
|
||||
status = wpa_supplicant_cmd("STATUS")
|
||||
except (OSError, ImportError):
|
||||
return {"wifi_ssid": None, "hotspot": False}
|
||||
hotspot = status.get("mode") == "AP"
|
||||
connected = status.get("wpa_state") == "COMPLETED" and not hotspot
|
||||
return {"wifi_ssid": (status.get("ssid") or None) if connected else None, "hotspot": hotspot}
|
||||
|
||||
|
||||
def _default_wifi():
|
||||
from openpilot.system.ui.lib.wifi_manager import WifiManager
|
||||
return WifiManager()
|
||||
|
||||
|
||||
class Rpc:
|
||||
def __init__(self, params, wifi=None):
|
||||
self._params = params
|
||||
self._wifi_factory = wifi or _default_wifi
|
||||
self._wifi_obj = None
|
||||
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]:
|
||||
# returns (response, after): response None means answered later by poll(); after "forget" drops the link
|
||||
try:
|
||||
request = json.loads(body)
|
||||
rid, method = request["id"], request["method"]
|
||||
if not isinstance(rid, int) or not isinstance(method, str):
|
||||
raise TypeError("id and method")
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return _envelope(None, error=(INVALID_REQUEST, "invalid request")), None
|
||||
args = request.get("params") or {}
|
||||
try:
|
||||
return self._dispatch(token, rid, method, args, grants, this, now)
|
||||
except RpcError as e:
|
||||
return _envelope(rid, error=(e.code, str(e))), None
|
||||
|
||||
def poll(self, now: float) -> list[tuple[str, dict]]:
|
||||
done, waiting = [], []
|
||||
for token, rid, deadline in self._pending:
|
||||
wifi = self._wifi()
|
||||
if wifi.is_tethering_active():
|
||||
done.append((token, _envelope(rid, result=self._credentials(wifi))))
|
||||
elif now >= deadline:
|
||||
done.append((token, _envelope(rid, error=(REFUSED, "hotspot did not start"))))
|
||||
else:
|
||||
waiting.append((token, rid, deadline))
|
||||
self._pending = waiting
|
||||
return done
|
||||
|
||||
def _dispatch(self, token, rid, method, args, grants, this, now):
|
||||
if method == "status.get":
|
||||
return _envelope(rid, result=self._status(grants)), None
|
||||
if method == "params.get":
|
||||
return _envelope(rid, result=self._get(args)), None
|
||||
if method == "params.set":
|
||||
return _envelope(rid, result=self._set(args)), None
|
||||
if method == "hotspot.start":
|
||||
wifi = self._wifi()
|
||||
if wifi.is_tethering_active():
|
||||
return _envelope(rid, result=self._credentials(wifi)), None
|
||||
wifi.set_tethering_active(True)
|
||||
self._pending.append((token, rid, now + HOTSPOT_WAIT))
|
||||
return None, None
|
||||
if method == "hotspot.stop":
|
||||
self._wifi().set_tethering_active(False)
|
||||
return _envelope(rid, result={}), None
|
||||
if method == "hotspot.credentials":
|
||||
wifi = self._wifi()
|
||||
if not wifi.is_tethering_active():
|
||||
raise _refused("hotspot is off")
|
||||
return _envelope(rid, result=self._credentials(wifi)), None
|
||||
if method == "phones.list":
|
||||
return _envelope(rid, result=[{"name": g["name"], "added": g["added"], "last_seen": g["last_seen"],
|
||||
"this": g["spki"] == this} for g in grants]), None
|
||||
if method == "phones.forgetSelf":
|
||||
return _envelope(rid, result={}), "forget"
|
||||
raise RpcError(METHOD_NOT_FOUND, f"unknown method {method}")
|
||||
|
||||
def _wifi(self):
|
||||
if self._wifi_obj is None:
|
||||
try:
|
||||
self._wifi_obj = self._wifi_factory()
|
||||
except Exception as e:
|
||||
raise _refused("wifi unavailable") from e
|
||||
return self._wifi_obj
|
||||
|
||||
def _credentials(self, wifi) -> dict:
|
||||
return {"ssid": wifi.tethering_ssid, "password": wifi.tethering_password}
|
||||
|
||||
def _status(self, grants: list[dict]) -> dict:
|
||||
return {"version": get_version(), "agnos": HARDWARE.get_os_version(), "dongle_id": self._params.get("DongleId"),
|
||||
"onroad": not self._params.get_bool("IsOffroad"), "engaged": self._params.get_bool("IsEngaged"),
|
||||
"network": _wifi_status(), "phones": len(grants)}
|
||||
|
||||
def _known(self) -> set[str]:
|
||||
return {key.decode() for key in self._params.all_keys()}
|
||||
|
||||
def _check_keys(self, keys: list[str]):
|
||||
for key in keys:
|
||||
if key in BLOCKED_PARAMS or is_local_param(key):
|
||||
raise _refused(f"{key} is not available")
|
||||
|
||||
def _check_known(self, keys: list[str]):
|
||||
known = self._known()
|
||||
for key in keys:
|
||||
if key not in known:
|
||||
raise _refused(f"unknown param {key}")
|
||||
|
||||
def _get(self, args: dict) -> dict:
|
||||
keys = args.get("keys")
|
||||
if not isinstance(keys, list) or len(keys) > MAX_PARAM_KEYS or not all(isinstance(k, str) for k in keys):
|
||||
raise _refused("keys must be a list of at most 32 names")
|
||||
self._check_keys(keys)
|
||||
known = self._known()
|
||||
values = {}
|
||||
for key in keys:
|
||||
value = self._params.get(key, return_default=True) if key in known else None
|
||||
if value is None and key in known:
|
||||
value = UNSET_VALUES.get(self._params.get_type(key))
|
||||
values[key] = None if isinstance(value, bytes) else value # raw bytes have no JSON form
|
||||
return {"values": values}
|
||||
|
||||
def _set(self, args: dict) -> dict:
|
||||
values = args.get("values")
|
||||
if not isinstance(values, dict):
|
||||
raise _refused("values must be an object")
|
||||
self._check_keys(list(values))
|
||||
self._check_known(list(values))
|
||||
for key, value in values.items():
|
||||
try:
|
||||
self._params.put(key, value, block=True)
|
||||
except (TypeError, ValueError, KeyError) as e:
|
||||
raise _refused(f"bad value for {key}") from e
|
||||
return {"ok": list(values)}
|
||||
|
||||
|
||||
def _envelope(rid, result=None, error=None) -> dict:
|
||||
if error is not None:
|
||||
return {"jsonrpc": "2.0", "id": rid, "error": {"code": error[0], "message": error[1]}}
|
||||
return {"jsonrpc": "2.0", "id": rid, "result": result}
|
||||
@@ -0,0 +1,325 @@
|
||||
"""
|
||||
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 json
|
||||
import secrets
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
from openpilot.sunnypilot.system import connect_phone
|
||||
from openpilot.sunnypilot.system.ble import cpace, grants, link, noise
|
||||
from openpilot.sunnypilot.system.ble.rpc import Rpc
|
||||
|
||||
PROTO = 1
|
||||
CONNECT_START, CONNECT_WINDOW, PAKE_A, PAKE_B, CONFIRM_A, CONFIRM_B = 0x01, 0x02, 0x03, 0x04, 0x05, 0x06
|
||||
RESUME_1, RESUME_2, ERROR = 0x10, 0x11, 0x7F
|
||||
DECISION, DEVICE_KEYS, PHONE_KEYS, GRANT_RESULT, RPC = 0x30, 0x31, 0x32, 0x33, 0x40
|
||||
ERR_NO_WINDOW, ERR_BUSY, ERR_VERSION, ERR_WRONG_CODE, ERR_WINDOW_CLOSED, ERR_TIMEOUT, ERR_UNKNOWN_PHONE = 1, 2, 3, 4, 5, 6, 8
|
||||
ALLOW, DENY, NO_ANSWER = 1, 2, 3
|
||||
GRANT_ADDED, GRANT_REFUSED = 1, 2 # 3 reserved
|
||||
RESUMED = 1
|
||||
RESUME_1_LEN = 32 + 1 + 16 # e, then one AEAD of the proto byte
|
||||
MAX_WRONG = 5
|
||||
IDLE_SECONDS = 10.0
|
||||
TOTAL_SECONDS = 60.0
|
||||
ALLOW_SECONDS = 30.0
|
||||
PRE_AUTH = ("new", "start", "confirm")
|
||||
CEREMONY = ("start", "confirm", "decide", "keys")
|
||||
HELD = ("decide", "keys") # the phone proved the code; the window waits on these
|
||||
|
||||
Action = tuple[str, object] # ("notify", frame bytes) or ("disconnect", device path)
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class _Link:
|
||||
device: str
|
||||
connected: float
|
||||
last: float
|
||||
mtu: int = 23
|
||||
link_id: int = 0
|
||||
reasm: link.Reassembler | None = None
|
||||
phase: str = "new"
|
||||
since: float = 0.0
|
||||
nonce: bytes = b""
|
||||
sid: bytes = b""
|
||||
start_body: bytes = b""
|
||||
window_body: bytes = b""
|
||||
cp: cpace.Cpace | None = None
|
||||
isk: bytes = b""
|
||||
ya: bytes = b""
|
||||
yb: bytes = b""
|
||||
th: bytes = b""
|
||||
check: str = ""
|
||||
records: link.Records | None = None
|
||||
phone: dict | None = None
|
||||
grant: str = ""
|
||||
|
||||
|
||||
class Engine:
|
||||
def __init__(self, params, window, *, wifi: Callable | None = None, wall: Callable[[], float] = time.time): # noqa: TID251 unix time: the app shows added and last_seen
|
||||
self._params = params
|
||||
self._window = window
|
||||
self._wall = wall
|
||||
self._links: dict[str, _Link] = {}
|
||||
self._fail_nonce = b""
|
||||
self._fails = 0
|
||||
self._rpc = Rpc(params, wifi)
|
||||
|
||||
def on_write(self, device: str, value: bytes, mtu: int, now: float) -> list[Action]:
|
||||
lk = self._links.get(device)
|
||||
if lk is None:
|
||||
lk = self._links[device] = _Link(device, connected=now, last=now)
|
||||
lk.mtu = mtu
|
||||
if lk.reasm is None:
|
||||
if len(value) < 3:
|
||||
return self._drop(lk)
|
||||
lid = int.from_bytes(value[1:3], "big")
|
||||
# the id is bound to the first connection that uses it; a newcomer with a used id is dropped
|
||||
if lid == 0 or any(o.link_id == lid for o in self._links.values() if o is not lk):
|
||||
return self._drop(lk)
|
||||
lk.link_id, lk.reasm = lid, link.Reassembler(lid)
|
||||
lk.last = now
|
||||
try:
|
||||
msg = lk.reasm.feed(value)
|
||||
if msg is None:
|
||||
return []
|
||||
return self._message(lk, msg, now)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return self._drop(lk)
|
||||
|
||||
def on_disconnect(self, device: str):
|
||||
if (lk := self._links.get(device)) is not None:
|
||||
self._drop(lk)
|
||||
|
||||
def tick(self, now: float) -> list[Action]:
|
||||
acts: list[Action] = []
|
||||
secret = self._window.secret()
|
||||
for lk in list(self._links.values()):
|
||||
if self._links.get(lk.device) is not lk:
|
||||
continue
|
||||
if lk.phase in CEREMONY and (secret is None or lk.nonce != secret[1]):
|
||||
acts += self._drop(lk)
|
||||
elif lk.phase in PRE_AUTH and (now - lk.last >= IDLE_SECONDS or now - lk.connected >= TOTAL_SECONDS):
|
||||
acts += self._error(lk, ERR_TIMEOUT)
|
||||
elif lk.phase == "decide" and now - lk.since >= ALLOW_SECONDS:
|
||||
self._window.cancel("no_answer")
|
||||
acts += self._record(lk, DECISION, bytes([NO_ANSWER])) + self._drop(lk)
|
||||
elif lk.phase == "keys" and now - lk.since >= ALLOW_SECONDS:
|
||||
self._window.cancel("timeout")
|
||||
acts += self._drop(lk)
|
||||
for device, response in self._rpc.poll(now):
|
||||
lk = self._links.get(device)
|
||||
if lk is not None and lk.phase == "session":
|
||||
acts += self._record(lk, RPC, _json(response))
|
||||
return acts
|
||||
|
||||
def prompt(self, now: float) -> dict | None:
|
||||
lk = next((o for o in self._links.values() if o.phase == "decide"), None)
|
||||
if lk is None:
|
||||
return None
|
||||
return {"step": "allow", "check": f"{lk.check[:3]} {lk.check[3:]}", "until": lk.since + ALLOW_SECONDS}
|
||||
|
||||
def connected(self) -> int:
|
||||
return sum(1 for lk in self._links.values() if lk.phase == "session")
|
||||
|
||||
def answer(self, allow: bool, now: float) -> list[Action]:
|
||||
lk = next((o for o in self._links.values() if o.phase == "decide"), None)
|
||||
if lk is None:
|
||||
return []
|
||||
if not allow:
|
||||
self._window.cancel("denied")
|
||||
return self._record(lk, DECISION, bytes([DENY])) + self._drop(lk)
|
||||
acts = self._record(lk, DECISION, bytes([ALLOW]))
|
||||
try:
|
||||
spki, key = connect_phone.device_identity()
|
||||
except RuntimeError:
|
||||
self._window.cancel("no_key")
|
||||
return acts + self._drop(lk)
|
||||
static = grants.static_private(self._params).public_key().public_bytes_raw()
|
||||
alg, sig = link.sign(key, link.signed_bytes("D", lk.th, spki, static))
|
||||
ids = {"dongle_id": self._params.get("DongleId"), "serial": self._params.get("HardwareSerial")}
|
||||
doc = {"v": 1, "spki": grants.b64(spki), "alg": alg, "static": grants.b64(static), "id": ids, "sig": grants.b64(sig)}
|
||||
lk.phase, lk.since, lk.last = "keys", now, now
|
||||
return acts + self._record(lk, DEVICE_KEYS, _json(doc))
|
||||
|
||||
def remove(self, phone: str | None) -> list[Action]:
|
||||
if not phone or not any(g["spki"] == phone for g in grants.load(self._params)):
|
||||
return []
|
||||
return self._remove_grant(phone)
|
||||
|
||||
def _message(self, lk: _Link, msg: bytes, now: float) -> list[Action]:
|
||||
if lk.records is not None:
|
||||
inner = lk.records.open(msg)
|
||||
if not inner:
|
||||
return self._drop(lk)
|
||||
typ, body = inner[0], inner[1:]
|
||||
if lk.phase == "keys" and typ == PHONE_KEYS:
|
||||
return self._phone_keys(lk, body, now)
|
||||
if lk.phase == "session" and typ == RPC:
|
||||
return self._rpc_request(lk, body, now)
|
||||
return self._drop(lk)
|
||||
typ, body = msg[0], msg[1:]
|
||||
if lk.phase == "new" and typ == CONNECT_START:
|
||||
return self._start(lk, body, now)
|
||||
if lk.phase == "new" and typ == RESUME_1:
|
||||
return self._resume(lk, body, now)
|
||||
if lk.phase == "start" and typ == PAKE_A:
|
||||
return self._pake(lk, body)
|
||||
if lk.phase == "confirm" and typ == CONFIRM_A:
|
||||
return self._confirm(lk, body, now)
|
||||
return self._drop(lk)
|
||||
|
||||
def _start(self, lk: _Link, body: bytes, now: float) -> list[Action]:
|
||||
if body != bytes([PROTO]):
|
||||
return self._error(lk, ERR_VERSION)
|
||||
secret = self._window.secret()
|
||||
if secret is None:
|
||||
return self._error(lk, ERR_NO_WINDOW)
|
||||
if any(o is not lk and o.phase in CEREMONY for o in self._links.values()):
|
||||
return self._error(lk, ERR_BUSY)
|
||||
prs, nonce = secret
|
||||
attempt = secrets.token_bytes(16)
|
||||
lk.nonce, lk.sid = nonce, nonce + attempt
|
||||
lk.start_body = body
|
||||
lk.window_body = bytes([PROTO, link.PAKE_SUITE]) + nonce + attempt
|
||||
lk.cp = cpace.Cpace(False, prs, lk.sid, lk.start_body, lk.window_body)
|
||||
lk.phase, lk.since = "start", now
|
||||
return self._plain(lk, CONNECT_WINDOW, lk.window_body)
|
||||
|
||||
def _pake(self, lk: _Link, body: bytes) -> list[Action]:
|
||||
if len(body) != 32:
|
||||
return self._drop(lk)
|
||||
try:
|
||||
lk.isk = lk.cp.isk(body)
|
||||
except cpace.CpaceError:
|
||||
return self._drop(lk)
|
||||
lk.ya, lk.yb = body, lk.cp.public
|
||||
lk.phase = "confirm"
|
||||
return self._plain(lk, PAKE_B, lk.yb)
|
||||
|
||||
def _confirm(self, lk: _Link, body: bytes, now: float) -> list[Action]:
|
||||
if len(body) != 64:
|
||||
return self._drop(lk)
|
||||
if not lk.cp.check(lk.isk, lk.ya, body):
|
||||
return self._wrong_code(lk)
|
||||
tag = lk.cp.tag(lk.isk)
|
||||
lk.th = link.transcript(lk.start_body, lk.window_body, lk.ya, lk.yb, body, tag)
|
||||
p2c, c2p, lk.check = link.session_keys(lk.isk, lk.sid)
|
||||
lk.records = link.Records(c2p, p2c, lk.link_id)
|
||||
lk.reasm.cap = link.SESSION_CAP
|
||||
lk.phase, lk.since, lk.last = "decide", now, now
|
||||
self._window.hold()
|
||||
return self._plain(lk, CONFIRM_B, tag)
|
||||
|
||||
def _wrong_code(self, lk: _Link) -> list[Action]:
|
||||
if lk.nonce != self._fail_nonce:
|
||||
self._fail_nonce, self._fails = lk.nonce, 0
|
||||
self._fails += 1
|
||||
if self._fails >= MAX_WRONG:
|
||||
self._window.cancel("wrong_codes")
|
||||
return self._error(lk, ERR_WINDOW_CLOSED)
|
||||
return self._error(lk, ERR_WRONG_CODE)
|
||||
|
||||
def _phone_keys(self, lk: _Link, body: bytes, now: float) -> list[Action]:
|
||||
doc = json.loads(body)
|
||||
if doc.get("v") != 1 or doc.get("alg") != "ES256":
|
||||
return self._drop(lk)
|
||||
spki, static, sig = grants.unb64(doc["spki"]), grants.unb64(doc["static"]), grants.unb64(doc["sig"])
|
||||
name = doc["id"]["name"]
|
||||
if len(static) != 32 or not isinstance(name, str) or len(name.encode()) > 80:
|
||||
return self._drop(lk)
|
||||
if not link.verify("ES256", spki, link.signed_bytes("P", lk.th, spki, static), sig):
|
||||
return self._drop(lk)
|
||||
lk.phone = {"spki": grants.b64(spki), "static": grants.b64(static), "name": " ".join(name.split()) or "phone"}
|
||||
lk.last = now
|
||||
saved = grants.load(self._params)
|
||||
known = any(g["spki"] == lk.phone["spki"] for g in saved)
|
||||
if not known and len(saved) >= grants.MAX_PHONES:
|
||||
self._window.cancel("limit")
|
||||
return self._record(lk, GRANT_RESULT, bytes([GRANT_REFUSED])) + self._drop(lk)
|
||||
return self._grant(lk)
|
||||
|
||||
def _grant(self, lk: _Link) -> list[Action]:
|
||||
wall = int(self._wall())
|
||||
saved = grants.load(self._params)
|
||||
old = next((g for g in saved if g["spki"] == lk.phone["spki"]), None)
|
||||
kept = [g for g in saved if g is not old]
|
||||
kept.append(lk.phone | {"added": old["added"] if old else wall, "last_seen": wall})
|
||||
grants.save(self._params, kept)
|
||||
self._window.cancel("granted")
|
||||
lk.grant, lk.phone, lk.phase = lk.phone["spki"], None, "session"
|
||||
return self._drop_grant(lk.grant, keep=lk) + self._record(lk, GRANT_RESULT, bytes([GRANT_ADDED]))
|
||||
|
||||
def _resume(self, lk: _Link, body: bytes, now: float) -> list[Action]:
|
||||
if len(body) != RESUME_1_LEN:
|
||||
return self._drop(lk)
|
||||
static = grants.static_private(self._params)
|
||||
for g in grants.load(self._params):
|
||||
hs = noise.KKHandshake(False, static, grants.unb64(g["static"]))
|
||||
try:
|
||||
payload = hs.read(body)
|
||||
except noise.NoiseError:
|
||||
continue
|
||||
if payload != bytes([PROTO]):
|
||||
return self._error(lk, ERR_VERSION)
|
||||
reply = hs.write(bytes([RESUMED]))
|
||||
send, recv = hs.split()
|
||||
lk.records = link.Records(send, recv, lk.link_id)
|
||||
lk.reasm.cap = link.SESSION_CAP
|
||||
lk.grant, lk.phase, lk.last = g["spki"], "session", now
|
||||
self._touch(g["spki"])
|
||||
return self._drop_grant(lk.grant, keep=lk) + self._plain(lk, RESUME_2, reply)
|
||||
return self._error(lk, ERR_UNKNOWN_PHONE)
|
||||
|
||||
def _touch(self, spki: str):
|
||||
saved = grants.load(self._params)
|
||||
for g in saved:
|
||||
if g["spki"] == spki:
|
||||
g["last_seen"] = int(self._wall())
|
||||
grants.save(self._params, saved)
|
||||
|
||||
def _rpc_request(self, lk: _Link, body: bytes, now: float) -> list[Action]:
|
||||
response, after = self._rpc.handle(lk.device, body, grants.load(self._params), lk.grant, now)
|
||||
acts = self._record(lk, RPC, _json(response)) if response is not None else []
|
||||
if after == "forget":
|
||||
acts += self._remove_grant(lk.grant)
|
||||
return acts
|
||||
|
||||
def _remove_grant(self, spki: str) -> list[Action]:
|
||||
grants.save(self._params, [g for g in grants.load(self._params) if g["spki"] != spki])
|
||||
return self._drop_grant(spki)
|
||||
|
||||
def _drop_grant(self, spki: str, keep: _Link | None = None) -> list[Action]:
|
||||
acts: list[Action] = []
|
||||
for lk in list(self._links.values()):
|
||||
if lk.grant == spki and lk is not keep:
|
||||
acts += self._drop(lk)
|
||||
return acts
|
||||
|
||||
def _send(self, lk: _Link, message: bytes) -> list[Action]:
|
||||
return [("notify", frame) for frame in link.frames(message, lk.link_id, lk.mtu - link.FRAME_HEADER)]
|
||||
|
||||
def _plain(self, lk: _Link, typ: int, body: bytes) -> list[Action]:
|
||||
return self._send(lk, bytes([typ]) + body)
|
||||
|
||||
def _record(self, lk: _Link, typ: int, body: bytes) -> list[Action]:
|
||||
return self._send(lk, lk.records.seal(bytes([typ]) + body))
|
||||
|
||||
def _error(self, lk: _Link, code: int) -> list[Action]:
|
||||
return self._plain(lk, ERROR, bytes([code])) + self._drop(lk)
|
||||
|
||||
def _drop(self, lk: _Link) -> list[Action]:
|
||||
if self._links.get(lk.device) is lk:
|
||||
del self._links[lk.device]
|
||||
if lk.phase in HELD:
|
||||
# the window was held for this phone; it does not reopen for another
|
||||
self._window.cancel("phone_left")
|
||||
return [("disconnect", lk.device)]
|
||||
|
||||
|
||||
def _json(obj) -> bytes:
|
||||
return json.dumps(obj, separators=(",", ":")).encode()
|
||||
@@ -0,0 +1,406 @@
|
||||
"""
|
||||
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 signal
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
from jeepney import DBusAddress, HeaderFields, Message, MessageFlag, MessageType, new_error, new_method_call, new_method_return, new_signal
|
||||
from jeepney.io.threading import open_dbus_connection
|
||||
from jeepney.wrappers import Properties
|
||||
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.common.swaglog import cloudlog
|
||||
from openpilot.sunnypilot.system.ble.session import Engine
|
||||
from openpilot.sunnypilot.system.connect_phone import REQUEST_KEY, STATUS_KEY, WINDOW_KEY, ConnectPhoneWindow, grant_count
|
||||
|
||||
BLUEZ = "org.bluez"
|
||||
ADAPTER_IFACE = "org.bluez.Adapter1"
|
||||
DEVICE_IFACE = "org.bluez.Device1"
|
||||
GATT_MANAGER_IFACE = "org.bluez.GattManager1"
|
||||
ADVERTISING_MANAGER_IFACE = "org.bluez.LEAdvertisingManager1"
|
||||
GATT_SERVICE_IFACE = "org.bluez.GattService1"
|
||||
GATT_CHARACTERISTIC_IFACE = "org.bluez.GattCharacteristic1"
|
||||
ADVERTISEMENT_IFACE = "org.bluez.LEAdvertisement1"
|
||||
OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager"
|
||||
PROPERTIES_IFACE = "org.freedesktop.DBus.Properties"
|
||||
|
||||
SERVICE_UUID = "6530b12c-c8cc-4b5c-a767-5b842c630dfa"
|
||||
RX_UUID = "a8b19254-6b8c-4074-8846-40b50f7f9583"
|
||||
TX_UUID = "936a1543-21ef-40a0-9318-201db2f992f7"
|
||||
|
||||
APP_PATH = "/sunnypilot/gatt"
|
||||
SERVICE_PATH = APP_PATH + "/service"
|
||||
RX_PATH = SERVICE_PATH + "/rx"
|
||||
TX_PATH = SERVICE_PATH + "/tx"
|
||||
ADVERTISEMENT_PATH = "/sunnypilot/advertisement"
|
||||
|
||||
# no characteristic may carry an encrypt, secure or authorize flag: those start OS pairing
|
||||
GATT_OBJECTS = {
|
||||
SERVICE_PATH: {GATT_SERVICE_IFACE: {"UUID": ("s", SERVICE_UUID), "Primary": ("b", True)}},
|
||||
RX_PATH: {GATT_CHARACTERISTIC_IFACE: {"UUID": ("s", RX_UUID), "Service": ("o", SERVICE_PATH), "Flags": ("as", ["write", "write-without-response"])}},
|
||||
TX_PATH: {GATT_CHARACTERISTIC_IFACE: {"UUID": ("s", TX_UUID), "Service": ("o", SERVICE_PATH), "Flags": ("as", ["notify"])}},
|
||||
}
|
||||
# no LocalName and no Includes: the advertisement carries neither a name nor TX power
|
||||
OBJECTS = GATT_OBJECTS | {ADVERTISEMENT_PATH: {ADVERTISEMENT_IFACE: {"Type": ("s", "peripheral"), "ServiceUUIDs": ("as", [SERVICE_UUID])}}}
|
||||
|
||||
# GAP Device Name, readable by any phone before it authenticates; the default is the hostname, which carries the serial.
|
||||
# At most 10 bytes: the kernel shortens a longer name in the default scan response.
|
||||
ALIAS = "comma"
|
||||
|
||||
RECONCILE_PERIOD = 1.0 # seconds
|
||||
CALL_TIMEOUT = 5.0 # seconds
|
||||
STOP_CALL_TIMEOUT = 0.5 # seconds, once stop() is called: the manager kills the process 5 s after SIGINT
|
||||
ENABLE_RETRY_AFTER = 10.0 # seconds enabled without a ready adapter
|
||||
RESTART_BACKOFF = 1.0 # seconds before a new manager replaces a failed one, doubling up to the maximum
|
||||
RESTART_BACKOFF_MAX = 60.0 # seconds
|
||||
|
||||
|
||||
def _prop(ifaces: dict, iface: str, name: str, default=None):
|
||||
return ifaces.get(iface, {}).get(name, (None, default))[1]
|
||||
|
||||
|
||||
class BluetoothManager:
|
||||
def __init__(self, on_write: Callable[[str, bytes, int], None], on_disconnect: Callable[[str], None] | None = None,
|
||||
on_tick: Callable[[], None] | None = None):
|
||||
# all three run on the run() thread
|
||||
self._on_write = on_write # device path, value, mtu
|
||||
self._on_disconnect = on_disconnect # device path
|
||||
self._on_tick = on_tick
|
||||
self._params = Params()
|
||||
self._conn = None
|
||||
self._enabled = False
|
||||
self._exit = False
|
||||
self._adapter: str | None = None # the adapter this manager has changed; ready implies it is set
|
||||
self._ready = False
|
||||
self._connected: frozenset[str] = frozenset()
|
||||
self._failed_step: str | None = None
|
||||
self._last_reconcile = 0.0
|
||||
self._last_tick = 0.0
|
||||
|
||||
@property
|
||||
def ready(self) -> bool:
|
||||
return self._ready
|
||||
|
||||
@property
|
||||
def connected(self) -> frozenset[str]:
|
||||
return self._connected
|
||||
|
||||
def set_enabled(self, enabled: bool):
|
||||
# off is written by run() after its teardown: AGNOS removes the adapter as soon as the param clears
|
||||
if enabled and not self._params.get_bool("BluetoothEnabled"):
|
||||
self._params.put_bool("BluetoothEnabled", True)
|
||||
self._enabled = enabled
|
||||
|
||||
def notify(self, data: bytes) -> bool:
|
||||
# BlueZ sends a notification to every subscribed device, never to one
|
||||
return self._send(new_signal(DBusAddress(TX_PATH, interface=PROPERTIES_IFACE), "PropertiesChanged", "sa{sv}as",
|
||||
(GATT_CHARACTERISTIC_IFACE, {"Value": ("ay", data)}, [])))
|
||||
|
||||
def disconnect(self, device: str):
|
||||
self._send(new_method_call(DBusAddress(device, BLUEZ, DEVICE_IFACE), "Disconnect"))
|
||||
|
||||
def stop(self):
|
||||
self._exit = True
|
||||
|
||||
def run(self):
|
||||
self._conn = open_dbus_connection(bus="SYSTEM")
|
||||
try:
|
||||
while not self._exit:
|
||||
if time.monotonic() - self._last_reconcile >= RECONCILE_PERIOD:
|
||||
self._last_reconcile = time.monotonic()
|
||||
self._reconcile()
|
||||
self._tick()
|
||||
try:
|
||||
self._dispatch(self._conn.receive(timeout=RECONCILE_PERIOD))
|
||||
except TimeoutError:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
self._teardown()
|
||||
except Exception:
|
||||
cloudlog.exception("bluetooth: teardown failed")
|
||||
conn, self._conn = self._conn, None
|
||||
conn.close()
|
||||
self._set_connected(frozenset())
|
||||
|
||||
def _send(self, msg: Message) -> bool:
|
||||
conn = self._conn
|
||||
if conn is None:
|
||||
return False
|
||||
try:
|
||||
conn.send(msg)
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def _callback(self, callback: Callable | None, *args):
|
||||
if callback is None:
|
||||
return
|
||||
try:
|
||||
callback(*args)
|
||||
except Exception:
|
||||
cloudlog.exception("bluetooth: callback failed")
|
||||
|
||||
def _tick(self):
|
||||
if not self._exit and time.monotonic() - self._last_tick >= RECONCILE_PERIOD:
|
||||
self._last_tick = time.monotonic()
|
||||
self._callback(self._on_tick)
|
||||
|
||||
def _set_connected(self, connected: frozenset[str]):
|
||||
gone, self._connected = self._connected - connected, connected
|
||||
for device in gone:
|
||||
self._callback(self._on_disconnect, device)
|
||||
|
||||
def _call(self, msg: Message) -> tuple | None:
|
||||
# RegisterApplication is answered only after BlueZ has read our objects, so keep serving while waiting
|
||||
serial = next(self._conn.outgoing_serial)
|
||||
self._conn.send(msg, serial=serial)
|
||||
stopping = self._exit
|
||||
deadline = time.monotonic() + (STOP_CALL_TIMEOUT if stopping else CALL_TIMEOUT)
|
||||
# a stop() abandons a call that is still waiting, and the tick keeps running while bluetoothd does not answer
|
||||
while (remaining := deadline - time.monotonic()) > 0 and self._exit == stopping:
|
||||
try:
|
||||
reply = self._conn.receive(timeout=min(remaining, RECONCILE_PERIOD))
|
||||
except TimeoutError:
|
||||
self._tick()
|
||||
continue
|
||||
if reply.header.fields.get(HeaderFields.reply_serial) == serial:
|
||||
return reply.body if reply.header.message_type == MessageType.method_return else None
|
||||
self._dispatch(reply)
|
||||
return None
|
||||
|
||||
def _reconcile(self):
|
||||
if not self._enabled:
|
||||
self._teardown()
|
||||
self._set_connected(frozenset())
|
||||
if self._params.get_bool("BluetoothEnabled"):
|
||||
self._params.put_bool("BluetoothEnabled", False)
|
||||
return
|
||||
|
||||
reply = self._call(new_method_call(DBusAddress("/", BLUEZ, OBJECT_MANAGER_IFACE), "GetManagedObjects"))
|
||||
if reply is None:
|
||||
# no answer says nothing about the adapter: forgetting it here would make the teardown skip the power-off
|
||||
return
|
||||
objects = reply[0]
|
||||
self._set_connected(frozenset(path for path, ifaces in objects.items() if _prop(ifaces, DEVICE_IFACE, "Connected")))
|
||||
adapter = next((path for path, ifaces in objects.items() if GATT_MANAGER_IFACE in ifaces and ADVERTISING_MANAGER_IFACE in ifaces), None)
|
||||
|
||||
if self._ready and adapter == self._adapter:
|
||||
ifaces = objects[adapter]
|
||||
# a restarted bluetoothd keeps the adapter powered but has no advertisement
|
||||
if (_prop(ifaces, ADAPTER_IFACE, "Powered") and not _prop(ifaces, ADAPTER_IFACE, "Pairable", True) and
|
||||
_prop(ifaces, ADVERTISING_MANAGER_IFACE, "ActiveInstances", 0) >= 1):
|
||||
return
|
||||
cloudlog.warning(f"bluetooth: lost {adapter}, setting up again")
|
||||
|
||||
self._ready = False
|
||||
self._adapter = adapter
|
||||
if adapter is not None:
|
||||
self._setup(adapter, objects)
|
||||
|
||||
def _setup(self, adapter: str, objects: dict):
|
||||
self._unregister(adapter)
|
||||
adapter_address = DBusAddress(adapter, BLUEZ, ADAPTER_IFACE)
|
||||
props = Properties(adapter_address)
|
||||
paired = [path for path, ifaces in objects.items() if _prop(ifaces, DEVICE_IFACE, "Paired")]
|
||||
steps = (
|
||||
# never advertise while bondable: phones authenticate in the app layer
|
||||
("Pairable", props.set("Pairable", "b", False)),
|
||||
("Alias", props.set("Alias", "s", ALIAS)),
|
||||
("Powered", props.set("Powered", "b", True)),
|
||||
# BlueZ refuses RemoveDevice on an unpowered adapter
|
||||
*(("RemoveDevice", new_method_call(adapter_address, "RemoveDevice", "o", (path,))) for path in paired),
|
||||
# on the adapter, not the advertisement: this kernel always writes its own Flags field and would send a second one
|
||||
("DiscoverableTimeout", props.set("DiscoverableTimeout", "u", 0)),
|
||||
("Discoverable", props.set("Discoverable", "b", True)),
|
||||
("RegisterApplication", new_method_call(DBusAddress(adapter, BLUEZ, GATT_MANAGER_IFACE), "RegisterApplication", "oa{sv}", (APP_PATH, {}))),
|
||||
("RegisterAdvertisement", new_method_call(DBusAddress(adapter, BLUEZ, ADVERTISING_MANAGER_IFACE), "RegisterAdvertisement", "oa{sv}",
|
||||
(ADVERTISEMENT_PATH, {}))),
|
||||
)
|
||||
for step, msg in steps:
|
||||
failed = not self._exit and self._call(msg) is None
|
||||
if self._exit:
|
||||
return
|
||||
if failed:
|
||||
if step != self._failed_step:
|
||||
cloudlog.warning(f"bluetooth: {step} failed on {adapter}")
|
||||
self._failed_step = step
|
||||
self._unregister(adapter)
|
||||
return
|
||||
|
||||
self._failed_step = None
|
||||
self._ready = True
|
||||
cloudlog.info(f"bluetooth: advertising on {adapter}")
|
||||
|
||||
def _unregister(self, adapter: str):
|
||||
self._ready = False
|
||||
self._call(new_method_call(DBusAddress(adapter, BLUEZ, ADVERTISING_MANAGER_IFACE), "UnregisterAdvertisement", "o", (ADVERTISEMENT_PATH,)))
|
||||
self._call(new_method_call(DBusAddress(adapter, BLUEZ, GATT_MANAGER_IFACE), "UnregisterApplication", "o", (APP_PATH,)))
|
||||
|
||||
def _teardown(self):
|
||||
adapter, self._adapter = self._adapter, None
|
||||
if adapter is None:
|
||||
return
|
||||
self._unregister(adapter)
|
||||
props = Properties(DBusAddress(adapter, BLUEZ, ADAPTER_IFACE))
|
||||
# BlueZ stores Discoverable and applies it again to every new adapter
|
||||
self._call(props.set("Discoverable", "b", False))
|
||||
self._call(props.set("Powered", "b", False))
|
||||
|
||||
def _dispatch(self, msg: Message):
|
||||
if msg.header.message_type != MessageType.method_call:
|
||||
return
|
||||
|
||||
fields = msg.header.fields
|
||||
target = (fields.get(HeaderFields.path), fields.get(HeaderFields.interface), fields.get(HeaderFields.member))
|
||||
|
||||
if target == (APP_PATH, OBJECT_MANAGER_IFACE, "GetManagedObjects"):
|
||||
reply = new_method_return(msg, "a{oa{sa{sv}}}", (GATT_OBJECTS,))
|
||||
elif target[1:] == (PROPERTIES_IFACE, "GetAll") and msg.body and msg.body[0] in OBJECTS.get(target[0], {}):
|
||||
reply = new_method_return(msg, "a{sv}", (OBJECTS[target[0]][msg.body[0]],))
|
||||
elif target == (RX_PATH, GATT_CHARACTERISTIC_IFACE, "WriteValue"):
|
||||
value, options = msg.body
|
||||
device, mtu = options["device"][1], options["mtu"][1]
|
||||
self._connected |= {device}
|
||||
# BlueZ has already acked the write and discards this reply, so the only refusal is a disconnect.
|
||||
# A long write arrives joined at offset 0, so the length is checked as well.
|
||||
if options.get("offset", ("q", 0))[1] != 0 or len(value) > mtu - 3:
|
||||
self.disconnect(device)
|
||||
else:
|
||||
self._callback(self._on_write, device, bytes(value), mtu)
|
||||
reply = new_method_return(msg)
|
||||
elif target in ((TX_PATH, GATT_CHARACTERISTIC_IFACE, "StartNotify"), (TX_PATH, GATT_CHARACTERISTIC_IFACE, "StopNotify")):
|
||||
reply = new_method_return(msg)
|
||||
elif target == (ADVERTISEMENT_PATH, ADVERTISEMENT_IFACE, "Release"):
|
||||
self._ready = False
|
||||
reply = new_method_return(msg)
|
||||
else:
|
||||
reply = new_error(msg, "org.freedesktop.DBus.Error.UnknownMethod")
|
||||
|
||||
if not msg.header.flags & MessageFlag.no_reply_expected:
|
||||
self._conn.send(reply)
|
||||
|
||||
|
||||
class Daemon:
|
||||
def __init__(self, params, window: ConnectPhoneWindow):
|
||||
self._params = params
|
||||
self._window = window
|
||||
self._engine = Engine(params, window)
|
||||
self.bt = self.new_manager()
|
||||
self._refused: dict | None = None # shown in place of the window state until the next request
|
||||
self._written: dict | None = None
|
||||
self._status: dict | None = None
|
||||
self._retry_at: float | None = None
|
||||
|
||||
def new_manager(self) -> BluetoothManager:
|
||||
self.bt = BluetoothManager(self.on_write, self._engine.on_disconnect, self.tick)
|
||||
return self.bt
|
||||
|
||||
def on_write(self, device: str, value: bytes, mtu: int):
|
||||
self._act(self._engine.on_write(device, value, mtu, time.monotonic()))
|
||||
|
||||
def _act(self, actions: list):
|
||||
for kind, data in actions:
|
||||
if kind == "notify":
|
||||
self.bt.notify(data)
|
||||
else:
|
||||
self.bt.disconnect(data)
|
||||
|
||||
def tick(self):
|
||||
try:
|
||||
self.step(time.monotonic())
|
||||
except Exception:
|
||||
cloudlog.exception("bluetooth: tick failed")
|
||||
|
||||
def step(self, now: float):
|
||||
params, bt, window = self._params, self.bt, self._window
|
||||
allowed = params.get_bool("BluetoothAllowed")
|
||||
|
||||
request = params.get(REQUEST_KEY)
|
||||
if request is not None:
|
||||
params.remove(REQUEST_KEY)
|
||||
if isinstance(request, dict):
|
||||
self._refused = None
|
||||
seq, action = request.get("seq", 0), request.get("action")
|
||||
if action == "cancel":
|
||||
window.cancel()
|
||||
elif action == "open" and not allowed:
|
||||
self._refused = {"seq": seq, "state": "closed", "reason": "bluetooth_off"}
|
||||
elif action == "open":
|
||||
try:
|
||||
window.open(now, seq)
|
||||
except Exception as e:
|
||||
cloudlog.exception("bluetooth: connect phone window not opened")
|
||||
self._refused = {"seq": seq, "state": "closed", "reason": "no_key" if isinstance(e, RuntimeError) else "error"}
|
||||
elif action in ("allow", "deny") and allowed:
|
||||
self._act(self._engine.answer(action == "allow", now))
|
||||
elif action == "remove" and allowed:
|
||||
self._act(self._engine.remove(request.get("phone")))
|
||||
|
||||
if not allowed:
|
||||
window.cancel("bluetooth_off")
|
||||
window.tick(now, bt.ready)
|
||||
self._act(self._engine.tick(now))
|
||||
|
||||
phones = grant_count()
|
||||
enabled = allowed and (window.active or phones >= 1)
|
||||
bt.set_enabled(enabled)
|
||||
if not enabled or bt.ready:
|
||||
self._retry_at = None
|
||||
elif self._retry_at is None:
|
||||
self._retry_at = now + ENABLE_RETRY_AFTER
|
||||
elif now >= self._retry_at:
|
||||
self._retry_at = float("inf")
|
||||
cloudlog.warning("bluetooth: no adapter, writing BluetoothEnabled again")
|
||||
params.put_bool("BluetoothEnabled", True)
|
||||
|
||||
state = self._refused or (window.state() | {"prompt": self._engine.prompt(now)})
|
||||
if state != self._written:
|
||||
params.put(WINDOW_KEY, state)
|
||||
self._written = state
|
||||
|
||||
status = {"enabled": enabled, "connected": self._engine.connected(), "phones": phones}
|
||||
if status != self._status:
|
||||
params.put(STATUS_KEY, status)
|
||||
self._status = status
|
||||
|
||||
|
||||
def main():
|
||||
# selfdrived blocks engagement while an always-run process is dead, and the manager never starts it again:
|
||||
# only a signal ends this loop
|
||||
exiting = threading.Event()
|
||||
daemon = Daemon(Params(), ConnectPhoneWindow())
|
||||
|
||||
def on_signal(*_):
|
||||
exiting.set()
|
||||
daemon.bt.stop()
|
||||
|
||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||
signal.signal(sig, on_signal)
|
||||
|
||||
backoff = RESTART_BACKOFF
|
||||
while True:
|
||||
started = time.monotonic()
|
||||
try:
|
||||
daemon.bt.run()
|
||||
except Exception:
|
||||
cloudlog.exception("bluetooth: manager failed")
|
||||
if time.monotonic() - started >= RESTART_BACKOFF_MAX:
|
||||
backoff = RESTART_BACKOFF
|
||||
retry_at = time.monotonic() + backoff
|
||||
backoff = min(backoff * 2, RESTART_BACKOFF_MAX)
|
||||
while not exiting.is_set() and time.monotonic() < retry_at:
|
||||
exiting.wait(RECONCILE_PERIOD)
|
||||
daemon.tick()
|
||||
if exiting.is_set():
|
||||
return
|
||||
daemon.new_manager()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,173 @@
|
||||
"""
|
||||
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 base64
|
||||
import hashlib
|
||||
import secrets
|
||||
import time
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec, rsa
|
||||
|
||||
from openpilot.common.api.base import BaseApi
|
||||
from openpilot.common.params import Params
|
||||
from openpilot.sunnypilot.system.ble import grants
|
||||
from openpilot.sunnypilot.system.ble.link import PAKE_SUITE
|
||||
from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID
|
||||
|
||||
WINDOW_SECONDS = 120
|
||||
|
||||
REQUEST_KEY = "SunnylinkLocalConnectPhoneRequest"
|
||||
REQUEST_ACTIONS = ("open", "cancel", "allow", "deny", "remove")
|
||||
WINDOW_KEY = "SunnylinkLocalConnectPhoneWindow"
|
||||
STATUS_KEY = "SunnylinkLocalBluetoothStatus"
|
||||
|
||||
# Matter's IsValidSetupPIN list; 00000000 and 99999999 are outside the drawn range
|
||||
REFUSED_CODES = frozenset({11111111 * digit for digit in range(1, 9)} | {12345678, 87654321})
|
||||
|
||||
def _private_key_pem() -> bytes:
|
||||
_, private, _ = BaseApi.get_key_pair()
|
||||
if private is None:
|
||||
raise RuntimeError("device key unavailable")
|
||||
return private.encode() if isinstance(private, str) else private
|
||||
|
||||
|
||||
def generate_code() -> int:
|
||||
while (code := secrets.randbelow(99_999_998) + 1) in REFUSED_CODES:
|
||||
pass
|
||||
return code
|
||||
|
||||
|
||||
def format_code(code: int) -> str:
|
||||
digits = f"{code:08d}"
|
||||
return f"{digits[:4]} {digits[4:]}"
|
||||
|
||||
|
||||
def device_identity() -> tuple[bytes, rsa.RSAPrivateKey | ec.EllipticCurvePrivateKey]:
|
||||
key = serialization.load_pem_private_key(_private_key_pem(), password=None)
|
||||
return key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo), key
|
||||
|
||||
|
||||
def device_key_hash() -> bytes:
|
||||
return hashlib.sha256(device_identity()[0]).digest()
|
||||
|
||||
|
||||
def qr_text(code: int, nonce: bytes) -> str:
|
||||
payload = code.to_bytes(4, "big") + device_key_hash() + nonce
|
||||
return f"SLC{PAKE_SUITE}:" + base64.urlsafe_b64encode(payload).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def grant_count() -> int:
|
||||
return len(grants.load(Params()))
|
||||
|
||||
|
||||
def display_name(params) -> str:
|
||||
# the sunnylink app builds the same name from DEVICE_KEYS: change both together
|
||||
dongle_id = params.get("DongleId")
|
||||
ident = dongle_id if dongle_id and dongle_id != UNREGISTERED_DONGLE_ID else params.get("HardwareSerial")
|
||||
return f"comma {ident[:4]}" if ident else "comma"
|
||||
|
||||
|
||||
def write_request(params, action: str, phone: str | None = None) -> int:
|
||||
if action not in REQUEST_ACTIONS:
|
||||
raise ValueError(action)
|
||||
seq = time.monotonic_ns()
|
||||
request = {"seq": seq, "action": action}
|
||||
if phone is not None:
|
||||
request["phone"] = phone
|
||||
params.put(REQUEST_KEY, request)
|
||||
return seq
|
||||
|
||||
|
||||
def read_window(params) -> dict | None:
|
||||
window = params.get(WINDOW_KEY)
|
||||
return window if isinstance(window, dict) else None
|
||||
|
||||
|
||||
def read_status(params) -> dict:
|
||||
status = params.get(STATUS_KEY)
|
||||
return status if isinstance(status, dict) else {}
|
||||
|
||||
|
||||
def phone_indicator(status: dict) -> str:
|
||||
# "hidden" radio off; "connected" at least one authenticated session; otherwise "waiting"
|
||||
if not status.get("enabled"):
|
||||
return "hidden"
|
||||
return "connected" if status.get("connected", 0) >= 1 else "waiting"
|
||||
|
||||
|
||||
class ConnectPhoneWindow:
|
||||
def __init__(self):
|
||||
self._open = False
|
||||
self._ready = False
|
||||
self._seq = 0
|
||||
self._reason = ""
|
||||
self._code = 0
|
||||
self._nonce = b""
|
||||
self._qr = ""
|
||||
self._deadline = 0.0
|
||||
self._shown = False
|
||||
self._held = False
|
||||
|
||||
@property
|
||||
def active(self) -> bool:
|
||||
return self._open
|
||||
|
||||
def open(self, now: float, seq: int = 0) -> str:
|
||||
if self._open and seq == self._seq:
|
||||
return "busy"
|
||||
# a new request never inherits the old window's code or what is left of its time
|
||||
self._close("replaced")
|
||||
self._seq = seq
|
||||
code = generate_code()
|
||||
nonce = secrets.token_bytes(8)
|
||||
self._qr = qr_text(code, nonce)
|
||||
self._code = code
|
||||
self._nonce = nonce
|
||||
self._deadline = now + WINDOW_SECONDS
|
||||
self._ready = False
|
||||
self._shown = False
|
||||
self._held = False
|
||||
self._reason = ""
|
||||
self._open = True
|
||||
return "ok"
|
||||
|
||||
def cancel(self, reason: str = "cancel"):
|
||||
self._close(reason)
|
||||
|
||||
def hold(self):
|
||||
# a phone proved the code: the Allow prompt has its own timer from here
|
||||
self._held = True
|
||||
|
||||
def tick(self, now: float, ready: bool = True):
|
||||
if now >= self._deadline and not self._held:
|
||||
self._close("timeout")
|
||||
return
|
||||
if ready and not self._shown:
|
||||
# the full time counts from when the code can first be used, not from the radio starting
|
||||
self._shown = True
|
||||
self._deadline = now + WINDOW_SECONDS
|
||||
self._ready = ready
|
||||
|
||||
def secret(self) -> tuple[bytes, bytes] | None:
|
||||
# the 8 ASCII digits (the CPace PRS) and the window nonce; None once the window is closed
|
||||
if not self._open:
|
||||
return None
|
||||
return f"{self._code:08d}".encode(), self._nonce
|
||||
|
||||
def state(self) -> dict:
|
||||
if not self._open:
|
||||
return {"seq": self._seq, "state": "closed", "reason": self._reason}
|
||||
return {"seq": self._seq, "state": "open" if self._ready else "starting", "code": f"{self._code:08d}", "qr": self._qr,
|
||||
"deadline": self._deadline, "held": self._held, "reason": ""}
|
||||
|
||||
def _close(self, reason: str):
|
||||
if self._open:
|
||||
self._open = False
|
||||
self._code = 0
|
||||
self._nonce = b""
|
||||
self._qr = ""
|
||||
self._reason = reason
|
||||
@@ -0,0 +1,94 @@
|
||||
"""
|
||||
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 unittest
|
||||
from unittest import mock
|
||||
|
||||
from openpilot.sunnypilot.system.ble import cpace
|
||||
|
||||
# draft-irtf-cfrg-cpace-21 appendix B.1 (identical in -20)
|
||||
DRAFT_CI = bytes.fromhex("0b415f696e69746961746f720b425f726573706f6e646572")
|
||||
DRAFT_SID = bytes.fromhex("7e4b4791d6a8ef019b936c79fb7f2c57")
|
||||
DRAFT_G = "d04bf6d41f6a289632a2e929fa29bebd51092512a7829fdde7d314b62f05a73f"
|
||||
DRAFT_YA_SCALAR = bytes.fromhex("21b4f4bd9e64ed355c3eb676a28ebedaf6d8f17bdc365995b319097153044080")
|
||||
DRAFT_YA = "1d13c89278cdadd826f6d8d7f887701430f8380ddc17611cdd6dc989ce0c9f32"
|
||||
DRAFT_YB_SCALAR = bytes.fromhex("848b0779ff415f0af4ea14df9dd1d3c29ac41d836c7808896c4eba19c51ac40a")
|
||||
DRAFT_YB = "248cccf6d5cdc3646f0ad593f9e6cef4e69d4945f8372e623512ecea32185623"
|
||||
DRAFT_K = "5b067effbdc0b2a0e1d907b21ebb25cfedb96a852179a847c37e43ee71322c6b"
|
||||
DRAFT_ISK = "6e19b875f7a561d6b3ca3dbb9ef42ac55de3e717881018204b8922b4d5e53bb2aa82c300bea7b65d2b671da71922ddf6472301b79bc270adfa8bf413285f2263"
|
||||
|
||||
SID = bytes(range(24))
|
||||
|
||||
|
||||
class TestCpace(unittest.TestCase):
|
||||
def setUp(self):
|
||||
patch = mock.patch.object(cpace, "CI", DRAFT_CI)
|
||||
patch.start()
|
||||
self.addCleanup(patch.stop)
|
||||
|
||||
def test_lv_encoding(self):
|
||||
self.assertEqual(cpace.lv(b"1234") + cpace.lv(b"5") + cpace.lv(b"") + cpace.lv(b"678"),
|
||||
bytes.fromhex("043132333401350003363738"))
|
||||
self.assertEqual(cpace.lv(bytes(128))[:2], b"\x80\x01")
|
||||
|
||||
def test_map_matches_draft_a5_reference(self):
|
||||
# draft appendix A.5 (Z = 2, A = 486662), an independent formulation of the same map
|
||||
p, a, z = cpace.P, cpace.J, 2
|
||||
for r in (2, 3, 0x123456789ABCDEF, p - 2):
|
||||
v = -a * pow(1 + z * r * r, -1, p) % p
|
||||
eps = pow((v**3 + a * v * v + v) % p, (p - 1) // 2, p)
|
||||
x = (eps * v - (1 - eps) * a * pow(2, -1, p)) % p
|
||||
self.assertEqual(cpace.map_to_curve_elligator2_curve25519(r), x)
|
||||
|
||||
def test_generator_draft_vector(self):
|
||||
self.assertEqual(cpace.generator(b"Password", DRAFT_CI, DRAFT_SID).hex(), DRAFT_G)
|
||||
|
||||
def test_shares_and_isk_draft_vector(self):
|
||||
a = cpace.Cpace(True, b"Password", DRAFT_SID, b"ADa", b"ADb", scalar=DRAFT_YA_SCALAR)
|
||||
b = cpace.Cpace(False, b"Password", DRAFT_SID, b"ADa", b"ADb", scalar=DRAFT_YB_SCALAR)
|
||||
self.assertEqual(a.public.hex(), DRAFT_YA)
|
||||
self.assertEqual(b.public.hex(), DRAFT_YB)
|
||||
self.assertEqual(cpace._scalar_mult(DRAFT_YA_SCALAR, b.public).hex(), DRAFT_K)
|
||||
self.assertEqual(cpace._scalar_mult(DRAFT_YB_SCALAR, a.public).hex(), DRAFT_K)
|
||||
isk = a.isk(b.public)
|
||||
self.assertEqual(isk.hex(), DRAFT_ISK)
|
||||
self.assertEqual(b.isk(a.public), isk)
|
||||
|
||||
def test_round_trip_confirmation(self):
|
||||
a = cpace.Cpace(True, b"12345678", SID, b"\x01", b"\x02")
|
||||
b = cpace.Cpace(False, b"12345678", SID, b"\x01", b"\x02")
|
||||
isk = a.isk(b.public)
|
||||
self.assertEqual(b.isk(a.public), isk)
|
||||
ta, tb = a.tag(isk), b.tag(isk)
|
||||
self.assertEqual(len(ta), 64)
|
||||
self.assertTrue(b.check(isk, a.public, ta))
|
||||
self.assertTrue(a.check(isk, b.public, tb))
|
||||
|
||||
def test_wrong_code_fails_confirmation(self):
|
||||
a = cpace.Cpace(True, b"12345678", SID, b"\x01", b"\x02")
|
||||
b = cpace.Cpace(False, b"12345678", SID, b"\x01", b"\x02")
|
||||
c = cpace.Cpace(False, b"12345679", SID, b"\x01", b"\x02")
|
||||
isk = a.isk(c.public)
|
||||
self.assertFalse(c.check(c.isk(a.public), a.public, a.tag(isk)))
|
||||
self.assertNotEqual(b.isk(a.public), c.isk(a.public))
|
||||
|
||||
def test_tampered_ad_fails_confirmation(self):
|
||||
a = cpace.Cpace(True, b"12345678", SID, b"\x01", b"\x02")
|
||||
b = cpace.Cpace(False, b"12345678", SID, b"\x01", b"\x03")
|
||||
isk_a = a.isk(b.public)
|
||||
self.assertFalse(b.check(b.isk(a.public), a.public, a.tag(isk_a)))
|
||||
|
||||
def test_low_order_point_aborts(self):
|
||||
a = cpace.Cpace(True, b"12345678", SID, b"\x01", b"\x02")
|
||||
for bad in (bytes(32), b"\x01" + bytes(31), bytes.fromhex("e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800")):
|
||||
with self.assertRaises(cpace.CpaceError):
|
||||
a.isk(bad)
|
||||
with self.assertRaises(cpace.CpaceError):
|
||||
a.isk(bytes(31))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,163 @@
|
||||
"""
|
||||
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 unittest
|
||||
|
||||
from cryptography.exceptions import InvalidTag
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec, rsa
|
||||
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
||||
|
||||
from openpilot.sunnypilot.system.ble import link
|
||||
|
||||
LINK = 0x1234
|
||||
|
||||
|
||||
class TestFraming(unittest.TestCase):
|
||||
def test_mtu_23_fragments(self):
|
||||
msg = bytes(range(40))
|
||||
frames = link.frames(msg, LINK, 20)
|
||||
self.assertEqual([len(f) for f in frames], [20, 20, 9])
|
||||
self.assertEqual([f[0] for f in frames], [1, 1, 0])
|
||||
self.assertEqual({f[1:3] for f in frames}, {LINK.to_bytes(2, "big")})
|
||||
r = link.Reassembler(LINK)
|
||||
out = [r.feed(f) for f in frames]
|
||||
self.assertEqual(out, [None, None, msg])
|
||||
|
||||
def test_single_frame_and_empty_rejected(self):
|
||||
self.assertEqual(len(link.frames(b"\x01", LINK, 20)), 1)
|
||||
with self.assertRaises(link.LinkError):
|
||||
link.frames(b"", LINK, 20)
|
||||
with self.assertRaises(link.LinkError):
|
||||
link.frames(b"\x01", 0, 20)
|
||||
with self.assertRaises(link.LinkError):
|
||||
link.frames(b"\x01", LINK, 19)
|
||||
|
||||
def test_frames_never_exceed_att_value_cap(self):
|
||||
frames = link.frames(bytes(900), LINK, 517 - 3)
|
||||
self.assertEqual([len(f) for f in frames], [512, 3 + 900 - 509])
|
||||
|
||||
def test_cap_before_and_after_session(self):
|
||||
r = link.Reassembler(LINK)
|
||||
with self.assertRaises(link.LinkError):
|
||||
for f in link.frames(bytes(1025), LINK, 244):
|
||||
r.feed(f)
|
||||
out = None
|
||||
for f in link.frames(bytes(1024), LINK, 244):
|
||||
out = r.feed(f)
|
||||
self.assertEqual(len(out), 1024)
|
||||
r.cap = link.SESSION_CAP
|
||||
for f in link.frames(bytes(16384), LINK, 244):
|
||||
out = r.feed(f)
|
||||
self.assertEqual(len(out), 16384)
|
||||
|
||||
def test_malformed_frames_rejected(self):
|
||||
r = link.Reassembler(LINK)
|
||||
bad = [
|
||||
b"\x02" + LINK.to_bytes(2, "big") + b"x", # bit 1 set
|
||||
b"\x80" + LINK.to_bytes(2, "big") + b"x", # bit 7 set
|
||||
b"\x00" + (LINK + 1).to_bytes(2, "big") + b"x", # other link id
|
||||
b"\x00" + LINK.to_bytes(2, "big"), # no fragment
|
||||
b"\x01\x00", # short
|
||||
]
|
||||
for frame in bad:
|
||||
with self.assertRaises(link.LinkError):
|
||||
r.feed(frame)
|
||||
|
||||
def test_reassembly_resets_after_error(self):
|
||||
r = link.Reassembler(LINK)
|
||||
r.feed(b"\x01" + LINK.to_bytes(2, "big") + b"ab")
|
||||
with self.assertRaises(link.LinkError):
|
||||
r.feed(b"\x02" + LINK.to_bytes(2, "big") + b"c")
|
||||
self.assertEqual(r.feed(b"\x00" + LINK.to_bytes(2, "big") + b"z"), b"z")
|
||||
|
||||
|
||||
class TestRecords(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.k_a, self.k_b = bytes([1]) * 32, bytes([2]) * 32
|
||||
|
||||
def pair(self, interval=link.REKEY_INTERVAL):
|
||||
return (link.Records(self.k_a, self.k_b, LINK, rekey_interval=interval),
|
||||
link.Records(self.k_b, self.k_a, LINK, rekey_interval=interval))
|
||||
|
||||
def test_round_trip_both_directions(self):
|
||||
a, b = self.pair()
|
||||
self.assertEqual(b.open(a.seal(b"\x30hi")), b"\x30hi")
|
||||
self.assertEqual(a.open(b.seal(b"\x40{}")), b"\x40{}")
|
||||
self.assertEqual(a.seal(b"\x30")[0], link.RECORD_TYPE)
|
||||
|
||||
def test_replay_and_reorder_rejected(self):
|
||||
a, b = self.pair()
|
||||
r0, r1 = a.seal(b"\x30zero"), a.seal(b"\x30one")
|
||||
with self.assertRaises(link.LinkError):
|
||||
b.open(r1)
|
||||
self.assertEqual(b.open(r0), b"\x30zero")
|
||||
self.assertEqual(b.open(r1), b"\x30one")
|
||||
with self.assertRaises(link.LinkError):
|
||||
b.open(r1)
|
||||
|
||||
def test_tamper_and_wrong_link_id_rejected(self):
|
||||
a, b = self.pair()
|
||||
rec = bytearray(a.seal(b"\x30x"))
|
||||
with self.assertRaises(link.LinkError):
|
||||
link.Records(self.k_b, self.k_a, LINK + 1).open(bytes(rec))
|
||||
rec[-1] ^= 1
|
||||
with self.assertRaises(link.LinkError):
|
||||
b.open(bytes(rec))
|
||||
with self.assertRaises(link.LinkError):
|
||||
b.open(b"\x21" + bytes(20))
|
||||
|
||||
def test_rekey_at_boundary(self):
|
||||
a, b = self.pair(interval=4)
|
||||
recs = [a.seal(bytes([0x30, i])) for i in range(10)]
|
||||
self.assertEqual([b.open(r) for r in recs], [bytes([0x30, i]) for i in range(10)])
|
||||
old = ChaCha20Poly1305(self.k_a)
|
||||
nonce = bytes(4) + (4).to_bytes(8, "little")
|
||||
with self.assertRaises(InvalidTag):
|
||||
old.decrypt(nonce, recs[4][1:], bytes([link.RECORD_TYPE]) + LINK.to_bytes(2, "big"))
|
||||
self.assertNotEqual(link._rekey(self.k_a), self.k_a)
|
||||
|
||||
|
||||
class TestKeysAndSignatures(unittest.TestCase):
|
||||
def test_transcript_and_signed_bytes_layout(self):
|
||||
with self.assertRaises(ValueError):
|
||||
link.transcript(b"\x01", b"")
|
||||
th = link.transcript(b"\x01", bytes(26), bytes(32), bytes(32), bytes(64), bytes(64))
|
||||
self.assertEqual(len(th), 32)
|
||||
signed = link.signed_bytes("D", th, b"spki", bytes(32))
|
||||
self.assertEqual(signed[:22], b"sunnylink-ble-keys-v1\x00")
|
||||
self.assertEqual(signed[22:23], b"D")
|
||||
self.assertEqual(len(signed), 22 + 1 + 32 + 32 + 32)
|
||||
with self.assertRaises(ValueError):
|
||||
link.signed_bytes("X", th, b"spki", bytes(32))
|
||||
|
||||
def test_session_keys(self):
|
||||
k1, k2, code = link.session_keys(bytes(64), bytes(24))
|
||||
self.assertEqual((len(k1), len(k2), len(code)), (32, 32, 6))
|
||||
self.assertNotEqual(k1, k2)
|
||||
self.assertEqual(link.session_keys(bytes(64), bytes(24)), (k1, k2, code))
|
||||
self.assertNotEqual(link.session_keys(bytes(64), bytes([1]) * 24)[0], k1)
|
||||
|
||||
def test_sign_verify_rs256_and_es256(self):
|
||||
data = b"signed bytes"
|
||||
for key in (rsa.generate_private_key(public_exponent=65537, key_size=2048), ec.generate_private_key(ec.SECP256R1())):
|
||||
alg, sig = link.sign(key, data)
|
||||
spki = key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||
self.assertEqual(alg, "RS256" if isinstance(key, rsa.RSAPrivateKey) else "ES256")
|
||||
self.assertTrue(link.verify(alg, spki, data, sig))
|
||||
self.assertFalse(link.verify(alg, spki, data + b"!", sig))
|
||||
self.assertFalse(link.verify(alg, spki, data, sig[:-1]))
|
||||
other = "ES256" if alg == "RS256" else "RS256"
|
||||
self.assertFalse(link.verify(other, spki, data, sig))
|
||||
self.assertFalse(link.verify(alg, b"junk", data, sig))
|
||||
|
||||
def test_unsupported_key_rejected(self):
|
||||
with self.assertRaises(ValueError):
|
||||
link.sign(ec.generate_private_key(ec.SECP384R1()), b"x")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
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 unittest
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
|
||||
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
||||
|
||||
from openpilot.sunnypilot.system.ble import noise
|
||||
|
||||
# Cacophony (noiseprotocol test vectors, centromere/cacophony vectors/cacophony.txt), the KK 25519 ChaChaPoly SHA256 entry
|
||||
VECTOR = {
|
||||
"init_prologue": "4a6f686e2047616c74",
|
||||
"init_static": "e61ef9919cde45dd5f82166404bd08e38bceb5dfdfded0a34c8df7ed542214d1",
|
||||
"init_ephemeral": "893e28b9dc6ca8d611ab664754b8ceb7bac5117349a4439a6b0569da977c464a",
|
||||
"init_remote_static": "31e0303fd6418d2f8c0e78b91f22e8caed0fbe48656dcf4767e4834f701b8f62",
|
||||
"resp_prologue": "4a6f686e2047616c74",
|
||||
"resp_static": "4a3acbfdb163dec651dfa3194dece676d437029c62a408b4c5ea9114246e4893",
|
||||
"resp_ephemeral": "bbdb4cdbd309f1a1f2e1456967fe288cadd6f712d65dc7b7793d5e63da6b375b",
|
||||
"resp_remote_static": "6bc3822a2aa7f4e6981d6538692b3cdf3e6df9eea6ed269eb41d93c22757b75a",
|
||||
"handshake_hash": "24c6b51ecb76277140ca018b5985bc9f03de321dae2d34dcae433dafef0131d9",
|
||||
"messages": [
|
||||
("4c756477696720766f6e204d69736573",
|
||||
"ca35def5ae56cec33dc2036731ab14896bc4c75dbb07a61f879f8e3afa4c79440177015efc1fe7a37c629af7120a9627" +
|
||||
"4e6ab7afcc9261901d0e09ae32a5bb96"),
|
||||
("4d757272617920526f746862617264",
|
||||
"95ebc60d2b1fa672c1f46a8aa265ef51bfe38e7ccb39ec5be34069f144808843b274d3429adc47ca093ba63ef90f8da8" +
|
||||
"9fda108db471dccfa4894aa7b00003"),
|
||||
("462e20412e20486179656b", "966b05bc69ec01b8454d3160a214e6f24a3d884eb31ec2408af63f"),
|
||||
("4361726c204d656e676572", "0ad887fba4f611bbb4afe44ba3556b8164332ca7d5934634d63d80"),
|
||||
("4a65616e2d426170746973746520536179", "012b28ae646ae7830e2c5472cb023eab071c1db3d8413ec69b513b83832f974c2d"),
|
||||
("457567656e2042f6686d20766f6e2042617765726b", "bb3e6a48160d9c5971d37f975727294e0d868342db31832e54d07191ab0ca3c3703b5ed3d9"),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _priv(hex_key: str) -> X25519PrivateKey:
|
||||
return X25519PrivateKey.from_private_bytes(bytes.fromhex(hex_key))
|
||||
|
||||
|
||||
def _pub(priv: X25519PrivateKey) -> bytes:
|
||||
return priv.public_key().public_bytes_raw()
|
||||
|
||||
|
||||
class TestNoiseKK(unittest.TestCase):
|
||||
def test_cacophony_vector(self):
|
||||
v = VECTOR
|
||||
ini = noise.KKHandshake(True, _priv(v["init_static"]), bytes.fromhex(v["init_remote_static"]),
|
||||
e=_priv(v["init_ephemeral"]), prologue=bytes.fromhex(v["init_prologue"]))
|
||||
res = noise.KKHandshake(False, _priv(v["resp_static"]), bytes.fromhex(v["resp_remote_static"]),
|
||||
e=_priv(v["resp_ephemeral"]), prologue=bytes.fromhex(v["resp_prologue"]))
|
||||
payload0, ct0 = v["messages"][0]
|
||||
payload1, ct1 = v["messages"][1]
|
||||
self.assertEqual(ini.write(bytes.fromhex(payload0)).hex(), ct0)
|
||||
self.assertEqual(res.read(bytes.fromhex(ct0)).hex(), payload0)
|
||||
self.assertEqual(res.write(bytes.fromhex(payload1)).hex(), ct1)
|
||||
self.assertEqual(ini.read(bytes.fromhex(ct1)).hex(), payload1)
|
||||
self.assertEqual(ini._h.hex(), v["handshake_hash"])
|
||||
|
||||
to_resp, to_ini = ini.split()
|
||||
self.assertEqual(res.split(), (to_ini, to_resp))
|
||||
for i, (payload, ct) in enumerate(v["messages"][2:], start=2):
|
||||
key = to_resp if i % 2 == 0 else to_ini
|
||||
counter = i // 2 - 1
|
||||
self.assertEqual(ChaCha20Poly1305(key).encrypt(bytes(4) + counter.to_bytes(8, "little"), bytes.fromhex(payload), b"").hex(), ct)
|
||||
|
||||
def test_round_trip_and_split_pairing(self):
|
||||
si, sr = X25519PrivateKey.generate(), X25519PrivateKey.generate()
|
||||
ini = noise.KKHandshake(True, si, _pub(sr))
|
||||
res = noise.KKHandshake(False, sr, _pub(si))
|
||||
self.assertEqual(res.read(ini.write(b"hello")), b"hello")
|
||||
self.assertEqual(ini.read(res.write(b"comma")), b"comma")
|
||||
i_send, i_recv = ini.split()
|
||||
r_send, r_recv = res.split()
|
||||
self.assertEqual((i_send, i_recv), (r_recv, r_send))
|
||||
self.assertNotEqual(i_send, i_recv)
|
||||
|
||||
def test_wrong_static_key_rejected(self):
|
||||
si, sr, other = (X25519PrivateKey.generate() for _ in range(3))
|
||||
ini = noise.KKHandshake(True, si, _pub(sr))
|
||||
msg = ini.write(b"")
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
noise.KKHandshake(False, other, _pub(si)).read(msg)
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
noise.KKHandshake(False, sr, _pub(other)).read(msg)
|
||||
|
||||
def test_tampered_message_rejected(self):
|
||||
si, sr = X25519PrivateKey.generate(), X25519PrivateKey.generate()
|
||||
msg = bytearray(noise.KKHandshake(True, si, _pub(sr)).write(b"\x01"))
|
||||
msg[-1] ^= 1
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
noise.KKHandshake(False, sr, _pub(si)).read(bytes(msg))
|
||||
|
||||
def test_low_order_remote_static_rejected(self):
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
noise.KKHandshake(True, X25519PrivateKey.generate(), bytes(32)).write()
|
||||
|
||||
def test_out_of_order_rejected(self):
|
||||
si, sr = X25519PrivateKey.generate(), X25519PrivateKey.generate()
|
||||
res = noise.KKHandshake(False, sr, _pub(si))
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
res.write()
|
||||
with self.assertRaises(noise.NoiseError):
|
||||
res.split()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,626 @@
|
||||
"""
|
||||
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 json
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
|
||||
|
||||
from openpilot.common.params import ParamKeyType
|
||||
from openpilot.common.test import Mocker, OpenpilotTestCase
|
||||
from openpilot.sunnypilot.system import connect_phone as cp
|
||||
from openpilot.sunnypilot.system.ble import cpace, grants, link, noise, session as s
|
||||
|
||||
DEVICE = "/org/bluez/hci0/dev_A"
|
||||
WALL = 1_700_000_000
|
||||
|
||||
|
||||
class MemParams:
|
||||
def __init__(self, values: dict | None = None, known: set[str] | None = None):
|
||||
self.data = dict(values or {})
|
||||
self.known = known if known is not None else set(self.data)
|
||||
self.types: dict[str, ParamKeyType] = {}
|
||||
self.defaults: dict = {}
|
||||
|
||||
def get(self, key, block=False, return_default=False):
|
||||
return self.data.get(key, self.defaults.get(key) if return_default else None)
|
||||
|
||||
def get_type(self, key):
|
||||
return self.types.get(key, ParamKeyType.BYTES)
|
||||
|
||||
def get_bool(self, key):
|
||||
return bool(self.data.get(key))
|
||||
|
||||
def put(self, key, value, block=False):
|
||||
self.data[key] = value
|
||||
|
||||
def put_bool(self, key, value, block=False):
|
||||
self.data[key] = value
|
||||
|
||||
def remove(self, key):
|
||||
self.data.pop(key, None)
|
||||
|
||||
def all_keys(self):
|
||||
return [k.encode() for k in self.known]
|
||||
|
||||
|
||||
def spki_of(key) -> bytes:
|
||||
return key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||
|
||||
|
||||
class Phone:
|
||||
"""An initiator built from the protocol core: CPace party A, Noise KK initiator, one link id."""
|
||||
|
||||
def __init__(self, h: "Harness", device: str, lid: int, name: str = "test phone"):
|
||||
self.h, self.device, self.lid, self.name = h, device, lid, name
|
||||
self.mtu = 23
|
||||
self.connected = True
|
||||
self.inbox: list[bytes] = []
|
||||
self.reasm = link.Reassembler(lid)
|
||||
self.broken = False
|
||||
self.static = X25519PrivateKey.generate()
|
||||
self.key = ec.generate_private_key(ec.SECP256R1())
|
||||
self.records: link.Records | None = None
|
||||
self.th = b""
|
||||
self.cp = None
|
||||
self.ya = self.yb = self.isk = b""
|
||||
self.sid = b""
|
||||
|
||||
def receive(self, frame: bytes):
|
||||
if int.from_bytes(frame[1:3], "big") != self.lid:
|
||||
return
|
||||
try:
|
||||
msg = self.reasm.feed(frame)
|
||||
except link.LinkError:
|
||||
self.broken = True
|
||||
return
|
||||
if msg is not None:
|
||||
self.inbox.append(msg)
|
||||
|
||||
def pop(self, typ: int) -> bytes:
|
||||
msg = self.inbox.pop(0)
|
||||
assert msg[0] == typ, (msg[0], typ)
|
||||
return msg[1:]
|
||||
|
||||
def pop_record(self, typ: int) -> bytes:
|
||||
inner = self.records.open(self.inbox.pop(0))
|
||||
assert inner[0] == typ, (inner[0], typ)
|
||||
return inner[1:]
|
||||
|
||||
def pop_error(self) -> int:
|
||||
return self.pop(s.ERROR)[0]
|
||||
|
||||
def start(self, now: float):
|
||||
return self.h.send(self, bytes([s.CONNECT_START, s.PROTO]), now)
|
||||
|
||||
def pake(self, prs: bytes, now: float):
|
||||
self.wbody = self.pop(s.CONNECT_WINDOW)
|
||||
self.sid = self.wbody[2:26]
|
||||
self.cp = cpace.Cpace(True, prs, self.sid, bytes([s.PROTO]), self.wbody)
|
||||
self.ya = self.cp.public
|
||||
self.h.send(self, bytes([s.PAKE_A]) + self.ya, now)
|
||||
if self.broken or not self.inbox:
|
||||
return
|
||||
self.yb = self.pop(s.PAKE_B)
|
||||
self.isk = self.cp.isk(self.yb)
|
||||
self.ta = self.cp.tag(self.isk)
|
||||
self.h.send(self, bytes([s.CONFIRM_A]) + self.ta, now)
|
||||
|
||||
def confirm(self):
|
||||
tb = self.pop(s.CONFIRM_B)
|
||||
assert self.cp.check(self.isk, self.yb, tb)
|
||||
self.th = link.transcript(bytes([s.PROTO]), self.wbody, self.ya, self.yb, self.ta, tb)
|
||||
p2c, c2p, self.check = link.session_keys(self.isk, self.sid)
|
||||
self.records = link.Records(p2c, c2p, self.lid)
|
||||
self.reasm.cap = link.SESSION_CAP
|
||||
|
||||
def ceremony(self, prs: bytes, now: float):
|
||||
self.start(now)
|
||||
self.pake(prs, now)
|
||||
if self.inbox and self.inbox[0][0] == s.CONFIRM_B:
|
||||
self.confirm()
|
||||
|
||||
def phone_keys(self, now: float):
|
||||
dev = self.pop_record(s.DEVICE_KEYS)
|
||||
doc = json.loads(dev)
|
||||
spki, static, sig = (grants.unb64(doc[k]) for k in ("spki", "static", "sig"))
|
||||
assert spki == self.h.identity_spki
|
||||
assert link.verify(doc["alg"], spki, link.signed_bytes("D", self.th, spki, static), sig)
|
||||
own_spki = spki_of(self.key)
|
||||
own_static = self.static.public_key().public_bytes_raw()
|
||||
alg, own_sig = link.sign(self.key, link.signed_bytes("P", self.th, own_spki, own_static))
|
||||
doc = {"v": 1, "spki": grants.b64(own_spki), "alg": alg, "static": grants.b64(own_static),
|
||||
"id": {"name": self.name}, "sig": grants.b64(own_sig)}
|
||||
self.h.send_record(self, s.PHONE_KEYS, json.dumps(doc).encode(), now)
|
||||
|
||||
def resume_start(self, comma_static: bytes, now: float):
|
||||
hs = noise.KKHandshake(True, self.static, comma_static)
|
||||
self.h.send(self, bytes([s.RESUME_1]) + hs.write(bytes([s.PROTO])), now)
|
||||
if self.broken or not self.inbox or self.inbox[0][0] == s.ERROR:
|
||||
return
|
||||
body = self.pop(s.RESUME_2)
|
||||
assert hs.read(body) == bytes([1])
|
||||
send, recv = hs.split()
|
||||
self.records = link.Records(send, recv, self.lid)
|
||||
self.reasm.cap = link.SESSION_CAP
|
||||
|
||||
def rpc(self, method: str, now: float, params=None, rid: int = 1) -> dict:
|
||||
body = json.dumps({"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}}).encode()
|
||||
self.h.send_record(self, s.RPC, body, now)
|
||||
return json.loads(self.pop_record(s.RPC))
|
||||
|
||||
|
||||
class Harness:
|
||||
def __init__(self, mocker: Mocker, values=None, known=None):
|
||||
self.identity = ec.generate_private_key(ec.SECP256R1())
|
||||
self.identity_spki = spki_of(self.identity)
|
||||
pem = self.identity.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL,
|
||||
serialization.NoEncryption()).decode()
|
||||
mocker.patch.object(cp.BaseApi, "get_key_pair", return_value=("ES256", pem, "unused"))
|
||||
self.clock = {"wall": WALL}
|
||||
self.params = MemParams({"DongleId": "dongle", "HardwareSerial": "serial"} | (values or {}), known=known)
|
||||
self.window = cp.ConnectPhoneWindow()
|
||||
self.engine = s.Engine(self.params, self.window, wifi=lambda: self.wifi, wall=lambda: self.clock["wall"])
|
||||
self.wifi = FakeWifi()
|
||||
self.phones: dict[str, Phone] = {}
|
||||
|
||||
def new_phone(self, lid: int = 0x1234, device: str = DEVICE, name: str = "test phone") -> Phone:
|
||||
phone = self.phones[device] = Phone(self, device, lid, name)
|
||||
return phone
|
||||
|
||||
def open_window(self, now: float = 0.0):
|
||||
assert self.window.open(now, 1) == "ok"
|
||||
|
||||
def send(self, phone: Phone, message: bytes, now: float):
|
||||
for frame in link.frames(message, phone.lid, phone.mtu - 3):
|
||||
if not phone.connected:
|
||||
return
|
||||
self.route(self.engine.on_write(phone.device, frame, phone.mtu, now))
|
||||
|
||||
def send_record(self, phone: Phone, typ: int, body: bytes, now: float):
|
||||
self.send(phone, phone.records.seal(bytes([typ]) + body), now)
|
||||
|
||||
def route(self, actions):
|
||||
for kind, data in actions:
|
||||
if kind == "notify":
|
||||
for phone in self.phones.values():
|
||||
if phone.connected:
|
||||
phone.receive(data)
|
||||
else:
|
||||
self.engine.on_disconnect(data)
|
||||
self.phones[data].connected = False
|
||||
|
||||
def tick(self, now: float):
|
||||
self.route(self.engine.tick(now))
|
||||
|
||||
def allow(self, now: float, allow: bool = True):
|
||||
self.route(self.engine.answer(allow, now))
|
||||
|
||||
def grant_list(self) -> list[dict]:
|
||||
return grants.load(self.params)
|
||||
|
||||
|
||||
class FakeWifi:
|
||||
def __init__(self):
|
||||
self.active = False # what the radio reports
|
||||
self.requested: bool | None = None # last set_tethering_active call
|
||||
self.connected_ssid = "home"
|
||||
self.tethering_ssid = "weedle-test"
|
||||
self.tethering_password = "pw-test"
|
||||
|
||||
def is_tethering_active(self):
|
||||
return self.active
|
||||
|
||||
def set_tethering_active(self, active: bool):
|
||||
self.requested = active
|
||||
|
||||
|
||||
def full_ceremony(h: Harness, phone: Phone, now: float = 0.0) -> int:
|
||||
prs, _ = h.window.secret()
|
||||
phone.ceremony(prs, now)
|
||||
h.allow(now)
|
||||
phone.pop_record(s.DECISION)
|
||||
phone.phone_keys(now)
|
||||
return phone.pop_record(s.GRANT_RESULT)[0]
|
||||
|
||||
|
||||
class TestCeremony(OpenpilotTestCase):
|
||||
def test_full_ceremony(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
prs = h.window.secret()[0]
|
||||
phone.ceremony(prs, 0.0)
|
||||
assert h.window.active and h.engine.prompt(0.0) == {"step": "allow", "check": phone.check[:3] + " " + phone.check[3:],
|
||||
"until": 30.0}
|
||||
h.allow(0.0)
|
||||
assert phone.pop_record(s.DECISION) == bytes([s.ALLOW])
|
||||
phone.phone_keys(0.0)
|
||||
assert phone.pop_record(s.GRANT_RESULT) == bytes([s.GRANT_ADDED])
|
||||
|
||||
grant = h.grant_list()
|
||||
assert [(g["name"], g["added"], g["last_seen"]) for g in grant] == [("test phone", WALL, WALL)]
|
||||
assert not h.window.active and h.engine.connected() == 1
|
||||
assert len(phone.inbox) == 0
|
||||
|
||||
def test_window_is_held_once_the_phone_proves_the_code(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
h.window.tick(0.0)
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 110.0)
|
||||
h.window.tick(130.0)
|
||||
assert h.window.active
|
||||
h.allow(135.0)
|
||||
phone.pop_record(s.DECISION)
|
||||
phone.phone_keys(136.0)
|
||||
assert phone.pop_record(s.GRANT_RESULT) == bytes([s.GRANT_ADDED])
|
||||
assert h.window.state()["reason"] == "granted"
|
||||
|
||||
def test_phone_keys_not_sent_in_time(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.allow(0.0)
|
||||
phone.pop_record(s.DECISION)
|
||||
h.tick(30.0)
|
||||
assert h.grant_list() == [] and not phone.connected
|
||||
assert h.window.state()["reason"] == "timeout"
|
||||
|
||||
def test_phone_leaving_closes_the_held_window(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.route([("disconnect", phone.device)])
|
||||
assert not h.window.active and h.window.state()["reason"] == "phone_left"
|
||||
|
||||
def test_deny_closes_window_without_a_grant(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.allow(1.0, allow=False)
|
||||
assert phone.pop_record(s.DECISION) == bytes([s.DENY])
|
||||
assert not phone.connected and not h.window.active
|
||||
assert h.window.state()["reason"] == "denied" and h.grant_list() == []
|
||||
|
||||
def test_no_answer_after_thirty_seconds(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.tick(29.9)
|
||||
assert phone.connected and h.engine.prompt(29.9) is not None
|
||||
h.tick(30.0)
|
||||
assert phone.pop_record(s.DECISION) == bytes([s.NO_ANSWER])
|
||||
assert not phone.connected and h.window.state()["reason"] == "no_answer"
|
||||
|
||||
def test_check_code_wait_is_not_cut_by_the_idle_rule(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.tick(20.0)
|
||||
assert phone.connected and not phone.broken
|
||||
|
||||
def test_no_idle_drop_after_allow(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.allow(5.0)
|
||||
phone.pop_record(s.DECISION)
|
||||
h.tick(25.0)
|
||||
assert phone.connected and h.engine.prompt(25.0) is None
|
||||
|
||||
def test_wrong_code_five_times_closes_the_window(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
for attempt in range(5):
|
||||
phone = h.new_phone(lid=0x100 + attempt, device=f"/dev/{attempt}")
|
||||
phone.ceremony(b"00000001" if attempt % 2 else b"00000002", 0.0)
|
||||
assert phone.pop_error() == (s.ERR_WINDOW_CLOSED if attempt == 4 else s.ERR_WRONG_CODE)
|
||||
assert not phone.connected
|
||||
assert h.window.active == (attempt < 4)
|
||||
assert h.window.state()["reason"] == "wrong_codes"
|
||||
|
||||
def test_wrong_code_counts_only_the_window_it_was_made_for(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window(0.0)
|
||||
for attempt in range(4):
|
||||
phone = h.new_phone(lid=0x200 + attempt, device=f"/w/{attempt}")
|
||||
phone.ceremony(b"00000001", 0.0)
|
||||
assert phone.pop_error() == s.ERR_WRONG_CODE
|
||||
h.window.cancel()
|
||||
h.open_window(1.0)
|
||||
phone = h.new_phone(lid=0x300, device="/w/new")
|
||||
phone.ceremony(h.window.secret()[0], 1.0)
|
||||
assert phone.connected and not phone.broken
|
||||
|
||||
def test_connect_start_with_no_window_gets_error_one(self, mocker):
|
||||
h = Harness(mocker)
|
||||
phone = h.new_phone()
|
||||
phone.start(0.0)
|
||||
assert phone.pop_error() == s.ERR_NO_WINDOW and not phone.connected
|
||||
|
||||
def test_wrong_protocol_version_gets_error_three(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
h.send(phone, bytes([s.CONNECT_START, 2]), 0.0)
|
||||
assert phone.pop_error() == s.ERR_VERSION
|
||||
|
||||
def test_second_ceremony_while_one_is_running_gets_busy(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
first = h.new_phone(lid=0x10, device="/a")
|
||||
second = h.new_phone(lid=0x20, device="/b")
|
||||
first.start(0.0)
|
||||
second.start(0.0)
|
||||
assert second.pop_error() == s.ERR_BUSY and not second.connected
|
||||
assert first.connected
|
||||
|
||||
def test_unauthenticated_idle_timeout(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.start(0.0)
|
||||
phone.pop(s.CONNECT_WINDOW)
|
||||
h.tick(9.9)
|
||||
assert phone.connected
|
||||
h.tick(10.0)
|
||||
assert phone.pop_error() == s.ERR_TIMEOUT and not phone.connected
|
||||
|
||||
def test_unauthenticated_total_timeout_is_sixty_seconds(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.start(0.0)
|
||||
phone.pop(s.CONNECT_WINDOW)
|
||||
h.engine.on_write(phone.device, link.frames(bytes([s.PAKE_A]) + b"\x00" * 32, phone.lid, 20)[0], 23, 55.0)
|
||||
h.tick(59.9)
|
||||
assert phone.connected
|
||||
h.tick(60.0)
|
||||
assert not phone.connected
|
||||
|
||||
def test_window_closing_drops_a_ceremony_in_progress(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.window.cancel("cancel")
|
||||
h.tick(1.0)
|
||||
assert not phone.connected
|
||||
|
||||
def test_new_window_drops_the_old_ceremony(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.window.open(1.0, 2)
|
||||
h.tick(1.0)
|
||||
assert not phone.connected
|
||||
|
||||
def test_bad_device_signature_drops_without_a_grant(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.ceremony(h.window.secret()[0], 0.0)
|
||||
h.allow(0.0)
|
||||
phone.pop_record(s.DECISION)
|
||||
phone.pop_record(s.DEVICE_KEYS)
|
||||
bad = {"v": 1, "spki": grants.b64(spki_of(phone.key)), "alg": "ES256", "static": grants.b64(b"\x01" * 32),
|
||||
"id": {"name": "x"}, "sig": grants.b64(b"\x00" * 70)}
|
||||
h.send_record(phone, s.PHONE_KEYS, json.dumps(bad).encode(), 0.0)
|
||||
assert not phone.connected and h.grant_list() == []
|
||||
|
||||
def test_limit_of_eight_phones(self, mocker):
|
||||
values = {"SunnylinkLocalBleGrants": [{"spki": f"x{i}", "static": grants.b64(b"\x02" * 32), "name": "p", "added": 1,
|
||||
"last_seen": 1} for i in range(grants.MAX_PHONES)]}
|
||||
h = Harness(mocker, values)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
assert full_ceremony(h, phone) == s.GRANT_REFUSED
|
||||
assert len(h.grant_list()) == grants.MAX_PHONES and not h.window.active
|
||||
assert not phone.connected
|
||||
|
||||
def test_duplicate_link_id_is_dropped(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
first = h.new_phone(lid=0x77, device="/first")
|
||||
second = h.new_phone(lid=0x77, device="/second")
|
||||
first.start(0.0)
|
||||
second.start(0.0)
|
||||
assert not second.connected and first.connected
|
||||
assert first.pop(s.CONNECT_WINDOW)[0] == s.PROTO
|
||||
|
||||
def test_bad_frame_flags_drop_the_link(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
frame = bytes([0x02]) + phone.lid.to_bytes(2, "big") + bytes([s.PROTO])
|
||||
h.engine.on_write(phone.device, frame, 23, 0.0)
|
||||
assert h.engine.on_write(phone.device, frame, 23, 0.0) == [("disconnect", phone.device)]
|
||||
|
||||
def test_oversized_clear_message_before_session_is_dropped(self, mocker):
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
phone.start(0.0)
|
||||
phone.pop(s.CONNECT_WINDOW)
|
||||
phone.mtu = 247
|
||||
h.send(phone, bytes([s.PAKE_A]) + b"\x00" * 1100, 0.0)
|
||||
assert not phone.connected
|
||||
|
||||
def test_grants_key_is_created_once(self, mocker):
|
||||
h = Harness(mocker)
|
||||
first = grants.static_private(h.params).public_key().public_bytes_raw()
|
||||
assert len(h.params.data[grants.KEY_KEY]) == 32
|
||||
assert grants.static_private(h.params).public_key().public_bytes_raw() == first
|
||||
|
||||
|
||||
class TestReconnect(OpenpilotTestCase):
|
||||
def granted(self, mocker) -> tuple[Harness, Phone]:
|
||||
h = Harness(mocker)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
assert full_ceremony(h, phone) == s.GRANT_ADDED
|
||||
h.engine.on_disconnect(phone.device)
|
||||
phone.connected = False
|
||||
return h, phone
|
||||
|
||||
def comma_static(self, h: Harness) -> bytes:
|
||||
return grants.static_private(h.params).public_key().public_bytes_raw()
|
||||
|
||||
def test_resume_with_a_known_phone(self, mocker):
|
||||
h, phone = self.granted(mocker)
|
||||
h.clock["wall"] = WALL + 500
|
||||
again = h.new_phone(lid=0x4321, device="/again")
|
||||
again.static = phone.static
|
||||
again.resume_start(self.comma_static(h), 10.0)
|
||||
assert again.connected and again.records is not None
|
||||
assert h.grant_list()[0]["last_seen"] == WALL + 500
|
||||
assert len(again.rpc("phones.list", 10.0)["result"]) == 1
|
||||
|
||||
def test_removed_phone_gets_error_eight(self, mocker):
|
||||
h, phone = self.granted(mocker)
|
||||
h.route(h.engine.remove(h.grant_list()[0]["spki"]))
|
||||
again = h.new_phone(lid=0x4321, device="/again")
|
||||
again.static = phone.static
|
||||
again.resume_start(self.comma_static(h), 10.0)
|
||||
assert again.pop_error() == s.ERR_UNKNOWN_PHONE and not again.connected
|
||||
assert h.grant_list() == []
|
||||
|
||||
def test_remove_drops_a_live_link_at_once(self, mocker):
|
||||
h, phone = self.granted(mocker)
|
||||
again = h.new_phone(lid=0x4321, device="/again")
|
||||
again.static = phone.static
|
||||
again.resume_start(self.comma_static(h), 10.0)
|
||||
assert again.connected
|
||||
h.route(h.engine.remove(h.grant_list()[0]["spki"]))
|
||||
assert not again.connected
|
||||
|
||||
def test_no_idle_drop_on_an_authenticated_session(self, mocker):
|
||||
h, phone = self.granted(mocker)
|
||||
again = h.new_phone(lid=0x4321, device="/again")
|
||||
again.static = phone.static
|
||||
again.resume_start(self.comma_static(h), 0.0)
|
||||
h.tick(500.0)
|
||||
assert again.connected and h.engine.connected() == 1
|
||||
|
||||
def test_resumed_phone_is_the_only_live_link_for_its_grant(self, mocker):
|
||||
h, phone = self.granted(mocker)
|
||||
first = h.new_phone(lid=0x4321, device="/one")
|
||||
first.static = phone.static
|
||||
first.resume_start(self.comma_static(h), 0.0)
|
||||
second = h.new_phone(lid=0x4322, device="/two")
|
||||
second.static = phone.static
|
||||
second.resume_start(self.comma_static(h), 1.0)
|
||||
assert second.connected and not first.connected
|
||||
|
||||
|
||||
class TestRpcOverSession(OpenpilotTestCase):
|
||||
def session(self, mocker, values=None) -> tuple[Harness, Phone]:
|
||||
known = {"DongleId", "CarParamsSP", "SunnylinkTempFault", "BluetoothAllowed", "BluetoothEnabled", "SunnylinkLocalBleGrants"}
|
||||
h = Harness(mocker, {"SunnylinkEnabled": True} | (values or {}), known)
|
||||
h.open_window()
|
||||
phone = h.new_phone()
|
||||
assert full_ceremony(h, phone) == s.GRANT_ADDED
|
||||
return h, phone
|
||||
|
||||
def test_status_get(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
mocker.patch("openpilot.sunnypilot.system.ble.rpc.get_version", return_value="0.9.0")
|
||||
mocker.patch("openpilot.sunnypilot.system.ble.rpc.HARDWARE.get_os_version", return_value="19.9")
|
||||
wpa = mocker.patch("openpilot.common.hardware.comma.hardware.wpa_supplicant_cmd",
|
||||
return_value={"mode": "station", "wpa_state": "COMPLETED", "ssid": "home"})
|
||||
result = phone.rpc("status.get", 0.0, rid=5)
|
||||
assert result["id"] == 5
|
||||
assert result["result"]["network"] == {"wifi_ssid": "home", "hotspot": False}
|
||||
assert result["result"]["phones"] == 1 and result["result"]["dongle_id"] == "dongle"
|
||||
wpa.return_value = {"mode": "AP", "wpa_state": "COMPLETED", "ssid": "weedle-1234"}
|
||||
assert phone.rpc("status.get", 1.0, rid=6)["result"]["network"] == {"wifi_ssid": None, "hotspot": True}
|
||||
|
||||
def test_unknown_method_is_not_found(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
assert phone.rpc("nope", 0.0)["error"]["code"] == -32601
|
||||
|
||||
def test_params_set_and_get(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
assert phone.rpc("params.set", 0.0, {"values": {"CarParamsSP": "x"}})["result"] == {"ok": ["CarParamsSP"]}
|
||||
got = phone.rpc("params.get", 0.0, {"keys": ["CarParamsSP", "SunnylinkTempFault"]})
|
||||
assert got["result"] == {"values": {"CarParamsSP": "x", "SunnylinkTempFault": None}}
|
||||
|
||||
def test_params_get_unset_reads_like_sunnylink(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
h.params.known |= {"IsMetric", "LongitudinalPersonality", "LanguageSetting"}
|
||||
h.params.types |= {"IsMetric": ParamKeyType.BOOL, "LongitudinalPersonality": ParamKeyType.INT, "LanguageSetting": ParamKeyType.STRING}
|
||||
h.params.defaults["LanguageSetting"] = "main_en"
|
||||
got = phone.rpc("params.get", 0.0, {"keys": ["IsMetric", "LongitudinalPersonality", "LanguageSetting"]})
|
||||
assert got["result"] == {"values": {"IsMetric": False, "LongitudinalPersonality": 0, "LanguageSetting": "main_en"}}
|
||||
|
||||
def test_params_refusals_are_all_or_nothing(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
for keys in (["BluetoothAllowed"], ["BluetoothEnabled"], ["SunnylinkLocalBleGrants"], ["AdbEnabled"]):
|
||||
assert phone.rpc("params.get", 0.0, {"keys": keys})["error"]["code"] == -32001
|
||||
refused = phone.rpc("params.set", 0.0, {"values": {"CarParamsSP": "y", "BluetoothAllowed": False}})
|
||||
assert refused["error"]["code"] == -32001
|
||||
assert h.params.data.get("CarParamsSP") is None
|
||||
assert phone.rpc("params.set", 0.0, {"values": {"NotAKey": 1}})["error"]["code"] == -32001
|
||||
|
||||
def test_params_get_limits_the_key_count(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
assert phone.rpc("params.get", 0.0, {"keys": ["DongleId"] * 33})["error"]["code"] == -32001
|
||||
|
||||
def test_hotspot_start_answers_when_up(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
h.send_record(phone, s.RPC, json.dumps({"jsonrpc": "2.0", "id": 4, "method": "hotspot.start"}).encode(), 0.0)
|
||||
assert phone.inbox == [] and h.wifi.requested is True
|
||||
h.wifi.active = True
|
||||
h.tick(1.0)
|
||||
assert json.loads(phone.pop_record(s.RPC)) == {"jsonrpc": "2.0", "id": 4, "result": {"ssid": "weedle-test", "password": "pw-test"}}
|
||||
|
||||
def test_hotspot_start_times_out(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
h.send_record(phone, s.RPC, json.dumps({"jsonrpc": "2.0", "id": 9, "method": "hotspot.start"}).encode(), 0.0)
|
||||
h.tick(30.0)
|
||||
reply = json.loads(phone.pop_record(s.RPC))
|
||||
assert reply["id"] == 9 and reply["error"]["code"] == -32001
|
||||
|
||||
def test_hotspot_credentials_refused_while_off(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
assert phone.rpc("hotspot.credentials", 0.0)["error"]["code"] == -32001
|
||||
h.wifi.active = True
|
||||
assert phone.rpc("hotspot.credentials", 0.0)["result"] == {"ssid": "weedle-test", "password": "pw-test"}
|
||||
|
||||
def test_hotspot_stop(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
h.wifi.active = True
|
||||
assert phone.rpc("hotspot.stop", 0.0)["result"] == {}
|
||||
assert h.wifi.requested is False
|
||||
|
||||
def test_phones_list_marks_this_phone(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
listing = phone.rpc("phones.list", 0.0)["result"]
|
||||
assert listing == [{"name": "test phone", "added": WALL, "last_seen": WALL, "this": True}]
|
||||
|
||||
def test_forget_self_drops_the_grant_and_the_link(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
response = phone.rpc("phones.forgetSelf", 0.0)
|
||||
assert response["result"] == {}
|
||||
assert h.grant_list() == [] and not phone.connected
|
||||
|
||||
def test_record_cap_after_session(self, mocker):
|
||||
h, phone = self.session(mocker)
|
||||
phone.mtu = 247
|
||||
big = {"jsonrpc": "2.0", "id": 3, "method": "nope", "params": {"pad": "x" * 9000}}
|
||||
h.send_record(phone, s.RPC, json.dumps(big).encode(), 0.0)
|
||||
assert phone.connected and json.loads(phone.pop_record(s.RPC))["error"]["code"] == -32601
|
||||
h.send(phone, phone.records.seal(bytes([s.RPC]) + b" " * 17000), 0.0)
|
||||
assert not phone.connected
|
||||
@@ -0,0 +1,669 @@
|
||||
"""
|
||||
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 signal
|
||||
import time
|
||||
from collections import deque
|
||||
from itertools import count
|
||||
|
||||
from jeepney import DBusAddress, HeaderFields, MessageType, new_error, new_method_call, new_method_return
|
||||
|
||||
from openpilot.common.test import Mocker, OpenpilotTestCase
|
||||
from openpilot.sunnypilot.system import bluetooth_manager as bm
|
||||
from openpilot.sunnypilot.system import connect_phone as cp
|
||||
|
||||
ADAPTER = "/org/bluez/hci0"
|
||||
DEVICE = ADAPTER + "/dev_4A_3B_2C_1D_0E_0F"
|
||||
SETUP = ["GetManagedObjects", "UnregisterAdvertisement", "UnregisterApplication", "Pairable", "Alias", "Powered",
|
||||
"DiscoverableTimeout", "Discoverable", "RegisterApplication", "RegisterAdvertisement"]
|
||||
TEARDOWN = ["UnregisterAdvertisement", "UnregisterApplication", "Discoverable", "Powered"]
|
||||
|
||||
|
||||
def variant(value) -> tuple:
|
||||
return "b" if isinstance(value, bool) else "s" if isinstance(value, str) else "u", value
|
||||
|
||||
|
||||
class FakeBus:
|
||||
"""Stands in for the system bus: records what is sent and answers method calls the way BlueZ does."""
|
||||
|
||||
def __init__(self, failing: tuple[str, ...] = (), adapter: bool = True):
|
||||
self.outgoing_serial = count(1)
|
||||
self.sent: list = []
|
||||
self.inbox: deque = deque()
|
||||
self.failing = failing # method names, or property names for Set
|
||||
self.adapter = adapter
|
||||
self.owner = 5 # bluetoothd is ":1.<owner>" on the bus
|
||||
self.registered: set[str] = set() # object paths registered with the running bluetoothd
|
||||
self.props = {"Powered": False, "Pairable": True, "Alias": "comma-0a1b2c3d", "Discoverable": False}
|
||||
self.devices: dict[str, dict[str, bool]] = {}
|
||||
self.dead = False
|
||||
self.hung = False # bluetoothd takes calls and never answers
|
||||
self.closed = False
|
||||
self.timeout = 0.0
|
||||
|
||||
def restart_bluetoothd(self):
|
||||
# a killed bluetoothd comes back under a new name without its registrations; the kernel keeps the adapter powered
|
||||
self.owner += 1
|
||||
self.registered.clear()
|
||||
|
||||
def objects(self) -> dict:
|
||||
if not self.adapter:
|
||||
return {}
|
||||
adapter = {
|
||||
bm.ADAPTER_IFACE: {name: variant(value) for name, value in self.props.items()},
|
||||
bm.GATT_MANAGER_IFACE: {},
|
||||
bm.ADVERTISING_MANAGER_IFACE: {"ActiveInstances": ("y", int(bm.ADVERTISEMENT_PATH in self.registered))},
|
||||
}
|
||||
return {ADAPTER: adapter} | {path: {bm.DEVICE_IFACE: {name: variant(value) for name, value in props.items()}}
|
||||
for path, props in self.devices.items()}
|
||||
|
||||
def send(self, msg, serial=None):
|
||||
if self.dead:
|
||||
raise BrokenPipeError
|
||||
msg.header.serial = next(self.outgoing_serial) if serial is None else serial
|
||||
msg.serialise() # raises when a body does not match its signature # codespell:ignore serialise
|
||||
self.sent.append(msg)
|
||||
if msg.header.message_type != MessageType.method_call or self.hung:
|
||||
return
|
||||
|
||||
member = msg.header.fields[HeaderFields.member]
|
||||
if (msg.body[1] if member == "Set" else member) in self.failing:
|
||||
reply = new_error(msg, "org.bluez.Error.Failed")
|
||||
elif not self.adapter and msg.header.fields[HeaderFields.path].startswith(ADAPTER):
|
||||
reply = new_error(msg, "org.freedesktop.DBus.Error.UnknownObject")
|
||||
elif member == "RemoveDevice" and not self.props["Powered"]:
|
||||
reply = new_error(msg, "org.bluez.Error.NotReady")
|
||||
elif member == "GetManagedObjects":
|
||||
reply = new_method_return(msg, "a{oa{sa{sv}}}", (self.objects(),))
|
||||
else:
|
||||
if member == "Set":
|
||||
self.props[msg.body[1]] = msg.body[2][1]
|
||||
elif member.startswith("Register"):
|
||||
self.registered.add(msg.body[0])
|
||||
elif member.startswith("Unregister"):
|
||||
self.registered.discard(msg.body[0])
|
||||
elif member == "RemoveDevice":
|
||||
del self.devices[msg.body[0]]
|
||||
reply = new_method_return(msg)
|
||||
reply.header.fields[HeaderFields.sender] = f":1.{self.owner}"
|
||||
self.inbox.append(reply)
|
||||
|
||||
def receive(self, timeout: float = 0.0):
|
||||
self.timeout = timeout
|
||||
if self.dead:
|
||||
raise ConnectionResetError
|
||||
if not self.inbox:
|
||||
raise TimeoutError
|
||||
return self.inbox.popleft()
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
def calls(self) -> list[str]:
|
||||
return [m.body[1] if (member := m.header.fields[HeaderFields.member]) == "Set" else member
|
||||
for m in self.sent if m.header.message_type == MessageType.method_call]
|
||||
|
||||
|
||||
class FakeParams:
|
||||
def __init__(self, values: dict | None = None, bus: FakeBus | None = None):
|
||||
self.bus = bus
|
||||
self.data = values or {}
|
||||
self.puts: list[str] = []
|
||||
|
||||
def get(self, key):
|
||||
return self.data.get(key)
|
||||
|
||||
def get_bool(self, key):
|
||||
return bool(self.data.get(key))
|
||||
|
||||
def put(self, key, value):
|
||||
self.data[key] = value
|
||||
self.puts.append(key)
|
||||
if self.bus is not None and key == "BluetoothEnabled" and not value:
|
||||
self.bus.adapter = False # AGNOS stops the UART attach, and BlueZ drops the adapter
|
||||
|
||||
put_bool = put
|
||||
|
||||
def remove(self, key):
|
||||
self.data.pop(key, None)
|
||||
|
||||
|
||||
def make(mocker: Mocker, **bus_kwargs) -> tuple[bm.BluetoothManager, FakeBus]:
|
||||
bus = FakeBus(**bus_kwargs)
|
||||
mocker.patch.object(bm, "Params", return_value=FakeParams(bus=bus))
|
||||
mocker.patch.object(bm, "CALL_TIMEOUT", 0.01)
|
||||
manager = bm.BluetoothManager(mocker.MagicMock(), mocker.MagicMock(), mocker.MagicMock())
|
||||
manager._conn = bus
|
||||
return manager, bus
|
||||
|
||||
|
||||
def make_ready(mocker: Mocker) -> tuple[bm.BluetoothManager, FakeBus]:
|
||||
manager, bus = make(mocker)
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
assert manager.ready
|
||||
bus.sent.clear()
|
||||
return manager, bus
|
||||
|
||||
|
||||
def incoming(path: str, iface: str, member: str, signature: str | None = None, body: tuple = ()):
|
||||
msg = new_method_call(DBusAddress(path, ":1.42", iface), member, signature, body)
|
||||
msg.header.serial = 1000
|
||||
msg.header.fields[HeaderFields.sender] = ":1.5"
|
||||
return msg
|
||||
|
||||
|
||||
def from_bluez(manager: bm.BluetoothManager, bus: FakeBus, *call):
|
||||
"""Deliver a method call from BlueZ and return the reply."""
|
||||
bus.sent.clear()
|
||||
manager._dispatch(incoming(*call))
|
||||
return bus.sent[-1]
|
||||
|
||||
|
||||
def write(manager: bm.BluetoothManager, bus: FakeBus, value: bytes, **options):
|
||||
options = {"device": ("o", DEVICE), "mtu": ("q", 247), "link": ("s", "LE")} | options
|
||||
return from_bluez(manager, bus, bm.RX_PATH, bm.GATT_CHARACTERISTIC_IFACE, "WriteValue", "aya{sv}", (value, options))
|
||||
|
||||
|
||||
def disconnects(bus: FakeBus) -> list[str]:
|
||||
return [m.header.fields[HeaderFields.path] for m in bus.sent if m.header.fields.get(HeaderFields.member) == "Disconnect"]
|
||||
|
||||
|
||||
class TestObjects(OpenpilotTestCase):
|
||||
def test_gatt_tree_never_asks_for_pairing(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
reply = from_bluez(manager, bus, bm.APP_PATH, bm.OBJECT_MANAGER_IFACE, "GetManagedObjects")
|
||||
|
||||
tree = reply.body[0]
|
||||
assert set(tree) == {bm.SERVICE_PATH, bm.RX_PATH, bm.TX_PATH}
|
||||
flags = [f for path in (bm.RX_PATH, bm.TX_PATH) for f in tree[path][bm.GATT_CHARACTERISTIC_IFACE]["Flags"][1]]
|
||||
assert sorted(flags) == ["notify", "write", "write-without-response"]
|
||||
|
||||
def test_advertisement_has_no_name_or_tx_power(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
reply = from_bluez(manager, bus, bm.ADVERTISEMENT_PATH, bm.PROPERTIES_IFACE, "GetAll", "s", (bm.ADVERTISEMENT_IFACE,))
|
||||
|
||||
assert reply.body[0] == {"Type": ("s", "peripheral"), "ServiceUUIDs": ("as", [bm.SERVICE_UUID])}
|
||||
|
||||
def test_unknown_method_gets_an_error(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
reply = from_bluez(manager, bus, bm.RX_PATH, bm.GATT_CHARACTERISTIC_IFACE, "ReadValue", "a{sv}", ({},))
|
||||
|
||||
assert reply.header.message_type == MessageType.error
|
||||
|
||||
|
||||
class TestWrite(OpenpilotTestCase):
|
||||
def test_write_reaches_callback(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
reply = write(manager, bus, b"\x01\x02")
|
||||
|
||||
manager._on_write.assert_called_once_with(DEVICE, b"\x01\x02", 247)
|
||||
assert manager.connected == {DEVICE}
|
||||
assert disconnects(bus) == []
|
||||
assert reply.header.message_type == MessageType.method_return
|
||||
assert reply.header.fields[HeaderFields.reply_serial] == 1000
|
||||
|
||||
def test_write_at_an_offset_disconnects(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
write(manager, bus, b"\x01", offset=("q", 20))
|
||||
|
||||
manager._on_write.assert_not_called()
|
||||
assert disconnects(bus) == [DEVICE]
|
||||
|
||||
def test_write_longer_than_one_packet_disconnects(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
write(manager, bus, bytes(244))
|
||||
manager._on_write.assert_called_once()
|
||||
|
||||
write(manager, bus, bytes(245))
|
||||
manager._on_write.assert_called_once()
|
||||
assert disconnects(bus) == [DEVICE]
|
||||
|
||||
def test_failing_callback_keeps_serving(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager._on_write.side_effect = ValueError
|
||||
reply = write(manager, bus, b"\x01")
|
||||
|
||||
assert reply.header.message_type == MessageType.method_return
|
||||
|
||||
def test_notify_sends_value(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
assert manager.notify(b"\x05\x06")
|
||||
|
||||
signal = bus.sent[-1]
|
||||
assert signal.header.fields[HeaderFields.path] == bm.TX_PATH
|
||||
assert signal.body == (bm.GATT_CHARACTERISTIC_IFACE, {"Value": ("ay", b"\x05\x06")}, [])
|
||||
|
||||
def test_notify_reports_what_was_not_sent(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
bus.dead = True
|
||||
assert not manager.notify(b"\x05")
|
||||
|
||||
manager._conn = None
|
||||
assert not manager.notify(b"\x05")
|
||||
|
||||
def test_disconnect(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager.disconnect(DEVICE)
|
||||
|
||||
assert disconnects(bus) == [DEVICE]
|
||||
assert bus.sent[-1].header.fields[HeaderFields.interface] == bm.DEVICE_IFACE
|
||||
|
||||
|
||||
class TestReconcile(OpenpilotTestCase):
|
||||
def test_setup_order(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.calls() == SETUP
|
||||
assert bus.props == {"Powered": True, "Pairable": False, "Alias": "comma", "DiscoverableTimeout": 0, "Discoverable": True}
|
||||
|
||||
def test_set_enabled_writes_only_on_change(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager.set_enabled(False)
|
||||
manager._reconcile()
|
||||
assert manager._params.puts == []
|
||||
|
||||
manager.set_enabled(True)
|
||||
manager.set_enabled(True)
|
||||
assert manager._params.puts == ["BluetoothEnabled"]
|
||||
assert manager._params.data["BluetoothEnabled"] is True
|
||||
|
||||
def test_disabled_does_nothing(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager._reconcile()
|
||||
|
||||
assert not manager.ready
|
||||
assert bus.calls() == []
|
||||
|
||||
def test_waits_for_adapter(self, mocker):
|
||||
manager, bus = make(mocker, adapter=False)
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
assert not manager.ready
|
||||
|
||||
bus.adapter = True
|
||||
manager._reconcile()
|
||||
assert manager.ready
|
||||
|
||||
def test_never_advertises_while_bondable(self, mocker):
|
||||
manager, bus = make(mocker, failing=("Pairable",))
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
|
||||
assert not manager.ready
|
||||
assert "Powered" not in bus.calls()
|
||||
assert "RegisterAdvertisement" not in bus.calls()
|
||||
|
||||
def test_never_powers_on_under_the_hostname(self, mocker):
|
||||
manager, bus = make(mocker, failing=("Alias",))
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
|
||||
assert not manager.ready
|
||||
assert "Powered" not in bus.calls()
|
||||
|
||||
def test_failed_registration_is_rolled_back(self, mocker):
|
||||
manager, bus = make(mocker, failing=("RegisterAdvertisement",))
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
|
||||
assert not manager.ready
|
||||
assert bus.calls()[-2:] == ["UnregisterAdvertisement", "UnregisterApplication"]
|
||||
|
||||
def test_healthy_adapter_costs_one_call(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.calls() == ["GetManagedObjects"]
|
||||
|
||||
def test_registers_again_after_power_loss(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.props["Powered"] = False
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.calls() == SETUP
|
||||
|
||||
def test_registers_again_when_made_pairable(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.props["Pairable"] = True
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.calls() == SETUP
|
||||
assert not bus.props["Pairable"]
|
||||
|
||||
def test_registers_again_after_bluetoothd_restart(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.restart_bluetoothd()
|
||||
assert bus.props["Powered"]
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.calls() == SETUP
|
||||
assert bus.registered == {bm.APP_PATH, bm.ADVERTISEMENT_PATH}
|
||||
|
||||
def test_paired_device_is_removed_before_advertising(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.props["Pairable"] = True
|
||||
bus.devices[DEVICE] = {"Connected": False, "Paired": True}
|
||||
manager._reconcile()
|
||||
|
||||
assert manager.ready
|
||||
assert bus.devices == {}
|
||||
calls = bus.calls()
|
||||
assert calls.index("Powered") < calls.index("RemoveDevice") < calls.index("RegisterApplication")
|
||||
|
||||
def test_registers_again_after_release(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
from_bluez(manager, bus, bm.ADVERTISEMENT_PATH, bm.ADVERTISEMENT_IFACE, "Release")
|
||||
assert not manager.ready
|
||||
|
||||
manager._reconcile()
|
||||
assert manager.ready
|
||||
|
||||
def test_disable_powers_off_before_the_param_clears(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
manager.set_enabled(False)
|
||||
assert manager._params.data["BluetoothEnabled"] is True
|
||||
|
||||
manager._reconcile()
|
||||
assert not manager.ready
|
||||
assert bus.calls() == TEARDOWN
|
||||
assert not bus.props["Powered"] and not bus.props["Discoverable"]
|
||||
assert manager._params.data["BluetoothEnabled"] is False
|
||||
assert not bus.adapter
|
||||
|
||||
manager._reconcile()
|
||||
assert bus.calls() == TEARDOWN
|
||||
assert manager._params.puts.count("BluetoothEnabled") == 2
|
||||
|
||||
def test_tick_runs_while_bluetoothd_does_not_answer(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.hung = True
|
||||
manager._reconcile()
|
||||
|
||||
manager._on_tick.assert_called_once_with()
|
||||
|
||||
def test_unanswered_reconcile_keeps_the_adapter_for_teardown(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
bus.hung = True
|
||||
manager._reconcile()
|
||||
assert manager.ready
|
||||
|
||||
bus.hung = False
|
||||
bus.sent.clear()
|
||||
manager.set_enabled(False)
|
||||
manager._reconcile()
|
||||
assert bus.calls() == TEARDOWN
|
||||
assert not bus.props["Powered"]
|
||||
|
||||
def test_stop_abandons_a_waiting_call(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
mocker.patch.object(bm, "CALL_TIMEOUT", 5.0)
|
||||
mocker.patch.object(manager, "_on_tick", side_effect=manager.stop)
|
||||
bus.hung = True
|
||||
started = time.monotonic()
|
||||
manager._reconcile()
|
||||
|
||||
assert time.monotonic() - started < 1.0
|
||||
|
||||
def test_stop_skips_the_remaining_setup_steps(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
send = bus.send
|
||||
|
||||
def stop_after_alias(msg, serial=None):
|
||||
send(msg, serial)
|
||||
if msg.body[1:2] == ("Alias",):
|
||||
manager.stop()
|
||||
mocker.patch.object(bus, "send", side_effect=stop_after_alias)
|
||||
manager.set_enabled(True)
|
||||
manager._reconcile()
|
||||
|
||||
assert not manager.ready
|
||||
assert bus.calls()[-1] == "Alias"
|
||||
|
||||
def test_connected_devices(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
mocker.patch.object(manager, "_on_disconnect", side_effect=ValueError)
|
||||
bus.devices[DEVICE] = {"Connected": True, "Paired": False}
|
||||
manager._reconcile()
|
||||
assert manager.connected == {DEVICE}
|
||||
manager._on_disconnect.assert_not_called()
|
||||
|
||||
bus.devices[DEVICE]["Connected"] = False
|
||||
manager._reconcile()
|
||||
assert manager.connected == frozenset()
|
||||
manager._on_disconnect.assert_called_once_with(DEVICE)
|
||||
assert manager.ready
|
||||
|
||||
def test_device_seen_only_by_its_write_is_reported_gone(self, mocker):
|
||||
manager, bus = make_ready(mocker)
|
||||
write(manager, bus, b"\x01")
|
||||
manager._reconcile()
|
||||
|
||||
manager._on_disconnect.assert_called_once_with(DEVICE)
|
||||
|
||||
def test_serves_bluez_while_waiting_for_a_reply(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
bus.inbox.append(incoming(bm.APP_PATH, bm.OBJECT_MANAGER_IFACE, "GetManagedObjects"))
|
||||
|
||||
assert manager._call(new_method_call(DBusAddress(ADAPTER, bm.BLUEZ, bm.GATT_MANAGER_IFACE), "RegisterApplication", "oa{sv}", (bm.APP_PATH, {}))) == ()
|
||||
assert bus.sent[-1].header.fields[HeaderFields.reply_serial] == 1000
|
||||
|
||||
|
||||
class TestRun(OpenpilotTestCase):
|
||||
def run_manager(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
manager._conn = None
|
||||
mocker.patch.object(bm, "open_dbus_connection", return_value=bus)
|
||||
mocker.patch.object(bm, "RECONCILE_PERIOD", 0)
|
||||
manager.set_enabled(True)
|
||||
return manager, bus
|
||||
|
||||
def test_stop_powers_off_and_closes(self, mocker):
|
||||
manager, bus = self.run_manager(mocker)
|
||||
manager._on_tick.side_effect = manager.stop
|
||||
manager.run()
|
||||
|
||||
manager._on_tick.assert_called_once_with()
|
||||
assert bus.calls() == SETUP + TEARDOWN
|
||||
assert not bus.props["Powered"] and not bus.props["Discoverable"]
|
||||
assert bus.closed
|
||||
assert not manager.ready
|
||||
assert not manager.notify(b"\x05")
|
||||
|
||||
def test_dead_bus_still_closes(self, mocker):
|
||||
manager, bus = self.run_manager(mocker)
|
||||
manager._on_tick.side_effect = lambda: setattr(bus, "dead", True)
|
||||
|
||||
with self.assertRaises(ConnectionResetError):
|
||||
manager.run()
|
||||
assert bus.closed
|
||||
assert manager._conn is None
|
||||
assert not manager.ready
|
||||
|
||||
def test_calls_are_short_once_stopping(self, mocker):
|
||||
manager, bus = make(mocker)
|
||||
mocker.patch.object(bm, "CALL_TIMEOUT", 5.0)
|
||||
manager.stop()
|
||||
manager._call(new_method_call(DBusAddress(ADAPTER, bm.BLUEZ, bm.GATT_MANAGER_IFACE), "UnregisterApplication", "o", (bm.APP_PATH,)))
|
||||
|
||||
assert 0 < bus.timeout <= bm.STOP_CALL_TIMEOUT
|
||||
|
||||
def test_failing_tick_keeps_running(self, mocker):
|
||||
manager, bus = self.run_manager(mocker)
|
||||
|
||||
def tick():
|
||||
if manager._on_tick.call_count == 1:
|
||||
raise ValueError
|
||||
manager.stop()
|
||||
manager._on_tick.side_effect = tick
|
||||
manager.run()
|
||||
|
||||
assert manager._on_tick.call_count == 2
|
||||
assert bus.closed
|
||||
|
||||
|
||||
def make_daemon(mocker: Mocker, **values):
|
||||
mocker.patch.object(cp, "qr_text", return_value="SLC1:qr")
|
||||
mocker.patch.object(bm, "grant_count", return_value=0)
|
||||
params = FakeParams({"BluetoothAllowed": True} | values)
|
||||
bt = mocker.patch.object(bm, "BluetoothManager").return_value
|
||||
bt.ready = False
|
||||
return bm.Daemon(params, cp.ConnectPhoneWindow()), params, bt
|
||||
|
||||
|
||||
def request(params: FakeParams, action: str, seq: int):
|
||||
params.data[cp.REQUEST_KEY] = {"seq": seq, "action": action}
|
||||
|
||||
|
||||
class TestDaemon(OpenpilotTestCase):
|
||||
def test_open_then_ready(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
request(params, "open", 7)
|
||||
daemon.step(100.0)
|
||||
|
||||
assert cp.REQUEST_KEY not in params.data
|
||||
window = params.data[cp.WINDOW_KEY]
|
||||
assert (window["seq"], window["state"], window["qr"], window["deadline"]) == (7, "starting", "SLC1:qr", 100.0 + cp.WINDOW_SECONDS)
|
||||
bt.set_enabled.assert_called_with(True)
|
||||
|
||||
bt.ready = True
|
||||
daemon.step(101.0)
|
||||
assert params.data[cp.WINDOW_KEY]["state"] == "open"
|
||||
|
||||
def test_window_is_written_only_when_it_changes(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
daemon.step(100.0)
|
||||
daemon.step(101.0)
|
||||
assert params.puts == [cp.WINDOW_KEY, bm.STATUS_KEY]
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 0, "state": "closed", "reason": "", "prompt": None}
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_cancel(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
request(params, "open", 7)
|
||||
daemon.step(100.0)
|
||||
request(params, "cancel", 8)
|
||||
daemon.step(101.0)
|
||||
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 7, "state": "closed", "reason": "cancel", "prompt": None}
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_not_opened_while_bluetooth_is_off(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker, BluetoothAllowed=False)
|
||||
request(params, "open", 7)
|
||||
daemon.step(100.0)
|
||||
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 7, "state": "closed", "reason": "bluetooth_off"}
|
||||
cp.qr_text.assert_not_called()
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_turning_bluetooth_off_closes_the_window(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
request(params, "open", 7)
|
||||
daemon.step(100.0)
|
||||
params.data["BluetoothAllowed"] = False
|
||||
daemon.step(101.0)
|
||||
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 7, "state": "closed", "reason": "bluetooth_off", "prompt": None}
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_missing_device_key(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
cp.qr_text.side_effect = RuntimeError
|
||||
request(params, "open", 7)
|
||||
daemon.step(100.0)
|
||||
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 7, "state": "closed", "reason": "no_key"}
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
cp.qr_text.side_effect = ValueError
|
||||
request(params, "open", 8)
|
||||
daemon.step(101.0)
|
||||
assert params.data[cp.WINDOW_KEY] == {"seq": 8, "state": "closed", "reason": "error"}
|
||||
|
||||
cp.qr_text.side_effect = None
|
||||
request(params, "open", 9)
|
||||
daemon.step(102.0)
|
||||
assert params.data[cp.WINDOW_KEY]["state"] == "starting"
|
||||
|
||||
def test_a_grant_keeps_bluetooth_on_without_a_window(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
mocker.patch.object(bm, "grant_count", return_value=1)
|
||||
daemon.step(100.0)
|
||||
bt.set_enabled.assert_called_with(True)
|
||||
|
||||
params.data["BluetoothAllowed"] = False
|
||||
daemon.step(101.0)
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_enable_is_written_again_once_without_an_adapter(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
mocker.patch.object(bm, "grant_count", return_value=1)
|
||||
for now in (100.0, 109.9):
|
||||
daemon.step(now)
|
||||
assert "BluetoothEnabled" not in params.puts
|
||||
|
||||
for now in (110.0, 111.0, 130.0):
|
||||
daemon.step(now)
|
||||
assert params.puts.count("BluetoothEnabled") == 1
|
||||
|
||||
bt.ready = True
|
||||
daemon.step(131.0)
|
||||
bt.ready = False
|
||||
for now in (132.0, 142.0):
|
||||
daemon.step(now)
|
||||
assert params.puts.count("BluetoothEnabled") == 2
|
||||
|
||||
def test_write_disconnects_the_phone(self, mocker):
|
||||
daemon, params, bt = make_daemon(mocker)
|
||||
daemon.on_write(DEVICE, b"\x01", 247)
|
||||
|
||||
bt.disconnect.assert_called_once_with(DEVICE)
|
||||
|
||||
def run_main(self, mocker, runs: list):
|
||||
handlers = mocker.patch.object(bm.signal, "signal")
|
||||
params = FakeParams({"BluetoothAllowed": True})
|
||||
mocker.patch.object(bm, "Params", return_value=params)
|
||||
mocker.patch.object(bm, "RESTART_BACKOFF", 0.03)
|
||||
mocker.patch.object(bm, "RECONCILE_PERIOD", 0.01)
|
||||
mocker.patch.object(bm, "grant_count", return_value=0)
|
||||
manager = mocker.patch.object(bm, "BluetoothManager")
|
||||
def run(*_):
|
||||
outcome = runs.pop(0)
|
||||
if outcome == "signal":
|
||||
handlers.call_args.args[1](signal.SIGTERM, None)
|
||||
else:
|
||||
raise outcome
|
||||
manager.return_value.run.side_effect = run
|
||||
bm.main()
|
||||
return manager, handlers, params
|
||||
|
||||
def test_main_wires_the_manager(self, mocker):
|
||||
manager, handlers, params = self.run_main(mocker, ["signal"])
|
||||
|
||||
bt = manager.return_value
|
||||
bt.run.assert_called_once_with()
|
||||
bt.stop.assert_called_once_with()
|
||||
assert [call.args[0] for call in handlers.call_args_list] == [signal.SIGINT, signal.SIGTERM]
|
||||
on_write, on_disconnect, on_tick = manager.call_args.args
|
||||
on_write(DEVICE, b"\x01", 247)
|
||||
bt.disconnect.assert_called_once_with(DEVICE)
|
||||
on_tick()
|
||||
bt.set_enabled.assert_called_with(False)
|
||||
|
||||
def test_main_replaces_a_failed_manager_and_keeps_ticking(self, mocker):
|
||||
manager, handlers, params = self.run_main(mocker, [ConnectionResetError(), ValueError(), "signal"])
|
||||
|
||||
assert manager.call_count == 3
|
||||
assert manager.return_value.run.call_count == 3
|
||||
assert params.puts == [cp.WINDOW_KEY, bm.STATUS_KEY]
|
||||
@@ -0,0 +1,269 @@
|
||||
"""
|
||||
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 base64
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
|
||||
from openpilot.common.test import Mocker, OpenpilotTestCase
|
||||
from openpilot.sunnypilot.system import connect_phone as cp
|
||||
|
||||
DEVICE = "/org/bluez/hci0/dev_4A_3B_2C_1D_0E_0F"
|
||||
|
||||
|
||||
class FakeParams:
|
||||
"""Stores JSON text like the real JSON params, so values that cannot be stored fail here too."""
|
||||
|
||||
def __init__(self):
|
||||
self.data: dict[str, str] = {}
|
||||
|
||||
def get(self, key, block=False, return_default=False):
|
||||
return json.loads(self.data[key]) if key in self.data else None
|
||||
|
||||
def put(self, key, value, block=False):
|
||||
self.data[key] = json.dumps(value)
|
||||
|
||||
def remove(self, key):
|
||||
self.data.pop(key, None)
|
||||
|
||||
|
||||
def use_key(mocker: Mocker) -> ec.EllipticCurvePrivateKey:
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption()).decode()
|
||||
mocker.patch.object(cp.BaseApi, "get_key_pair", return_value=("ES256", pem, "unused"))
|
||||
return key
|
||||
|
||||
|
||||
def spki_hash(key: ec.EllipticCurvePrivateKey) -> bytes:
|
||||
return hashlib.sha256(key.public_key().public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)).digest()
|
||||
|
||||
|
||||
class TestCode(OpenpilotTestCase):
|
||||
def test_refused_codes_are_redrawn(self, mocker):
|
||||
randbelow = mocker.patch.object(cp.secrets, "randbelow", side_effect=[11111110, 88888887, 12345677, 87654320, 0])
|
||||
|
||||
assert cp.generate_code() == 1
|
||||
assert randbelow.call_args_list == [mocker.call(99_999_998)] * 5
|
||||
|
||||
def test_highest_code(self, mocker):
|
||||
mocker.patch.object(cp.secrets, "randbelow", return_value=99_999_997)
|
||||
|
||||
assert cp.generate_code() == 99_999_998
|
||||
|
||||
def test_format(self):
|
||||
assert cp.format_code(12345679) == "1234 5679"
|
||||
assert cp.format_code(1) == "0000 0001"
|
||||
|
||||
|
||||
class TestQr(OpenpilotTestCase):
|
||||
def test_device_key_hash_is_sha256_of_spki(self, mocker):
|
||||
key = use_key(mocker)
|
||||
|
||||
assert cp.device_key_hash() == spki_hash(key)
|
||||
|
||||
def test_missing_device_key_raises(self, mocker):
|
||||
mocker.patch.object(cp.BaseApi, "get_key_pair", return_value=(None, None, None))
|
||||
|
||||
with self.assertRaises(RuntimeError):
|
||||
cp.device_key_hash()
|
||||
|
||||
def test_payload(self, mocker):
|
||||
key = use_key(mocker)
|
||||
text = cp.qr_text(1234, b"\xaa" * 8)
|
||||
|
||||
assert text.startswith("SLC1:") and len(text) == 64
|
||||
payload = base64.urlsafe_b64decode(text[5:] + "=")
|
||||
assert payload == (1234).to_bytes(4, "big") + spki_hash(key) + b"\xaa" * 8
|
||||
|
||||
|
||||
class TestWindow(OpenpilotTestCase):
|
||||
def test_open_starts_then_reports_ready(self, mocker):
|
||||
use_key(mocker)
|
||||
mocker.patch.object(cp, "generate_code", return_value=42)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
|
||||
assert window.state() == {"seq": 0, "state": "closed", "reason": ""}
|
||||
assert window.open(1000.0, seq=7) == "ok"
|
||||
assert window.active
|
||||
state = window.state()
|
||||
assert state == {"seq": 7, "state": "starting", "code": "00000042", "qr": state["qr"],
|
||||
"deadline": 1000.0 + cp.WINDOW_SECONDS, "held": False, "reason": ""}
|
||||
assert state["qr"].startswith("SLC1:")
|
||||
|
||||
window.tick(1001.0, ready=False)
|
||||
assert window.state()["state"] == "starting"
|
||||
window.tick(1002.0)
|
||||
assert window.state()["state"] == "open"
|
||||
|
||||
def test_same_request_again_changes_nothing(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0, seq=1)
|
||||
first = window.state()
|
||||
|
||||
assert window.open(1050.0, seq=1) == "busy"
|
||||
assert window.state() == first
|
||||
|
||||
def test_new_request_replaces_the_open_window(self, mocker):
|
||||
use_key(mocker)
|
||||
mocker.patch.object(cp, "generate_code", side_effect=[11, 22])
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0, seq=1)
|
||||
window.tick(1001.0)
|
||||
first = window.state()
|
||||
|
||||
assert window.open(1050.0, seq=2) == "ok"
|
||||
second = window.state()
|
||||
assert second == {"seq": 2, "state": "starting", "code": "00000022", "qr": second["qr"],
|
||||
"deadline": 1050.0 + cp.WINDOW_SECONDS, "held": False, "reason": ""}
|
||||
assert second["qr"] != first["qr"]
|
||||
|
||||
def test_closes_itself_after_the_window(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0)
|
||||
window.tick(1004.0)
|
||||
|
||||
window.tick(1004.0 + cp.WINDOW_SECONDS - 0.1)
|
||||
assert window.active
|
||||
window.tick(1004.0 + cp.WINDOW_SECONDS)
|
||||
assert not window.active
|
||||
assert window.state() == {"seq": 0, "state": "closed", "reason": "timeout"}
|
||||
|
||||
def test_full_time_counts_from_ready(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0)
|
||||
window.tick(1003.0, ready=False)
|
||||
window.tick(1005.0)
|
||||
assert window.state()["deadline"] == 1005.0 + cp.WINDOW_SECONDS
|
||||
window.tick(1006.0, ready=False)
|
||||
window.tick(1007.0)
|
||||
assert window.state()["deadline"] == 1005.0 + cp.WINDOW_SECONDS
|
||||
|
||||
def test_held_window_does_not_time_out(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0)
|
||||
window.tick(1000.0)
|
||||
window.hold()
|
||||
window.tick(1000.0 + cp.WINDOW_SECONDS + 60)
|
||||
assert window.active
|
||||
window.cancel("granted")
|
||||
assert window.state()["reason"] == "granted"
|
||||
|
||||
def test_cancel(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.cancel()
|
||||
assert window.state()["reason"] == ""
|
||||
|
||||
window.open(1000.0)
|
||||
window.cancel()
|
||||
assert window.state() == {"seq": 0, "state": "closed", "reason": "cancel"}
|
||||
|
||||
window.open(1000.0)
|
||||
window.cancel("bluetooth_off")
|
||||
assert window.state() == {"seq": 0, "state": "closed", "reason": "bluetooth_off"}
|
||||
|
||||
def test_reopen_draws_a_new_code_and_nonce(self, mocker):
|
||||
use_key(mocker)
|
||||
mocker.patch.object(cp, "generate_code", side_effect=[11, 22])
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0)
|
||||
first = window.state()
|
||||
window.cancel()
|
||||
|
||||
assert window.open(1010.0) == "ok"
|
||||
second = window.state()
|
||||
assert (first["code"], second["code"]) == ("00000011", "00000022")
|
||||
assert first["qr"] != second["qr"]
|
||||
assert second["deadline"] == 1010.0 + cp.WINDOW_SECONDS
|
||||
|
||||
def test_missing_device_key_leaves_the_window_closed(self, mocker):
|
||||
mocker.patch.object(cp.BaseApi, "get_key_pair", return_value=(None, None, None))
|
||||
window = cp.ConnectPhoneWindow()
|
||||
|
||||
with self.assertRaises(RuntimeError):
|
||||
window.open(1000.0)
|
||||
assert not window.active
|
||||
|
||||
def test_secret_only_while_open(self, mocker):
|
||||
use_key(mocker)
|
||||
window = cp.ConnectPhoneWindow()
|
||||
|
||||
assert cp.PAKE_SUITE == 1
|
||||
assert window.secret() is None
|
||||
window.open(1000.0)
|
||||
digits, nonce = window.secret()
|
||||
assert len(digits) == 8 and digits.isdigit() and len(nonce) == 8
|
||||
window.cancel()
|
||||
assert window.secret() is None
|
||||
|
||||
|
||||
class TestParams(OpenpilotTestCase):
|
||||
def test_request(self):
|
||||
params = FakeParams()
|
||||
|
||||
first = cp.write_request(params, "open")
|
||||
assert params.get(cp.REQUEST_KEY) == {"seq": first, "action": "open"}
|
||||
second = cp.write_request(params, "cancel")
|
||||
assert second > first
|
||||
assert params.get(cp.REQUEST_KEY) == {"seq": second, "action": "cancel"}
|
||||
|
||||
def test_unknown_action_is_refused(self):
|
||||
params = FakeParams()
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
cp.write_request(params, "bogus")
|
||||
assert params.data == {}
|
||||
|
||||
def test_window_round_trip(self, mocker):
|
||||
use_key(mocker)
|
||||
params = FakeParams()
|
||||
assert cp.read_window(params) is None
|
||||
|
||||
window = cp.ConnectPhoneWindow()
|
||||
window.open(1000.0, seq=5)
|
||||
params.put(cp.WINDOW_KEY, window.state())
|
||||
assert cp.read_window(params) == window.state()
|
||||
|
||||
def test_remove_request_carries_the_phone(self):
|
||||
params = FakeParams()
|
||||
|
||||
seq = cp.write_request(params, "remove", phone="abc")
|
||||
assert params.get(cp.REQUEST_KEY) == {"seq": seq, "action": "remove", "phone": "abc"}
|
||||
|
||||
def test_status_and_indicator(self):
|
||||
params = FakeParams()
|
||||
assert cp.read_status(params) == {}
|
||||
assert cp.phone_indicator({}) == "hidden"
|
||||
|
||||
params.put(cp.STATUS_KEY, {"enabled": True, "connected": 0, "phones": 1})
|
||||
assert cp.phone_indicator(cp.read_status(params)) == "waiting"
|
||||
params.put(cp.STATUS_KEY, {"enabled": True, "connected": 2, "phones": 1})
|
||||
assert cp.phone_indicator(cp.read_status(params)) == "connected"
|
||||
params.put(cp.STATUS_KEY, {"enabled": False, "connected": 0, "phones": 0})
|
||||
assert cp.phone_indicator(cp.read_status(params)) == "hidden"
|
||||
|
||||
def test_no_grants_yet(self, mocker):
|
||||
mocker.patch.object(cp, "Params", return_value=FakeParams())
|
||||
assert cp.grant_count() == 0
|
||||
|
||||
|
||||
class TestDisplayName(OpenpilotTestCase):
|
||||
def test_dongle_id_then_serial(self):
|
||||
params = FakeParams()
|
||||
assert cp.display_name(params) == "comma"
|
||||
params.put("HardwareSerial", "a1b2c3d4")
|
||||
assert cp.display_name(params) == "comma a1b2"
|
||||
params.put("DongleId", cp.UNREGISTERED_DONGLE_ID)
|
||||
assert cp.display_name(params) == "comma a1b2"
|
||||
params.put("DongleId", "3f12aa0000000000")
|
||||
assert cp.display_name(params) == "comma 3f12"
|
||||
@@ -185,6 +185,8 @@ procs += [
|
||||
PythonProcess("mapd_manager", "openpilot.sunnypilot.mapd.mapd_manager", always_run),
|
||||
|
||||
PythonProcess("gps_fuser", "openpilot.sunnypilot.selfdrive.locationd.gps_fuser", only_onroad),
|
||||
|
||||
PythonProcess("bluetooth_manager", "openpilot.sunnypilot.system.bluetooth_manager", always_run, enabled=not PC),
|
||||
]
|
||||
|
||||
if os.path.exists("../../sunnypilot/sunnylink/uploader.py"):
|
||||
|
||||
@@ -302,6 +302,10 @@ class WifiManager:
|
||||
wifi_state = self._wifi_state
|
||||
return wifi_state.ssid if wifi_state.status == ConnectStatus.CONNECTED else None
|
||||
|
||||
@property
|
||||
def tethering_ssid(self) -> str:
|
||||
return self._tethering_ssid
|
||||
|
||||
@property
|
||||
def tethering_password(self) -> str:
|
||||
return self._tethering_password
|
||||
|
||||
Reference in New Issue
Block a user