All checks were successful
CI Code / Check spelling (push) Successful in 21s
CI Code / Check coding style (push) Successful in 31s
CI Code / Code Coverage (push) Successful in 2m21s
CI Code / Linux (ubuntu) (push) Successful in 4m30s
CI Code / Linux (debian) (push) Successful in 6m43s
CI Code / Linux (arch) (push) Successful in 10m8s
A flat-file alternative to the SQLite chatlog backend with runtime
switching, full migration tooling, integrity verification, and a
synthetic load harness. SQLite remains the default; both backends share
one dispatch layer (db_backend_t vtable) so callers don't change.
Storage layout
- Per-contact append-only `flatlog/<account>/<contact>/history.log`
under XDG_DATA_HOME, one line per message
- Single-line file header with embedded format-version marker
(FLATFILE_FORMAT_VERSION); reader warns on missing or mismatched
marker, writer and checker stay in sync via preprocessor
stringification
- Deterministic key=value metadata (`id`, `aid`, `corrects`, `to`,
`to_res`, `read`) plus escaped body \u2014 `\|`, `\]`, `\\`, `\n`, `\r`
literals prevent log injection
- Sparse byte-offset index (FF_INDEX_STEP=500) per contact for
O(log n) time-range lookups; rebuilt on inode / size / mtime
change, extended in-place when the file just grew
- Per-contact GHashTable caches for archive_id presence and
stanza_id \u2192 from_jid mapping (O(1) MAM dedup, O(1) LMC sender
validation)
Hardening
- Path-traversal protection: JID directory name normalisation
(`@` \u2192 `_at_`, slashes and `..` rejected at construction); every
per-contact path is anchored under the account's flatlog/
directory and validated before open
- Symlink-attack protection: every fopen / open uses O_NOFOLLOW; on
ELOOP the operation aborts with an error rather than following
- Filesystem permissions: log files created with mode 0600,
directories with mode 0700; both enforced at creation, verified
on each open and reported on drift by `/history verify`
- Atomic crash-safe export: write to a temp file via mkstemp (mode
0600, random suffix, no name collisions between concurrent
exports), fsync, then rename \u2014 partial state never replaces the
live file
- Concurrency: advisory flock(LOCK_EX) held for the duration of
every write, including append from live messages and full rewrite
from export, so two profanity processes can't interleave bytes
on the same log
- DoS / abuse guards:
* FF_MAX_LINE_LEN = 10 MB \u2014 lines longer than this are rejected
at read with a warning; the parser will not allocate
unbounded memory for a single record
* FF_MAX_LMC_DEPTH = 100 \u2014 `corrects:` chain walk stops at this
depth and emits a warning, preventing a malicious correction
cycle from spinning the apply pass
* FF_VERSION_SCAN_MAX = 16 \u2014 header version probe never reads
past 16 leading comment lines, even on garbage input
* Empty / inverted byte-range early-return in page-up read path
so a malformed time filter cannot cause an unbounded scan
* Zero-entry index guard so a file whose every line failed to
parse cannot cause a NULL deref on later page-up
- LMC sender validation: an incoming correction whose sender does
not match the original message's sender is rejected at write
time and surfaced via cons_show_error; a cycle in the apply pass
is broken via a visited-set
- jid_create_from_bare_and_resource treats NULL, empty string, and
the literal "(null)" as no resource and returns a bare jid;
similar normalisation for barejid eliminates the legacy
"user@host/(null)" artefact that leaked into stored fulljids
whenever g_strdup_printf("%s", NULL) ran inside create_fulljid
Commands
- `/history switch sqlite|flatfile` \u2014 runtime backend swap, closes
the old backend and opens the new one without reconnecting
- `/history export [<jid>]` \u2014 SQLite -> flat-file, merging with any
existing flatlog (dedup keyed on a SHA-256 hash mixing stanza_id,
timestamp, from_jid, body \u2014 robust against id reuse by older
clients)
- `/history import [<jid>]` \u2014 flat-file -> SQLite, same merge
semantics, runs inside a single SQLite transaction with rollback
on per-contact failure
- `/history verify [<jid>]` \u2014 integrity check; emits a structured
list of issues (ERROR / WARNING / INFO) per file:
* file-level: missing log, wrong permissions (\u2260 0600), UTF-8
BOM present, CRLF line endings, empty file
* line-level: invalid UTF-8 (with byte offset), embedded
control characters, unparsable lines, timestamps out of
order, duplicate `id:` and `aid:` (tracked separately so a
stanza/archive id collision isn't double-reported)
* cross-line: broken `corrects:` references whose target id is
not present in the file
- `/history backend` \u2014 show currently active backend
- Active backend indicator `[sqlite]` / `[flatfile]` in the status
bar next to the JID
- Roster-JID autocomplete for verify / export / import
- export and import open a SQLite handle on demand when the
flatfile backend is currently active, so migration works
regardless of which backend is live
Tests
- Unit: database_export (parser round-trip, escape/unescape, dedup
key stability, JID normalisation), database_stress (14 cases
exercising rapid writes, large messages, deep LMC chains, MAM
dedup, concurrent contacts)
- Functional: history persistence across reconnects, export /
import round-trip with content equality, MUC migration,
timestamp normalisation across timezones
- Bench harness P1\u2013P5 (synthetic load: bulk insert, time-range
read, page-up scroll, MAM ingest, mixed workload) and failure
modes F1\u2013F17 (page-up cursor and forward-iteration symmetry,
oversized lines, MAM dedup, LMC depth and cycles, BOM/CRLF,
missing log, empty file, mtime+inode flip, broken corrects, etc.)
- All bench tests integrate with the existing make targets and
emit CSV rows for baseline comparison
Author: jabber.developer2 <jabber.developer2@jabber.space>
Reviewed-by: jabber.developer <jabber.developer@jabber.space>
173 lines
5.5 KiB
C
173 lines
5.5 KiB
C
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
//
|
|
// This file is part of CProof.
|
|
// See LICENSE for the full GPLv3 text and the special OpenSSL linking exception.
|
|
|
|
/*
|
|
* database_flatfile.h
|
|
* vim: expandtab:ts=4:sts=4:sw=4
|
|
*
|
|
* Internal header shared between database_flatfile*.c modules.
|
|
* Not part of the public API — do not include from outside the flatfile backend.
|
|
*/
|
|
|
|
#ifndef DATABASE_FLATFILE_H
|
|
#define DATABASE_FLATFILE_H
|
|
|
|
#include <glib.h>
|
|
#include <stdio.h>
|
|
#include <sys/types.h>
|
|
|
|
#include "database.h"
|
|
#include "xmpp/xmpp.h"
|
|
#include "xmpp/message.h"
|
|
|
|
// --- Constants ---
|
|
|
|
#define DIR_FLATLOG "flatlog"
|
|
#define FLATFILE_FORMAT_VERSION 1
|
|
#define FF_VERSION_MARKER "format-version: "
|
|
#define FF_STRINGIFY_(x) #x
|
|
#define FF_STRINGIFY(x) FF_STRINGIFY_(x)
|
|
#define FLATFILE_HEADER "# cproof chat log — UTF-8, LF line endings, " FF_VERSION_MARKER FF_STRINGIFY(FLATFILE_FORMAT_VERSION) "\n"
|
|
#define FF_MAX_LINE_LEN (10 * 1024 * 1024) /* 10 MB — reject lines longer than this */
|
|
#define FF_MAX_LMC_DEPTH 100 /* max correction chain depth */
|
|
|
|
// --- Shared global ---
|
|
|
|
// Account JID stored during init for path construction.
|
|
// Defined in database_flatfile.c, used by all flatfile modules.
|
|
extern char* g_flatfile_account_jid;
|
|
|
|
// --- Parsed line structure ---
|
|
|
|
typedef struct
|
|
{
|
|
char* timestamp_str;
|
|
GDateTime* timestamp;
|
|
char* type;
|
|
char* enc;
|
|
char* stanza_id;
|
|
char* archive_id;
|
|
char* replace_id;
|
|
char* from_jid;
|
|
char* from_resource;
|
|
char* to_jid;
|
|
char* to_resource;
|
|
int marked_read; // -1 = unset (NULL in DB), 0 = unread, 1 = read
|
|
char* message;
|
|
off_t file_offset;
|
|
} ff_parsed_line_t;
|
|
|
|
// --- Sparse index for single-file lookup ---
|
|
|
|
// Sample every N-th log line for the sparse index.
|
|
// 500 lines ≈ one index entry per ~50 KB of log data, so a 100K-message
|
|
// contact requires only ~200 entries (~3 KB) for O(log n) time-range lookup.
|
|
#define FF_INDEX_STEP 500
|
|
|
|
// --- Metadata field prefixes (used in _ff_cache_line_ids and ff_parse_line) ---
|
|
|
|
#define FF_META_PREFIX_ID "id:"
|
|
#define FF_META_PREFIX_AID "aid:"
|
|
|
|
typedef struct
|
|
{
|
|
off_t byte_offset;
|
|
gint64 timestamp_epoch;
|
|
} ff_index_entry_t;
|
|
|
|
typedef struct
|
|
{
|
|
time_t mtime;
|
|
off_t size;
|
|
ino_t inode;
|
|
} ff_file_stamp_t;
|
|
|
|
typedef struct
|
|
{
|
|
char* filepath;
|
|
ff_index_entry_t* entries;
|
|
size_t n_entries;
|
|
size_t cap_entries;
|
|
size_t total_lines;
|
|
ff_file_stamp_t stamp;
|
|
int bom_len;
|
|
GHashTable* archive_ids; // set: archive_id -> NULL (MAM dedup, O(1))
|
|
GHashTable* stanza_senders; // map: stanza_id -> from_jid (LMC validation, O(1))
|
|
} ff_contact_state_t;
|
|
|
|
// State management
|
|
ff_contact_state_t* ff_state_new(const char* filepath);
|
|
void ff_state_free(ff_contact_state_t* state);
|
|
gboolean ff_state_ensure_fresh(ff_contact_state_t* state);
|
|
off_t ff_state_offset_for_time(ff_contact_state_t* state, const char* iso_time);
|
|
|
|
// --- Type conversion helpers ---
|
|
|
|
const char* ff_get_message_type_str(prof_msg_type_t type);
|
|
prof_msg_type_t ff_get_message_type_type(const char* const type);
|
|
const char* ff_get_message_enc_str(prof_enc_t enc);
|
|
prof_enc_t ff_get_message_enc_type(const char* const encstr);
|
|
|
|
// --- Path helpers ---
|
|
|
|
char* ff_jid_to_dir(const char* jid);
|
|
char* ff_get_contact_dir(const char* contact_barejid);
|
|
char* ff_get_log_path(const char* contact_barejid);
|
|
gboolean ff_ensure_dir(const char* path);
|
|
|
|
// --- Escape / unescape ---
|
|
|
|
char* ff_escape_message(const char* text);
|
|
char* ff_unescape_message(const char* text);
|
|
char* ff_escape_meta_value(const char* val);
|
|
char* ff_unescape_meta_value(const char* val);
|
|
|
|
// --- I/O ---
|
|
|
|
// Skip UTF-8 BOM if present; returns 3 if skipped, 0 otherwise.
|
|
int ff_skip_bom(FILE* fp);
|
|
|
|
// Scan leading '#' comment lines for the format-version marker. Returns
|
|
// the version found, 0 if no marker is present, or -1 on read error.
|
|
// File position is rewound to the start of the comment block on entry.
|
|
int ff_read_format_version(FILE* fp);
|
|
|
|
char* ff_readline(FILE* fp, gboolean* truncated);
|
|
void ff_write_line(FILE* fp, const char* timestamp, const char* type, const char* enc,
|
|
const char* stanza_id, const char* archive_id, const char* replace_id,
|
|
const char* from_jid, const char* from_resource,
|
|
const char* to_jid, const char* to_resource, int marked_read,
|
|
const char* message_text);
|
|
|
|
// --- Parser helpers ---
|
|
|
|
const char* ff_find_unescaped_char(const char* str, char ch);
|
|
char** ff_split_meta(const char* meta);
|
|
const char* ff_find_unescaped_colonspace(const char* str);
|
|
char* ff_unescape_sender_resource(const char* res);
|
|
|
|
// --- Parser ---
|
|
|
|
void ff_parsed_line_free(ff_parsed_line_t* pl);
|
|
ff_parsed_line_t* ff_parse_line(const char* line);
|
|
ProfMessage* ff_parsed_to_profmessage(ff_parsed_line_t* pl);
|
|
|
|
// --- Integrity verification (database_flatfile_verify.c) ---
|
|
|
|
// Run integrity checks against one contact's history.log (or every contact
|
|
// when contact_barejid == NULL).
|
|
//
|
|
// Returns a freshly allocated GSList<integrity_issue_t*> reporting:
|
|
// - File-level: missing log, BOM, CRLF, empty, wrong permissions
|
|
// - Line-level: invalid UTF-8, control characters, unparsable lines,
|
|
// timestamps out of order, duplicate stanza-id /
|
|
// archive-id (tracked separately)
|
|
// - Cross-line: broken `corrects:` LMC references
|
|
//
|
|
// Callers must free with g_slist_free_full(issues, integrity_issue_free).
|
|
GSList* ff_verify_integrity(const gchar* const contact_barejid);
|
|
|
|
#endif
|