#include "link_service.hpp" #include "link_fragment.hpp" #include "simple_ble.hpp" #include "serial_link.hpp" #include #include namespace microbu { namespace { const char* TAG = "link"; } LinkService::LinkService(Station& station) : station_(station) { station_.on_indication([this](const link::BtpDataIndication& indication) { broadcast(link::Opcode::BTP_DATA_INDICATION, ++own_sequence_, link::encode(indication)); }); station_.on_raw_frame([this](const link::Bytes& body) { if (raw_transport_ == LinkTransport::ble && !ble::connected()) return; send_fragmented(raw_transport_, link::Opcode::RAW_FRAME, ++own_sequence_, body); }); // MicrOBU: every ITS message heard on air, verified or not (Station::on_raw_its). station_.on_raw_its([this](const link::Bytes& body) { return broadcast(link::Opcode::V2X_RX, ++own_sequence_, body); }); // T_GenVam is included in the status snapshot returned on request. station_.on_id_event([this](const link::IdChangeEvent& event) { // PREPARE/COMMIT responses match the subscription; their header sequence is unused. broadcast(link::Opcode::SF_IDCHANGE_EVENT, ++own_sequence_, link::encode(event)); }); } bool LinkService::send(LinkTransport transport, link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body, std::uint8_t flags) { link::Bytes octets; link::Message message {{opcode, flags, sequence}, body}; if (!link::encode(message, octets)) { ESP_LOGE(TAG, "message 0x%02x too long (%u)", unsigned(opcode), unsigned(body.size())); return false; } if (transport == LinkTransport::serial) { // Never wait for the host: RAW_FRAME and the fragments of a large V2X_RX are best effort, a stalled USB // host must not hold the station task that also drains the radio queue. A V2X_RX that fits one message // keeps the blocking write it always had. if (opcode == link::Opcode::RAW_FRAME || (opcode == link::Opcode::V2X_RX && flags != 0)) return serial::try_write(serial::FrameType::LINK, octets); return serial::write(serial::FrameType::LINK, octets); } return ble::write(octets); } bool LinkService::send_fragmented(LinkTransport transport, link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body) { const std::size_t limit = transport == LinkTransport::ble ? ble::max_message() : link::maximum_message; if (body.size() <= link::unfragmented_capacity(limit)) return send(transport, opcode, sequence, body); // A received message is never worth a flood of notifications: with a small ATT MTU (no exchange yet, 23) one // MAPEM would need dozens, so beyond max_received_fragments that transport skips the message. const std::size_t max_fragments = opcode == link::Opcode::V2X_RX ? max_received_fragments : 65535; std::vector fragments; if (!link::split_fragments(body, limit, fragments, max_fragments)) return false; for (const auto& fragment : fragments) { // The first failed fragment ends this message (the app drops the incomplete stream by itself); nothing is // retried, and nothing here waits for the transport. if (!send(transport, opcode, sequence, fragment.body, fragment.flags)) return false; } return true; } bool LinkService::broadcast(link::Opcode opcode, std::uint16_t sequence, const link::Bytes& body) { // Fragmented when needed: a MAPEM indication is larger than one message on either transport. const bool serial_taken = send_fragmented(LinkTransport::serial, opcode, sequence, body); const bool ble_taken = ble::connected() && send_fragmented(LinkTransport::ble, opcode, sequence, body); return serial_taken || ble_taken; } void LinkService::reply(LinkTransport transport, std::uint16_t sequence, link::Code code, const link::Bytes& detail) { send_fragmented(transport, link::Opcode::CONFIRM, sequence, link::encode(link::Confirm {code, detail})); } link::Status LinkService::status() { auto value = station_.status(); const auto serial_counters = serial::counters(); const auto ble_counters = ble::counters(); value.link_rx_frames = serial_counters.frames + ble_counters.rx_messages; value.link_crc_errors = serial_counters.crc_errors; value.link_malformed += ble_counters.malformed; value.battery_mv = battery_millivolts(); return value; } link::Code LinkService::provision_segment(const link::CredentialsProvision& c, link::Bytes& detail) { if (c.offset == 0) { bundle_.clear(); bundle_total_ = c.total_length; } if (c.total_length != bundle_total_ || c.offset != bundle_.size() || c.total_length > 8192) { bundle_.clear(); return link::Code::malformed; } bundle_.insert(bundle_.end(), c.segment.begin(), c.segment.end()); if (bundle_.size() < bundle_total_) return link::Code::accepted; link::ApplyReport report; link::Code result = link::Code::accepted; try { result = station_.provision(bundle_, report); } catch (const std::exception& e) { ESP_LOGE(TAG, "provision exception: %s", e.what()); result = link::Code::invalid_argument; } bundle_.clear(); detail = {static_cast(report.roots), static_cast(report.authorities), static_cast(report.tickets)}; return result; } void LinkService::handle(const link::Bytes& octets, LinkTransport origin) { link::Message m; if (!link::decode(octets, m)) return; auto joined = request_reassembly_.feed(m, unsigned(origin), esp_timer_get_time() / 1000); if (request_reassembly_.take_overflow()) { // Every request gets a CONFIRM, also one too large to join. ESP_LOGW(TAG, "request 0x%02x exceeds %u octets", unsigned(m.header.opcode), unsigned(link::maximum_request_body)); reply(origin, m.header.sequence, link::Code::resource_limit); return; } if (!joined) return; m = std::move(*joined); // Every request gets a CONFIRM: an exception below (e.g. a certificate the codec cannot read) is answered with // rejected instead of leaving the phone waiting for a reply that never comes. try { dispatch(m, origin); } catch (const std::bad_alloc&) { ESP_LOGE(TAG, "out of memory handling opcode 0x%02x", unsigned(m.header.opcode)); reply(origin, m.header.sequence, link::Code::resource_limit); } catch (const std::exception& e) { ESP_LOGE(TAG, "opcode 0x%02x failed: %s", unsigned(m.header.opcode), e.what()); reply(origin, m.header.sequence, link::Code::rejected); } } void LinkService::dispatch(const link::Message& m, LinkTransport origin) { const auto seq = m.header.sequence; using link::Opcode; using link::Code; switch (m.header.opcode) { case Opcode::STATION_CONFIGURE: { link::StationConfigure c; if (!link::decode(m.body, c)) return reply(origin, seq, Code::malformed); link::Bytes detail; const auto result = station_.configure(c, detail); ESP_LOGI(TAG, "station configured: security %u, radio %u, result %d", unsigned(c.security), unsigned(c.radio), int(result)); return reply(origin, seq, result, detail); } case Opcode::POTI_UPDATE: { link::PotiUpdate p; if (!link::decode(m.body, p)) return reply(origin, seq, Code::malformed); const auto result = station_.poti(p); if (result != Code::accepted) reply(origin, seq, result); // accepted updates are silent return; } case Opcode::BTP_DATA_REQUEST: { link::BtpDataRequest q; if (!link::decode(m.body, q)) return reply(origin, seq, Code::malformed); return reply(origin, seq, station_.btp_request(q)); } case Opcode::CREDENTIALS_PROVISION: { link::CredentialsProvision c; if (!link::decode(m.body, c)) return reply(origin, seq, Code::malformed); link::Bytes detail; const auto result = provision_segment(c, detail); return reply(origin, seq, result, detail); } case Opcode::CREDENTIALS_ERASE: return reply(origin, seq, station_.erase_credentials()); case Opcode::SF_IDCHANGE_SUBSCRIBE: { link::Reader r(m.body); const auto data = r.bytes(r.u8()); if (!r.done()) { ESP_LOGW(TAG, "SF_IDCHANGE_SUBSCRIBE malformed (len=%u)", (unsigned)m.body.size()); return reply(origin, seq, Code::malformed); } std::uint64_t handle = 0; const auto result = station_.subscribe(data, handle); ESP_LOGI(TAG, "SF_IDCHANGE_SUBSCRIBE handle=%llu result=%d", (unsigned long long)handle, int(result)); link::Writer w; w.u64(handle); return reply(origin, seq, result, result == Code::accepted ? w.out : link::Bytes {}); } case Opcode::SF_IDCHANGE_UNSUBSCRIBE: { link::Reader r(m.body); const auto handle = r.u64(); if (!r.done()) return reply(origin, seq, Code::malformed); return reply(origin, seq, station_.unsubscribe(handle)); } case Opcode::SF_IDCHANGE_EVENT_RESPONSE: { link::IdChangeEventResponse e; if (!link::decode(m.body, e)) return; // no reply defined for a response station_.event_response(e.subscription, e.return_code != 0); return; } case Opcode::SF_IDCHANGE_TRIGGER: return reply(origin, seq, station_.trigger()); case Opcode::SF_ID_LOCK: { link::Reader r(m.body); const auto seconds = r.u8(); if (!r.done()) return reply(origin, seq, Code::malformed); std::uint64_t handle = 0; const auto result = station_.lock(seconds, handle); link::Writer w; w.u64(handle); return reply(origin, seq, result, result == Code::accepted ? w.out : link::Bytes {}); } case Opcode::SF_ID_UNLOCK: { link::Reader r(m.body); const auto handle = r.u64(); if (!r.done()) return reply(origin, seq, Code::malformed); return reply(origin, seq, station_.unlock(handle)); } case Opcode::STATUS_REQUEST: if (!m.body.empty()) return reply(origin, seq, Code::malformed); return reply(origin, seq, Code::accepted, link::encode(status())); case Opcode::RAW_CAPTURE: { link::Reader r(m.body); const auto mode = r.u8(); if (!r.done()) return reply(origin, seq, Code::malformed); const auto result = station_.raw_capture(mode); if (result == Code::accepted) raw_transport_ = origin; // frames go back over the requesting transport // measuring over USB: no BLE advertising events while capturing (they blind the shared radio) if (result == Code::accepted && origin == LinkTransport::serial) ble::set_advertising(!(mode & 0x01)); ESP_LOGI(TAG, "RAW_CAPTURE mode 0x%02x over %s: %d", unsigned(mode), origin == LinkTransport::ble ? "BLE" : "serial", int(result)); return reply(origin, seq, result); } case Opcode::PKI_TRUST_BOOTSTRAP: if (origin != LinkTransport::serial) return reply(origin, seq, Code::rejected); return reply(origin, seq, station_.pki_trust_bootstrap(m.body)); case Opcode::PKI_TRUST_UPDATE: { link::Reader reader(m.body); const auto total = reader.u16(), offset = reader.u16(); const auto segment = reader.rest(); if (!reader.ok() || !total || total > 60000 || segment.empty() || segment.size() > total) return reply(origin, seq, Code::malformed); if (offset == 0) { trust_update_.clear(); trust_total_ = total; } if (total != trust_total_ || offset != trust_update_.size() || segment.size() > total - offset) { trust_update_.clear(); return reply(origin, seq, Code::malformed); } trust_update_.insert(trust_update_.end(), segment.begin(), segment.end()); if (trust_update_.size() < total) return reply(origin, seq, Code::accepted); const auto result = station_.pki_trust_update(trust_update_); trust_update_.clear(); trust_update_.shrink_to_fit(); return reply(origin, seq, result); } case Opcode::PKI_STATUS: { if (!m.body.empty()) return reply(origin, seq, Code::malformed); link::Bytes detail; const auto result = station_.pki_status(detail); return reply(origin, seq, result, detail); } case Opcode::PKI_IDENTITY: { link::Bytes detail; const auto result = station_.pki_identity(detail); return reply(origin, seq, result, detail); } case Opcode::PKI_ENROL_REQUEST: case Opcode::PKI_AUTH_REQUEST: { const std::uint8_t kind = m.header.opcode == Opcode::PKI_ENROL_REQUEST ? 1 : 2; link::Bytes request; const auto result = station_.pki_request(kind, m.body, request); reply(origin, seq, result); if (result == Code::accepted) { // the encrypted request for the phone to relay, same sequence link::Bytes body {kind}; body.insert(body.end(), request.begin(), request.end()); send_fragmented(origin, Opcode::PKI_REQUEST_DATA, seq, body); } return; } case Opcode::PKI_CANCEL: { if (m.body.size() != 1) return reply(origin, seq, Code::malformed); return reply(origin, seq, station_.pki_cancel(m.body[0])); } case Opcode::PKI_RETRY: { if (m.body.size() != 1) return reply(origin, seq, Code::malformed); link::Bytes request; const auto result = station_.pki_retry(m.body[0], request); reply(origin, seq, result); if (result == Code::accepted) { link::Bytes body {m.body[0]}; body.insert(body.end(), request.begin(), request.end()); send_fragmented(origin, Opcode::PKI_REQUEST_DATA, seq, body); } return; } case Opcode::PKI_RESPONSE: { link::Reader r(m.body); const auto kind = r.u8(); const auto total = r.u16(); const auto offset = r.u16(); const auto segment = r.rest(); if (!r.ok() || total == 0 || total > 4096) return reply(origin, seq, Code::malformed); if (offset == 0) { pki_response_.clear(); pki_total_ = total; pki_kind_ = kind; } if (total != pki_total_ || kind != pki_kind_ || offset != pki_response_.size()) { pki_response_.clear(); return reply(origin, seq, Code::malformed); } pki_response_.insert(pki_response_.end(), segment.begin(), segment.end()); if (pki_response_.size() < pki_total_) return reply(origin, seq, Code::accepted); link::Bytes detail; const auto result = station_.pki_response(kind, pki_response_, detail); pki_response_.clear(); return reply(origin, seq, result, detail); } default: return reply(origin, seq, Code::unknown_opcode); } } } // namespace microbu