no-DB mode implementation #94

Manually merged
jabber.developer merged 34 commits from feat/no-db-mode into master 2026-05-05 19:32:42 +00:00

34 Commits

Author SHA1 Message Date
26db671a38 fix(export): hash stanza_id with content instead of trusting it as sole dedup key
All checks were successful
CI Code / Check spelling (pull_request) Successful in 26s
CI Code / Check coding style (pull_request) Successful in 1m6s
CI Code / Code Coverage (pull_request) Successful in 2m44s
CI Code / Linux (ubuntu) (pull_request) Successful in 4m50s
CI Code / Linux (arch) (pull_request) Successful in 5m25s
CI Code / Linux (debian) (pull_request) Successful in 6m50s
2026-05-05 16:06:54 +03:00
2990ec795a refactor(flatfile): single-line file header with format-version marker
All checks were successful
CI Code / Check spelling (pull_request) Successful in 1m32s
CI Code / Check coding style (pull_request) Successful in 3m14s
CI Code / Code Coverage (pull_request) Successful in 2m44s
CI Code / Linux (debian) (pull_request) Successful in 4m50s
CI Code / Linux (arch) (pull_request) Successful in 5m33s
CI Code / Linux (ubuntu) (pull_request) Successful in 6m51s
2026-05-05 14:56:07 +03:00
b8a4900393 fix(jid): treat NULL/empty/"(null)" barejid the same as resource
Some checks failed
CI Code / Check spelling (pull_request) Successful in 2m0s
CI Code / Check coding style (pull_request) Failing after 2m10s
CI Code / Linux (debian) (pull_request) Successful in 8m29s
CI Code / Linux (ubuntu) (pull_request) Successful in 8m33s
CI Code / Code Coverage (pull_request) Successful in 6m50s
CI Code / Linux (arch) (pull_request) Successful in 10m30s
2026-05-04 18:52:39 +03:00
3daee1216b fix(jid): treat NULL/empty/"(null)" resource as bare jid
Some checks failed
CI Code / Code Coverage (pull_request) Failing after 13m44s
CI Code / Check spelling (pull_request) Failing after 14m13s
CI Code / Check coding style (pull_request) Failing after 14m43s
CI Code / Linux (ubuntu) (pull_request) Failing after 15m16s
CI Code / Linux (debian) (pull_request) Failing after 15m53s
CI Code / Linux (arch) (pull_request) Failing after 16m23s
2026-05-04 18:29:55 +03:00
024e4b2336 style(flatfile): drop vim modeline from log file header 2026-05-04 18:29:55 +03:00
09b2295414 fix(export): open sqlite on demand when flatfile is active backend
Some checks failed
CI Code / Code Coverage (pull_request) Failing after 12m27s
CI Code / Check spelling (pull_request) Failing after 12m56s
CI Code / Check coding style (pull_request) Failing after 13m33s
CI Code / Linux (ubuntu) (pull_request) Failing after 14m3s
CI Code / Linux (debian) (pull_request) Failing after 14m38s
CI Code / Linux (arch) (pull_request) Failing after 15m12s
2026-05-04 17:35:59 +03:00
16aa569329 feat(history): /history backend command and status-bar indicator
Some checks failed
CI Code / Code Coverage (pull_request) Failing after 10m31s
CI Code / Check spelling (pull_request) Failing after 11m2s
CI Code / Check coding style (pull_request) Failing after 11m33s
CI Code / Linux (ubuntu) (pull_request) Failing after 12m2s
CI Code / Linux (debian) (pull_request) Failing after 12m33s
CI Code / Linux (arch) (pull_request) Failing after 13m5s
2026-05-04 17:17:41 +03:00
48b89460b7 feat(flatfile): warn on missing or mismatched log format-version 2026-05-04 17:17:33 +03:00
a9b181beb7 test(bench): add F17 forward-iteration coverage symmetric to F16 2026-05-04 17:16:01 +03:00
52f97f7195 feat(history): autocomplete JID for verify/export/import
Some checks failed
CI Code / Code Coverage (pull_request) Failing after 12m11s
CI Code / Check spelling (pull_request) Failing after 12m14s
CI Code / Check coding style (pull_request) Failing after 12m19s
CI Code / Linux (ubuntu) (pull_request) Failing after 12m25s
CI Code / Linux (debian) (pull_request) Failing after 12m28s
CI Code / Linux (arch) (pull_request) Failing after 12m32s
2026-05-04 15:42:19 +03:00
352eb26f71 refactor(flatfile): drop dead cursor_offset, guard inverted range
Some checks failed
CI Code / Check spelling (pull_request) Successful in 1m25s
CI Code / Check coding style (pull_request) Successful in 2m11s
CI Code / Linux (ubuntu) (pull_request) Successful in 4m47s
CI Code / Linux (debian) (pull_request) Successful in 7m58s
CI Code / Code Coverage (pull_request) Failing after 11m18s
CI Code / Linux (arch) (pull_request) Failing after 11m32s
2026-05-04 15:30:45 +03:00
875f8f4100 fix(flatfile): drop cursor optim + guard n_entries==0
Some checks failed
CI Code / Check spelling (pull_request) Failing after 22s
CI Code / Check coding style (pull_request) Successful in 34s
CI Code / Linux (debian) (pull_request) Successful in 5m23s
CI Code / Linux (arch) (pull_request) Successful in 6m1s
CI Code / Linux (ubuntu) (pull_request) Successful in 7m18s
CI Code / Code Coverage (pull_request) Successful in 7m32s
Cursor was set to oldest of read window, not oldest of returned
batch — each page-up jumped past entire ranges (F16: 600/2000 msgs).
Always bisect now; correct + simpler. Cost: +5-10 ms per page-up at
1M msgs, well below UI threshold.

