3#include <QtCore/QMetaEnum>
4#include <QtCore/QMetaObject>
19 return QMetaEnum::fromType<SigningFailure::Reason>().valueToKey(
static_cast<int>(r));
25 : QObject(parent), _mavlinkChannel(
channel)
27 _timeout.setSingleShot(
true);
28 connect(&_timeout, &QTimer::timeout,
this, &SigningController::_onTimeout);
29 _wallClockRefresh.setInterval(kWallClockRefreshInterval);
30 connect(&_wallClockRefresh, &QTimer::timeout,
this, [
this]() { _channel.refreshOutgoingTimestamp(); });
31 qCDebug(SigningControllerLog) <<
"SigningController ctor — channel" << _mavlinkChannel;
36 qCDebug(SigningControllerLog) <<
"SigningController dtor — channel" << _mavlinkChannel;
38 _wallClockRefresh.stop();
40 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
41 _autoDetectGuard.reset();
42 if (_op.kind == OpKind::Enable) {
49 _channel.init(_mavlinkChannel, QByteArrayView(),
nullptr);
52void SigningController::_setOpLocked(PendingOp next)
54 _op = std::move(next);
55 QMetaObject::invokeMethod(
this, [
this]() { emit
stateChanged(); }, Qt::AutoConnection);
58void SigningController::_setWallClockRefresh(
bool on)
61 QMetaObject::invokeMethod(&_wallClockRefresh, on ?
"start" :
"stop", Qt::AutoConnection);
68 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
73 return State::Enabling;
75 return State::Disabling;
79 return _channel.isEnabled() ? State::On : State::Off;
99 return (s == State::On) || (s == State::Disabling);
104 return _channel.keyHint();
110 if (s == State::Enabling) {
111 return tr(
"Configuring…");
113 if (s == State::Disabling) {
114 return tr(
"Disabling…");
116 if (!_channel.isEnabled()) {
121 return detail.isEmpty() ? tr(
"On") : detail;
126 if (_channel.isEnabled()) {
127 const auto snap = _channel.currentTimestampAndName();
128 if (!snap.keyName.isEmpty() && snap.timestamp > 0) {
132 const bool ok = _channel.init(_mavlinkChannel, QByteArrayView(),
nullptr);
133 _channel.clearDetectCooldown();
134 _setWallClockRefresh(
false);
139 const QString& keyNameHint)
143 _setWallClockRefresh(_channel.isEnabled());
151 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
152 if (_isPendingLocked()) {
153 qCWarning(SigningControllerLog)
154 <<
"[ch" << _mavlinkChannel <<
"] enable rejected: operation already pending";
155 return SigningFailure{FailReason::VehicleUnreachable, tr(
"Signing operation already pending")};
160 const QByteArrayView keyView(
reinterpret_cast<const char*
>(keyBytes.data()), keyBytes.size());
162 if (!_channel.init(_mavlinkChannel, keyView,
164 persisted, kName,
false)) {
165 qCWarning(SigningControllerLog) <<
"[ch" << _mavlinkChannel <<
"] enable rejected: signing init failed";
166 return SigningFailure{FailReason::InitFailed, tr(
"Failed to install signing for pending verification")};
169 _autoDetectGuard.emplace(_channel.suspendAutoDetect());
170 _setOpLocked(PendingOp{
171 .kind = OpKind::Enable,
172 .expectedSysId = expectedSysId,
174 .keyBytes = keyBytes,
178 _timeout.setInterval(_effectiveTimeout());
180 _setWallClockRefresh(
true);
181 qCDebug(SigningControllerLog) <<
"[ch" << _mavlinkChannel <<
"] enable pending — key" << kName <<
"sysid"
182 << expectedSysId <<
"timeout" << kTimeout <<
"ms";
189 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
190 if (_isPendingLocked()) {
191 qCWarning(SigningControllerLog)
192 <<
"[ch" << _mavlinkChannel <<
"] disable rejected: operation already pending";
193 return SigningFailure{FailReason::VehicleUnreachable, tr(
"Signing operation already pending")};
196 if (!_channel.setAcceptUnsignedCallback(
198 qCWarning(SigningControllerLog) <<
"[ch" << _mavlinkChannel <<
"] disable rejected: channel not signing";
199 return SigningFailure{FailReason::VehicleUnreachable, tr(
"Channel not signing — cannot disable")};
202 _setOpLocked(PendingOp{
203 .kind = OpKind::Disable,
204 .expectedSysId = expectedSysId,
209 _timeout.setInterval(_effectiveTimeout());
211 qCDebug(SigningControllerLog) <<
"[ch" << _mavlinkChannel <<
"] disable pending — sysid" << expectedSysId
212 <<
"timeout" << kTimeout <<
"ms";
218 if (_channel.consumeStatusTransition(_mavlinkChannel)) {
219 QMetaObject::invokeMethod(
this, [
this]() { emit
stateChanged(); }, Qt::AutoConnection);
224 bool burstFired =
false;
225 uint8_t burstCount = 0;
226 bool pendingEnable =
false;
228 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
229 burstFired = _badSigBurst.record();
230 burstCount = _badSigBurst.count();
231 pendingEnable = (_op.kind == OpKind::Enable);
235 const QString detail =
237 ? tr(
"MAVLink signing: %1 consecutive bad signatures while enabling — the chosen key likely "
238 "does not match the vehicle's stored key. Verify the key on the vehicle, then retry.")
240 : tr(
"MAVLink signing: %1 consecutive bad signatures on this link — wrong key or vehicle clock "
243 QMetaObject::invokeMethod(
this, [
this, detail]() { emit
alertRaised(detail); }, Qt::AutoConnection);
249 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
250 _badSigBurst.reset();
253 bool autoDetected =
false;
258 if (!detected.isEmpty()) {
259 QMetaObject::invokeMethod(
this, [
this, detected]() { emit
keyAutoDetected(detected); }, Qt::AutoConnection);
265 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
266 _handleFsmFrameLocked(message);
274 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
275 _badSigBurst.reset();
280 if (!_isPendingLocked()) {
283 if (message.sysid != _op.expectedSysId) {
288 if (message.msgid == MAVLINK_MSG_ID_STATUSTEXT) {
289 mavlink_statustext_t st;
290 mavlink_msg_statustext_decode(&message, &st);
292 const bool errorSeverity = (st.severity <= MAV_SEVERITY_ERROR);
293 const bool mentionsSigning = text.contains(QLatin1String(
"signing"), Qt::CaseInsensitive);
294 if (errorSeverity && mentionsSigning) {
295 _failLocked(FailReason::InitFailed, tr(
"Vehicle rejected signing change: %1").arg(text));
300 if (_op.kind == OpKind::Enable) {
305 qCWarning(SigningControllerLog)
306 <<
"[ch" << _mavlinkChannel
307 <<
"] pending-enable HEARTBEAT signature did not verify against committed key";
312 }
else if (_op.kind == OpKind::Disable) {
314 _op.unsignedSeen =
true;
320void SigningController::_confirmLocked()
323 QMetaObject::invokeMethod(&_timeout,
"stop", Qt::AutoConnection);
325 if (_op.kind == OpKind::Enable) {
326 const QString confirmedName = _op.keyName;
329 const QString detail = tr(
"Signing confirmation received but local activation failed");
330 qCCritical(SigningControllerLog) <<
"[ch" << _mavlinkChannel <<
"]" << detail;
331 _failLocked(FailReason::InitFailed, detail);
334 qCDebug(SigningControllerLog) <<
"[ch" << _mavlinkChannel <<
"] enable confirmed — key" << confirmedName;
336 QMetaObject::invokeMethod(
337 this, [
this, confirmedName]() { emit
signingConfirmed(confirmedName); }, Qt::AutoConnection);
338 }
else if (_op.kind == OpKind::Disable) {
339 qCDebug(SigningControllerLog) <<
"[ch" << _mavlinkChannel <<
"] disable confirmed";
340 _completeDisableSuccessLocked();
344void SigningController::_completeDisableSuccessLocked()
346 _channel.init(_mavlinkChannel, QByteArrayView(),
nullptr);
348 QMetaObject::invokeMethod(
this, [
this]() { emit
signingConfirmed(QString{}); }, Qt::AutoConnection);
351void SigningController::_failLocked(FailReason reason,
const QString& detail,
bool cancelled)
353 QMetaObject::invokeMethod(&_timeout,
"stop", Qt::AutoConnection);
356 if (_op.kind == OpKind::Disable && _op.unsignedSeen && !cancelled) {
357 _completeDisableSuccessLocked();
362 QString effectiveDetail = detail;
364 if (_op.kind == OpKind::Enable) {
365 _channel.init(_mavlinkChannel, QByteArrayView(),
nullptr);
366 }
else if (_op.kind == OpKind::Disable) {
367 _channel.setAcceptUnsignedCallback(
369 effectiveReason = FailReason::VehicleUnreachable;
371 tr(
"Signing disable not confirmed — vehicle is unreachable or still requires signed messages. Local "
372 "signing remains enabled.");
375 qCWarning(SigningControllerLog) <<
"[ch" << _mavlinkChannel
376 <<
"] signing operation failed:" << failReasonName(effectiveReason)
379 SigningFailure failure{effectiveReason, effectiveDetail};
381 QMetaObject::invokeMethod(
this, [
this, failure]() { emit
signingFailed(failure); }, Qt::AutoConnection);
386 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
387 if (!_isPendingLocked()) {
390 const QString effectiveDetail =
392 ? tr(
"Signing operation cancelled — primary link changed before vehicle confirmation")
394 _failLocked(FailReason::VehicleUnreachable, effectiveDetail,
true);
397void SigningController::_onTimeout()
399 QMutexLocker<QRecursiveMutex> locker(&_fsmMutex);
400 if (!_isPendingLocked()) {
403 qCDebug(SigningControllerLog) <<
"[ch" << _mavlinkChannel <<
"] timeout fired —"
404 << (_op.kind == OpKind::Enable ?
"enable" :
"disable") <<
"not confirmed";
405 const QString detail = (_op.kind == OpKind::Enable) ? tr(
"Signing setup not confirmed by vehicle (timeout)")
406 : tr(
"Signing disable not confirmed by vehicle (timeout)");
407 _failLocked(FailReason::Timeout, detail);
410void SigningController::_clearLocked()
412 _autoDetectGuard.reset();
414 _setOpLocked(PendingOp{});
416 _setWallClockRefresh(_channel.isEnabled());
struct __mavlink_message mavlink_message_t
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static MAVLinkSigningKeys * instance()
void recordTimestamp(const QString &name, uint64_t ts)
Update in-memory + persisted last-timestamp for name. Monotonic — older values are dropped.
QString tryDetectKey(SigningController *controller, const mavlink_message_t &message)
Try every stored key against message's signature; on match, configures channel and returns the key na...
uint64_t lastTimestamp(const QString &name) const
Last persisted signing timestamp for name, or 0 if unknown / no entry.
static QString boundedStringField(std::span< const char > raw)
Decodes UTF-8 up to the first NUL or the field boundary, preserving whitespace.
void signingConfirmed(const QString &keyName)
Emitted exactly once per begin*() on success. keyName is the enabled key, or empty for disable.
SigningController(mavlink_channel_t channel, QObject *parent=nullptr)
SigningStatus::State State
std::optional< SigningFailure > tryBeginEnable(quint32 expectedSysId, const QString &keyName, const MAVLinkSigning::SigningKey &keyBytes)
Begin pending-enable. Caller must send SETUP_SIGNING only on nullopt; outcome arrives via signingConf...
bool initSigningImmediate(QByteArrayView key, MAVLinkSigning::UnsignedAcceptancePolicy policy, const QString &keyNameHint={})
Bypasses the FSM; used by tests and auto-detect. Non-empty keyNameHint seeds the persisted timestamp.
bool processFrame(bool framingOk, const mavlink_message_t &message)
Per-frame entry point; drives burst alerts, auto-detect, and the FSM. Returns true on auto-detect.
QString statusText() const
SigningFailure::Reason FailReason
void cancelPending(const QString &detail={})
void alertRaised(const QString &detail)
~SigningController() override
SigningStatus status() const
void keyAutoDetected(const QString &keyName)
void signingFailed(SigningFailure failure)
Emitted exactly once per begin*() on failure (timeout, init error, cancel, re-entry).
const SigningChannel & channel() const
std::optional< SigningFailure > tryBeginDisable(quint32 expectedSysId)
Atomic check-and-commit for disable; same contract as tryBeginEnable.
Reason a signing operation failed. Used by SigningController error path and Vehicle::signingFailed.
QString signingStatusString(mavlink_channel_t channel)
bool verifySignature(QByteArrayView key, const mavlink_message_t &message)
Verify a key against a signed message's signature.
bool isMessageSigned(const mavlink_message_t &message)
Returns true if the message has a MAVLink2 signature.
mavlink_accept_unsigned_t callbackForPolicy(UnsignedAcceptancePolicy policy)
Maps a high-level policy to the underlying libmavlink callback.
void logSigningFailure(mavlink_channel_t channel)
std::array< uint8_t, kSigningKeySize > SigningKey
std::array avoids QByteArray COW detach so secureZero() actually wipes the bytes.
void secureZero(void *data, size_t size)