From 84e1819ec104a168f7904134b6212669133c955f Mon Sep 17 00:00:00 2001
From: Lennart Poettering <lennart@poettering.net>
Date: Tue, 8 Jun 2021 22:14:40 +0200
Subject: [PATCH] journal: add some careful overflow checking

(cherry picked from commit d8671b1c6f036ce270b9631973314e7de24e74b1)

Reference: https://github.com/systemd/systemd-stable/commit/84e1819ec104a168f7904134b6212669133c955f
Conflict: adapt context
---
 src/journal/sd-journal.c | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/src/journal/sd-journal.c b/src/journal/sd-journal.c
index 02ac260..244ea91 100644
--- a/src/journal/sd-journal.c
+++ b/src/journal/sd-journal.c
@@ -2761,25 +2761,33 @@ void journal_print_header(sd_journal *j) {
         }
 }

-_public_ int sd_journal_get_usage(sd_journal *j, uint64_t *bytes) {
+_public_ int sd_journal_get_usage(sd_journal *j, uint64_t *ret) {
         Iterator i;
         JournalFile *f;
         uint64_t sum = 0;

         assert_return(j, -EINVAL);
         assert_return(!journal_pid_changed(j), -ECHILD);
-        assert_return(bytes, -EINVAL);
+        assert_return(ret, -EINVAL);

         ORDERED_HASHMAP_FOREACH(f, j->files, i) {
                 struct stat st;
+                uint64_t b;

                 if (fstat(f->fd, &st) < 0)
                         return -errno;

-                sum += (uint64_t) st.st_blocks * 512ULL;
+                b = (uint64_t) st.st_blocks;
+                if (b > UINT64_MAX / 512)
+                        return -EOVERFLOW;
+                b *= 512;
+
+                if (sum > UINT64_MAX - b)
+                        return -EOVERFLOW;
+                sum += b;
         }

-        *bytes = sum;
+        *ret = sum;
         return 0;
 }

--
2.27.0
