Commit attachment result state and key before acknowledging delivery

This commit is contained in:
evgeny committed 2026-10-26 23:03:19 +01:00
1 parent 65cc26fdc9
commit a05bb97fa7
2 files changed
+132 -50

No files matched your search

+128 -48
View File
@@ -194,6 +194,22 @@ static void ak_file_done(void* arg, int error) {
OPENSSL_cleanse(job->key, 32); u_free(job);
}
/* Вызывается только для собственной транзакции; открытая после отказа БД требует остановки владельцем. */
static void ak_rollback(struct UTUN_INSTANCE* inst, const char* operation, const char* channel) {
sqlite3* db = CC(inst)->db;
if (sqlite3_get_autocommit(db)) return;
int rc = sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
if (rc != SQLITE_OK)
DEBUG_ERROR(DEBUG_CATEGORY_MEDIA, "attachment keys: rollback operation=%s channel=%s rc=%d (%s) db=%s",
operation, channel, rc, sqlite3_errstr(rc), sqlite3_errmsg(db));
if (!sqlite3_get_autocommit(db)) {
DEBUG_ERROR(DEBUG_CATEGORY_MEDIA, "attachment keys: transaction remains open operation=%s channel=%s; requesting core stop",
operation, channel);
chat_attachment_quiesce(inst);
utun_instance_stop(inst);
} else DEBUG_DEBUG(DEBUG_CATEGORY_MEDIA, "attachment keys: rolled back operation=%s channel=%s", operation, channel);
}
/* Полная авторская подготовка фиксируется до передачи файла worker; внешняя транзакция запрещена. */
static int ak_store_preparation(struct ak_file* job, const uint8_t* info, int info_len) {
struct UTUN_INSTANCE* inst = job->inst;
@@ -241,18 +257,7 @@ fail:
int final_rc = sqlite3_finalize(st);
if (final_rc != SQLITE_OK)
DEBUG_ERROR(DEBUG_CATEGORY_MEDIA, "attachment keys: preparation cleanup finalize channel=%s rc=%d", job->channel, final_rc);
if (!sqlite3_get_autocommit(db)) {
int rollback_rc = sqlite3_exec(db, "ROLLBACK", NULL, NULL, NULL);
if (rollback_rc != SQLITE_OK)
DEBUG_ERROR(DEBUG_CATEGORY_MEDIA, "attachment keys: preparation rollback channel=%s rc=%d (%s) db=%s",
job->channel, rollback_rc, sqlite3_errstr(rollback_rc), sqlite3_errmsg(db));
if (!sqlite3_get_autocommit(db)) {
DEBUG_ERROR(DEBUG_CATEGORY_MEDIA, "attachment keys: transaction remains open channel=%s; quiescing attachments and requesting core stop",
job->channel);
chat_attachment_quiesce(inst);
utun_instance_stop(inst);
}
}
ak_rollback(inst, "preparation", job->channel);
return -1;
}
@@ -393,6 +398,115 @@ static void ak_ack(struct UTUN_INSTANCE* inst, const char* channel, uint64_t pee
if (rc < 0) DEBUG_WARN(DEBUG_CATEGORY_MEDIA, "attachment keys: acknowledgment deferred channel=%s command=%u", channel, cmd);
}
/* Ответ меняет ключ, запрос и очередь одним commit; сетевое подтверждение остаётся вызывающему. */
static int ak_apply_result(struct UTUN_INSTANCE* inst, const char* channel, uint64_t peer, const uint8_t* body, int* next_out) {
sqlite3* db = CC(inst)->db;
uint8_t cmd = body[4];
if (!sqlite3_get_autocommit(db)) {
DEBUG_ERROR(DEBUG_CATEGORY_MEDIA, "attachment keys: result rejected inside external transaction channel=%s peer=%llu command=%u",
channel, (unsigned long long)peer, cmd); return -1;
}
sqlite3_stmt* st = NULL;
const char* stage = "begin";
int rc = sqlite3_exec(db, "BEGIN IMMEDIATE", NULL, NULL, NULL);
if (rc != SQLITE_OK) goto fail;
stage = "read prepare";
rc = sqlite3_prepare_v2(db, "SELECT r.incoming,r.state,o.command FROM attachment_key_requests r"
" LEFT JOIN attachment_key_outbox o ON o.channel=r.channel AND o.message_id=r.message_id AND o.peer=r.peer"
" WHERE r.channel=? AND r.message_id=? AND r.peer=?", -1, &st, NULL);
if (rc != SQLITE_OK) goto fail;
stage = "read bind channel"; rc = sqlite3_bind_text(st, 1, channel, -1, SQLITE_STATIC);
if (rc != SQLITE_OK) goto fail;
stage = "read bind message"; rc = sqlite3_bind_blob(st, 2, body + 5, 32, SQLITE_STATIC);
if (rc != SQLITE_OK) goto fail;
stage = "read bind peer"; rc = sqlite3_bind_int64(st, 3, (sqlite3_int64)peer);
if (rc != SQLITE_OK) goto fail;
stage = "read step"; rc = sqlite3_step(st);
if (rc != SQLITE_ROW) goto fail;
int incoming = sqlite3_column_int(st, 0), state = sqlite3_column_int(st, 1), queued = sqlite3_column_int(st, 2);
stage = "read finalize"; rc = sqlite3_finalize(st); st = NULL;
if (rc != SQLITE_OK) goto fail;
if ((incoming != 0 && incoming != 1) || state < 0 || state > 4 ||
(cmd == AK_RESULT_ACK ? !incoming || (state != 2 && state != 3 && state != 4) : incoming || state > 3) ||
((cmd == AK_GRANT || cmd == AK_DENY) && ((state == 2 && cmd != AK_GRANT) || (state == 3 && cmd != AK_DENY)))) {
DEBUG_WARN(DEBUG_CATEGORY_MEDIA, "attachment keys: conflicting result channel=%s peer=%llu command=%u incoming=%d state=%d",
channel, (unsigned long long)peer, cmd, incoming, state);
ak_rollback(inst, "result", channel); return -1;
}
int changed;
if (cmd == AK_GRANT) {
stage = "key prepare";
rc = sqlite3_prepare_v2(db, "UPDATE attachment_keys SET key=?,error=0 WHERE channel=? AND message_id=? AND author=?"
" AND (key IS NULL OR key=?)", -1, &st, NULL);
if (rc != SQLITE_OK) goto fail;
stage = "key bind key"; rc = sqlite3_bind_blob(st, 1, body + AK_BODY, 32, SQLITE_STATIC);
if (rc != SQLITE_OK) goto fail;
stage = "key bind channel"; rc = sqlite3_bind_text(st, 2, channel, -1, SQLITE_STATIC);
if (rc != SQLITE_OK) goto fail;
stage = "key bind message"; rc = sqlite3_bind_blob(st, 3, body + 5, 32, SQLITE_STATIC);
if (rc != SQLITE_OK) goto fail;
stage = "key bind author"; rc = sqlite3_bind_int64(st, 4, (sqlite3_int64)peer);
if (rc != SQLITE_OK) goto fail;
stage = "key bind previous"; rc = sqlite3_bind_blob(st, 5, body + AK_BODY, 32, SQLITE_STATIC);
if (rc != SQLITE_OK) goto fail;
stage = "key step"; rc = sqlite3_step(st);
if (rc != SQLITE_DONE) goto fail;
changed = sqlite3_changes(db);
stage = "key finalize"; rc = sqlite3_finalize(st); st = NULL;
if (rc != SQLITE_OK) goto fail;
if (changed != 1) { stage = "key row count"; rc = SQLITE_CONSTRAINT; goto fail; }
}
int next = cmd == AK_REQUEST_ACK ? (state == 0 ? 1 : state) : cmd == AK_RESULT_ACK ? (state == 3 ? 3 : 4) : cmd == AK_GRANT ? 2 : 3;
stage = "state prepare";
rc = sqlite3_prepare_v2(db, "UPDATE attachment_key_requests SET state=? WHERE channel=? AND message_id=? AND peer=?", -1, &st, NULL);
if (rc != SQLITE_OK) goto fail;
stage = "state bind state"; rc = sqlite3_bind_int(st, 1, next);
if (rc != SQLITE_OK) goto fail;
stage = "state bind channel"; rc = sqlite3_bind_text(st, 2, channel, -1, SQLITE_STATIC);
if (rc != SQLITE_OK) goto fail;
stage = "state bind message"; rc = sqlite3_bind_blob(st, 3, body + 5, 32, SQLITE_STATIC);
if (rc != SQLITE_OK) goto fail;
stage = "state bind peer"; rc = sqlite3_bind_int64(st, 4, (sqlite3_int64)peer);
if (rc != SQLITE_OK) goto fail;
stage = "state step"; rc = sqlite3_step(st);
if (rc != SQLITE_DONE) goto fail;
changed = sqlite3_changes(db);
stage = "state finalize"; rc = sqlite3_finalize(st); st = NULL;
if (rc != SQLITE_OK) goto fail;
if (changed != 1) { stage = "state row count"; rc = SQLITE_CONSTRAINT; goto fail; }
int command = cmd == AK_RESULT_ACK ? (state == 3 ? AK_DENY : AK_GRANT) : AK_REQUEST;
stage = "outbox prepare";
rc = sqlite3_prepare_v2(db, "DELETE FROM attachment_key_outbox WHERE channel=? AND message_id=? AND peer=? AND command=?", -1, &st, NULL);
if (rc != SQLITE_OK) goto fail;
stage = "outbox bind channel"; rc = sqlite3_bind_text(st, 1, channel, -1, SQLITE_STATIC);
if (rc != SQLITE_OK) goto fail;
stage = "outbox bind message"; rc = sqlite3_bind_blob(st, 2, body + 5, 32, SQLITE_STATIC);
if (rc != SQLITE_OK) goto fail;
stage = "outbox bind peer"; rc = sqlite3_bind_int64(st, 3, (sqlite3_int64)peer);
if (rc != SQLITE_OK) goto fail;
stage = "outbox bind command"; rc = sqlite3_bind_int(st, 4, command);
if (rc != SQLITE_OK) goto fail;
stage = "outbox step"; rc = sqlite3_step(st);
if (rc != SQLITE_DONE) goto fail;
changed = sqlite3_changes(db);
stage = "outbox finalize"; rc = sqlite3_finalize(st); st = NULL;
if (rc != SQLITE_OK) goto fail;
/* REQUEST_ACK мог удалить REQUEST раньше GRANT; дубликат результата также не требует строки outbox. */
if (changed != (queued == command)) { stage = "outbox row count"; rc = SQLITE_CONSTRAINT; goto fail; }
stage = "commit"; rc = sqlite3_exec(db, "COMMIT", NULL, NULL, NULL);
if (rc != SQLITE_OK) goto fail;
*next_out = next;
return 0;
fail:
DEBUG_ERROR(DEBUG_CATEGORY_MEDIA, "attachment keys: result channel=%s peer=%llu command=%u stage=%s rc=%d (%s) db=%s",
channel, (unsigned long long)peer, cmd, stage, rc, sqlite3_errstr(rc), sqlite3_errmsg(db));
int final_rc = sqlite3_finalize(st);
if (final_rc != SQLITE_OK)
DEBUG_ERROR(DEBUG_CATEGORY_MEDIA, "attachment keys: result cleanup finalize channel=%s rc=%d", channel, final_rc);
ak_rollback(inst, "result", channel);
return -1;
}
/* Приём строго адресного E2E control. Дубликат возвращает сохранённое решение. */
static void ak_receive(struct ETCP_CONN* conn, struct ll_entry* entry) {
struct UTUN_INSTANCE* inst = conn->instance;
@@ -428,46 +542,12 @@ static void ak_receive(struct ETCP_CONN* conn, struct ll_entry* entry) {
rollback_request:
ak_exec(inst, "ROLLBACK TO attachment_request"); ak_exec(inst, "RELEASE attachment_request"); goto done;
}
if (ak_exec(inst, "SAVEPOINT attachment_result")) goto done;
sqlite3_stmt* st = ak_prepare(inst, "SELECT incoming,state FROM attachment_key_requests WHERE channel=? AND message_id=? AND peer=?");
if (!st) goto rollback_result;
sqlite3_bind_text(st, 1, channel, -1, SQLITE_STATIC); sqlite3_bind_blob(st, 2, body + 5, 32, SQLITE_STATIC);
sqlite3_bind_int64(st, 3, (sqlite3_int64)peer);
int rc = sqlite3_step(st), incoming = rc == SQLITE_ROW ? sqlite3_column_int(st, 0) : -1,
state = rc == SQLITE_ROW ? sqlite3_column_int(st, 1) : -1; sqlite3_finalize(st);
if (incoming < 0 || (cmd == AK_RESULT_ACK ? !incoming || state == 0 : incoming)) goto rollback_result;
if (cmd == AK_GRANT || cmd == AK_DENY) {
if ((state == 2 && cmd != AK_GRANT) || (state == 3 && cmd != AK_DENY)) goto rollback_result;
if (cmd == AK_GRANT) {
st = ak_prepare(inst, "UPDATE attachment_keys SET key=?,error=0 WHERE channel=? AND message_id=? AND author=?"
" AND (key IS NULL OR key=?)");
if (!st) goto rollback_result;
sqlite3_bind_blob(st, 1, body + AK_BODY, 32, SQLITE_STATIC); sqlite3_bind_text(st, 2, channel, -1, SQLITE_STATIC);
sqlite3_bind_blob(st, 3, body + 5, 32, SQLITE_STATIC); sqlite3_bind_int64(st, 4, (sqlite3_int64)peer);
sqlite3_bind_blob(st, 5, body + AK_BODY, 32, SQLITE_STATIC);
if (ak_step(inst, st) || sqlite3_changes(CC(inst)->db) != 1) goto rollback_result;
}
}
int next = cmd == AK_REQUEST_ACK ? (state == 0 ? 1 : state) : cmd == AK_RESULT_ACK ? (state == 3 ? 3 : 4) : cmd == AK_GRANT ? 2 : 3;
st = ak_prepare(inst, "UPDATE attachment_key_requests SET state=? WHERE channel=? AND message_id=? AND peer=?");
if (!st) goto rollback_result;
sqlite3_bind_int(st, 1, next); sqlite3_bind_text(st, 2, channel, -1, SQLITE_STATIC);
sqlite3_bind_blob(st, 3, body + 5, 32, SQLITE_STATIC); sqlite3_bind_int64(st, 4, (sqlite3_int64)peer);
if (ak_step(inst, st)) goto rollback_result;
st = ak_prepare(inst, "DELETE FROM attachment_key_outbox WHERE channel=? AND message_id=? AND peer=? AND command=?");
if (!st) goto rollback_result;
sqlite3_bind_text(st, 1, channel, -1, SQLITE_STATIC); sqlite3_bind_blob(st, 2, body + 5, 32, SQLITE_STATIC);
sqlite3_bind_int64(st, 3, (sqlite3_int64)peer);
sqlite3_bind_int(st, 4, cmd == AK_RESULT_ACK ? (state == 3 ? AK_DENY : AK_GRANT) : AK_REQUEST);
if (ak_step(inst, st) || ak_exec(inst, "RELEASE attachment_result")) goto rollback_result;
int next;
if (ak_apply_result(inst, channel, peer, body, &next)) goto done;
DEBUG_INFO(DEBUG_CATEGORY_MEDIA, "attachment keys: control committed channel=%s peer=%llu command=%u state=%d", channel,
(unsigned long long)peer, cmd, next);
if (cmd == AK_GRANT || cmd == AK_DENY) ak_ack(inst, channel, peer, body, AK_RESULT_ACK);
ak_changed(inst, channel); goto done;
rollback_result:
DEBUG_WARN(DEBUG_CATEGORY_MEDIA, "attachment keys: unexpected/conflicting control channel=%s peer=%llu command=%u", channel,
(unsigned long long)peer, cmd);
ak_exec(inst, "ROLLBACK TO attachment_result"); ak_exec(inst, "RELEASE attachment_result"); goto done;
invalid:
DEBUG_WARN(DEBUG_CATEGORY_MEDIA, "attachment keys: rejected control source=%llu group=%llu bytes=%u", (unsigned long long)peer,
(unsigned long long)group, (unsigned)entry->len);
+4 -2
View File
@@ -3,8 +3,10 @@
* Автор отвечает на запрос через decide. Ключи и очередь доставки сохраняются в локальной БД.
* Все вызовы, кроме identity, — uasync. init после media_async; quiesce до остановки workers, destroy после них.
* Обмен ключами подписан и зашифрован; для доставки нужен живой маршрут обеих сторон.
* Известный дефект приёма GRANT: ошибка bind ключа может привести к RESULT_ACK при key=NULL.
* Подтверждение пока не гарантирует сохранение ключа; см. doc/chat_audit_findings.txt, аудит приёма GRANT. */
* Ответы REQUEST_ACK/GRANT/DENY/RESULT_ACK атомарно меняют ключ, запрос и outbox собственной транзакцией.
* Внешняя транзакция для ответов запрещена. GRANT/DENY подтверждаются только после проверенного commit;
* повтор с тем же результатом допустим, конфликтующий ключ/решение отклоняется. Отказ SQL сохраняет прежнее состояние.
* Незавершённый rollback отключает модуль и запрашивает остановку ядра владельцем вне callback. */
#ifndef CHAT_ATTACHMENT_H
#define CHAT_ATTACHMENT_H
#include "../media_async/attachment.h"