The firmware dropped every received ITS message over 494 bytes (one link message), so a road RSU's 888-byte SPATEM and 1198-byte MAPEM never reached the phone. V2X_RX now goes out in link fragments up to 2300 bytes, best effort and non-blocking; messages up to 494 bytes are unchanged. The app's SPATEM decoder then refused those messages because they carry intersection and movement names and advisory speed lists. It now reads past both, checked against asn1tools on 718 distinct messages. Adds the pure fragmenter with host tests and a pcap replay, a Kotlin cross-check on the firmware's own fragments, tools/rx_size_compare.py, docs/08-large-message-reception.md and station-link revision 3.
337 lines
17 KiB
C++
337 lines
17 KiB
C++
#pragma once
|
|
// The ESP32-C5 half of the VRU ITS-S: BTP-B, GeoNetworking, the SN-SAP
|
|
// security entity with the station's provisioned credentials, and the ITS-G5 access adapter.
|
|
// Everything here runs on one task (the station task).
|
|
#include "c5_radio.hpp"
|
|
#include "its_clock.hpp"
|
|
#include "link_protocol.hpp"
|
|
#include <microbu_v2x/stack.hpp>
|
|
#include <microbu_v2x/security.hpp>
|
|
#include <microbu_v2x/credentials.hpp>
|
|
#include <microbu_v2x/security_backend.hpp>
|
|
#include <vanetza/common/manual_runtime.hpp>
|
|
#include <vanetza/common/position_provider.hpp>
|
|
#include <deque>
|
|
#include <functional>
|
|
#include <map>
|
|
#include <memory>
|
|
#include <optional>
|
|
#include <utility>
|
|
|
|
namespace microbu {
|
|
|
|
|
|
/// @note All public members except the on_*() callback setters must be called from the station task.
|
|
class Station final : public microbu_v2x::Access, public vanetza::PositionProvider {
|
|
public:
|
|
using Indication = std::function<void(const link::BtpDataIndication&)>;
|
|
using IdEvent = std::function<void(const link::IdChangeEvent&)>;
|
|
using Disseminated = std::function<void()>;
|
|
using Received = std::function<void()>;
|
|
/// RAW_FRAME body (u32 counter, u8 flags, i8 RSSI, ITS5 record) for the link service.
|
|
using RawFrame = std::function<void(const link::Bytes&)>;
|
|
/// MicrOBU: body of one link V2X_RX message (see link_protocol.hpp). Returns whether a transport took it;
|
|
/// a body above one link message goes out in fragments, best effort (a false return is only counted).
|
|
using RawIts = std::function<bool(const link::Bytes&)>;
|
|
/// DCC_T_GEN_VAM body for the link service (TS 103 300-3 clause 6.2: T_GenVam from management).
|
|
using DccUpdate = std::function<void(const link::Bytes&)>;
|
|
|
|
/// @brief Constructs an unconfigured station (call configure() before use).
|
|
Station();
|
|
/// @brief Tears down the stack, security entity and radio in dependency order.
|
|
~Station() override;
|
|
|
|
// ---- link primitives (station task) ----
|
|
/// @brief (Re)builds the stack and security entity for a new station configuration.
|
|
/// @param config Requested configuration.
|
|
/// @param detail Receives the assigned GN address, identifier, and ticket count.
|
|
/// @return Result code.
|
|
link::Code configure(const link::StationConfigure& config, link::Bytes& detail);
|
|
|
|
/// @brief Applies a position/time fix from the phone and advances the ITS clock.
|
|
/// @param fix Position/time fix to apply.
|
|
/// @return Result code.
|
|
link::Code poti(const link::PotiUpdate& fix);
|
|
|
|
/// @brief Validates a BTP data request and queues it; signing and submission follow in
|
|
/// submit_pending(), so the CONFIRM does not wait for them. A request whose generated_at_ms lies more
|
|
/// than one packet lifetime in the past is refused as stale.
|
|
/// @param request Request to queue.
|
|
/// @return Result code (accepted = validated and queued).
|
|
link::Code btp_request(const link::BtpDataRequest& request);
|
|
|
|
/// @brief Signs and submits the queued BTP requests; call from the station task loop after replying.
|
|
void submit_pending();
|
|
|
|
/// @brief Decodes and stores a credential bundle, rebuilding the security entity if configured.
|
|
/// @param bundle Raw credential bundle bytes.
|
|
/// @param report Receives the applied root/authority/ticket counts.
|
|
/// @return Result code.
|
|
link::Code provision(const link::Bytes& bundle, link::ApplyReport& report);
|
|
|
|
/// @brief Erases stored credentials and rebuilds if security is configured.
|
|
/// @return Result code.
|
|
link::Code erase_credentials();
|
|
|
|
// ---- TS 102 941 V2.2.1 on the device : the micrOBU is the ITS-S security entity. It keeps its
|
|
// canonical key, generates its enrolment and ticket key pairs itself and builds the encrypted requests; the
|
|
// phone only relays the opaque requests and responses to the EA/AA. kind: 1 enrolment, 2 authorization.
|
|
/// @brief Canonical identifier and canonical public key (uncompressed point), generated once on the device.
|
|
link::Code pki_identity(link::Bytes& detail);
|
|
link::Code pki_status(link::Bytes& detail);
|
|
link::Code pki_trust_bootstrap(const link::Bytes&);
|
|
link::Code pki_trust_update(const link::Bytes&);
|
|
/// @brief Builds an EnrolmentRequest (body: EA HashedId8) or an AuthorizationRequest (body: EA and AA
|
|
/// HashedId8); `request` receives the encoded EtsiTs103097Data-Encrypted.
|
|
link::Code pki_request(std::uint8_t kind, const link::Bytes& body, link::Bytes& request);
|
|
/// @brief Decrypts and checks the EA/AA response of the outstanding request; stores the EC or the new ticket.
|
|
link::Code pki_retry(std::uint8_t kind, link::Bytes& request);
|
|
link::Code pki_cancel(std::uint8_t kind);
|
|
link::Code pki_response(std::uint8_t kind, const link::Bytes& response, link::Bytes& detail);
|
|
|
|
/// @brief Subscribes to pseudonym-change events.
|
|
/// @param subscriber_data Opaque data echoed back with events for this subscription.
|
|
/// @param subscription Receives the assigned subscription handle.
|
|
/// @return Result code.
|
|
link::Code subscribe(const link::Bytes& subscriber_data, std::uint64_t& subscription);
|
|
|
|
/// @brief Cancels a pseudonym-change subscription.
|
|
/// @param subscription Handle returned by subscribe().
|
|
/// @return Result code.
|
|
link::Code unsubscribe(std::uint64_t subscription);
|
|
|
|
/// @brief Resolves a pending PREPARE/COMMIT identity-change event.
|
|
/// @param subscription Handle the event was delivered for.
|
|
/// @param return_code Caller's response (accept/reject) to the pending event.
|
|
/// @return Result code.
|
|
link::Code event_response(std::uint64_t subscription, bool return_code);
|
|
|
|
/// @brief Triggers an immediate pseudonym change.
|
|
/// @return Result code.
|
|
link::Code trigger();
|
|
|
|
/// @brief Locks the current pseudonym for the given duration.
|
|
/// @param seconds Lock duration in seconds.
|
|
/// @param handle Receives the assigned lock handle.
|
|
/// @return Result code.
|
|
link::Code lock(std::uint8_t seconds, std::uint64_t& handle);
|
|
|
|
/// @brief Releases a pseudonym lock.
|
|
/// @param handle Handle returned by lock().
|
|
/// @return Result code.
|
|
link::Code unlock(std::uint64_t handle);
|
|
|
|
/// @return Current station status snapshot.
|
|
link::Status status();
|
|
|
|
/// @brief Advances the ITS clock, runs timers, polls the radio; call every few milliseconds.
|
|
void tick();
|
|
|
|
/// @brief Registers the callback invoked when a BTP data indication arrives.
|
|
/// @param f Callback to invoke; replaces any previously registered callback.
|
|
void on_indication(Indication f) { indication_ = std::move(f); }
|
|
|
|
/// @brief Registers the callback invoked when a pseudonym-change event fires.
|
|
/// @param f Callback to invoke; replaces any previously registered callback.
|
|
void on_id_event(IdEvent f) { id_event_ = std::move(f); }
|
|
|
|
/// @brief Registers the callback invoked after a frame is disseminated.
|
|
/// @param f Callback to invoke; replaces any previously registered callback.
|
|
void on_disseminated(Disseminated f) { disseminated_ = std::move(f); }
|
|
|
|
/// @brief Registers the callback invoked after a frame is received.
|
|
/// @param f Callback to invoke; replaces any previously registered callback.
|
|
void on_received(Received f) { received_ = std::move(f); }
|
|
|
|
/// @brief Switches the raw capture debug path (RAW_CAPTURE): every valid 802.11 frame the radio
|
|
/// receives (and, with C5Radio::capture_own_tx, transmits) goes to the phone as an ITS5 record,
|
|
/// like the OpenTrafficMap / V2X2Map receiver firmware. Needs a started radio unless mode is 0.
|
|
/// @param mode C5Radio capture mode bits; 0 switches it off.
|
|
/// @return Result code.
|
|
link::Code raw_capture(std::uint8_t mode);
|
|
|
|
/// @brief MicrOBU: registers the callback for every ITS message heard on air, unwrapped by
|
|
/// gn_unwrap.c before (and independently of) the stack's security checks. The stack drops what
|
|
/// it cannot verify (decapsulation is strict): unsigned traffic, and anything signed under a root
|
|
/// other than the provisioned one, i.e. every RSU. This path is how those still reach the phone.
|
|
/// @param f Callback to invoke with a V2X_RX body; replaces any previously registered callback.
|
|
void on_raw_its(RawIts f) { raw_its_ = std::move(f); }
|
|
|
|
/// @brief Registers the callback that sends one RAW_FRAME body to the phone.
|
|
void on_raw_frame(RawFrame f) { raw_frame_ = std::move(f); }
|
|
|
|
/// @brief Registers the callback that sends T_GenVam_DCC (DCC_T_GEN_VAM) to the phone's VBS.
|
|
void on_dcc_update(DccUpdate f) { dcc_update_ = std::move(f); }
|
|
|
|
|
|
// microbu_v2x::Access
|
|
/// @param request Frame and transmit parameters from the access layer.
|
|
/// @return Result code.
|
|
microbu_v2x::Result request(microbu_v2x::AlDataRequest request) override;
|
|
|
|
// vanetza::PositionProvider
|
|
/// @return The most recently applied position fix.
|
|
const vanetza::PositionFix& position_fix() override { return fix_; }
|
|
|
|
private:
|
|
struct Security;
|
|
struct Clock {
|
|
bool synchronised = false;
|
|
std::int64_t base_its_us = 0; // ITS time at base_esp_us
|
|
std::int64_t base_esp_us = 0;
|
|
std::int64_t slew_us = 0; // correction applied from base_esp_us on at 1/its_clock::slew_divisor
|
|
std::int64_t now_us() const;
|
|
std::int64_t remaining_slew_us() const;
|
|
};
|
|
|
|
/// @brief (Re)builds the stack and security entity from config_, stored credentials and the clock.
|
|
/// @return Result code.
|
|
link::Code build();
|
|
|
|
/// @brief Destroys the stack, security entity and runtime in dependency order.
|
|
void teardown();
|
|
|
|
/// @brief Maps a station configuration onto the GeoNetworking MIB.
|
|
/// @param mib MIB to populate.
|
|
/// @param config Station configuration to map from.
|
|
void apply_mib(microbu_v2x::StackConfig& mib, const link::StationConfigure& config) const;
|
|
|
|
/// @brief Re-subscribes existing pseudonym-change handles to a freshly built security entity.
|
|
void resubscribe_id_change();
|
|
|
|
/// @brief Subscribes one link handle to the identity manager's change events.
|
|
/// @param handle Link subscription handle echoed in every SF_IDCHANGE_EVENT.
|
|
/// @param subscriber_data Opaque data passed back with the events.
|
|
/// @return The identity manager's service handle.
|
|
std::uint64_t subscribe_id_change(std::uint64_t handle, const link::Bytes& subscriber_data);
|
|
|
|
/// @brief The security module holding the station's keys, created on first use.
|
|
/// @return nullptr when it cannot be opened (logged); secured operation is then refused.
|
|
microbu_v2x::security::SecurityModule* module();
|
|
|
|
/// @brief Loads the stored credentials into a fresh security entity (station task, NVS access).
|
|
/// @return false without a security module.
|
|
bool load_security();
|
|
|
|
/// @brief Builds the security entity on the loaded set and carries the subscriptions over.
|
|
void new_entity();
|
|
|
|
/// @brief Replaces the stored credentials; destroys the module keys only the old set referenced.
|
|
microbu_v2x::Result store_credentials(const microbu_v2x::security::StoredCredentials& next);
|
|
|
|
/// @brief The canonical key (TS 102 941 clause 6.2.3.2.1), generated in the module on first use.
|
|
/// @return none without a module, or when the module no longer holds the stored key.
|
|
std::optional<microbu_v2x::security::KeyId> canonical_key();
|
|
|
|
/// @brief The stored enrolment credential and the KeyId of its key, none if there is none.
|
|
std::optional<std::pair<vanetza::security::v3::Certificate, microbu_v2x::security::KeyId>> enrolment_credential();
|
|
|
|
/// @brief Replaces the radio for a new configuration (radio_ stays empty for radio = 0).
|
|
/// @return Result code.
|
|
link::Code start_radio(const link::StationConfigure& config);
|
|
|
|
/// @return CONFIGURE detail: GN address, identifier, credentials-loaded flag and ticket count.
|
|
link::Bytes configuration_detail() const;
|
|
|
|
/// @brief Moves the ITS clock by one PoTi time reference (restarting the station if it must).
|
|
/// @param its_us Reference time from the phone.
|
|
/// @return The step applied.
|
|
its_clock::Step apply_time_reference(std::int64_t its_us);
|
|
|
|
/// @brief Holds the calling task while a frame's hand-off would collide with a BLE connection event.
|
|
/// @return The applied delay in microseconds.
|
|
std::int64_t hold_for_ble_guard() const;
|
|
|
|
/// @brief Counts a radio result and signals a disseminated frame.
|
|
void count_radio_result(microbu_v2x::Result result);
|
|
|
|
/// @brief Pushes the current position fix into the stack, clamped to not precede the station clock.
|
|
void apply_position();
|
|
|
|
/// @brief Samples the hardware CCA counters at the DCC cadence and feeds both DCC entities.
|
|
void sample_dcc_channel_load();
|
|
|
|
|
|
/// @param indication Indication received from the stack.
|
|
void deliver(microbu_v2x::BtpIndication indication);
|
|
|
|
/// @brief MicrOBU: unwraps one received frame with gn_unwrap.c and hands it to raw_its_.
|
|
/// @param frame Complete 802.11 frame as captured (FCS included; gn_unwrap reads declared lengths).
|
|
/// @param rssi Received signal strength, dBm.
|
|
void forward_raw(const vanetza::ByteBuffer& frame, int rssi);
|
|
|
|
/// @brief MicrOBU: transmits an unsecured BTP-B/SHB request with geonet.c's GN header and the
|
|
/// Source Position Vector of the last PoTi. The stack only signs, so this bypasses it.
|
|
/// @param request The phone's request.
|
|
/// @return Result code.
|
|
link::Code unsecured_request(const link::BtpDataRequest& request);
|
|
|
|
/// @brief Wraps one captured frame as a RAW_FRAME body and hands it to the link service.
|
|
/// @param data MPDU without FCS.
|
|
/// @param size Octets in data.
|
|
/// @param rssi Received signal strength (0 for own transmissions).
|
|
/// @param local_us Local receive/submit time in microseconds (rx_ctrl.timestamp base, 32 bit).
|
|
/// @param own_tx true for a frame this radio transmitted.
|
|
void emit_raw(const std::uint8_t* data, std::size_t size, int rssi, std::uint32_t local_us, bool own_tx);
|
|
|
|
link::Status counters_;
|
|
|
|
std::optional<link::StationConfigure> config_;
|
|
Clock clock_;
|
|
its_clock::Regression regression_; // backward PoTi references: stale (late-delivered) vs. a real correction
|
|
its_clock::Lag lag_; // backward references below 1 s: the clock may run ahead (slew back)
|
|
vanetza::PositionFix fix_;
|
|
bool have_fix_ = false;
|
|
link::PotiUpdate last_poti_; // MicrOBU: the GN Source Position Vector of unsecured_request()
|
|
std::uint8_t unsecured_mid_[6] = {2, 0, 0, 0, 0, 1}; // MicrOBU: random per configure(); MAC of unsecured frames
|
|
// MicrOBU V2X_RX: forwarded in one message, forwarded in fragments (and how many of those no transport took),
|
|
// dropped as unusable or beyond v2x_rx_max_forward, and large ones left to the RAW_FRAME copy.
|
|
std::uint32_t raw_forwarded_ = 0, raw_fragmented_ = 0, raw_fragment_failed_ = 0, raw_oversize_ = 0, raw_covered_ = 0;
|
|
// declared before everything that refers to its keys (security_, pki_pending_), so it is destroyed last
|
|
std::unique_ptr<microbu_v2x::security::SecurityModule> module_;
|
|
std::unique_ptr<vanetza::ManualRuntime> runtime_;
|
|
std::unique_ptr<Security> security_;
|
|
// the decoded trust set and ticket pool outlive station builds; they are decoded from NVS again only
|
|
// after the stored credentials changed (provision, erase) or were never loaded.
|
|
bool credentials_stale_ = true;
|
|
std::uint32_t managed_trust_deadline_ = 0;
|
|
bool managed_trust_expired_ = false;
|
|
std::unique_ptr<microbu_v2x::Stack> stack_;
|
|
std::unique_ptr<C5Radio> radio_;
|
|
std::unique_ptr<microbu_v2x::AccessStack> access_stack_; // DCC_ACC gate in front of radio_
|
|
microbu_v2x::AlDataRequest radio_parameters_;
|
|
std::optional<CcaCounters> dcc_cca_last_; // previous read_cca_counters() sample, for the 100 ms LCBR delta
|
|
std::int64_t dcc_last_sample_its_us_ = 0;
|
|
std::int64_t dcc_last_sample_mono_us_ = 0; // esp_timer time of that sample (window length, never steps)
|
|
std::uint32_t dcc_invalid_windows_ = 0; // windows skipped: delayed beyond a counter wrap, or no elapsed cycles
|
|
Indication indication_;
|
|
IdEvent id_event_;
|
|
Disseminated disseminated_;
|
|
Received received_;
|
|
RawFrame raw_frame_;
|
|
RawIts raw_its_;
|
|
DccUpdate dcc_update_;
|
|
/// @brief Derives T_GenVam_DCC from the Adaptive DCC state and notifies the VBS on change.
|
|
void update_t_gen_vam(std::int64_t its_us);
|
|
std::optional<double> cbr_local_, cbr_global_;
|
|
std::uint32_t vam_ton_us_ = 0; // airtime of the most recent VAM frame
|
|
bool vam_pending_ = false; // the BTP request in progress carries a VAM (ITS-AID 638)
|
|
std::uint16_t t_gen_vam_ms_ = 0; // last computed T_GenVam_DCC
|
|
std::uint16_t t_gen_vam_sent_ms_ = 0;
|
|
std::int64_t t_gen_vam_sent_us_ = 0;
|
|
// BTP requests validated and answered, waiting for signing and submission (submit_pending()).
|
|
struct Pending;
|
|
struct PkiPending; // the outstanding enrolment (0) and authorization (1) request: context and new key
|
|
std::unique_ptr<PkiPending> pki_pending_[2];
|
|
/// @brief Hands one prepared request to the stack (signing happens inside).
|
|
void submit(Pending& pending);
|
|
std::deque<std::unique_ptr<Pending>> pending_;
|
|
std::uint8_t raw_mode_ = 0;
|
|
std::uint32_t raw_counter_ = 0;
|
|
std::map<std::uint64_t, std::shared_ptr<microbu_v2x::security::IdChangeResponder>> pending_responders_;
|
|
std::map<std::uint64_t, std::uint64_t> link_subscriptions_; // subscription -> service handle (identity)
|
|
bool rebuilding_ = false;
|
|
};
|
|
|
|
} // namespace microbu
|