Also guard state->entries NULL when total_lines>0 && n_entries==0
(every line failed _ff_maybe_index_line). Backup would segfault.

F16 tightened to received == total_msgs. Catches both stuck-on-
entries[0] and cursor-jumping regressions.
2026-05-04 15:09:51 +03:00
a7da9e2add fix(flatfile): page-up cursor must not stick on entries[0]
All checks were successful
CI Code / Check spelling (pull_request) Successful in 23s
CI Code / Check coding style (pull_request) Successful in 37s
CI Code / Code Coverage (pull_request) Successful in 2m39s
CI Code / Linux (debian) (pull_request) Successful in 4m51s
CI Code / Linux (ubuntu) (pull_request) Successful in 6m47s
CI Code / Linux (arch) (pull_request) Successful in 9m59s
When the cursor lands on entries[0].byte_offset, the !from_start
backup logic produces an empty [X, X) range, get_previous_chat
returns DB_RESPONSE_EMPTY, the UI sets WIN_SCROLL_REACHED_TOP and
never tries again — page-up is permanently stuck.

Guard the cursor optimisation with two conditions: index must be
non-empty AND cursor must not equal entries[0].byte_offset. When
either fails, fall through to the end_time bisect path which
correctly locates the byte range with older messages.

F16 regression test in bench_failure_modes:
  without guard: received=200 in 3 iters (premature EMPTY)
  with guard:    received=600 in 7 iters (truly reaches top)
