Files
cproof/src/database_flatfile_parser.c
Jabber Developer 3f36c303c2
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
feat(history): flat-file backend with bidirectional SQLite migration
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>
2026-05-05 19:26:07 +00:00

826 lines
25 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_parser.c
* vim: expandtab:ts=4:sts=4:sw=4
*
* Flat-file backend: type helpers, path helpers, escape/unescape,
* line I/O, and the tolerant log-line parser.
*/
#include "config.h"
#include <sys/stat.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "log.h"
#include "common.h"
#include "config/files.h"
#include "database_flatfile.h"
// =========================================================================
// Type conversion helpers
// =========================================================================
const char*
ff_get_message_type_str(prof_msg_type_t type)
{
switch (type) {
case PROF_MSG_TYPE_CHAT:
return "chat";
case PROF_MSG_TYPE_MUC:
return "muc";
case PROF_MSG_TYPE_MUCPM:
return "mucpm";
case PROF_MSG_TYPE_UNINITIALIZED:
return "chat";
}
return "chat";
}
prof_msg_type_t
ff_get_message_type_type(const char* const type)
{
if (g_strcmp0(type, "chat") == 0) {
return PROF_MSG_TYPE_CHAT;
} else if (g_strcmp0(type, "muc") == 0) {
return PROF_MSG_TYPE_MUC;
} else if (g_strcmp0(type, "mucpm") == 0) {
return PROF_MSG_TYPE_MUCPM;
}
return PROF_MSG_TYPE_CHAT;
}
const char*
ff_get_message_enc_str(prof_enc_t enc)
{
switch (enc) {
case PROF_MSG_ENC_OX:
return "ox";
case PROF_MSG_ENC_PGP:
return "pgp";
case PROF_MSG_ENC_OTR:
return "otr";
case PROF_MSG_ENC_OMEMO:
return "omemo";
case PROF_MSG_ENC_NONE:
return "none";
}
return "none";
}
prof_enc_t
ff_get_message_enc_type(const char* const encstr)
{
if (g_strcmp0(encstr, "ox") == 0) {
return PROF_MSG_ENC_OX;
} else if (g_strcmp0(encstr, "pgp") == 0) {
return PROF_MSG_ENC_PGP;
} else if (g_strcmp0(encstr, "otr") == 0) {
return PROF_MSG_ENC_OTR;
} else if (g_strcmp0(encstr, "omemo") == 0) {
return PROF_MSG_ENC_OMEMO;
}
return PROF_MSG_ENC_NONE;
}
// =========================================================================
// Path helpers
// =========================================================================
// Sanitise a JID for use as a directory name.
// 1. Replace '@' with '_at_'
// 2. Reject / strip path-separator and traversal characters: '/', '\\', '..'
// This prevents a malicious federated JID like "../../../tmp/pwned" from
// escaping the log directory tree.
char*
ff_jid_to_dir(const char* jid)
{
if (!jid || jid[0] == '\0')
return NULL;
// Replace '@' with '_at_' (str_replace returns a freshly allocated string)
char* result = str_replace(jid, "@", "_at_");
if (!result)
return NULL;
// Replace path-separator characters in place
for (char* p = result; *p; p++) {
if (*p == '/' || *p == '\\')
*p = '_';
}
// Collapse any remaining ".." sequences to "__" (belt-and-suspenders)
char* dotdot;
while ((dotdot = strstr(result, "..")) != NULL) {
dotdot[0] = '_';
dotdot[1] = '_';
}
if (result[0] == '\0') {
free(result);
return NULL;
}
// Callers free via g_free, str_replace allocates via malloc — handover.
char* gresult = g_strdup(result);
free(result);
return gresult;
}
// Get the base directory for a contact's logs:
// ~/.local/share/profanity/flatlog/{my_jid_dir}/{contact_jid_dir}/
char*
ff_get_contact_dir(const char* contact_barejid)
{
if (!g_flatfile_account_jid || !contact_barejid)
return NULL;
auto_gchar gchar* data_path = files_get_data_path(DIR_FLATLOG);
auto_gchar gchar* my_dir = ff_jid_to_dir(g_flatfile_account_jid);
auto_gchar gchar* contact_dir = ff_jid_to_dir(contact_barejid);
char* result = g_strdup_printf("%s/%s/%s", data_path, my_dir, contact_dir);
return result;
}
// Get the single log file path for a contact: {contact_dir}/history.log
char*
ff_get_log_path(const char* contact_barejid)
{
auto_gchar gchar* contact_dir = ff_get_contact_dir(contact_barejid);
if (!contact_dir)
return NULL;
char* result = g_strdup_printf("%s/history.log", contact_dir);
return result;
}
// Ensure the directory exists, create if needed.
// Refuses to follow symlinks at the final component.
gboolean
ff_ensure_dir(const char* path)
{
if (g_file_test(path, G_FILE_TEST_IS_SYMLINK)) {
log_error("flatfile: directory path is a symlink, refusing: %s", path);
return FALSE;
}
if (g_file_test(path, G_FILE_TEST_IS_DIR))
return TRUE;
if (g_mkdir_with_parents(path, S_IRWXU) != 0) {
log_error("flatfile: Could not create directory: %s (errno=%d)", path, errno);
return FALSE;
}
return TRUE;
}
// =========================================================================
// Escape / unescape helpers
// =========================================================================
//
// Message text and metadata values from remote peers can contain arbitrary
// characters including newlines, pipes and brackets. Without escaping, a
// crafted message could inject fake log lines (log injection / format
// injection). We escape on write and unescape on read.
// Escape message body: \ -> \\, \n -> \n literal, \r -> \r literal
char*
ff_escape_message(const char* text)
{
if (!text)
return g_strdup("");
GString* out = g_string_sized_new(strlen(text));
for (const char* p = text; *p; p++) {
switch (*p) {
case '\\':
g_string_append(out, "\\\\");
break;
case '\n':
g_string_append(out, "\\n");
break;
case '\r':
g_string_append(out, "\\r");
break;
default:
g_string_append_c(out, *p);
break;
}
}
return g_string_free(out, FALSE);
}
// Unescape message body: \\ -> \, \n -> newline, \r -> CR
char*
ff_unescape_message(const char* text)
{
if (!text)
return g_strdup("");
GString* out = g_string_sized_new(strlen(text));
for (const char* p = text; *p; p++) {
if (*p != '\\' || !*(p + 1)) {
g_string_append_c(out, *p);
continue;
}
p++;
switch (*p) {
case '\\':
g_string_append_c(out, '\\');
break;
case 'n':
g_string_append_c(out, '\n');
break;
case 'r':
g_string_append_c(out, '\r');
break;
default:
g_string_append_c(out, '\\');
g_string_append_c(out, *p);
break;
}
}
return g_string_free(out, FALSE);
}
// Escape metadata value (stanza_id, archive_id, replace_id):
// these come from remote servers and may contain |, ], \, newlines.
char*
ff_escape_meta_value(const char* val)
{
if (!val || strlen(val) == 0)
return NULL;
GString* out = g_string_sized_new(strlen(val));
for (const char* p = val; *p; p++) {
switch (*p) {
case '|':
g_string_append(out, "\\|");
break;
case ']':
g_string_append(out, "\\]");
break;
case '\\':
g_string_append(out, "\\\\");
break;
case '\n':
g_string_append(out, "\\n");
break;
case '\r':
g_string_append(out, "\\r");
break;
default:
g_string_append_c(out, *p);
break;
}
}
return g_string_free(out, FALSE);
}
// Unescape metadata value
char*
ff_unescape_meta_value(const char* val)
{
if (!val)
return NULL;
GString* out = g_string_sized_new(strlen(val));
for (const char* p = val; *p; p++) {
if (*p != '\\' || !*(p + 1)) {
g_string_append_c(out, *p);
continue;
}
p++;
switch (*p) {
case '|':
g_string_append_c(out, '|');
break;
case ']':
g_string_append_c(out, ']');
break;
case '\\':
g_string_append_c(out, '\\');
break;
case 'n':
g_string_append_c(out, '\n');
break;
case 'r':
g_string_append_c(out, '\r');
break;
default:
g_string_append_c(out, '\\');
g_string_append_c(out, *p);
break;
}
}
return g_string_free(out, FALSE);
}
// =========================================================================
// BOM helper
// =========================================================================
//
// Skip UTF-8 BOM (EF BB BF) at the beginning of a file.
// Returns 3 if BOM was present, 0 otherwise. File position is set past
// the BOM (or rewound to the start).
int
ff_skip_bom(FILE* fp)
{
int c1 = fgetc(fp);
int c2 = fgetc(fp);
int c3 = fgetc(fp);
if (c1 == 0xEF && c2 == 0xBB && c3 == 0xBF)
return 3;
fseek(fp, 0, SEEK_SET);
return 0;
}
// Format-version helper
// =========================================================================
//
// Scan leading '#' comment lines for the `format-version: <N>` marker
// (anywhere within the comment line). Stops at the first non-comment
// line or after FF_VERSION_SCAN_MAX comments. Restores fp to its
// position at entry, so callers can re-parse the header normally
// afterwards.
#define FF_VERSION_SCAN_MAX 16
int
ff_read_format_version(FILE* fp)
{
long start = ftell(fp);
if (start < 0)
return -1;
int version = 0;
size_t marker_len = strlen(FF_VERSION_MARKER);
for (int i = 0; i < FF_VERSION_SCAN_MAX; i++) {
gboolean truncated = FALSE;
char* line = ff_readline(fp, &truncated);
if (!line)
break;
if (line[0] != '#') {
free(line);
break;
}
char* found = strstr(line, FF_VERSION_MARKER);
if (found) {
char* num_start = found + marker_len;
char* endptr = NULL;
long v = strtol(num_start, &endptr, 10);
if (endptr != num_start && v > 0 && v <= INT_MAX)
version = (int)v;
free(line);
break;
}
free(line);
}
fseek(fp, start, SEEK_SET);
return version;
}
// Readline helper
// =========================================================================
//
// POSIX getline() for dynamic-length lines. Returns line without trailing
// newline, or NULL on EOF. Sets *truncated=TRUE if the line had no trailing
// newline at EOF (partial write detection).
char*
ff_readline(FILE* fp, gboolean* truncated)
{
char* line = NULL;
size_t cap = 0;
ssize_t nread = getline(&line, &cap, fp);
if (nread == -1) {
free(line);
return NULL;
}
// Guard against pathological lines that could exhaust memory.
// getline() already allocated, so we free and skip if too long.
if (nread > FF_MAX_LINE_LEN) {
log_error("flatfile: line too long (%zd bytes), skipping", nread);
// Check newline termination before freeing
gboolean had_newline = (nread > 0 && line[nread - 1] == '\n');
free(line);
// Skip to next newline if the overlength line wasn't newline-terminated
if (!had_newline) {
int ch;
while ((ch = fgetc(fp)) != EOF && ch != '\n') {}
}
if (truncated)
*truncated = FALSE;
// Return empty string so caller's loop continues (parse will reject it).
// strdup() so callers can always free() consistently.
return strdup("");
}
if (truncated)
*truncated = FALSE;
if (nread > 0 && line[nread - 1] == '\n') {
line[--nread] = '\0';
} else if (feof(fp)) {
// Line without trailing newline at EOF — likely a partial write
if (truncated)
*truncated = TRUE;
}
return line;
}
// =========================================================================
// Line writer
// =========================================================================
//
// Format: {ISO8601} [{type}|{enc}|id:{stanza_id}|aid:{archive_id}|corrects:{replace_id}] {from_jid}/{resource}: {message}
//
// Message text is escaped: \\ -> \\\\, newline -> \\n, CR -> \\r
// Metadata values are escaped: |, ], \\, newline, CR
// Lines starting with '#' are comments.
// Empty lines are skipped.
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)
{
// Escape metadata values from remote peers
auto_gchar gchar* safe_sid = ff_escape_meta_value(stanza_id);
auto_gchar gchar* safe_aid = ff_escape_meta_value(archive_id);
auto_gchar gchar* safe_rid = ff_escape_meta_value(replace_id);
// Build metadata section: [type|enc|id:...|aid:...|corrects:...|to:...|to_res:...|read:...]
GString* meta = g_string_new("[");
g_string_append(meta, type ? type : "chat");
g_string_append_c(meta, '|');
g_string_append(meta, enc ? enc : "none");
if (safe_sid) {
g_string_append_printf(meta, "|id:%s", safe_sid);
}
if (safe_aid) {
g_string_append_printf(meta, "|aid:%s", safe_aid);
}
if (safe_rid) {
g_string_append_printf(meta, "|corrects:%s", safe_rid);
}
if (to_jid && strlen(to_jid) > 0
&& g_strcmp0(to_jid, "(null)") != 0) {
auto_gchar gchar* safe_to = ff_escape_meta_value(to_jid);
g_string_append_printf(meta, "|to:%s", safe_to);
}
if (to_resource && strlen(to_resource) > 0
&& g_strcmp0(to_resource, "(null)") != 0) {
auto_gchar gchar* safe_tores = ff_escape_meta_value(to_resource);
g_string_append_printf(meta, "|to_res:%s", safe_tores);
}
if (marked_read >= 0) {
g_string_append_printf(meta, "|read:%d", marked_read ? 1 : 0);
}
g_string_append_c(meta, ']');
// Build sender — escape ": " in the resource part to prevent
// the parser from splitting at the wrong point.
const gboolean from_jid_usable = from_jid && *from_jid
&& g_strcmp0(from_jid, "(null)") != 0;
GString* sender = g_string_new(from_jid_usable ? from_jid : "unknown");
if (from_resource && strlen(from_resource) > 0
&& g_strcmp0(from_resource, "(null)") != 0) {
// Escape backslash and colon-space in resource
GString* safe_res = g_string_sized_new(strlen(from_resource));
for (const char* p = from_resource; *p; p++) {
if (*p == '\\') {
g_string_append(safe_res, "\\\\");
} else if (*p == ':' && *(p + 1) == ' ') {
g_string_append(safe_res, "\\: ");
p++; // skip the space too
} else {
g_string_append_c(safe_res, *p);
}
}
g_string_append_printf(sender, "/%s", safe_res->str);
g_string_free(safe_res, TRUE);
}
// Escape message body to prevent log injection
auto_char char* safe_msg = ff_escape_message(message_text);
int ret = fprintf(fp, "%s %s %s: %s\n",
timestamp, meta->str, sender->str, safe_msg);
if (ret < 0) {
log_error("flatfile: fprintf failed (errno=%d)", errno);
}
g_string_free(meta, TRUE);
g_string_free(sender, TRUE);
}
// =========================================================================
// Parser helpers
// =========================================================================
// Find the first occurrence of 'ch' that is not preceded by an unescaped backslash.
const char*
ff_find_unescaped_char(const char* str, char ch)
{
if (!str)
return NULL;
for (const char* p = str; *p; p++) {
if (*p == '\\' && *(p + 1)) {
p++; // skip escaped character
continue;
}
if (*p == ch)
return p;
}
return NULL;
}
// Split metadata content on unescaped '|'. Returns a NULL-terminated array.
// Caller must g_strfreev() the result.
char**
ff_split_meta(const char* meta)
{
GPtrArray* arr = g_ptr_array_new();
const char* start = meta;
for (const char* p = meta;; p++) {
if (*p == '\\' && *(p + 1)) {
p++; // skip escaped char
continue;
}
if (*p == '|' || *p == '\0') {
g_ptr_array_add(arr, g_strndup(start, p - start));
if (*p == '\0')
break;
start = p + 1;
}
}
g_ptr_array_add(arr, NULL);
return (char**)g_ptr_array_free(arr, FALSE);
}
// Find first unescaped ": " (colon-space) in a string.
const char*
ff_find_unescaped_colonspace(const char* str)
{
if (!str)
return NULL;
for (const char* p = str; *p; p++) {
if (*p == '\\' && *(p + 1)) {
p++; // skip escaped character
continue;
}
if (*p == ':' && *(p + 1) == ' ') {
return p;
}
}
return NULL;
}
// Unescape a sender resource: "\\" -> '\', "\: " -> ": "
char*
ff_unescape_sender_resource(const char* res)
{
if (!res)
return NULL;
GString* out = g_string_sized_new(strlen(res));
for (const char* p = res; *p; p++) {
if (*p != '\\' || !*(p + 1)) {
g_string_append_c(out, *p);
continue;
}
p++;
if (*p == '\\') {
g_string_append_c(out, '\\');
} else if (*p == ':' && *(p + 1) == ' ') {
g_string_append(out, ": ");
p++; // skip the space
} else {
// Unknown escape — preserve literally
g_string_append_c(out, '\\');
g_string_append_c(out, *p);
}
}
return g_string_free(out, FALSE);
}
// =========================================================================
// Line parser
// =========================================================================
void
ff_parsed_line_free(ff_parsed_line_t* pl)
{
if (!pl)
return;
g_free(pl->timestamp_str);
if (pl->timestamp)
g_date_time_unref(pl->timestamp);
g_free(pl->type);
g_free(pl->enc);
g_free(pl->stanza_id);
g_free(pl->archive_id);
g_free(pl->replace_id);
g_free(pl->from_jid);
g_free(pl->from_resource);
g_free(pl->to_jid);
g_free(pl->to_resource);
g_free(pl->message);
g_free(pl);
}
// Populate the parsed-line metadata fields from the pipe-split parts[]
// (the contents of a "[...]" section). Index 0 is type, index 1 is enc;
// remaining parts are key:value pairs (id:, aid:, corrects:, to:, to_res:, read:).
static void
_ff_parse_meta_parts(char** parts, ff_parsed_line_t* out)
{
for (int i = 0; parts[i]; i++) {
if (i == 0) {
out->type = g_strdup(parts[i]);
} else if (i == 1) {
out->enc = g_strdup(parts[i]);
} else if (g_str_has_prefix(parts[i], FF_META_PREFIX_ID)) {
out->stanza_id = ff_unescape_meta_value(parts[i] + strlen(FF_META_PREFIX_ID));
} else if (g_str_has_prefix(parts[i], FF_META_PREFIX_AID)) {
out->archive_id = ff_unescape_meta_value(parts[i] + strlen(FF_META_PREFIX_AID));
} else if (g_str_has_prefix(parts[i], "corrects:")) {
out->replace_id = ff_unescape_meta_value(parts[i] + strlen("corrects:"));
} else if (g_str_has_prefix(parts[i], "to:")) {
out->to_jid = ff_unescape_meta_value(parts[i] + strlen("to:"));
} else if (g_str_has_prefix(parts[i], "to_res:")) {
out->to_resource = ff_unescape_meta_value(parts[i] + strlen("to_res:"));
} else if (g_str_has_prefix(parts[i], "read:")) {
out->marked_read = atoi(parts[i] + strlen("read:")) ? 1 : 0;
}
}
}
// Parse a single line. Returns NULL on parse failure.
// Line format: {timestamp} [{metadata}] {sender}: {message}
ff_parsed_line_t*
ff_parse_line(const char* line)
{
if (!line || line[0] == '\0' || line[0] == '#') {
return NULL;
}
// Strip trailing \r if present (CRLF handling)
char* work = g_strdup(line);
gsize len = strlen(work);
if (len > 0 && work[len - 1] == '\r') {
work[len - 1] = '\0';
len--;
}
if (len == 0) {
g_free(work);
return NULL;
}
// UTF-8 validation
const gchar* end;
if (!g_utf8_validate(work, -1, &end)) {
log_warning("flatfile: invalid UTF-8 at byte offset %ld", (long)(end - work));
// Attempt Latin-1 fallback
gsize br, bw;
GError* err = NULL;
char* converted = g_convert(work, -1, "UTF-8", "ISO-8859-1", &br, &bw, &err);
if (converted) {
g_free(work);
work = converted;
} else {
if (err)
g_error_free(err);
g_free(work);
return NULL;
}
}
ff_parsed_line_t* result = g_malloc0(sizeof(ff_parsed_line_t));
result->file_offset = -1;
result->marked_read = -1; // unset by default
// Parse timestamp — everything up to first space followed by '['
char* bracket_start = strchr(work, '[');
char* first_space = strchr(work, ' ');
if (bracket_start && first_space && first_space < bracket_start) {
// Standard format with metadata: {timestamp} [{meta}] {sender}: {msg}
result->timestamp_str = g_strndup(work, first_space - work);
// Parse metadata section [...]
const char* bracket_end = ff_find_unescaped_char(bracket_start + 1, ']');
if (!bracket_end) {
// No closing bracket — malformed metadata
ff_parsed_line_free(result);
g_free(work);
return NULL;
}
auto_gchar gchar* meta_content = g_strndup(bracket_start + 1, bracket_end - bracket_start - 1);
char** parts = ff_split_meta(meta_content);
if (parts) {
_ff_parse_meta_parts(parts, result);
g_strfreev(parts);
}
// Parse sender: message after '] '
const char* after_meta = bracket_end + 1;
if (*after_meta == ' ')
after_meta++;
// Find first *unescaped* ': ' which separates sender from message.
const char* colon = ff_find_unescaped_colonspace(after_meta);
if (colon) {
auto_gchar gchar* raw_sender = g_strndup(after_meta, colon - after_meta);
// Split sender into jid/resource, then unescape resource
char* slash = strchr(raw_sender, '/');
if (slash) {
result->from_jid = g_strndup(raw_sender, slash - raw_sender);
result->from_resource = ff_unescape_sender_resource(slash + 1);
} else {
result->from_jid = g_strdup(raw_sender);
}
result->message = ff_unescape_message(colon + 2);
} else {
// No ': ' found, treat entire rest as message with unknown sender
result->from_jid = g_strdup("unknown");
result->message = ff_unescape_message(after_meta);
}
} else if (first_space) {
// Legacy/simple format without metadata: {timestamp} - {sender}: {msg}
result->timestamp_str = g_strndup(work, first_space - work);
result->type = g_strdup("chat");
result->enc = g_strdup("none");
char* rest = first_space + 1;
// Skip " - " if present (chatlog.c format)
if (g_str_has_prefix(rest, "- ")) {
rest += 2;
}
char* colon = strstr(rest, ": ");
if (colon) {
char* sender = g_strndup(rest, colon - rest);
char* slash = strchr(sender, '/');
if (slash) {
result->from_jid = g_strndup(sender, slash - sender);
result->from_resource = g_strdup(slash + 1);
} else {
result->from_jid = g_strdup(sender);
}
g_free(sender);
result->message = ff_unescape_message(colon + 2);
} else {
result->from_jid = g_strdup("unknown");
result->message = ff_unescape_message(rest);
}
} else {
// No space at all — can't parse
ff_parsed_line_free(result);
g_free(work);
return NULL;
}
// Parse timestamp
result->timestamp = g_date_time_new_from_iso8601(result->timestamp_str, NULL);
if (!result->timestamp) {
log_warning("flatfile: unparsable timestamp: %s", result->timestamp_str);
ff_parsed_line_free(result);
g_free(work);
return NULL;
}
// Default type/enc if missing
if (!result->type)
result->type = g_strdup("chat");
if (!result->enc)
result->enc = g_strdup("none");
g_free(work);
return result;
}
// Convert parsed line to ProfMessage
ProfMessage*
ff_parsed_to_profmessage(ff_parsed_line_t* pl)
{
ProfMessage* msg = message_init();
msg->id = pl->stanza_id ? g_strdup(pl->stanza_id) : NULL;
msg->from_jid = jid_create_from_bare_and_resource(pl->from_jid, pl->from_resource);
if (pl->to_jid) {
msg->to_jid = jid_create_from_bare_and_resource(pl->to_jid, pl->to_resource);
}
msg->plain = g_strdup(pl->message ? pl->message : "");
msg->timestamp = g_date_time_ref(pl->timestamp);
msg->type = ff_get_message_type_type(pl->type);
msg->enc = ff_get_message_enc_type(pl->enc);
return msg;
}