From 3d88973ff61a7e2c572fa2d80ab5446510c9a8b2 Mon Sep 17 00:00:00 2001
From: Daan De Meyer <daan.j.demeyer@gmail.com>
Date: Wed, 26 Apr 2023 13:21:55 +0200
Subject: [PATCH] journal: Don't try to write garbage if journal entry is
 corrupted

If journal_file_data_payload() returns -EBADMSG or -EADDRNOTAVAIL,
we skip the entry and go to the next entry, but we never modify
the number of items that we pass to journal_file_append_entry_internal()
if that happens, which means we could try to append garbage to the
journal file.

Let's keep track of the number of fields we've appended to avoid this
problem.

(cherry picked from commit f81409f844ae8077f7ee7664871f73fa7d440581)
(cherry picked from commit 3821e3ea077810a7271dbdaccf67b08c33a28fcf)
(cherry picked from commit b9d96f2803b6fbf703463b72bb63d0c936f558e8)

Conflict:code context adaptation
Reference:https://github.com/systemd/systemd-stable/commit/3d88973ff61a7e2c572fa2d80ab5446510c9a8b2
---
 src/libsystemd/sd-journal/journal-file.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/src/libsystemd/sd-journal/journal-file.c b/src/libsystemd/sd-journal/journal-file.c
index 3c9221c..1988488 100644
--- a/src/libsystemd/sd-journal/journal-file.c
+++ b/src/libsystemd/sd-journal/journal-file.c
@@ -3839,7 +3839,7 @@ int journal_file_open_reliably(
 }
 
 int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint64_t p) {
-        uint64_t q, n, xor_hash = 0;
+        uint64_t q, n, m = 0, xor_hash = 0;
         const sd_id128_t *boot_id;
         dual_timestamp ts;
         EntryItem *items;
@@ -3918,15 +3918,18 @@ int journal_file_copy_entry(JournalFile *from, JournalFile *to, Object *o, uint6
                 else
                         xor_hash ^= le64toh(u->data.hash);
 
-                items[i].object_offset = htole64(h);
-                items[i].hash = u->data.hash;
+                items[m].object_offset = htole64(h);
+                items[m++].hash = u->data.hash;
 
                 r = journal_file_move_to_object(from, OBJECT_ENTRY, p, &o);
                 if (r < 0)
                         return r;
         }
 
-        r = journal_file_append_entry_internal(to, &ts, boot_id, xor_hash, items, n,
+        if (m == 0)
+                return 0;
+
+        r = journal_file_append_entry_internal(to, &ts, boot_id, xor_hash, items, m,
                                                NULL, NULL, NULL);
 
         if (mmap_cache_got_sigbus(to->mmap, to->cache_fd))
-- 
2.33.0