2026-05-04 12:14:54 +03:00
1fe3808b23 style(export): gchar*/g_free consistency + auto_char in read loop
All checks were successful
CI Code / Check spelling (pull_request) Successful in 2m12s
CI Code / Check coding style (pull_request) Successful in 2m23s
CI Code / Linux (arch) (pull_request) Successful in 5m35s
CI Code / Linux (debian) (pull_request) Successful in 6m59s
CI Code / Linux (ubuntu) (pull_request) Successful in 7m41s
CI Code / Code Coverage (pull_request) Successful in 6m59s
2026-05-02 16:18:48 +03:00
555faaa232 perf+harden(export): 25x faster export at 1M, mkstemp, full-body dedup
Some checks failed
CI Code / Check spelling (pull_request) Failing after 21s
CI Code / Linux (arch) (pull_request) Failing after 3m6s
CI Code / Check coding style (pull_request) Failing after 3m10s
CI Code / Code Coverage (pull_request) Successful in 2m49s
CI Code / Linux (debian) (pull_request) Successful in 4m26s
CI Code / Linux (ubuntu) (pull_request) Successful in 4m38s
Address 6 of 7 high/medium audit findings on database_export.c.
End-to-end migration of 1M rows: ~5 min -> ~1 min.

  H1  cache g_slist_length(merged) out of the write loop — was O(n²)
      via 2000 list walks at 500-row progress interval, now O(1).
        S7a_export_cold @ 1M:  309 s -> 11.2 s  (-96 %)

  L1  splice existing flatfile lines into merged via ownership
      transfer instead of 12-strdup deep-copy + g_date_time_ref;
      free list nodes only, NULL out existing.
        S7b_export_dedup @ 1M: 304 s -> 13.3 s  (-96 %)
        RSS @ S7b 1M: 2.4 GB -> 1.9 GB

  H2  mkstemp() with random suffix instead of fixed
      "{log_path}.export.tmp". Eliminates the unlink-and-retry race
      where two concurrent exports could clobber each other's
      in-flight tmp files.

  M4  SHA-256 over full body (incremental g_checksum_update) in
      the dedup-key fallback. Previous body[:256] hash collided
      on common preambles (signatures, code blocks) — second
      occurrence silently dropped on import.

  M2  Refuse _ff_read_all_lines on files > 2 GB. Each line expands
      ~10x in heap on parse; without a cap we OOM-kill prof on
      large flatfiles. Surface a clear error instead.

  M5  Break the outer import loop on system-level INSERT failure.
      Was cascading "Import of X failed" through every remaining
      contact when the real issue was disk-full / sqlite locked.

Verified on bench-pipeline-max: 1M rows, full content diff,
mismatches=0. baseline.csv updated.

Deferred: M3 O_TMPFILE (platform-conditional + linkat dance;
mkstemp covers most of the same window) and M6 SIGINT cancellation
(needs event-loop architecture changes).
2026-04-30 17:10:39 +03:00
b1d820462a feat(bench): synthetic load harness for flat-file backend (P1-P5)
End-to-end performance and correctness harness for the flat-file +
SQLite database backends. Lives in tests/bench/, built only on
demand (`make bench`); not part of `make check`.

Components

  gen_history (P1)
    Deterministic corpus generator. Knobs: lines, contacts, years,
    seed, stanza-id mode (uuid/libpurple/conversations/mixed), LMC
    rate, MAM-OOO rate, resources/contact, length profile
    (short/mixed/long/extreme). Emits the canonical
    flatlog/<account>/<contact>/history.log layout used by
    ff_verify_integrity. ~340 LOC.

  bench_runner (P1, P2.5)
    S1 cold tail-access via sparse index
    S2 warm tail-access (page cache hot)
    S3 deep pagination (1000 binary-search lookups)
    S4 first-time index build (cold file -> ff_state_ensure_fresh)
    S5 incremental extend (asserts no full rebuild path)
    S6 real ff_verify_integrity over the contact tree
    Reports total/err/warn/info issue counts in the CSV note.

  bench_long_messages (P2)
    L1-L14 long-message stress: 1KB up to 9.9MB bodies, plus
    oversized line rejection (10MB+1 -> ff_readline returns ""),
    embedded-newline / pipe / emoji body patterns, full parse on
    100x1MB, 1000x100KB sustained append.

  bench_failure_modes (P3)
    F1-F15 failure-injection: truncated last line, mid-file CRLF,
    mid-file BOM, LMC cycle, LMC depth>FF_MAX_LMC_DEPTH, manual
    ': ' in resource, RTL/ZWSP, Latin-1 byte, empty body,
    mtime/inode flip, empty file. Each test asserts expected issue
    levels and reports PASS/FAIL.

  bench_export_import (P5)
    Links real database_export.c + database_sqlite.c + database.c
    and drives log_database_export_to_flatfile /
    log_database_import_from_flatfile under load.
    Subcommands: seed, export, import, roundtrip, verify.
    S7a/b export, S8a/b import, S8e roundtrip with full byte-by-byte
    content diff of every row in (from_jid, to_jid, message,
    timestamp, type, stanza_id, archive_id, encryption, replace_id).

Make targets

  bench-quick / bench / bench-full
  bench-longmsg, bench-failure
  bench-multicontact, bench-lmc, bench-ooo
  bench-export, bench-import, bench-roundtrip
  bench-pipeline, bench-pipeline-max (1M rows)
  bench-compare, bench-update-baseline

Volume controls: BENCH_VOLUME (small/medium/max), BENCH_PIPE_ROWS,
BENCH_PIPE_ROWS_MAX, BENCH_DATA_DIR, BENCH_CSV.

Baseline + regression checking (P4)

  tests/bench/baseline.csv       51 rows: S1-S6 x {small,lmc,ooo}
                                 + L1-L14 + F1-F15 (11 of 15) +
                                 S7/S8 x {pipe100k, pipe1M}.
  compare_baseline.py            median over duplicate rows;
                                 exits 1 on any (scenario, volume)
                                 slowdown >= threshold (default 25%).

Verified at scale

  bench-pipeline-max: 1,000,000 rows, full content diff
    seed   17 s, export 304 s, import 31 s, idempotent re-import 10 s,
    diff 2.7 s -- mismatches=0.

Findings surfaced by the harness

  Export scales super-linearly: 4 s @ 100k -> 304 s @ 1M (76x for
    10x rows). Cause: g_slist_sort on the merged list + per-row
    ProfMessage/ff_parsed_line_t allocations. RSS peaks at 1.4 GB
    on 1M. Worth a follow-up.
  Export progress reporting only fires during the write phase --
    the merge+sort phase (~95% of wall time at 1M) is silent.
  /history export and /history import are blocking on the main
    UI thread; profanity is frozen for the duration (~5 min @ 1M).
  ff_readline sets *truncated=TRUE on partial-write tail but
    ff_verify_integrity does not surface this -- partial writes
    go unflagged (failure-injection F1).
  Parser silently truncates body at first unescaped ': ' if a
    resource was manually edited to contain it (F9).
  In gen_history (caught by the bench's own real-verify pass):
    g_strndup mid-codepoint truncation on UTF-8 bank strings -- fixed.

Linkage strategy

  database_flatfile.c + parser + verify + common.c are linked
  unconditionally. The export/import bench additionally links
  database.c + database_sqlite.c + database_export.c. bench_stubs.c
  provides minimal stubs for log_*, prefs_*, connection_get_jid,
  jid_create, files_*, message_*, ui hooks. integrity_issue_free
  is a weak symbol so it falls back to the real database.c
  implementation when that file is linked.
2026-04-30 15:39:30 +03:00
8868d58920 fix(review): address PR #94 review #37/#38 reviewer comments
Parser (src/database_flatfile_parser.c):
- ff_jid_to_dir: drop GString+step1, in-place mutate str_replace result
- ff_ensure_dir: g_file_test(G_FILE_TEST_IS_SYMLINK) instead of g_lstat
- ff_unescape_*: early-continue for non-escape branch (less nesting)
- ff_readline: strdup("") instead of malloc(1)+'\0' for skip-line return
- ff_write_line: auto_char safe_msg + single fprintf (drop GString full_line)
- ff_parse_line: early return on missing closing bracket;
  extract metadata-parts loop into _ff_parse_meta_parts helper

Verify (src/database_flatfile_verify.c):
- Split monolithic ff_verify_integrity into _collect_contact_dirs,
  _check_permissions, _first_pass, _lmc_pass, _verify_contact_dir
- _issue_new constructor; g_new0 throughout
- Separate seen_stanza_ids and seen_archive_ids tables (no cross-kind
  duplicate confusion)
- ff_skip_bom in second pass (drop manual fgetc x3)
- log_debug when skipping a contact dir without history.log
- Doc comment on ff_verify_integrity in header

SQLite (src/database_sqlite.c):
- Doc block on ChatLogs schema (replaces_db_id <-> replaced_by_db_id
  invariant maintained by AFTER INSERT trigger)
- log_error when _get_db_filename returns NULL during init

Flatfile dispatch (src/database_flatfile.c):
- Replace if/else with is_outgoing ternary for log-path contact pick

Tests:
- 6 new invalid-date parser tests: empty / partial ISO / garbage /
  impossible calendar / negative year / far future timestamp
- New functional test message_db_history_multi_resource verifying
  same-JID-different-resource history rehydration preserves resources
- test_database_stress.c LMC chain loop: auto_char buf, drop redundant
  comment/empty pre-filter (ff_parse_line handles those)
2026-04-30 10:53:03 +03:00
7ba7e53291 refactor: extract helpers for verify print, scan loop, and per-contact export
- extract _show_integrity_issues() from cmd_history verify block
- extract _ff_scan_lines() shared by _ff_state_build and _ff_state_extend
- extract _export_one_contact() from log_database_export_to_flatfile loop
2026-03-28 12:58:27 +03:00
a96a4ad41e fix(review): address PR #94 reviewer comments
Blockers:
- SPDX/CProof copyright headers (7 files)
- stanza-id non-uniqueness: warn-only, don't skip (matches SQLite)
- fopen → open(O_EXCL|O_NOFOLLOW, 0600) + fdopen in export

Medium:
- log_info → log_warning for SQLite fallback
- remove prefs_save() auto-save from backend switch
- vtable null → log_warning in 4 dispatch functions
- log_debug → log_warning + null error handling in export
- rename failure → cons_show_error to user
- remove unused total_skipped variable
- LMC respects PREF_CORRECTION_ALLOW

Low nits:
- man page .SS fix + jabber.space URL
- profrc.example simplified
- show flatfile path on /logging flatfile
- EXPORT_PROGRESS_INTERVAL constant (magic 500)
- FF_META_PREFIX_ID/AID constants + FF_INDEX_STEP comment
- buffer overflow guard on close[1]/close[2]
- for-loop → memchr for JID resource scan
- BOM check extracted to ff_skip_bom() (DRY)
- index building extracted to _ff_maybe_index_line()
- O_APPEND+O_EXCL comment rewritten
- Makefile.am spaces → tabs
2026-03-28 12:38:39 +03:00
58002409ff test(functests): migration/MUC/timestamp tests, group rebalancing
All checks were successful
CI Code / Check spelling (pull_request) Successful in 24s
CI Code / Check coding style (pull_request) Successful in 41s
CI Code / Linux (ubuntu) (pull_request) Successful in 6m56s
CI Code / Linux (debian) (pull_request) Successful in 7m0s
CI Code / Code Coverage (pull_request) Successful in 7m5s
CI Code / Linux (arch) (pull_request) Successful in 9m29s
Add 11 new export/import tests (24 → 35): 4 MUC database, 3 timestamp
verification, 3 migration stress, 1 LMC correction with negative assert.

Add delay-stamp timestamp checks to 5 base tests via /time chat set
iso8601 and /history on (previously passed by accident from PTY buffer).

Replace magic numbers: NEGATIVE_ASSERT_TIMEOUT, MIN_ELAPSED_INIT.
Add per-test slow/fast thresholds and TZ override (prof_test_tz).

Rebalance groups by whole logical blocks (spread 46s → 3s):
G1=52s G2=50s G3=53s G4=53s. All 129 tests pass.
2026-03-19 19:05:36 +03:00
2b1b70665b fix(functests): fix send_receipt_request 60s timeout, rebalance groups, add per-test timing
All checks were successful
CI Code / Check spelling (pull_request) Successful in 19s
CI Code / Check coding style (pull_request) Successful in 35s
CI Code / Code Coverage (pull_request) Successful in 2m28s
CI Code / Linux (debian) (pull_request) Successful in 4m23s
CI Code / Linux (arch) (pull_request) Successful in 4m41s
CI Code / Linux (ubuntu) (pull_request) Successful in 5m14s
Fix send_receipt_request test that wasted 60s on every run:
- Change caps hash from sha-256 to sha-1 (profanity only supports sha-1
  for standard caps path, sha-256 goes to unsupported-hash fallback)
- Fix expected output: 'Buddy1 is online' → 'Buddy1 (laptop) is online'
  (resource is always shown for full JID presence)
- Wrap prof_output_exact in assert_true so mismatches fail fast instead
  of silently waiting the full expect_timeout

Rebalance test groups for parallel execution:
- Move Disco tests (14) from Group 3 → Group 1
- Move DB History tests (12) from Group 2 → Group 3
- Before: G1=31s G2=63s G3=30s G4=37s (bottleneck 63s)
- After:  G1=46s G2=38s G3=40s G4=36s (bottleneck 46s, -27%)

Add per-test wall-clock timing via clock_gettime(CLOCK_MONOTONIC)
in init_prof_test/close_prof_test for profiling individual tests.
2026-03-12 21:02:22 +03:00
0d38a0a2cb test: add database stress tests (14 tests, rapid writes, large messages, LMC chains, dedup)
All checks were successful
CI Code / Check spelling (pull_request) Successful in 17s
CI Code / Check coding style (pull_request) Successful in 31s
CI Code / Code Coverage (pull_request) Successful in 4m1s
CI Code / Linux (debian) (pull_request) Successful in 5m38s
CI Code / Linux (ubuntu) (pull_request) Successful in 5m39s
CI Code / Linux (arch) (pull_request) Successful in 6m7s
2026-03-12 18:58:52 +03:00
71f9ab5007 perf: O(1) dedup/LMC cache, g_slist_append → prepend+reverse
- Add archive_ids hash set and stanza_senders hash map to
  ff_contact_state_t, populated during index build/extend via
  lightweight _ff_cache_line_ids() (no full parse overhead).
- Replace O(n) file scans in _ff_has_archive_id() and
  _ff_find_original_sender() with O(1) hash table lookups.
- Replace g_slist_append with g_slist_prepend + g_slist_reverse
  in _ff_apply_lmc, _flatfile_get_previous_chat, and
  ff_verify_integrity to avoid O(n²) list building.
- Add db_sqlite_last_changes() declaration to database.h.
2026-03-12 18:52:00 +03:00
06463b75b4 style: apply clang-format and const qualifiers from master 2026-03-12 18:52:00 +03:00
507ef91b5f feat: complete field parity, harden export/import, add tests
Export/Import improvements:
- Replace pagination with direct SQL query (db_sqlite_get_all_chat)
- Wrap import in SQL transaction with rollback on error
- Add fsync before fclose in export for data safety
- Sort merged output by timestamp with secondary key (stanza_id, from_jid)
- Export archive_id and marked_read from SQLite (lossless migration)
- Add progress indication every 500 messages during write/import
- Expand dedup key body prefix from 64 to 256 chars
- Fix g_slist_append O(n²) → g_slist_prepend + g_slist_reverse O(n)

Field parity (to_jid, to_resource, marked_read):
- Add fields to ff_parsed_line_t struct
- Write/parse to:|to_res:|read: metadata tags in flatfile format
- Pass to_resource through _ff_add_message and all callers
- Add marked_read to ProfMessage struct with -1 default (unset)
- Preserve fields across export/import round-trips

Tests (19 new: 11 unit + 8 functional):
- Unit: to_jid_and_marked_read, bracket_in_stanza_id, backslash_in_resource,
  mucpm_type, all_enc_types, crlf_handling, to_jid_special_chars,
  multiple_lines, parsed_line_free_null_safe, no_space_rejected,
  unclosed_bracket
- Functional: export_idempotent_no_duplicates, export_lmc_correction_survives,
  switch_preserves_old_backend_data, export_all_contacts,
  import_double_dedup, verify_after_export,
  switch_backends_independent_messages, export_empty_contact
- Rebalance test groups: move Chat Session from Group 3 to Group 4
  (25/33/30/27 instead of 25/33/36/21)
- Remove hardcoded test counts from group comments

Man page:
- Document /history switch sqlite|flatfile
2026-03-12 18:46:42 +03:00
9f3020e40a Add functional and unit tests for DB export/import
- 2 functional tests: export_sqlite_to_flatfile, import_flatfile_to_sqlite
  with XEP-0203 delay timestamps for deterministic verification
- 27 unit tests for database_export covering edge cases
- Merge test/db-functional-tests: 12 DB persistence tests (test_history)
- Group 2 rebalanced: 25 tests (23 base + 2 SQLite-only export/import)
- #ifdef HAVE_SQLITE guards for export/import tests
- prof_stop() helper in proftest.c
- Makefile.am: source ordering cleanup, new test files added
2026-03-12 18:46:42 +03:00
7e320ccdb0 tests: add functional tests for DB message persistence, rebalance groups
Add backend-agnostic functional tests for database message persistence.
All tests work with both SQLite and flat-file backends.

New tests in test_history.c:
- message_db_history_on_reopen: basic incoming write+read round-trip
- message_db_history_multiple: 3 messages from different resources
- message_db_history_contact_isolation: buddy1 msg absent from buddy2
- message_db_history_special_chars: XML entities survive decode+DB
- message_db_history_outgoing: sent message persists across reopen
- message_db_history_dialog: outgoing + incoming both in history
- message_db_history_empty: no crash on contact with no history
- message_db_history_long_message: 1000+ char body not truncated
- message_db_history_newline: embedded LF stored correctly
- message_db_history_service_chars: backslash pipe percent braces etc
- message_db_history_verify: /history verify (ifdef HAVE_HISTORY_VERIFY)
- message_db_history_lmc: XEP-0308 correction replaces original in DB

Rebalance test groups for parallel execution (19/22/22/21):
- Group 1: Connect, Ping, Rooms, Software, LastActivity
- Group 2: Message, Receipts, Roster, DB History
- Group 3: Chat Session, Presence, Disconnect
- Group 4: MUC, Carbons
2026-03-12 18:46:42 +03:00
b5fe714a89 feat: add /history switch for runtime database backend switching
Add log_database_switch_backend() that closes the current backend,
updates PREF_DBLOG preference, and reinitializes with the new backend
without requiring a reconnect or restart.

New command: /history switch sqlite|flatfile
- Validates connection state and backend name
- Skips if already using the requested backend
- Autocomplete support for the subcommand
2026-03-12 18:46:42 +03:00
1f3d3117bf feat(draft): add /history export|import for SQLite<->flatfile migration
DRAFT — not yet tested end-to-end with a live XMPP session.

New commands:
  /history export [<jid>]  — copy messages from SQLite to flat-file
  /history import [<jid>]  — copy messages from flat-file to SQLite
Both merge with existing data; duplicates are skipped using stanza-id
or a SHA-256 fallback key (timestamp + sender + body prefix).

Implementation (src/database_export.c):
- Export: paginate SQLite via get_previous_chat, read existing flatfile
  for dedup, write merged result via ff_write_line + atomic rename
- Import: parse flatfile lines via ff_parse_line, build dedup set from
  SQLite, insert new messages via add_incoming (preserves original
  timestamps for both directions)
- List all contacts: db_sqlite_list_contacts() queries UNION of
  DISTINCT from_jid/to_jid; flatfile enumerates flatlog directories

Wiring:
- database.h: declare export/import functions + db_sqlite_list_contacts
- database_sqlite.c: add db_sqlite_list_contacts()
- cmd_defs.c: add export/import to /history synopsis and args
- cmd_funcs.c: add export/import handlers in cmd_history()
- cmd_ac.c: add 'export' and 'import' to history_ac
- Makefile.am: add database_export.c to core_sources
- stub_database.c: add stubs for test linking
- profanity.1: document export/import in man page

All code guarded with #ifdef HAVE_SQLITE — builds cleanly without it.
2026-03-12 18:46:42 +03:00
23723376c6 fix: harden flatfile backend, make SQLite optional
Build system:
- Add --without-sqlite configure flag (AM_CONDITIONAL BUILD_SQLITE)
- Guard database_sqlite.c with HAVE_SQLITE in Makefile.am, database.c,
  database.h and stub_database.c
- Fall back to flatfile when SQLite not compiled in

Security (database_flatfile.c):
- MAM dedup: skip incoming messages with duplicate stanza-id (archive_id)
- LMC sender validation: reject corrections from mismatched JIDs
- Add flock() advisory locking to prevent interleaved writes from
  concurrent instances
- Check fprintf return when writing file header

Autocomplete (cmd_ac.c):
- Add 'flatfile' to /privacy logging autocomplete
- Add dedicated /history autocomplete with on/off/verify (was boolean-only)

Code quality:
- Fix fwrite return type: size_t not ssize_t (database_flatfile_parser.c)
- Fix mixed allocators in ff_readline: use malloc() consistently for
  overlength-line fallback instead of g_strdup()
- Fix index alignment in _ff_state_extend: use local counter so index
  step doesn't depend on total_lines from initial build

Documentation:
- Fix page: correct directory structure (history.log not per-day files)
- Fix page: add aid:{archive_id} to line format example
- Fix page: missing newline before .SH BUGS
2026-03-12 18:46:42 +03:00
16ae7fb85c database_flatfile: single-file storage with sparse index
Replace per-contact directory structure with a single flat file per contact.
Each file uses pipe-delimited records with a sparse byte-offset index
that is rebuilt on demand and cached in memory.

- Rewrite _ff_write_record / _ff_read_records for single-file format
- Add sparse index (every Nth record) for O(log N) seek on history read
- Cursor-based pagination: _ff_get_previous_chat uses saved byte offset
- LMC corrections applied in-place during read (_ff_apply_lmc)
- Newline escaping (\n) in message bodies for line-based storage
- Simplify verify: parse + timestamp order + LMC reference check
- Update parser helpers for new field layout
2026-03-12 18:46:42 +03:00
d25f90899c refactor: split database_flatfile.c into functional modules
Split the monolithic database_flatfile.c into:
- database_flatfile.h: internal header with shared types and prototypes
- database_flatfile_parser.c: parsing, escaping, IO helpers
- database_flatfile_verify.c: integrity verification logic
- database_flatfile.c: core backend (init, write, read, LMC, vtable)
2026-03-12 18:46:42 +03:00
89b90e5cf2 fix(flatfile): harden flat-file backend against injection and traversal attacks
Security fixes for 7 vulnerabilities in database_flatfile.c:

1. Path traversal via crafted JID (HIGH):
   _ff_jid_to_dir() now strips '/', '\' -> '_' and collapses '..' -> '__',
   preventing a malicious federated JID from escaping the log directory.

2. Log injection via unescaped message body (HIGH):
   Add _ff_escape_message()/_ff_unescape_message() -- escape \n, \r, \\
   in message text on write, unescape on read. Prevents remote contacts
   from injecting fake log lines with forged sender/timestamp/encryption.

3. Metadata field injection (HIGH):
   Add _ff_escape_meta_value()/_ff_unescape_meta_value() -- escape |, ],
   \\, \n, \r in stanza_id/archive_id/replace_id. Parser uses escape-aware
   _ff_find_unescaped_char() and _ff_split_meta() instead of strchr/strsplit.

4. Sender ": " parsing confusion (MEDIUM):
   Escape ": " -> "\: " in XMPP resource on write. Parser uses
   _ff_find_unescaped_colonspace() + _ff_unescape_sender_resource().

5. LMC correction chain cycle -> infinite loop (MEDIUM):
   Add visited hash-set and FF_MAX_LMC_DEPTH (100) limit to chain walker.

6. Unbounded getline() -> OOM (MEDIUM):
   Add FF_MAX_LINE_LEN (10 MB) cap in _ff_readline(); overlength lines
   are skipped with a warning. Replaces all char buf[8192]/fgets() sites
   with dynamic getline() + truncated-line detection at EOF.

7. Symlink attack + TOCTOU on file creation (MEDIUM):
   Replace fopen("a") with open(O_WRONLY|O_APPEND|O_CREAT|O_EXCL|O_NOFOLLOW)
   + fdopen() -- atomic new-file detection, symlink rejection via O_NOFOLLOW.
   _ff_ensure_dir() checks g_lstat() for symlinks. File permissions 0600
   set via open() mode, not post-hoc g_chmod().
2026-03-12 18:46:42 +03:00
31e8c30c34 feat: add flat-file database backend for message history
Add pluggable storage backend abstraction (vtable) to the database layer,
allowing selection between SQLite (default) and a new flat-file backend
that stores messages as human-readable plain text files.

New files:
- database_sqlite.c: extracted SQLite backend from database.c
- database_flatfile.c: plain text backend with tolerant parser,
  LMC correction chains, UTF-8/BOM/CRLF handling, integrity checks

Commands:
- /privacy logging flatfile — switch to flat-file backend
- /history verify [<jid>] — check integrity of stored history

Fixes:
- Add missing 'off' guard in flatfile backend
- Enable CHLOG/HISTORY prefs when switching to flatfile mode

Logs stored in ~/.local/share/profanity/flatlog/{account}/{contact}/{date}.log
Format: {ISO8601} [{type}|{enc}|id:{id}|corrects:{id}] {sender}: {message}

Updated: CHANGELOG, CONTRIBUTING.md, profrc.example, man page, cmd_defs,
Makefile.am, test stubs, functional test support (PROF_FLATFILE=1)
2026-03-12 18:46:42 +03:00